diff --git a/src/main.rs b/src/main.rs index f6689ef..5730afd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -127,17 +127,35 @@ fn pointer_event( } } +/// Escape is captured by focused text inputs, so it is listened for globally +/// instead of through `keyboard::listen`. +fn escape_event( + event: iced::Event, + _status: iced::event::Status, + window: window::Id, +) -> Option { + match event { + iced::Event::Keyboard(keyboard::Event::KeyPressed { + key: keyboard::Key::Named(keyboard::key::Named::Escape), + repeat: false, + .. + }) => Some(Message::CloseCommandPalette(window)), + _ => None, + } +} + fn subscription(state: &Moorly) -> Subscription { let active_window = state.focused_window.or(state.main_window); let keyboard = keyboard::listen() .with(( state.saved_shortcuts.settings.clone(), state.saved_shortcuts.quit.clone(), + state.saved_shortcuts.command_palette.clone(), state.shortcut_capture.is_some(), active_window, )) .filter_map( - |((settings_shortcut, quit_shortcut, capturing, window), event)| { + |((settings_shortcut, quit_shortcut, palette_shortcut, capturing, window), event)| { let keyboard::Event::KeyPressed { key, modifiers, @@ -159,6 +177,13 @@ fn subscription(state: &Moorly) -> Subscription { return Some(Message::Quit); } + if palette_shortcut + .as_ref() + .is_some_and(|shortcut| shortcut.matches(&key, modifiers)) + { + return window.map(Message::ToggleCommandPalette); + } + if let Some(shortcut) = &settings_shortcut { if shortcut.matches(&key, modifiers) { return window.map(|window| Message::SelectTab(window, Tab::Settings)); @@ -207,6 +232,7 @@ fn subscription(state: &Moorly) -> Subscription { iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes), window::events().map(|(window, event)| Message::WindowEvent(window, event)), iced::event::listen_with(pointer_event), + iced::event::listen_with(escape_event), ]; if state.drag.is_some() { @@ -252,16 +278,20 @@ impl Shortcut { .collect(); let (key, modifiers) = parts.split_last()?; - // Only single-character keys are supported for now. - if key.chars().count() != 1 { + // Only single-character keys and Space are supported for now. + let key = if key.eq_ignore_ascii_case("space") { + "space".to_owned() + } else if key.chars().count() == 1 { + key.to_ascii_lowercase() + } else { return None; - } + }; let mut shortcut = Self { control: false, shift: false, alt: false, - key: key.to_ascii_lowercase(), + key, }; for modifier in modifiers { @@ -277,23 +307,15 @@ impl Shortcut { } fn matches(&self, key: &keyboard::Key, modifiers: keyboard::Modifiers) -> bool { - let keyboard::Key::Character(key) = key else { - return false; - }; - self.control == modifiers.control() && self.shift == modifiers.shift() && self.alt == modifiers.alt() - && key.as_str().eq_ignore_ascii_case(&self.key) + && key_name(key).is_some_and(|name| name == self.key) } /// Builds a shortcut from a captured key press. Plain keys are rejected so /// a shortcut cannot hijack ordinary typing. fn from_key(key: &keyboard::Key, modifiers: keyboard::Modifiers) -> Option { - let keyboard::Key::Character(key) = key else { - return None; - }; - if !(modifiers.control() || modifiers.alt()) { return None; } @@ -302,11 +324,15 @@ impl Shortcut { control: modifiers.control(), shift: modifiers.shift(), alt: modifiers.alt(), - key: key.as_str().to_ascii_lowercase(), + key: key_name(key)?, }) } fn key_label(&self) -> String { + if self.key == "space" { + return "Space".to_owned(); + } + let is_letter = self.key.chars().count() == 1 && self.key.chars().next().is_some_and(char::is_alphabetic); @@ -318,6 +344,15 @@ impl Shortcut { } } +/// Normalized name of a key that shortcuts can bind to. +fn key_name(key: &keyboard::Key) -> Option { + match key { + keyboard::Key::Character(key) => Some(key.as_str().to_ascii_lowercase()), + keyboard::Key::Named(keyboard::key::Named::Space) => Some("space".to_owned()), + _ => None, + } +} + impl std::fmt::Display for Shortcut { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut parts = Vec::new(); @@ -340,6 +375,7 @@ impl std::fmt::Display for Shortcut { enum ShortcutAction { Settings, Quit, + CommandPalette, } impl ShortcutAction { @@ -347,6 +383,7 @@ impl ShortcutAction { match self { Self::Settings => "Settings", Self::Quit => "Quit", + Self::CommandPalette => "Command palette", } } } @@ -355,6 +392,7 @@ impl ShortcutAction { struct Shortcuts { settings: Option, quit: Option, + command_palette: Option, } impl Default for Shortcuts { @@ -362,6 +400,7 @@ impl Default for Shortcuts { Self { settings: Shortcut::parse("Ctrl+,"), quit: Shortcut::parse("Ctrl+Shift+Q"), + command_palette: Shortcut::parse("Ctrl+Shift+Space"), } } } @@ -371,6 +410,7 @@ impl Shortcuts { match action { ShortcutAction::Settings => self.settings.as_ref(), ShortcutAction::Quit => self.quit.as_ref(), + ShortcutAction::CommandPalette => self.command_palette.as_ref(), } } @@ -378,6 +418,7 @@ impl Shortcuts { match action { ShortcutAction::Settings => self.settings = shortcut, ShortcutAction::Quit => self.quit = shortcut, + ShortcutAction::CommandPalette => self.command_palette = shortcut, } } @@ -387,6 +428,7 @@ impl Shortcuts { let configurable = [ (ShortcutAction::Settings, &self.settings), (ShortcutAction::Quit, &self.quit), + (ShortcutAction::CommandPalette, &self.command_palette), ]; if let Some((action, _)) = configurable .iter() @@ -922,6 +964,9 @@ struct WindowState { active_tab: Option, menu_open: bool, tabs_submenu_open: bool, + command_palette_open: bool, + command_palette_query: String, + command_palette_input: Id, tab_offset: f32, scroll_id: Id, size: Size, @@ -940,6 +985,9 @@ impl WindowState { active_tab: show_start_tab.then_some(Tab::Start), menu_open: false, tabs_submenu_open: false, + command_palette_open: false, + command_palette_query: String::new(), + command_palette_input: Id::unique(), tab_offset: 0.0, scroll_id: Id::unique(), size, @@ -954,6 +1002,9 @@ impl WindowState { active_tab: Some(tab), menu_open: false, tabs_submenu_open: false, + command_palette_open: false, + command_palette_query: String::new(), + command_palette_input: Id::unique(), tab_offset: 0.0, scroll_id: Id::unique(), size, @@ -1414,6 +1465,8 @@ struct ShortcutConfig { settings: String, #[serde(default = "default_quit_shortcut")] quit: String, + #[serde(default = "default_command_palette_shortcut")] + command_palette: String, } impl Default for ShortcutConfig { @@ -1421,6 +1474,7 @@ impl Default for ShortcutConfig { Self { settings: default_settings_shortcut(), quit: default_quit_shortcut(), + command_palette: default_command_palette_shortcut(), } } } @@ -1447,6 +1501,13 @@ fn default_quit_shortcut() -> String { .unwrap_or_default() } +fn default_command_palette_shortcut() -> String { + Shortcuts::default() + .command_palette + .map(|shortcut| shortcut.to_string()) + .unwrap_or_default() +} + fn color_to_hex(color: Color) -> String { let r = (color.r * 255.0).round() as u8; let g = (color.g * 255.0).round() as u8; @@ -2731,6 +2792,12 @@ fn config_file(state: &Moorly) -> ConfigFile { .as_ref() .map(ToString::to_string) .unwrap_or_default(), + command_palette: state + .saved_shortcuts + .command_palette + .as_ref() + .map(ToString::to_string) + .unwrap_or_default(), }, } } @@ -2749,6 +2816,7 @@ impl Default for Moorly { let shortcuts = Shortcuts { settings: Shortcut::parse(&config.shortcuts.settings), quit: Shortcut::parse(&config.shortcuts.quit), + command_palette: Shortcut::parse(&config.shortcuts.command_palette), }; let mut notifications = notifications::NotificationManager::default(); @@ -2828,6 +2896,9 @@ enum Message { AddTab(window::Id), CloseActiveTab(window::Id), CloseOtherTabs(window::Id), + ToggleCommandPalette(window::Id), + CloseCommandPalette(window::Id), + CommandPaletteChanged(window::Id, String), SelectTheme(ThemeOption), OpenThemeNameDialog, ThemeNameChanged(String), @@ -3048,6 +3119,31 @@ fn update(state: &mut Moorly, message: Message) -> Task { return close_window_if_empty(state, window); } + Message::ToggleCommandPalette(window) => { + let Some(window_state) = state.windows.get_mut(&window) else { + return Task::none(); + }; + + window_state.command_palette_open = !window_state.command_palette_open; + window_state.command_palette_query.clear(); + + if window_state.command_palette_open { + return operation::focus(window_state.command_palette_input.clone()); + } + } + Message::CloseCommandPalette(window) => { + if let Some(window_state) = state.windows.get_mut(&window) { + window_state.command_palette_open = false; + window_state.command_palette_query.clear(); + } + } + Message::CommandPaletteChanged(window, query) => { + if let Some(window_state) = state.windows.get_mut(&window) + && window_state.command_palette_open + { + window_state.command_palette_query = query; + } + } Message::SelectTheme(option) => { if let ThemeOption::Theme { choice, .. } = option { apply_theme_choice(state, choice); @@ -4974,6 +5070,10 @@ fn shortcuts_panel(state: &Moorly) -> Element<'_, Message> { ShortcutAction::Quit, state.shortcuts.get(ShortcutAction::Quit) ), + shortcut_row( + ShortcutAction::CommandPalette, + state.shortcuts.get(ShortcutAction::CommandPalette), + ), ] .spacing(8); @@ -6720,28 +6820,63 @@ fn main_view(state: &Moorly, window: window::Id) -> Element<'_, Message> { root.into() } +/// Top-of-window command palette field. It is empty until commands exist. +fn command_palette_layer(state: &Moorly, window: window::Id) -> Option> { + let window_state = state.windows.get(&window)?; + if !window_state.command_palette_open { + return None; + } + + let field = text_input("Type a command...", &window_state.command_palette_query) + .id(window_state.command_palette_input.clone()) + .on_input(move |query| Message::CommandPaletteChanged(window, query)) + .padding([10, 12]) + .style(theme::filter_field) + .width(Length::Fill); + + let panel = container(field).width(560).padding(6).style(theme::menu); + + Some( + container(panel) + .width(Length::Fill) + .height(Length::Fill) + .align_x(Alignment::Center) + .align_y(Alignment::Start) + .padding(Padding::ZERO.top(8.0)) + .into(), + ) +} + /// The application content with the notification stack rendered above it. fn view(state: &Moorly, window: window::Id) -> Element<'_, Message> { let content = main_view(state, window); + let palette = command_palette_layer(state, window); - if state.notifications.is_empty() { + if state.notifications.is_empty() && palette.is_none() { return content; } - let toasts = state - .notifications - .view( - Instant::now(), - state - .custom_toasts - .then(|| notifications::ToastColors::from_array(state.toast_colors)), - ) - .map(Message::Notification); + let mut root = stack![content]; - stack![content, toasts] - .width(Length::Fill) - .height(Length::Fill) - .into() + if !state.notifications.is_empty() { + let toasts = state + .notifications + .view( + Instant::now(), + state + .custom_toasts + .then(|| notifications::ToastColors::from_array(state.toast_colors)), + ) + .map(Message::Notification); + + root = root.push(toasts); + } + + if let Some(palette) = palette { + root = root.push(palette); + } + + root.width(Length::Fill).height(Length::Fill).into() } #[cfg(test)] @@ -7450,10 +7585,42 @@ mod tests { super::Shortcut::parse("Ctrl+,").unwrap().to_string(), "Ctrl+," ); + assert_eq!( + super::Shortcut::parse("Ctrl+Shift+Space") + .unwrap() + .to_string(), + "Ctrl+Shift+Space" + ); assert_eq!(super::Shortcut::parse("Ctrl+"), None); assert_eq!(super::Shortcut::parse("Hyper+K"), None); } + #[test] + fn space_shortcuts_match_the_space_key() { + let shortcut = super::Shortcut::parse("Ctrl+Shift+Space").unwrap(); + + assert!(shortcut.matches( + &keyboard::Key::Named(keyboard::key::Named::Space), + keyboard::Modifiers::CTRL | keyboard::Modifiers::SHIFT, + )); + } + + #[test] + fn command_palette_toggles_and_closes() { + let mut state = state(); + let window = test_window(); + + let _ = update(&mut state, Message::ToggleCommandPalette(window)); + assert!(window_state(&state).command_palette_open); + + let _ = update(&mut state, Message::ToggleCommandPalette(window)); + assert!(!window_state(&state).command_palette_open); + + let _ = update(&mut state, Message::ToggleCommandPalette(window)); + let _ = update(&mut state, Message::CloseCommandPalette(window)); + assert!(!window_state(&state).command_palette_open); + } + fn press(key: keyboard::Key, modifiers: keyboard::Modifiers) -> Message { Message::CaptureKey { key, modifiers } }