Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop-gpui): rebuild the Shortcuts settings page

Richie McIlroyb16ce3fb357d
diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs
index 79ac7abca..ac747c962 100644
--- a/apps/desktop-gpui/src/app_windows.rs
+++ b/apps/desktop-gpui/src/app_windows.rs
@@ -1448,6 +1448,8 @@ pub fn onboarding_is_open(cx: &App) -> bool {
}
fn restore_after_settings(cx: &mut App) {
+ // A Shortcuts row may have been recording when the window went away.
+ crate::hotkeys::resume(cx);
// Not while recording: the main window is deliberately hidden then, and
// the session observer brings it back when the recording ends.
if RecordingSession::global(cx).read(cx).phase == Phase::Idle {
diff --git a/apps/desktop-gpui/src/hotkeys.rs b/apps/desktop-gpui/src/hotkeys.rs
index 3a0675faa..3b307c7c7 100644
--- a/apps/desktop-gpui/src/hotkeys.rs
+++ b/apps/desktop-gpui/src/hotkeys.rs
@@ -51,26 +51,47 @@ pub enum HotkeyAction {
ScreenshotArea,
}
+const ACTION_KEYS: [(&str, HotkeyAction); 13] = [
+ ("startStudioRecording", HotkeyAction::StartStudioRecording),
+ ("startInstantRecording", HotkeyAction::StartInstantRecording),
+ ("stopRecording", HotkeyAction::StopRecording),
+ ("restartRecording", HotkeyAction::RestartRecording),
+ ("togglePauseRecording", HotkeyAction::TogglePauseRecording),
+ ("cycleRecordingMode", HotkeyAction::CycleRecordingMode),
+ ("openRecordingPicker", HotkeyAction::OpenRecordingPicker),
+ (
+ "openRecordingPickerDisplay",
+ HotkeyAction::OpenRecordingPickerDisplay,
+ ),
+ (
+ "openRecordingPickerWindow",
+ HotkeyAction::OpenRecordingPickerWindow,
+ ),
+ (
+ "openRecordingPickerArea",
+ HotkeyAction::OpenRecordingPickerArea,
+ ),
+ ("screenshotDisplay", HotkeyAction::ScreenshotDisplay),
+ ("screenshotWindow", HotkeyAction::ScreenshotWindow),
+ ("screenshotArea", HotkeyAction::ScreenshotArea),
+];
+
impl HotkeyAction {
+ /// `#[serde(other)] Other` over there: a newer app's action survives in
+ /// the store and registers nothing here.
fn from_store_key(key: &str) -> Option<Self> {
- Some(match key {
- "startStudioRecording" => Self::StartStudioRecording,
- "startInstantRecording" => Self::StartInstantRecording,
- "stopRecording" => Self::StopRecording,
- "restartRecording" => Self::RestartRecording,
- "togglePauseRecording" => Self::TogglePauseRecording,
- "cycleRecordingMode" => Self::CycleRecordingMode,
- "openRecordingPicker" => Self::OpenRecordingPicker,
- "openRecordingPickerDisplay" => Self::OpenRecordingPickerDisplay,
- "openRecordingPickerWindow" => Self::OpenRecordingPickerWindow,
- "openRecordingPickerArea" => Self::OpenRecordingPickerArea,
- "screenshotDisplay" => Self::ScreenshotDisplay,
- "screenshotWindow" => Self::ScreenshotWindow,
- "screenshotArea" => Self::ScreenshotArea,
- // `#[serde(other)] Other` over there: a newer app's action
- // survives in the store and registers nothing here.
- _ => return None,
- })
+ ACTION_KEYS
+ .iter()
+ .find(|(stored, _)| *stored == key)
+ .map(|(_, action)| *action)
+ }
+
+ fn store_key(self) -> &'static str {
+ ACTION_KEYS
+ .iter()
+ .find(|(_, action)| *action == self)
+ .map(|(key, _)| *key)
+ .unwrap_or_default()
}
}
@@ -80,6 +101,12 @@ struct Hotkeys {
/// grabbed.
manager: Option<GlobalHotKeyManager>,
bindings: Vec<(HotKey, HotkeyAction)>,
+ /// Bindings the OS refused, usually because macOS or another app already
+ /// owns the combo. The Shortcuts page flags these rows.
+ unavailable: Vec<HotkeyAction>,
+ /// Set while the Shortcuts page records a new combo: a registered combo
+ /// would otherwise fire its action instead of reaching the page.
+ paused: bool,
#[cfg(target_os = "linux")]
capture_stop: Option<HotKey>,
}
@@ -119,6 +146,8 @@ pub fn init(cx: &mut App) {
cx.set_global(Hotkeys {
manager: None,
bindings: Vec::new(),
+ unavailable: Vec::new(),
+ paused: false,
#[cfg(target_os = "linux")]
capture_stop: None,
});
@@ -157,13 +186,59 @@ pub fn init(cx: &mut App) {
/// Re-read the store and swap every OS registration -- the settings page's
/// commit seam (`commands.setHotkey` re-registers over there).
pub fn reload(cx: &mut App) {
- if !cx.has_global::<Hotkeys>() {
+ if !cx.has_global::<Hotkeys>() || cx.global::<Hotkeys>().paused {
return;
}
#[cfg(target_os = "linux")]
if cx.global::<Hotkeys>().capture_stop.is_some() {
return;
}
+ unregister_all(cx);
+ register_from_store(cx);
+}
+
+/// Drop every OS registration while the Shortcuts page records a combo, so
+/// pressing an already-bound combo reaches the page instead of firing.
+pub fn pause(cx: &mut App) {
+ if !cx.has_global::<Hotkeys>() || cx.global::<Hotkeys>().paused {
+ return;
+ }
+ #[cfg(target_os = "linux")]
+ if cx.global::<Hotkeys>().capture_stop.is_some() {
+ return;
+ }
+ unregister_all(cx);
+ let hotkeys = cx.global_mut::<Hotkeys>();
+ hotkeys.paused = true;
+ hotkeys.release_idle_manager();
+ tracing::info!("global hotkeys paused while a shortcut is recorded");
+}
+
+/// End a [`pause`] and register the store's bindings again. Returns whether
+/// anything was paused; without a pause the registrations are left alone.
+pub fn resume(cx: &mut App) -> bool {
+ if !cx.has_global::<Hotkeys>() || !cx.global::<Hotkeys>().paused {
+ return false;
+ }
+ cx.global_mut::<Hotkeys>().paused = false;
+ reload(cx);
+ true
+}
+
+/// Store keys of the bindings the OS refused at the last registration.
+pub fn unavailable_actions(cx: &App) -> Vec<&'static str> {
+ cx.try_global::<Hotkeys>()
+ .map(|hotkeys| {
+ hotkeys
+ .unavailable
+ .iter()
+ .map(|action| action.store_key())
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+fn unregister_all(cx: &mut App) {
let hotkeys = cx.global_mut::<Hotkeys>();
// Two actions on one combo share one OS registration, so unregister each
// combo once.
@@ -179,7 +254,7 @@ pub fn reload(cx: &mut App) {
tracing::warn!("unregistering global hotkeys failed: {error}");
}
hotkeys.bindings.clear();
- register_from_store(cx);
+ hotkeys.unavailable.clear();
}
#[cfg(target_os = "linux")]
@@ -598,7 +673,8 @@ fn register_from_store(cx: &mut App) {
match registered {
Ok(()) => hotkeys.bindings.push((hotkey, action)),
Err(error) => {
- tracing::warn!(?action, code = %binding.code, "registering global hotkey failed: {error}")
+ tracing::warn!(?action, code = %binding.code, "registering global hotkey failed: {error}");
+ hotkeys.unavailable.push(action);
}
}
}
@@ -865,6 +941,8 @@ mod tests {
let mut hotkeys = Hotkeys {
manager: None,
bindings: Vec::new(),
+ unavailable: Vec::new(),
+ paused: false,
#[cfg(target_os = "linux")]
capture_stop: None,
};
@@ -962,6 +1040,9 @@ mod tests {
);
}
assert_eq!(HotkeyAction::from_store_key("someFutureAction"), None);
+ for (key, action) in ACTION_KEYS {
+ assert_eq!(action.store_key(), key);
+ }
}
fn window(id: &str) -> ScreenCaptureTarget {
diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rs
index 528a55b6c..f076c6b04 100644
--- a/apps/desktop-gpui/src/settings_pages.rs
+++ b/apps/desktop-gpui/src/settings_pages.rs
@@ -189,11 +189,18 @@ struct DriveQuota {
stale: bool,
}
-/// hotkeys.tsx's `listening` signal: which action is armed, and the binding
-/// to restore when the capture is abandoned.
+/// The row recording a new combo. Global hotkeys are paused for as long as
+/// this is set, so pressing an already-bound combo reaches the page.
struct ListeningHotkey {
- action: usize,
- prev: Option<Value>,
+ action: &'static str,
+ modifiers: gpui::Modifiers,
+ error: Option<&'static str>,
+}
+
+/// The confirmation a row shows for a few seconds after a combo is saved.
+struct SavedShortcut {
+ action: &'static str,
+ moved_from: Option<&'static str>,
}
/// The S3 form's five text fields, in render order.
@@ -285,6 +292,8 @@ pub(crate) struct PagesState {
// Shortcuts (hotkeys.tsx)
hotkeys: Map<String, Value>,
listening: Option<ListeningHotkey>,
+ shortcut_saved: Option<SavedShortcut>,
+ shortcut_saved_reset: Option<gpui::Task<()>>,
// CLI (cli.tsx). `None` while the status fetch is in flight.
cli_status: Option<Result<cli_install::CliInstallStatus, String>>,
@@ -403,10 +412,19 @@ impl PagesState {
this.page_field_event(PageField::S3(index), input, event, cx)
}));
}
+ // Keys stop arriving once the window loses focus, so a recording row
+ // would otherwise keep every global shortcut paused.
+ subscriptions.push(cx.observe_window_activation(window, |this, window, cx| {
+ if !window.is_window_active() {
+ this.shortcuts_cancel(cx);
+ }
+ }));
Self {
hotkeys: store::hotkeys_raw(),
listening: None,
+ shortcut_saved: None,
+ shortcut_saved_reset: None,
cli_status: None,
cli_installing: false,
cli_uninstalling: false,
@@ -485,7 +503,8 @@ impl SettingsWindow {
match self.page {
Page::Shortcuts => {
self.pages.hotkeys = store::hotkeys_raw();
- self.pages.listening = None;
+ self.pages.shortcut_saved = None;
+ self.pages.shortcut_saved_reset = None;
}
Page::Cli => self.cli_refresh(window, cx),
Page::Transcription => {
@@ -909,24 +928,206 @@ impl SettingsWindow {
}
// ---------------------------------------------------------------------------
-// Shortcuts (hotkeys.tsx)
+// Shortcuts
// ---------------------------------------------------------------------------
-/// `actions()` in hotkeys.tsx, with `ACTION_TEXT`'s labels, in render order.
-const HOTKEY_ACTIONS: [(&str, &str); 11] = [
- ("screenshotDisplay", "Screenshot current display"),
- ("screenshotWindow", "Screenshot current window"),
- ("screenshotArea", "Screenshot area picker"),
- ("openRecordingPicker", "Open recording picker"),
- ("stopRecording", "Stop recording"),
- ("restartRecording", "Restart recording"),
- ("togglePauseRecording", "Pause/resume recording"),
- ("cycleRecordingMode", "Cycle recording mode"),
- ("openRecordingPickerDisplay", "Record display"),
- ("openRecordingPickerWindow", "Record window"),
- ("openRecordingPickerArea", "Record area"),
+const SCREENSHOT_SHORTCUTS: [&str; 3] = ["screenshotArea", "screenshotWindow", "screenshotDisplay"];
+
+const RECORDING_SHORTCUTS: [&str; 7] = [
+ "startStudioRecording",
+ "startInstantRecording",
+ "openRecordingPickerArea",
+ "openRecordingPickerWindow",
+ "openRecordingPickerDisplay",
+ "openRecordingPicker",
+ "cycleRecordingMode",
+];
+
+const WHILE_RECORDING_SHORTCUTS: [&str; 3] =
+ ["stopRecording", "togglePauseRecording", "restartRecording"];
+
+const SHORTCUT_SAVED_NOTICE: std::time::Duration = std::time::Duration::from_secs(6);
+
+/// One choice in an "After ..." panel.
+#[derive(Clone, Copy)]
+struct OutcomeOption {
+ icon: &'static str,
+ label: &'static str,
+ hint: &'static str,
+}
+
+const SCREENSHOT_OUTCOMES: [(store::PostScreenshotBehaviour, OutcomeOption); 4] = [
+ (
+ store::PostScreenshotBehaviour::OpenEditor,
+ OutcomeOption {
+ icon: "icons/edit.svg",
+ label: "Open editor",
+ hint: "Annotate first",
+ },
+ ),
+ (
+ store::PostScreenshotBehaviour::Copy,
+ OutcomeOption {
+ icon: "icons/copy.svg",
+ label: "Copy",
+ hint: "Paste anywhere",
+ },
+ ),
+ (
+ store::PostScreenshotBehaviour::CopyAndOpenEditor,
+ OutcomeOption {
+ icon: "icons/layers.svg",
+ label: "Copy and edit",
+ hint: "Both at once",
+ },
+ ),
+ (
+ store::PostScreenshotBehaviour::Save,
+ OutcomeOption {
+ icon: "icons/folder-down.svg",
+ label: "Do nothing",
+ hint: "Saved to library",
+ },
+ ),
+];
+
+const STUDIO_OUTCOMES: [(store::PostStudioBehaviour, OutcomeOption); 3] = [
+ (
+ store::PostStudioBehaviour::OpenEditor,
+ OutcomeOption {
+ icon: "icons/edit.svg",
+ label: "Open editor",
+ hint: "Edit right away",
+ },
+ ),
+ (
+ store::PostStudioBehaviour::ShowOverlay,
+ OutcomeOption {
+ icon: "icons/app-window.svg",
+ label: "Show Cap",
+ hint: "Back to the recorder",
+ },
+ ),
+ (
+ store::PostStudioBehaviour::DoNothing,
+ OutcomeOption {
+ icon: "icons/folder-down.svg",
+ label: "Do nothing",
+ hint: "Saved to library",
+ },
+ ),
];
+/// `disableAutoOpenLinks`, phrased as what an Instant recording does.
+const INSTANT_OUTCOMES: [(bool, OutcomeOption); 2] = [
+ (
+ false,
+ OutcomeOption {
+ icon: "icons/globe.svg",
+ label: "Open link",
+ hint: "In your browser",
+ },
+ ),
+ (
+ true,
+ OutcomeOption {
+ icon: "icons/link.svg",
+ label: "Copy link only",
+ hint: "Nothing opens",
+ },
+ ),
+];
+
+fn shortcut_label(action: &str) -> &'static str {
+ match action {
+ "screenshotArea" => "Screenshot an area",
+ "screenshotWindow" => "Screenshot a window",
+ "screenshotDisplay" => "Screenshot the display",
+ "startStudioRecording" => "Start Studio recording",
+ "startInstantRecording" => "Start Instant recording",
+ "openRecordingPickerArea" => "Record an area",
+ "openRecordingPickerWindow" => "Record a window",
+ "openRecordingPickerDisplay" => "Record a display",
+ "openRecordingPicker" => "Open recording picker",
+ "cycleRecordingMode" => "Cycle recording mode",
+ "stopRecording" => "Stop recording",
+ "togglePauseRecording" => "Pause or resume",
+ "restartRecording" => "Restart recording",
+ _ => "Shortcut",
+ }
+}
+
+fn screenshot_outcome(behaviour: store::PostScreenshotBehaviour) -> &'static str {
+ match behaviour {
+ store::PostScreenshotBehaviour::OpenEditor => "open it in the editor",
+ store::PostScreenshotBehaviour::Copy => "copy it to your clipboard",
+ store::PostScreenshotBehaviour::CopyAndOpenEditor => "copy it and open the editor",
+ store::PostScreenshotBehaviour::Save => "save it to your library without opening anything",
+ }
+}
+
+fn picker_outcome(mode: crate::main_window::Mode) -> &'static str {
+ match mode {
+ crate::main_window::Mode::Studio => "record it in Studio mode",
+ crate::main_window::Mode::Instant => "record it in Instant mode",
+ crate::main_window::Mode::Screenshot => "take a screenshot of it",
+ }
+}
+
+/// What pressing the shortcut does, as a phrase that completes "Press ⌘⇧4
+/// to ...". It follows the after-capture settings and the current mode, so
+/// the row always describes what will actually happen.
+fn shortcut_effect(
+ action: &str,
+ settings: &store::GeneralSettings,
+ mode: crate::main_window::Mode,
+) -> String {
+ let screenshot = screenshot_outcome(settings.post_screenshot_behaviour);
+ let studio_stop = match settings.post_studio_recording_behaviour {
+ store::PostStudioBehaviour::OpenEditor => ", then open the editor when you stop",
+ store::PostStudioBehaviour::ShowOverlay | store::PostStudioBehaviour::DoNothing => "",
+ };
+ let instant_stop = if settings.disable_auto_open_links {
+ ", then copy its share link when you stop"
+ } else {
+ ", then copy and open its share link when you stop"
+ };
+ match action {
+ "screenshotArea" => format!("select an area and {screenshot}"),
+ "screenshotWindow" => format!("capture the window under your pointer and {screenshot}"),
+ "screenshotDisplay" => format!("capture the display under your pointer and {screenshot}"),
+ "startStudioRecording" => {
+ format!("record your selected screen or window in Studio mode{studio_stop}")
+ }
+ "startInstantRecording" => {
+ format!("record your selected screen or window in Instant mode{instant_stop}")
+ }
+ "openRecordingPickerArea" => format!("select an area, then {}", picker_outcome(mode)),
+ "openRecordingPickerWindow" => format!("choose a window, then {}", picker_outcome(mode)),
+ "openRecordingPickerDisplay" => format!("choose a display, then {}", picker_outcome(mode)),
+ "openRecordingPicker" => "open Cap so you can choose what to record".into(),
+ "cycleRecordingMode" => "switch between Studio, Instant and Screenshot mode".into(),
+ "stopRecording" => "stop the current recording".into(),
+ "togglePauseRecording" => "pause the current recording, or resume it".into(),
+ "restartRecording" => "throw away the current take and start again".into(),
+ _ => String::new(),
+ }
+}
+
+/// Rows whose description quotes an "After ..." choice on this page.
+fn description_follows_outcome(action: &str) -> bool {
+ SCREENSHOT_SHORTCUTS.contains(&action)
+ || matches!(action, "startStudioRecording" | "startInstantRecording")
+}
+
+fn capitalized_sentence(phrase: &str) -> String {
+ let mut chars = phrase.chars();
+ match chars.next() {
+ Some(first) => format!("{}{}.", first.to_uppercase(), chars.as_str()),
+ None => String::new(),
+ }
+}
+
/// The gpui keystroke name for a key, as the W3C `KeyboardEvent.code` string
/// the Tauri app stores (`e.code` in hotkeys.tsx, `global_hotkey::Code` in
/// hotkeys.rs). `None` for keys neither side can bind.
@@ -977,6 +1178,31 @@ fn hotkey_code_for_key(key: &str) -> Option<String> {
Some(code.to_string())
}
+fn is_function_key(code: &str) -> bool {
+ code.strip_prefix('F')
+ .is_some_and(|rest| !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit()))
+}
+
+/// Bare letters, digits and Shift-only combos would fire while typing in any
+/// app, so a shortcut needs ⌘, ⌃ or ⌥ unless it is a function key.
+fn shortcut_needs_modifier(hotkey: &Hotkey) -> bool {
+ !(hotkey.meta || hotkey.ctrl || hotkey.alt) && !is_function_key(&hotkey.code)
+}
+
+const NEEDS_MODIFIER: &str = if cfg!(target_os = "macos") {
+ "Include ⌘, ⌃ or ⌥ so the shortcut doesn't get in the way of typing."
+} else {
+ "Include Ctrl, Alt or Win so the shortcut doesn't get in the way of typing."
+};
+
+const UNSUPPORTED_KEY: &str =
+ "That key can't be used in a shortcut. Try a letter, number or F-key.";
+
+const RECORDING_HINT: &str = "Press the keys you want to use. Esc cancels, Delete removes it.";
+
+const UNAVAILABLE: &str =
+ "Another app or the system already uses this shortcut. Click to choose a different one.";
+
/// `HotkeyText`'s key list: modifiers in ⌘⌃⌥⇧ order, then the main key.
/// [`ui::kbd_symbol`] does the per-OS glyph mapping.
fn hotkey_display_keys(hotkey: &Hotkey) -> Vec<String> {
@@ -997,305 +1223,706 @@ fn hotkey_display_keys(hotkey: &Hotkey) -> Vec<String> {
keys
}
+fn held_modifier_keys(modifiers: gpui::Modifiers) -> Vec<String> {
+ let mut keys = Vec::new();
+ if modifiers.platform {
+ keys.push("meta".to_string());
+ }
+ if modifiers.control {
+ keys.push("ctrl".to_string());
+ }
+ if modifiers.alt {
+ keys.push("alt".to_string());
+ }
+ if modifiers.shift {
+ keys.push("shift".to_string());
+ }
+ keys
+}
+
+/// A combo written into a sentence: `⌘⇧4` on macOS, `Ctrl+Shift+4` elsewhere.
+fn hotkey_inline_text(hotkey: &Hotkey) -> String {
+ let separator = if cfg!(target_os = "macos") { "" } else { "+" };
+ hotkey_display_keys(hotkey)
+ .iter()
+ .map(|key| hotkey_key_text(key))
+ .collect::<Vec<_>>()
+ .join(separator)
+}
+
+fn hotkey_key_text(key: &str) -> SharedString {
+ if let Some(digit) = key.strip_prefix("Digit") {
+ return SharedString::from(digit.to_string());
+ }
+ let named = match key {
+ "Comma" => ",",
+ "Period" => ".",
+ "Slash" => "/",
+ "Semicolon" => ";",
+ "Quote" => "'",
+ "BracketLeft" => "[",
+ "BracketRight" => "]",
+ "Backslash" => "\\",
+ "Minus" => "-",
+ "Equal" => "=",
+ "Backquote" => "`",
+ "ArrowUp" => "↑",
+ "ArrowDown" => "↓",
+ "ArrowLeft" => "←",
+ "ArrowRight" => "→",
+ "Tab" => "⇥",
+ "Delete" => "⌦",
+ _ => return ui::kbd_symbol(key),
+ };
+ SharedString::from(named)
+}
+
+fn shortcut_key_cap(theme: &Theme, key: &str) -> gpui::Div {
+ div()
+ .flex()
+ .items_center()
+ .justify_center()
+ .flex_shrink_0()
+ .h(px(20.))
+ .min_w(px(20.))
+ .px(px(5.))
+ .rounded(px(5.))
+ .bg(theme.settings_card_bg())
+ .border_1()
+ .border_color(theme.settings_border())
+ .text_size(px(11.))
+ .font_weight(gpui::FontWeight::MEDIUM)
+ .text_color(theme.settings_text())
+ .child(hotkey_key_text(key))
+}
+
impl SettingsWindow {
- /// The window keydown listener while a binding is armed. Returns whether
+ fn shortcut_binding(&self, action: &str) -> Option<Hotkey> {
+ self.pages
+ .hotkeys
+ .get(action)
+ .and_then(store::hotkey_from_value)
+ }
+
+ fn shortcuts_start_listening(
+ &mut self,
+ action: &'static str,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.pages.listening = Some(ListeningHotkey {
+ action,
+ modifiers: window.modifiers(),
+ error: None,
+ });
+ self.pages.shortcut_saved = None;
+ self.pages.shortcut_saved_reset = None;
+ crate::hotkeys::pause(cx);
+ // Keys must reach the root's on_key_down, not a focused field.
+ self.focus_root(window, cx);
+ cx.notify();
+ }
+
+ /// 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.
+ pub(crate) fn shortcuts_cancel(&mut self, cx: &mut Context<Self>) {
+ if self.pages.listening.take().is_none() {
+ return;
+ }
+ crate::hotkeys::resume(cx);
+ cx.notify();
+ }
+
+ pub(crate) fn shortcuts_modifiers_changed(
+ &mut self,
+ modifiers: gpui::Modifiers,
+ cx: &mut Context<Self>,
+ ) {
+ if let Some(listening) = self.pages.listening.as_mut() {
+ listening.modifiers = modifiers;
+ cx.notify();
+ }
+ }
+
+ /// The window keydown listener while a row is recording. Returns whether
/// the key was consumed. Modifier-only presses never arrive as
- /// `KeyDownEvent`s in gpui, so `MODIFIER_KEYS` needs no equivalent.
+ /// `KeyDownEvent`s in gpui; they come through
+ /// [`Self::shortcuts_modifiers_changed`].
pub(crate) fn shortcuts_capture_key(
&mut self,
keystroke: &gpui::Keystroke,
cx: &mut Context<Self>,
) -> bool {
- if self.page != Page::Shortcuts || self.pages.listening.is_none() {
+ if self.page != Page::Shortcuts {
return false;
}
- // Escape restores the previous binding instead of becoming one --
- // the one deliberate divergence from the DOM listener, which cannot
- // bind Escape globally anyway (it is the overlay-cancel key).
+ let Some(listening) = self.pages.listening.as_mut() else {
+ return false;
+ };
+ let action = listening.action;
+ let modifiers = keystroke.modifiers;
+ let bare = !modifiers.platform && !modifiers.control && !modifiers.alt && !modifiers.shift;
+
+ // Escape is the picker's cancel key, so it is never a binding.
if keystroke.key == "escape" {
- self.shortcuts_restore_prev(cx);
+ self.shortcuts_cancel(cx);
return true;
}
- let Some(code) = hotkey_code_for_key(&keystroke.key) else {
+ if bare && matches!(keystroke.key.as_str(), "backspace" | "delete") {
+ self.pages.listening = None;
+ self.pages.hotkeys.remove(action);
+ self.shortcuts_commit(cx);
return true;
- };
+ }
+
// A code the Tauri app cannot parse must never reach the store: its
// `HotkeysStore` deserializes the whole `hotkeys` map strictly
// (`serde_json::from_value` in `HotkeysStore::get`), so one bad entry
// would silently drop every binding over there.
- if global_hotkey::hotkey::Code::from_str(&code).is_err() {
- return true;
- }
- let Some(listening) = self.pages.listening.as_ref() else {
+ let Some(code) = hotkey_code_for_key(&keystroke.key)
+ .filter(|code| global_hotkey::hotkey::Code::from_str(code).is_ok())
+ else {
+ listening.error = Some(UNSUPPORTED_KEY);
+ cx.notify();
return true;
};
- let action = HOTKEY_ACTIONS[listening.action].0;
let hotkey = Hotkey {
code,
- meta: keystroke.modifiers.platform,
- ctrl: keystroke.modifiers.control,
- alt: keystroke.modifiers.alt,
- shift: keystroke.modifiers.shift,
+ meta: modifiers.platform,
+ ctrl: modifiers.control,
+ alt: modifiers.alt,
+ shift: modifiers.shift,
};
+ if shortcut_needs_modifier(&hotkey) {
+ listening.error = Some(NEEDS_MODIFIER);
+ cx.notify();
+ return true;
+ }
+
+ // One combo, one action: taking a combo another row uses moves it
+ // here, and the confirmation says where it came from.
+ let mut moved_from = None;
+ for other in SCREENSHOT_SHORTCUTS
+ .iter()
+ .chain(RECORDING_SHORTCUTS.iter())
+ .chain(WHILE_RECORDING_SHORTCUTS.iter())
+ {
+ if *other != action && self.shortcut_binding(other).as_ref() == Some(&hotkey) {
+ self.pages.hotkeys.remove(*other);
+ moved_from.get_or_insert(*other);
+ }
+ }
+
let value = serde_json::to_value(&hotkey).unwrap_or(Value::Null);
self.pages.hotkeys.insert(action.to_string(), value);
- // `createEffect` persists on every store change, captures included --
- // but the OS registration waits for the confirm, exactly as
- // `commands.setHotkey` only runs from the buttons over there. Pressing
- // the candidate combo again keeps re-capturing it instead of firing
- // the action.
- self.shortcuts_save();
- cx.notify();
+ self.pages.listening = None;
+ self.shortcuts_commit(cx);
+ self.pages.shortcut_saved = Some(SavedShortcut { action, moved_from });
+ self.pages.shortcut_saved_reset = Some(cx.spawn(async move |this, cx| {
+ cx.background_executor().timer(SHORTCUT_SAVED_NOTICE).await;
+ this.update(cx, |this, cx| {
+ if this
+ .pages
+ .shortcut_saved
+ .as_ref()
+ .is_some_and(|saved| saved.action == action)
+ {
+ this.pages.shortcut_saved = None;
+ cx.notify();
+ }
+ })
+ .ok();
+ }));
true
}
- /// The `createEffect` half: write the map to the shared store, touch
- /// nothing at the OS.
- fn shortcuts_save(&self) {
+ /// Persist the map and swap the OS registrations. Deferred because the
+ /// registry swap reads the store this just wrote; resuming re-registers
+ /// from the store, and so does a reload when nothing was paused.
+ fn shortcuts_commit(&mut self, cx: &mut Context<Self>) {
if !store::set_hotkeys_raw(&self.pages.hotkeys) {
tracing::warn!("saving the hotkeys store failed");
}
- }
-
- /// The `commands.setHotkey` half: persist and swap the OS registrations.
- /// Deferred because the registry swap reads the store this just wrote.
- fn shortcuts_commit(&self, cx: &mut Context<Self>) {
- self.shortcuts_save();
- cx.defer(crate::hotkeys::reload);
- }
-
- /// The window click listener: an abandoned capture puts the previous
- /// binding back. Store only -- the capture never touched the OS
- /// registration, so there is nothing to swap back (the TSX cancel path
- /// never calls `setHotkey` either).
- fn shortcuts_restore_prev(&mut self, cx: &mut Context<Self>) {
- let Some(listening) = self.pages.listening.take() else {
- return;
- };
- let action = HOTKEY_ACTIONS[listening.action].0;
- match listening.prev {
- Some(prev) => {
- self.pages.hotkeys.insert(action.to_string(), prev);
- }
- None => {
- self.pages.hotkeys.remove(action);
+ cx.defer(|cx| {
+ if !crate::hotkeys::resume(cx) {
+ crate::hotkeys::reload(cx);
}
- }
- self.shortcuts_save();
+ cx.refresh_windows();
+ });
cx.notify();
}
pub(crate) fn render_shortcuts(&self, cx: &mut Context<Self>) -> Vec<gpui::AnyElement> {
- let theme = self.theme;
- let listening_any = self.pages.listening.is_some();
+ let unavailable = crate::hotkeys::unavailable_actions(cx);
+ let mode = crate::main_window::Mode::from_store();
+ let rows_for = |actions: &[&'static str], cx: &mut Context<Self>| {
+ actions
+ .iter()
+ .map(|action| {
+ self.render_shortcut_row(action, mode, unavailable.contains(action), cx)
+ })
+ .collect::<Vec<_>>()
+ };
- let mut rows: Vec<gpui::AnyElement> = Vec::new();
- for (index, (action, label)) in HOTKEY_ACTIONS.iter().enumerate() {
- let binding = self
- .pages
- .hotkeys
- .get(*action)
- .and_then(store::hotkey_from_value);
- let listening = self
- .pages
- .listening
- .as_ref()
- .is_some_and(|listening| listening.action == index);
-
- let right: gpui::AnyElement = if listening {
- self.render_shortcut_listening(index, binding.as_ref(), cx)
- .into_any_element()
- } else {
- self.render_shortcut_idle(index, binding.as_ref(), cx)
- .into_any_element()
- };
+ let mut screenshots = rows_for(&SCREENSHOT_SHORTCUTS, cx);
+ screenshots.push(
+ self.render_outcome_panel(
+ "outcome-screenshot",
+ "After a screenshot",
+ "For every screenshot, from a shortcut or from Cap",
+ &SCREENSHOT_OUTCOMES
+ .iter()
+ .map(|(value, option)| {
+ (*option, *value == self.settings.post_screenshot_behaviour)
+ })
+ .collect::<Vec<_>>(),
+ |this, index, cx| {
+ if let Some((value, _)) = SCREENSHOT_OUTCOMES.get(index) {
+ this.settings.post_screenshot_behaviour = *value;
+ this.write_enum("postScreenshotBehaviour", *value, cx);
+ }
+ },
+ cx,
+ ),
+ );
- rows.push(
- // `flex flex-row justify-between items-center w-full h-8`.
- div()
- .flex()
- .flex_row()
- .justify_between()
- .items_center()
- .w_full()
- .h(px(32.))
- .child(div().text_size(px(13.)).child(*label))
- .child(right)
- .into_any_element(),
- );
- if index + 1 != HOTKEY_ACTIONS.len() {
- // `w-full h-px bg-gray-3`.
- rows.push(
- div()
- .w_full()
- .h(px(1.))
- .bg(theme.settings_border())
- .into_any_element(),
- );
- }
- }
+ let mut recording = rows_for(&RECORDING_SHORTCUTS, cx);
+ recording.push(
+ self.render_outcome_panel(
+ "outcome-studio",
+ "After a Studio recording",
+ "When you stop",
+ &STUDIO_OUTCOMES
+ .iter()
+ .map(|(value, option)| {
+ (
+ *option,
+ *value == self.settings.post_studio_recording_behaviour,
+ )
+ })
+ .collect::<Vec<_>>(),
+ |this, index, cx| {
+ if let Some((value, _)) = STUDIO_OUTCOMES.get(index) {
+ this.settings.post_studio_recording_behaviour = *value;
+ this.write_enum("postStudioRecordingBehaviour", *value, cx);
+ }
+ },
+ cx,
+ ),
+ );
+ recording.push(
+ self.render_outcome_panel(
+ "outcome-instant",
+ "After an Instant recording",
+ "The share link is always copied",
+ &INSTANT_OUTCOMES
+ .iter()
+ .map(|(disabled, option)| {
+ (*option, *disabled == self.settings.disable_auto_open_links)
+ })
+ .collect::<Vec<_>>(),
+ |this, index, cx| {
+ if let Some((disabled, _)) = INSTANT_OUTCOMES.get(index) {
+ this.settings.disable_auto_open_links = *disabled;
+ this.write_bool("disableAutoOpenLinks", *disabled, cx);
+ }
+ },
+ cx,
+ ),
+ );
- let card = self
- .card(false)
- .id("shortcuts-card")
- .flex()
- .flex_col()
- .gap(px(12.))
- .p(px(16.))
- // The window click listener: any press that reaches the card while
- // a capture is armed abandons it and restores the old binding.
- .when(listening_any, |this| {
- this.on_mouse_down(
- MouseButton::Left,
- cx.listener(|this, _, _window, cx| this.shortcuts_restore_prev(cx)),
- )
- })
- .children(rows);
+ let while_recording = rows_for(&WHILE_RECORDING_SHORTCUTS, cx);
+
+ let listening_any = self.pages.listening.is_some();
+ let card = |id: &'static str, rows: Vec<gpui::AnyElement>, cx: &mut Context<Self>| {
+ self.rows(rows)
+ .id(id)
+ // A press anywhere else on the card abandons a recording row.
+ .when(listening_any, |this| {
+ this.on_mouse_down(
+ MouseButton::Left,
+ cx.listener(|this, _, _window, cx| this.shortcuts_cancel(cx)),
+ )
+ })
+ .into_any_element()
+ };
vec![
self.section(
- "Shortcuts",
- Some("Configure system-wide keyboard shortcuts to control Cap."),
+ "Screenshots",
+ Some("Shortcuts work from any app. Click one to change it."),
None,
- vec![card.into_any_element()],
+ vec![card("shortcuts-screenshots", screenshots, cx)],
+ )
+ .into_any_element(),
+ self.section(
+ "Recording",
+ Some("Start a recording without opening Cap first."),
+ None,
+ vec![card("shortcuts-recording", recording, cx)],
+ )
+ .into_any_element(),
+ self.section(
+ "While recording",
+ None,
+ None,
+ vec![card("shortcuts-while-recording", while_recording, cx)],
)
.into_any_element(),
]
}
- /// The resting state: the binding as keycap chips, or the `None` pill.
- fn render_shortcut_idle(
+ /// The "After ..." choices: a tinted panel at the foot of a group with
+ /// every option visible as a card, so what happens next reads as
+ /// something to pick rather than one more setting row.
+ fn render_outcome_panel(
&self,
- index: usize,
- binding: Option<&Hotkey>,
+ id: &'static str,
+ title: &'static str,
+ hint: &'static str,
+ options: &[(OutcomeOption, bool)],
+ on_select: impl Fn(&mut Self, usize, &mut Context<Self>) + 'static,
cx: &mut Context<Self>,
- ) -> impl IntoElement {
+ ) -> gpui::AnyElement {
let theme = self.theme;
- let content: gpui::AnyElement = match binding {
- Some(hotkey) => div()
- .flex()
- .flex_row()
- .items_center()
- .gap(px(4.))
- .children(
- hotkey_display_keys(hotkey)
- .into_iter()
- .map(|key| ui::KbdChip::row(&theme, key)),
- )
- .into_any_element(),
- // `text-[11px] uppercase py-3 px-2.5 h-5 bg-gray-4 border
- // border-gray-5 rounded-lg text-gray-11`.
- None => div()
- .flex()
- .items_center()
- .h(px(20.))
- .px(px(10.))
- .rounded(px(8.))
- .bg(theme.settings_fill())
- .border_1()
- .border_color(theme.settings_border())
- .text_size(px(11.))
- .text_color(theme.settings_muted())
- .child("NONE")
- .into_any_element(),
+ let ink = theme.settings_text();
+ // The card tokens are translucent, so on this tinted panel they read
+ // as gray; the chosen option needs a solid, lighter surface.
+ let raised = if theme.is_dark() {
+ gpui::hsla(0., 0., 1., 0.1)
+ } else {
+ gpui::white()
};
+ let on_select = std::rc::Rc::new(on_select);
- div()
- .id(("hotkey", index))
- .cursor_pointer()
- .child(content)
- .on_click(cx.listener(move |this, _, window, cx| {
- let prev = this.pages.hotkeys.get(HOTKEY_ACTIONS[index].0).cloned();
- this.pages.listening = Some(ListeningHotkey {
- action: index,
- prev,
+ let cards =
+ options
+ .iter()
+ .enumerate()
+ .map(|(index, (option, selected))| {
+ let selected = *selected;
+ let on_select = on_select.clone();
+ div()
+ .id((id, index))
+ .relative()
+ .flex()
+ .flex_col()
+ .gap(px(8.))
+ .flex_1()
+ .min_w_0()
+ .p(px(10.))
+ .rounded(px(10.))
+ .border_1()
+ .when(selected, |this| this.border_color(ink).bg(raised))
+ .when(!selected, |this| {
+ this.border_color(theme.settings_border())
+ .cursor_pointer()
+ .hover(|style| style.bg(theme.settings_hover()))
+ })
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .justify_center()
+ .size(px(28.))
+ .rounded(px(7.))
+ .bg(theme.settings_fill())
+ .child(svg().path(option.icon).size(px(16.)).text_color(
+ if selected {
+ ink
+ } else {
+ theme.settings_muted()
+ },
+ )),
+ )
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(2.))
+ .child(
+ div()
+ .text_size(px(12.))
+ .font_weight(gpui::FontWeight::MEDIUM)
+ .text_color(ink)
+ .child(option.label),
+ )
+ .child(
+ div()
+ .text_size(px(11.))
+ .line_height(px(14.))
+ .text_color(theme.settings_muted())
+ .child(option.hint),
+ ),
+ )
+ .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
+ .on_click(cx.listener(move |this, _, _window, cx| {
+ this.shortcuts_cancel(cx);
+ on_select(this, index, cx);
+ cx.notify();
+ }))
});
- // Keys must reach the root's on_key_down, not a focused field.
- this.focus_root(window, cx);
- cx.notify();
- }))
+
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(10.))
+ .p(px(12.))
+ .bg(theme.settings_fill())
+ .child(
+ div()
+ .flex()
+ .flex_row()
+ .items_center()
+ .justify_between()
+ .gap(px(12.))
+ .child(
+ div()
+ .text_size(px(13.))
+ .font_weight(gpui::FontWeight::MEDIUM)
+ .child(title),
+ )
+ .child(
+ div()
+ .text_size(px(11.))
+ .text_color(theme.settings_muted())
+ .child(hint),
+ ),
+ )
+ .child(div().flex().flex_row().gap(px(8.)).children(cards))
+ .into_any_element()
}
- /// The armed state: confirm/clear buttons on the left, the live capture
- /// (or "Set hotkeys...") on the right -- `flex-row-reverse` in the TSX.
- fn render_shortcut_listening(
+ fn render_shortcut_row(
&self,
- index: usize,
- binding: Option<&Hotkey>,
+ action: &'static str,
+ mode: crate::main_window::Mode,
+ unavailable: bool,
cx: &mut Context<Self>,
- ) -> impl IntoElement {
+ ) -> gpui::AnyElement {
let theme = self.theme;
- let has_binding = binding.is_some();
+ let binding = self.shortcut_binding(action);
+ let listening = self
+ .pages
+ .listening
+ .as_ref()
+ .filter(|listening| listening.action == action);
+ let saved = self
+ .pages
+ .shortcut_saved
+ .as_ref()
+ .filter(|saved| saved.action == action);
+ let effect = shortcut_effect(action, &self.settings, mode);
+ let red: Hsla = theme.red_11.into();
+ let amber: Hsla = theme.amber_11.into();
+
+ let (detail, detail_color, detail_icon): (String, Hsla, Option<(&str, Hsla)>) =
+ if let Some(listening) = listening {
+ match listening.error {
+ Some(error) => (error.into(), red, None),
+ None => (RECORDING_HINT.into(), theme.settings_muted(), None),
+ }
+ } else if unavailable && binding.is_some() {
+ (UNAVAILABLE.into(), amber, None)
+ } else if let (Some(saved), Some(binding)) = (saved, binding.as_ref()) {
+ let mut text = format!(
+ "Saved. Press {} in any app to {effect}.",
+ hotkey_inline_text(binding)
+ );
+ if let Some(from) = saved.moved_from {
+ text.push_str(&format!(" Removed from {}.", shortcut_label(from)));
+ }
+ (
+ text,
+ theme.settings_text(),
+ Some(("icons/circle-check.svg", theme.settings_text())),
+ )
+ } else {
+ (capitalized_sentence(&effect), theme.settings_muted(), None)
+ };
+
+ let group: SharedString = format!("shortcut-row-{action}").into();
+
+ let field = self.render_shortcut_field(action, binding.as_ref(), listening, cx);
+ let clear = div()
+ .id(SharedString::from(format!("shortcut-clear-{action}")))
+ .flex()
+ .items_center()
+ .justify_center()
+ .size(px(20.))
+ .rounded(px(6.))
+ .cursor_pointer()
+ .invisible()
+ .when(binding.is_some() && listening.is_none(), |this| {
+ this.group_hover(group.clone(), |style| style.visible())
+ })
+ .hover(|style| style.bg(theme.settings_hover()))
+ .child(
+ svg()
+ .path("icons/x.svg")
+ .size(px(12.))
+ .text_color(theme.settings_muted()),
+ )
+ .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
+ .on_click(cx.listener(move |this, _, _window, cx| {
+ this.shortcuts_cancel(cx);
+ this.pages.hotkeys.remove(action);
+ if this
+ .pages
+ .shortcut_saved
+ .as_ref()
+ .is_some_and(|saved| saved.action == action)
+ {
+ this.pages.shortcut_saved = None;
+ }
+ this.shortcuts_commit(cx);
+ }));
- let mut buttons = div().flex().flex_row().items_center().gap(px(2.));
- if has_binding {
- // IconCapCircleCheck: commit and stop listening.
- buttons = buttons.child(
+ div()
+ .id(SharedString::from(format!("shortcut-{action}")))
+ .group(group)
+ .flex()
+ .flex_row()
+ .items_center()
+ .justify_between()
+ .gap(px(16.))
+ .min_h(px(56.))
+ .p(px(12.))
+ .child(
div()
- .id(("hotkey-confirm", index))
- .cursor_pointer()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w_0()
+ .gap(px(2.))
+ .child(div().text_size(px(13.)).child(shortcut_label(action)))
.child(
- svg()
- .path("icons/circle-check.svg")
- .size(px(20.))
- .text_color(theme.settings_text()),
- )
- .hover(|style| style.opacity(0.7))
- .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
- .on_click(cx.listener(move |this, _, _window, cx| {
- this.pages.listening = None;
- this.shortcuts_commit(cx);
- cx.notify();
- })),
- );
- }
- // IconCapCircleX: clear the binding entirely.
- buttons = buttons.child(
- div()
- .id(("hotkey-clear", index))
- .cursor_pointer()
- .child(
- svg()
- .path("icons/circle-x.svg")
- .size(px(20.))
- .text_color(Hsla::from(rgb(0xef4444))),
- )
- .hover(|style| style.opacity(0.7))
- .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
- .on_click(cx.listener(move |this, _, _window, cx| {
- this.pages.listening = None;
- this.pages.hotkeys.remove(HOTKEY_ACTIONS[index].0);
- this.shortcuts_commit(cx);
- cx.notify();
- })),
- );
+ div()
+ .flex()
+ .flex_row()
+ .items_start()
+ .gap(px(5.))
+ .text_size(px(12.))
+ .line_height(px(16.))
+ .text_color(detail_color)
+ // Picking an "After ..." option rewrites this text,
+ // and a one-line/two-line swap moved the panel out
+ // from under the pointer. Two lines are reserved
+ // for every description that can change that way.
+ .when(description_follows_outcome(action), |this| {
+ this.min_h(px(32.))
+ })
+ .when_some(detail_icon, |this, (path, color)| {
+ this.child(
+ svg()
+ .path(path)
+ .flex_shrink_0()
+ .mt(px(2.))
+ .size(px(12.))
+ .text_color(color),
+ )
+ })
+ .child(div().min_w_0().child(detail)),
+ ),
+ )
+ .child(
+ div()
+ .flex()
+ .flex_row()
+ .items_center()
+ .justify_end()
+ .gap(px(4.))
+ .flex_shrink_0()
+ .child(clear)
+ .child(field),
+ )
+ .into_any_element()
+ }
- let capture: gpui::AnyElement = match binding {
- Some(hotkey) => div()
- .flex()
- .flex_row()
- .items_center()
- .gap(px(4.))
+ /// The combo as key caps in a pill, "Record shortcut" when unbound, or the
+ /// live recording state with whatever modifiers are held.
+ fn render_shortcut_field(
+ &self,
+ action: &'static str,
+ binding: Option<&Hotkey>,
+ listening: Option<&ListeningHotkey>,
+ cx: &mut Context<Self>,
+ ) -> gpui::AnyElement {
+ let theme = self.theme;
+
+ let base = div()
+ .id(SharedString::from(format!("shortcut-field-{action}")))
+ .flex()
+ .flex_row()
+ .items_center()
+ .justify_center()
+ .gap(px(3.))
+ .h(px(30.))
+ .min_w(px(132.))
+ .px(px(5.))
+ .rounded(px(8.))
+ .border_1()
+ .cursor_pointer();
+
+ let field = match (listening, binding) {
+ (Some(listening), _) => {
+ let held = held_modifier_keys(listening.modifiers);
+ let mut field = base
+ .border_color(theme.settings_text())
+ .bg(theme.settings_card_bg())
+ .children(held.iter().map(|key| shortcut_key_cap(&theme, key)));
+ if held.is_empty() {
+ field = field.child(
+ div()
+ .px(px(4.))
+ .text_size(px(12.))
+ .text_color(theme.settings_muted())
+ .child("Type shortcut…"),
+ );
+ } else {
+ field = field.child(
+ div()
+ .px(px(2.))
+ .text_size(px(12.))
+ .text_color(theme.settings_muted())
+ .child("…"),
+ );
+ }
+ field.into_any_element()
+ }
+ (None, Some(hotkey)) => base
+ .border_color(theme.settings_border())
+ .bg(theme.settings_fill())
+ .hover(|style| style.bg(theme.settings_hover()))
.children(
hotkey_display_keys(hotkey)
- .into_iter()
- .map(|key| ui::KbdChip::row(&theme, key)),
+ .iter()
+ .map(|key| shortcut_key_cap(&theme, key)),
)
+ .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.shortcuts_start_listening(action, window, cx);
+ }))
.into_any_element(),
- None => div()
- .text_size(px(13.))
- .text_color(theme.settings_muted())
- .child("Set hotkeys...")
+ (None, None) => base
+ .border_color(theme.settings_border())
+ .border_dashed()
+ .hover(|style| style.bg(theme.settings_hover()))
+ .child(
+ div()
+ .px(px(4.))
+ .text_size(px(12.))
+ .text_color(theme.settings_muted())
+ .child("Record shortcut"),
+ )
+ .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.shortcuts_start_listening(action, window, cx);
+ }))
.into_any_element(),
};
-
- div()
- .flex()
- .flex_row()
- .items_center()
- .gap(px(8.))
- .child(buttons)
- .child(capture)
+ div().child(field).into_any_element()
}
}
@@ -8133,6 +8760,191 @@ mod cli_install {
mod tests {
use super::*;
+ fn hotkey(code: &str, meta: bool, ctrl: bool, alt: bool, shift: bool) -> Hotkey {
+ Hotkey {
+ code: code.into(),
+ meta,
+ ctrl,
+ alt,
+ shift,
+ }
+ }
+
+ #[test]
+ fn shortcuts_need_a_typing_safe_modifier() {
+ assert!(shortcut_needs_modifier(&hotkey(
+ "KeyA", false, false, false, false
+ )));
+ assert!(shortcut_needs_modifier(&hotkey(
+ "Digit4", false, false, false, true
+ )));
+ assert!(!shortcut_needs_modifier(&hotkey(
+ "Digit4", true, false, false, true
+ )));
+ assert!(!shortcut_needs_modifier(&hotkey(
+ "KeyS", false, true, false, false
+ )));
+ assert!(!shortcut_needs_modifier(&hotkey(
+ "KeyS", false, false, true, false
+ )));
+ assert!(!shortcut_needs_modifier(&hotkey(
+ "F5", false, false, false, false
+ )));
+ assert!(!shortcut_needs_modifier(&hotkey(
+ "F12", false, false, false, true
+ )));
+ assert!(shortcut_needs_modifier(&hotkey(
+ "Space", false, false, false, false
+ )));
+ }
+
+ #[test]
+ fn every_hotkey_action_appears_once_with_a_label_and_effect() {
+ let shown: Vec<&str> = SCREENSHOT_SHORTCUTS
+ .iter()
+ .chain(RECORDING_SHORTCUTS.iter())
+ .chain(WHILE_RECORDING_SHORTCUTS.iter())
+ .copied()
+ .collect();
+ assert_eq!(shown.len(), 13);
+ let settings = store::GeneralSettings::default();
+ for action in &shown {
+ assert_eq!(shown.iter().filter(|other| *other == action).count(), 1);
+ assert_ne!(shortcut_label(action), "Shortcut", "{action}");
+ assert!(
+ !shortcut_effect(action, &settings, crate::main_window::Mode::Studio).is_empty(),
+ "{action}"
+ );
+ }
+ }
+
+ /// The reserved two lines only hold if no outcome-dependent description
+ /// wraps to a third at the window's minimum width (about 55 characters
+ /// per line there).
+ #[test]
+ fn outcome_descriptions_fit_the_reserved_two_lines() {
+ let mut settings = store::GeneralSettings::default();
+ let mut longest = 0;
+ for screenshot in [
+ store::PostScreenshotBehaviour::OpenEditor,
+ store::PostScreenshotBehaviour::Copy,
+ store::PostScreenshotBehaviour::CopyAndOpenEditor,
+ store::PostScreenshotBehaviour::Save,
+ ] {
+ settings.post_screenshot_behaviour = screenshot;
+ for open_links_disabled in [false, true] {
+ settings.disable_auto_open_links = open_links_disabled;
+ for studio in [
+ store::PostStudioBehaviour::OpenEditor,
+ store::PostStudioBehaviour::ShowOverlay,
+ store::PostStudioBehaviour::DoNothing,
+ ] {
+ settings.post_studio_recording_behaviour = studio;
+ for action in SCREENSHOT_SHORTCUTS
+ .iter()
+ .chain(RECORDING_SHORTCUTS.iter())
+ .filter(|action| description_follows_outcome(action))
+ {
+ let text = capitalized_sentence(&shortcut_effect(
+ action,
+ &settings,
+ crate::main_window::Mode::Studio,
+ ));
+ longest = longest.max(text.chars().count());
+ }
+ }
+ }
+ }
+ assert!(
+ longest <= 104,
+ "longest outcome description is {longest} characters"
+ );
+ }
+
+ #[test]
+ fn every_after_capture_value_has_exactly_one_card() {
+ use store::SettingsEnum as _;
+ for value in store::PostScreenshotBehaviour::ALL {
+ assert_eq!(
+ SCREENSHOT_OUTCOMES
+ .iter()
+ .filter(|(v, _)| v == value)
+ .count(),
+ 1
+ );
+ }
+ for value in store::PostStudioBehaviour::ALL {
+ assert_eq!(
+ STUDIO_OUTCOMES.iter().filter(|(v, _)| v == value).count(),
+ 1
+ );
+ }
+ for disabled in [false, true] {
+ assert_eq!(
+ INSTANT_OUTCOMES
+ .iter()
+ .filter(|(v, _)| *v == disabled)
+ .count(),
+ 1
+ );
+ }
+ }
+
+ #[test]
+ fn descriptions_follow_the_after_capture_settings() {
+ let mut settings = store::GeneralSettings::default();
+ let studio = crate::main_window::Mode::Studio;
+ assert_eq!(
+ shortcut_effect("screenshotArea", &settings, studio),
+ "select an area and open it in the editor"
+ );
+ settings.post_screenshot_behaviour = store::PostScreenshotBehaviour::Copy;
+ assert_eq!(
+ shortcut_effect("screenshotArea", &settings, studio),
+ "select an area and copy it to your clipboard"
+ );
+ assert!(
+ shortcut_effect("startStudioRecording", &settings, studio)
+ .ends_with("open the editor when you stop")
+ );
+ settings.post_studio_recording_behaviour = store::PostStudioBehaviour::ShowOverlay;
+ assert!(!shortcut_effect("startStudioRecording", &settings, studio).contains("editor"));
+ settings.disable_auto_open_links = true;
+ assert!(
+ shortcut_effect("startInstantRecording", &settings, studio)
+ .ends_with("copy its share link when you stop")
+ );
+ assert_eq!(
+ shortcut_effect(
+ "openRecordingPickerWindow",
+ &settings,
+ crate::main_window::Mode::Instant
+ ),
+ "choose a window, then record it in Instant mode"
+ );
+ assert_eq!(
+ capitalized_sentence("stop the current recording"),
+ "Stop the current recording."
+ );
+ }
+
+ #[test]
+ #[cfg(target_os = "macos")]
+ fn combos_read_naturally_inside_a_sentence() {
+ assert_eq!(
+ hotkey_inline_text(&hotkey("Digit4", true, false, false, true)),
+ "⌘⇧4"
+ );
+ assert_eq!(
+ hotkey_inline_text(&hotkey("KeyR", false, true, true, false)),
+ "⌃⌥R"
+ );
+ assert_eq!(
+ hotkey_inline_text(&hotkey("Slash", true, false, false, false)),
+ "⌘/"
+ );
+ }
+
/// gpui keystroke names against the `KeyboardEvent.code` strings hotkeys
/// written by the Tauri app carry.
#[test]
diff --git a/apps/desktop-gpui/src/settings_window.rs b/apps/desktop-gpui/src/settings_window.rs
index d61a57349..4765e3135 100644
--- a/apps/desktop-gpui/src/settings_window.rs
+++ b/apps/desktop-gpui/src/settings_window.rs
@@ -807,6 +807,7 @@ impl SettingsWindow {
self.instant_quality_notice = None;
self.studio_quality_save_failed = false;
self.has_cap_pro = store::auth_snapshot().is_upgraded();
+ self.shortcuts_cancel(cx);
self.page = page;
self.menu = None;
// The store may have changed under us while the window was in the
@@ -1273,7 +1274,12 @@ impl SettingsWindow {
self.write(key, Value::from(value), cx);
}
- fn write_enum<T: SettingsEnum>(&mut self, key: &'static str, value: T, cx: &mut Context<Self>) {
+ pub(crate) fn write_enum<T: SettingsEnum>(
+ &mut self,
+ key: &'static str,
+ value: T,
+ cx: &mut Context<Self>,
+ ) {
self.write(key, Value::String(value.as_json().to_string()), cx);
}
@@ -1563,6 +1569,11 @@ impl Render for SettingsWindow {
cx.defer(crate::app_windows::close_settings);
}
}))
+ .on_modifiers_changed(cx.listener(
+ |this, event: &gpui::ModifiersChangedEvent, _window, cx| {
+ this.shortcuts_modifiers_changed(event.modifiers, cx);
+ },
+ ))
.size_full()
.flex()
.flex_row()