Added a couple of commands to the palette functions.
Moorly CI / windows-build (push) Successful in 3m7s
Moorly CI / linux-build (push) Successful in 3m35s

This commit is contained in:
Squid committed 2026-11-07 22:31:09 +01:00
1 parent e4f6afada9
commit dadf0d5b4d
1 file changed
+485 -30
+485 -30
View File
@@ -127,19 +127,49 @@ fn pointer_event(
} }
} }
/// Escape is captured by focused text inputs, so it is listened for globally /// Key presses are captured by focused text inputs, so palette keys are
/// instead of through `keyboard::listen`. /// listened for globally instead of through `keyboard::listen`.
fn escape_event( fn key_press_event(
event: iced::Event,
_status: iced::event::Status,
window: window::Id,
) -> Option<(keyboard::Key, keyboard::Modifiers, window::Id)> {
match event {
iced::Event::Keyboard(keyboard::Event::KeyPressed {
key,
modifiers,
repeat: false,
..
}) => Some((key, modifiers, window)),
_ => None,
}
}
fn palette_event(
event: iced::Event, event: iced::Event,
_status: iced::event::Status, _status: iced::event::Status,
window: window::Id, window: window::Id,
) -> Option<Message> { ) -> Option<Message> {
match event { let iced::Event::Keyboard(keyboard::Event::KeyPressed {
iced::Event::Keyboard(keyboard::Event::KeyPressed { key, repeat: false, ..
key: keyboard::Key::Named(keyboard::key::Named::Escape), }) = event
repeat: false, else {
.. return None;
}) => Some(Message::CloseCommandPalette(window)), };
match key {
keyboard::Key::Named(keyboard::key::Named::Escape) => {
Some(Message::CloseCommandPalette(window))
}
keyboard::Key::Named(keyboard::key::Named::ArrowUp) => {
Some(Message::CommandPaletteUp(window))
}
keyboard::Key::Named(keyboard::key::Named::ArrowDown) => {
Some(Message::CommandPaletteDown(window))
}
keyboard::Key::Named(keyboard::key::Named::Enter) => {
Some(Message::RunSelectedCommand(window))
}
_ => None, _ => None,
} }
} }
@@ -150,12 +180,11 @@ fn subscription(state: &Moorly) -> Subscription<Message> {
.with(( .with((
state.saved_shortcuts.settings.clone(), state.saved_shortcuts.settings.clone(),
state.saved_shortcuts.quit.clone(), state.saved_shortcuts.quit.clone(),
state.saved_shortcuts.command_palette.clone(),
state.shortcut_capture.is_some(), state.shortcut_capture.is_some(),
active_window, active_window,
)) ))
.filter_map( .filter_map(
|((settings_shortcut, quit_shortcut, palette_shortcut, capturing, window), event)| { |((settings_shortcut, quit_shortcut, capturing, window), event)| {
let keyboard::Event::KeyPressed { let keyboard::Event::KeyPressed {
key, key,
modifiers, modifiers,
@@ -177,13 +206,6 @@ fn subscription(state: &Moorly) -> Subscription<Message> {
return Some(Message::Quit); 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 let Some(shortcut) = &settings_shortcut {
if shortcut.matches(&key, modifiers) { if shortcut.matches(&key, modifiers) {
return window.map(|window| Message::SelectTab(window, Tab::Settings)); return window.map(|window| Message::SelectTab(window, Tab::Settings));
@@ -227,12 +249,26 @@ fn subscription(state: &Moorly) -> Subscription<Message> {
.values() .values()
.any(|animation| animation.is_animating(now)); .any(|animation| animation.is_animating(now));
let palette_shortcut = iced::event::listen_with(key_press_event)
.with((
state.saved_shortcuts.command_palette.clone(),
state.shortcut_capture.is_some(),
))
.filter_map(|((shortcut, capturing), (key, modifiers, window))| {
(!capturing
&& shortcut
.as_ref()
.is_some_and(|shortcut| shortcut.matches(&key, modifiers)))
.then_some(Message::ToggleCommandPalette(window))
});
let mut subscriptions = vec![ let mut subscriptions = vec![
keyboard, keyboard,
palette_shortcut,
iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes), iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes),
window::events().map(|(window, event)| Message::WindowEvent(window, event)), window::events().map(|(window, event)| Message::WindowEvent(window, event)),
iced::event::listen_with(pointer_event), iced::event::listen_with(pointer_event),
iced::event::listen_with(escape_event), iced::event::listen_with(palette_event),
]; ];
if state.drag.is_some() { if state.drag.is_some() {
@@ -958,6 +994,99 @@ struct TransferDialog {
destination: usize, destination: usize,
} }
/// Actions offered by the command palette.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Command {
Settings,
Close,
Move,
MoveToWindow(window::Id),
FocusWindow(window::Id),
FocusTab(window::Id, Tab),
Exit,
}
impl Command {
const ALL: [Self; 4] = [Self::Settings, Self::Close, Self::Move, Self::Exit];
fn label(&self, state: &Moorly) -> String {
match self {
Self::Settings => "Settings".to_owned(),
Self::Close => "Close".to_owned(),
Self::Move => "Move".to_owned(),
Self::MoveToWindow(id) | Self::FocusWindow(id) => window_title(state, *id),
Self::FocusTab(_, tab) => tab.title(),
Self::Exit => "Exit".to_owned(),
}
}
fn description(&self, state: &Moorly) -> String {
match self {
Self::Settings => "Opens the settings tab".to_owned(),
Self::Close => "Closes the active tab".to_owned(),
Self::Move => "Moves the active tab to a new window".to_owned(),
Self::MoveToWindow(id) => {
format!("Moves the active tab to {}", window_title(state, *id))
}
Self::FocusWindow(_) => "Focuses this window".to_owned(),
Self::FocusTab(id, _) => {
format!("Focuses this tab in {}", window_title(state, *id))
}
Self::Exit => "Quits the program".to_owned(),
}
}
fn matching(state: &Moorly, source: window::Id, query: &str) -> Vec<Self> {
let mut commands: Vec<Self> = Self::ALL
.into_iter()
.filter(|command| fuzzy_match(&command.label(state), query))
.collect();
for id in &state.window_order {
let Some(window_state) = state.windows.get(id) else {
continue;
};
if *id != source && fuzzy_match(&window_title(state, *id), query) {
commands.push(Self::FocusWindow(*id));
}
commands.extend(
window_state
.tabs
.iter()
.filter(|tab| fuzzy_match(&tab.title(), query))
.map(|tab| Self::FocusTab(*id, *tab)),
);
}
// While Move matches, offer every other window as a destination.
if commands.contains(&Self::Move) {
commands.extend(
drop_targets(state, source)
.into_iter()
.map(|(id, _)| Self::MoveToWindow(id)),
);
}
commands
}
}
/// Case-insensitive subsequence match, so `stg` finds `Settings`.
fn fuzzy_match(haystack: &str, needle: &str) -> bool {
let needle = needle.trim();
if needle.is_empty() {
return true;
}
let mut haystack = haystack.chars().flat_map(char::to_lowercase);
needle
.chars()
.flat_map(char::to_lowercase)
.all(|needle| haystack.any(|haystack| haystack == needle))
}
/// Per-window UI state: tabs, menus and tab-strip scrolling. /// Per-window UI state: tabs, menus and tab-strip scrolling.
struct WindowState { struct WindowState {
tabs: Vec<Tab>, tabs: Vec<Tab>,
@@ -966,6 +1095,7 @@ struct WindowState {
tabs_submenu_open: bool, tabs_submenu_open: bool,
command_palette_open: bool, command_palette_open: bool,
command_palette_query: String, command_palette_query: String,
command_palette_selected: usize,
command_palette_input: Id, command_palette_input: Id,
tab_offset: f32, tab_offset: f32,
scroll_id: Id, scroll_id: Id,
@@ -987,6 +1117,7 @@ impl WindowState {
tabs_submenu_open: false, tabs_submenu_open: false,
command_palette_open: false, command_palette_open: false,
command_palette_query: String::new(), command_palette_query: String::new(),
command_palette_selected: 0,
command_palette_input: Id::unique(), command_palette_input: Id::unique(),
tab_offset: 0.0, tab_offset: 0.0,
scroll_id: Id::unique(), scroll_id: Id::unique(),
@@ -1004,6 +1135,7 @@ impl WindowState {
tabs_submenu_open: false, tabs_submenu_open: false,
command_palette_open: false, command_palette_open: false,
command_palette_query: String::new(), command_palette_query: String::new(),
command_palette_selected: 0,
command_palette_input: Id::unique(), command_palette_input: Id::unique(),
tab_offset: 0.0, tab_offset: 0.0,
scroll_id: Id::unique(), scroll_id: Id::unique(),
@@ -2899,6 +3031,10 @@ enum Message {
ToggleCommandPalette(window::Id), ToggleCommandPalette(window::Id),
CloseCommandPalette(window::Id), CloseCommandPalette(window::Id),
CommandPaletteChanged(window::Id, String), CommandPaletteChanged(window::Id, String),
CommandPaletteUp(window::Id),
CommandPaletteDown(window::Id),
RunSelectedCommand(window::Id),
RunCommand(window::Id, Command),
SelectTheme(ThemeOption), SelectTheme(ThemeOption),
OpenThemeNameDialog, OpenThemeNameDialog,
ThemeNameChanged(String), ThemeNameChanged(String),
@@ -3124,24 +3260,104 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
return Task::none(); 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 { if window_state.command_palette_open {
close_command_palette(state, window);
} else {
window_state.command_palette_open = true;
window_state.command_palette_query.clear();
window_state.command_palette_selected = 0;
return operation::focus(window_state.command_palette_input.clone()); return operation::focus(window_state.command_palette_input.clone());
} }
} }
Message::CloseCommandPalette(window) => { Message::CloseCommandPalette(window) => close_command_palette(state, 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) => { Message::CommandPaletteChanged(window, query) => {
if let Some(window_state) = state.windows.get_mut(&window) if let Some(window_state) = state.windows.get_mut(&window)
&& window_state.command_palette_open && window_state.command_palette_open
{ {
window_state.command_palette_query = query; window_state.command_palette_query = query;
window_state.command_palette_selected = 0;
}
}
Message::CommandPaletteUp(window) => {
if let Some(window_state) = state.windows.get_mut(&window)
&& window_state.command_palette_open
{
window_state.command_palette_selected =
window_state.command_palette_selected.saturating_sub(1);
}
}
Message::CommandPaletteDown(window) => {
let query = state
.windows
.get(&window)
.filter(|window_state| window_state.command_palette_open)
.map(|window_state| window_state.command_palette_query.clone());
if let Some(query) = query {
let last = Command::matching(state, window, &query)
.len()
.saturating_sub(1);
if let Some(window_state) = state.windows.get_mut(&window) {
window_state.command_palette_selected =
(window_state.command_palette_selected + 1).min(last);
}
}
}
Message::RunSelectedCommand(window) => {
let command = state
.windows
.get(&window)
.filter(|window_state| window_state.command_palette_open)
.and_then(|window_state| {
Command::matching(state, window, &window_state.command_palette_query)
.get(window_state.command_palette_selected)
.copied()
});
if let Some(command) = command {
return update(state, Message::RunCommand(window, command));
}
}
Message::RunCommand(window, command) => {
let tab = state
.windows
.get(&window)
.and_then(|window_state| window_state.active_tab);
close_command_palette(state, window);
match command {
Command::Settings => {
return update(state, Message::SelectTab(window, Tab::Settings));
}
Command::Close => {
return update(state, Message::CloseActiveTab(window));
}
Command::Move => {
if let Some(tab) = tab {
return detach_tab(state, window, tab, None);
}
}
Command::MoveToWindow(destination) => {
if let Some(tab) = tab {
move_tab_to_window(state, window, destination, tab);
return close_window_if_empty(state, window);
}
}
Command::FocusWindow(id) => {
state.focused_window = Some(id);
return window::gain_focus(id);
}
Command::FocusTab(id, tab) => {
state.focused_window = Some(id);
return Task::batch([
update(state, Message::SelectTab(id, tab)),
window::gain_focus(id),
]);
}
Command::Exit => {
return update(state, Message::Quit);
}
} }
} }
Message::SelectTheme(option) => { Message::SelectTheme(option) => {
@@ -3867,6 +4083,14 @@ fn update(state: &mut Moorly, message: Message) -> Task<Message> {
Task::none() Task::none()
} }
fn close_command_palette(state: &mut Moorly, window: window::Id) {
if let Some(window_state) = state.windows.get_mut(&window) {
window_state.command_palette_open = false;
window_state.command_palette_query.clear();
window_state.command_palette_selected = 0;
}
}
/// Commits the captured shortcut if it is valid and unused. /// Commits the captured shortcut if it is valid and unused.
fn apply_shortcut(state: &mut Moorly) { fn apply_shortcut(state: &mut Moorly) {
let Some(capture) = state.shortcut_capture.as_ref() else { let Some(capture) = state.shortcut_capture.as_ref() else {
@@ -6820,7 +7044,55 @@ fn main_view(state: &Moorly, window: window::Id) -> Element<'_, Message> {
root.into() root.into()
} }
/// Top-of-window command palette field. It is empty until commands exist. /// One command row: name over description, with the Enter hint on the
/// selected row.
fn command_palette_item(
state: &Moorly,
window: window::Id,
command: Command,
selected: bool,
) -> Element<'static, Message> {
let details = column![
text(command.label(state)).size(16),
text(command.description(state)).size(12),
]
.spacing(2);
let mut content = row![details.width(Length::Fill)]
.align_y(Alignment::Center)
.height(Length::Fill);
if selected {
content = content.push(
container(text("Enter").size(11))
.height(Length::Fill)
.align_y(Alignment::Center)
.padding([0, 8])
.style(|theme: &iced::Theme| {
let palette = theme.extended_palette();
container::Style {
border: Border {
color: palette.background.strong.color,
width: 1.0,
radius: 4.0.into(),
},
..container::Style::default()
}
}),
);
}
button(content)
.on_press(Message::RunCommand(window, command))
.width(Length::Fill)
.height(52)
.padding([4, 10])
.style(move |theme, status| theme::selectable_row(theme, status, selected))
.into()
}
/// Top-of-window command palette field and matching command list.
fn command_palette_layer(state: &Moorly, window: window::Id) -> Option<Element<'_, Message>> { fn command_palette_layer(state: &Moorly, window: window::Id) -> Option<Element<'_, Message>> {
let window_state = state.windows.get(&window)?; let window_state = state.windows.get(&window)?;
if !window_state.command_palette_open { if !window_state.command_palette_open {
@@ -6834,7 +7106,29 @@ fn command_palette_layer(state: &Moorly, window: window::Id) -> Option<Element<'
.style(theme::filter_field) .style(theme::filter_field)
.width(Length::Fill); .width(Length::Fill);
let panel = container(field).width(560).padding(6).style(theme::menu); let matches = Command::matching(state, window, &window_state.command_palette_query);
let selected = window_state
.command_palette_selected
.min(matches.len().saturating_sub(1));
let mut list = column![].spacing(2);
if matches.is_empty() {
list = list.push(container(text("No matching commands").size(12)).padding(8));
} else {
for (index, command) in matches.into_iter().enumerate() {
list = list.push(command_palette_item(
state,
window,
command,
index == selected,
));
}
}
let panel = container(column![field, list].spacing(6))
.width(560)
.padding(6)
.style(theme::menu);
Some( Some(
container(panel) container(panel)
@@ -7621,6 +7915,167 @@ mod tests {
assert!(!window_state(&state).command_palette_open); assert!(!window_state(&state).command_palette_open);
} }
#[test]
fn command_palette_fuzzy_matches_and_runs_settings() {
assert!(super::fuzzy_match("Settings", "stg"));
assert!(super::fuzzy_match("Settings", ""));
assert!(!super::fuzzy_match("Settings", "xyz"));
let mut state = state();
let window = test_window();
let _ = update(&mut state, Message::ToggleCommandPalette(window));
let _ = update(
&mut state,
Message::CommandPaletteChanged(window, "sett".to_owned()),
);
assert_eq!(
super::Command::matching(&state, window, "sett"),
vec![super::Command::Settings]
);
assert_eq!(
super::Command::matching(&state, window, "exit"),
vec![super::Command::Exit]
);
let _ = update(&mut state, Message::RunSelectedCommand(window));
assert_eq!(window_state(&state).active_tab, Some(Tab::Settings));
assert!(!window_state(&state).command_palette_open);
}
#[test]
fn command_palette_close_closes_the_active_tab() {
let mut state = state();
let window = test_window();
window_state_mut(&mut state).tabs = vec![Tab::Settings, Tab::Blank(1)];
window_state_mut(&mut state).active_tab = Some(Tab::Settings);
let _ = update(&mut state, Message::ToggleCommandPalette(window));
let _ = update(
&mut state,
Message::CommandPaletteChanged(window, "close".to_owned()),
);
let _ = update(&mut state, Message::RunSelectedCommand(window));
assert_eq!(window_state(&state).tabs, vec![Tab::Blank(1)]);
assert_eq!(window_state(&state).active_tab, Some(Tab::Blank(1)));
assert!(!window_state(&state).command_palette_open);
}
#[test]
fn move_command_detaches_the_active_tab_to_a_new_window() {
let mut state = state();
let window = test_window();
window_state_mut(&mut state).tabs = vec![Tab::Settings, Tab::Blank(1)];
window_state_mut(&mut state).active_tab = Some(Tab::Settings);
let _ = update(&mut state, Message::ToggleCommandPalette(window));
let _ = update(
&mut state,
Message::CommandPaletteChanged(window, "move".to_owned()),
);
let _ = update(&mut state, Message::RunSelectedCommand(window));
assert_eq!(state.windows.len(), 2);
let detached = *state.window_order.last().unwrap();
assert_eq!(state.windows[&detached].active_tab, Some(Tab::Settings));
assert_eq!(window_state(&state).active_tab, Some(Tab::Blank(1)));
}
#[test]
fn move_command_lists_windows_and_moves_to_the_selected_one() {
let mut state = state();
let window = test_window();
let destination = iced::window::Id::unique();
state.windows.insert(
destination,
super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None),
);
state.window_order.push(destination);
window_state_mut(&mut state).tabs = vec![Tab::Settings, Tab::Blank(1)];
window_state_mut(&mut state).active_tab = Some(Tab::Settings);
assert_eq!(
super::Command::matching(&state, window, "move"),
vec![
super::Command::Move,
super::Command::MoveToWindow(destination)
]
);
let _ = update(&mut state, Message::ToggleCommandPalette(window));
let _ = update(
&mut state,
Message::CommandPaletteChanged(window, "move".to_owned()),
);
let _ = update(&mut state, Message::CommandPaletteDown(window));
let _ = update(&mut state, Message::RunSelectedCommand(window));
assert_eq!(window_state(&state).tabs, vec![Tab::Blank(1)]);
assert_eq!(state.windows[&destination].active_tab, Some(Tab::Settings));
}
#[test]
fn command_palette_focuses_a_matching_window() {
let mut state = state();
let window = test_window();
let destination = iced::window::Id::unique();
state.windows.insert(
destination,
super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None),
);
state.window_order.push(destination);
assert_eq!(
super::Command::matching(&state, window, "temp 9"),
vec![
super::Command::FocusWindow(destination),
super::Command::FocusTab(destination, Tab::Blank(9))
]
);
let _ = update(&mut state, Message::ToggleCommandPalette(window));
let _ = update(
&mut state,
Message::CommandPaletteChanged(window, "temp 9".to_owned()),
);
let _ = update(&mut state, Message::RunSelectedCommand(window));
assert_eq!(state.focused_window, Some(destination));
}
#[test]
fn command_palette_focuses_a_matching_tab_in_its_window() {
let mut state = state();
let window = test_window();
let destination = iced::window::Id::unique();
let mut destination_state =
super::WindowState::with_tab(Tab::Blank(9), iced::Size::new(800.0, 600.0), None);
destination_state.tabs.push(Tab::Settings);
state.windows.insert(destination, destination_state);
state.window_order.push(destination);
assert_eq!(
super::Command::matching(&state, window, "settings"),
vec![
super::Command::Settings,
super::Command::FocusTab(destination, Tab::Settings)
]
);
let _ = update(&mut state, Message::ToggleCommandPalette(window));
let _ = update(
&mut state,
Message::CommandPaletteChanged(window, "settings".to_owned()),
);
let _ = update(&mut state, Message::CommandPaletteDown(window));
let _ = update(&mut state, Message::RunSelectedCommand(window));
assert_eq!(state.focused_window, Some(destination));
assert_eq!(state.windows[&destination].active_tab, Some(Tab::Settings));
}
fn press(key: keyboard::Key, modifiers: keyboard::Modifiers) -> Message { fn press(key: keyboard::Key, modifiers: keyboard::Modifiers) -> Message {
Message::CaptureKey { key, modifiers } Message::CaptureKey { key, modifiers }
} }