diff --git a/config/src/config.rs b/config/src/config.rs index 7fdc8ea8a..e77e35fd5 100644 --- a/config/src/config.rs +++ b/config/src/config.rs @@ -117,6 +117,15 @@ pub struct Config { #[dynamic(default = "default_char_select_font_size")] pub char_select_font_size: f64, + #[dynamic(default = "default_command_palette_font_size")] + pub command_palette_font_size: f64, + + #[dynamic(default = "default_command_palette_fg_color")] + pub command_palette_fg_color: RgbaColor, + + #[dynamic(default = "default_command_palette_bg_color")] + pub command_palette_bg_color: RgbaColor, + #[dynamic(default = "default_pane_select_font_size")] pub pane_select_font_size: f64, @@ -1332,6 +1341,18 @@ fn default_char_select_font_size() -> f64 { 18.0 } +fn default_command_palette_font_size() -> f64 { + 12.0 +} + +fn default_command_palette_fg_color() -> RgbaColor { + SrgbaTuple(0.75, 0.75, 0.75, 1.0).into() +} + +fn default_command_palette_bg_color() -> RgbaColor { + (0x33, 0x33, 0x33).into() +} + fn default_swallow_mouse_click_on_window_focus() -> bool { cfg!(target_os = "macos") } diff --git a/config/src/keyassignment.rs b/config/src/keyassignment.rs index 65f1332e4..e914e494d 100644 --- a/config/src/keyassignment.rs +++ b/config/src/keyassignment.rs @@ -533,6 +533,7 @@ pub enum KeyAssignment { ResetTerminal, OpenUri(String), + ActivateCommandPalette, } impl_lua_conversion_dynamic!(KeyAssignment); diff --git a/docs/changelog.md b/docs/changelog.md index 4b29a3ea7..5b2e5bc52 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -27,6 +27,8 @@ As features stabilize some brief notes about them will accumulate here. [#2819](https://github.com/wez/wezterm/issues/2819) #### Changed +* `CTRL-SHIFT-P` now activates the new command palette, instead of `PaneSelect` + [#1485](https://github.com/wez/wezterm/issues/1485) * Window title reporting escape sequences are now disabled by default. [See here for more details](https://marc.info/?l=bugtraq&m=104612710031920&w=2) * Withdraw DEC private SGR escapes that affect superscript and diff --git a/wezterm-font/src/lib.rs b/wezterm-font/src/lib.rs index 9bdb4120f..0d4feaed6 100644 --- a/wezterm-font/src/lib.rs +++ b/wezterm-font/src/lib.rs @@ -459,6 +459,7 @@ struct FontConfigInner { title_font: RefCell>>, pane_select_font: RefCell>>, char_select_font: RefCell>>, + command_palette_font: RefCell>>, fallback_channel: RefCell>>, } @@ -479,6 +480,7 @@ impl FontConfigInner { title_font: RefCell::new(None), pane_select_font: RefCell::new(None), char_select_font: RefCell::new(None), + command_palette_font: RefCell::new(None), font_scale: RefCell::new(1.0), dpi: RefCell::new(dpi), config: RefCell::new(config.clone()), @@ -496,6 +498,7 @@ impl FontConfigInner { self.title_font.borrow_mut().take(); self.pane_select_font.borrow_mut().take(); self.char_select_font.borrow_mut().take(); + self.command_palette_font.borrow_mut().take(); self.metrics.borrow_mut().take(); *self.font_dirs.borrow_mut() = Arc::new(FontDatabase::with_font_dirs(config)?); Ok(()) @@ -540,7 +543,7 @@ impl FontConfigInner { } } - fn compute_title_font(&self, config: &ConfigHandle) -> (TextStyle, f64) { + fn compute_title_font(&self, config: &ConfigHandle, make_bold: bool) -> (TextStyle, f64) { fn bold(family: &str) -> FontAttributes { FontAttributes { family: family.to_string(), @@ -549,7 +552,12 @@ impl FontConfigInner { } } - let mut fonts = vec![bold("Roboto")]; + let mut fonts = vec![if make_bold { + bold("Roboto") + } else { + FontAttributes::new("Roboto") + }]; + // Fallback to their main font selection, so that we can pick up // any fallback fonts they might have configured in the main // config and so that they don't have to replicate that list for @@ -575,9 +583,10 @@ impl FontConfigInner { &self, myself: &Rc, pref_size: Option, + make_bold: bool, ) -> anyhow::Result> { let config = self.config.borrow(); - let (sys_font, sys_size) = self.compute_title_font(&config); + let (sys_font, sys_size) = self.compute_title_font(&config, make_bold); let font_size = pref_size.unwrap_or(sys_size); @@ -628,13 +637,30 @@ impl FontConfigInner { return Ok(Rc::clone(entry)); } - let loaded = self.make_title_font_impl(myself, config.window_frame.font_size)?; + let loaded = self.make_title_font_impl(myself, config.window_frame.font_size, true)?; title_font.replace(Rc::clone(&loaded)); Ok(loaded) } + fn command_palette_font(&self, myself: &Rc) -> anyhow::Result> { + let config = self.config.borrow(); + + let mut command_palette_font = self.command_palette_font.borrow_mut(); + + if let Some(entry) = command_palette_font.as_ref() { + return Ok(Rc::clone(entry)); + } + + let loaded = + self.make_title_font_impl(myself, Some(config.command_palette_font_size), false)?; + + command_palette_font.replace(Rc::clone(&loaded)); + + Ok(loaded) + } + fn char_select_font(&self, myself: &Rc) -> anyhow::Result> { let config = self.config.borrow(); @@ -644,7 +670,7 @@ impl FontConfigInner { return Ok(Rc::clone(entry)); } - let loaded = self.make_title_font_impl(myself, Some(config.char_select_font_size))?; + let loaded = self.make_title_font_impl(myself, Some(config.char_select_font_size), true)?; char_select_font.replace(Rc::clone(&loaded)); @@ -660,7 +686,7 @@ impl FontConfigInner { return Ok(Rc::clone(entry)); } - let loaded = self.make_title_font_impl(myself, Some(config.pane_select_font_size))?; + let loaded = self.make_title_font_impl(myself, Some(config.pane_select_font_size), true)?; pane_select_font.replace(Rc::clone(&loaded)); @@ -1005,6 +1031,10 @@ impl FontConfiguration { self.inner.title_font(&self.inner) } + pub fn command_palette_font(&self) -> anyhow::Result> { + self.inner.command_palette_font(&self.inner) + } + pub fn pane_select_font(&self) -> anyhow::Result> { self.inner.pane_select_font(&self.inner) } diff --git a/wezterm-gui/src/commands.rs b/wezterm-gui/src/commands.rs index ae19c6478..5e1c3b25d 100644 --- a/wezterm-gui/src/commands.rs +++ b/wezterm-gui/src/commands.rs @@ -412,7 +412,7 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option CommandDef { brief: "Enter Pane selection mode".into(), doc: "Activates the pane selection UI".into(), - keys: vec![(Modifiers::CTRL.union(Modifiers::SHIFT), "p".into())], + keys: vec![], // FIXME: find a new assignment args: &[ArgType::ActivePane], menubar: &["Window"], }, @@ -1329,6 +1329,13 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option CommandDef { + brief: "Activate Command Palette".into(), + doc: "Shows the command palette modal".into(), + keys: vec![(Modifiers::CTRL.union(Modifiers::SHIFT), "p".into())], + args: &[ArgType::ActivePane], + menubar: &["Edit"], + }, }) } @@ -1371,6 +1378,7 @@ fn compute_default_actions() -> Vec { CharSelect(CharSelectArguments::default()), ActivateCopyMode, ClearKeyTableStack, + ActivateCommandPalette, // ----------------- View DecreaseFontSize, IncreaseFontSize, diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs index 41233673d..472faa4cf 100644 --- a/wezterm-gui/src/termwindow/mod.rs +++ b/wezterm-gui/src/termwindow/mod.rs @@ -71,6 +71,7 @@ pub mod clipboard; mod keyevent; pub mod modal; mod mouseevent; +pub mod palette; pub mod paneselect; mod prevcursor; mod render; @@ -2765,6 +2766,10 @@ impl TermWindow { } }); } + ActivateCommandPalette => { + let modal = crate::termwindow::palette::CommandPalette::new(self); + self.modal.borrow_mut().replace(Rc::new(modal)); + } }; Ok(PerformAssignmentResult::Handled) } diff --git a/wezterm-gui/src/termwindow/palette.rs b/wezterm-gui/src/termwindow/palette.rs new file mode 100644 index 000000000..143102525 --- /dev/null +++ b/wezterm-gui/src/termwindow/palette.rs @@ -0,0 +1,516 @@ +use crate::commands::{CommandDef, ExpandedCommand}; +use crate::termwindow::box_model::*; +use crate::termwindow::modal::Modal; +use crate::termwindow::render::{ + BOTTOM_LEFT_ROUNDED_CORNER, BOTTOM_RIGHT_ROUNDED_CORNER, TOP_LEFT_ROUNDED_CORNER, + TOP_RIGHT_ROUNDED_CORNER, +}; +use crate::termwindow::{DimensionContext, TermWindow}; +use crate::utilsprites::RenderMetrics; +use config::keyassignment::KeyAssignment; +use config::Dimension; +use frecency::Frecency; +use fuzzy_matcher::skim::SkimMatcherV2; +use fuzzy_matcher::FuzzyMatcher; +use serde::{Deserialize, Serialize}; +use std::cell::{Ref, RefCell}; +use std::cmp::Ordering; +use std::collections::HashMap; +use std::path::PathBuf; +use wezterm_term::{KeyCode, KeyModifiers, MouseEvent}; +use window::color::LinearRgba; + +struct MatchResults { + selection: String, + matches: Vec, +} + +pub struct CommandPalette { + element: RefCell>>, + selection: RefCell, + matches: RefCell>, + selected_row: RefCell, + top_row: RefCell, + max_rows_on_screen: RefCell, + commands: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +struct Recent { + brief: String, + frecency: Frecency, +} + +fn recent_file_name() -> PathBuf { + config::RUNTIME_DIR.join("recent-commands.json") +} + +fn load_recents() -> anyhow::Result> { + let file_name = recent_file_name(); + let f = std::fs::File::open(&file_name)?; + let mut recents: Vec = serde_json::from_reader(f)?; + recents.sort_by(|a, b| b.frecency.score().partial_cmp(&a.frecency.score()).unwrap()); + Ok(recents) +} + +fn save_recent(command: &ExpandedCommand) -> anyhow::Result<()> { + let mut recents = load_recents().unwrap_or_else(|_| vec![]); + if let Some(recent_idx) = recents.iter().position(|r| r.brief == command.brief) { + let recent = recents.get_mut(recent_idx).unwrap(); + recent.frecency.register_access(); + } else { + let mut frecency = Frecency::new(); + frecency.register_access(); + recents.push(Recent { + brief: command.brief.to_string(), + frecency, + }); + } + + let json = serde_json::to_string(&recents)?; + let file_name = recent_file_name(); + std::fs::write(&file_name, json)?; + Ok(()) +} + +fn build_commands() -> Vec { + let mut commands = CommandDef::expanded_commands(&config::configuration()); + + let mut scores: HashMap<&str, f64> = HashMap::new(); + let recents = load_recents(); + if let Ok(recents) = &recents { + for r in recents { + scores.insert(&r.brief, r.frecency.score()); + } + } + + commands.sort_by(|a, b| { + match (scores.get(&*a.brief), scores.get(&*b.brief)) { + // Want descending frecency score, so swap a<->b + // for the compare here + (Some(a), Some(b)) => match b.partial_cmp(&a) { + Some(Ordering::Equal) | None => {} + Some(ordering) => return ordering, + }, + (Some(_), None) => return Ordering::Less, + (None, Some(_)) => return Ordering::Greater, + (None, None) => {} + } + + match a.menubar.cmp(&b.menubar) { + Ordering::Equal => a.brief.cmp(&b.brief), + ordering => ordering, + } + }); + + commands +} + +#[derive(Debug)] +struct MatchResult { + row_idx: usize, + score: i64, +} + +impl MatchResult { + fn new(row_idx: usize, score: i64, selection: &str, commands: &[ExpandedCommand]) -> Self { + Self { + row_idx, + score: if commands[row_idx].brief == selection { + // Pump up the score for an exact match, otherwise + // the order may be undesirable if there are a lot + // of candidates with the same score + i64::max_value() + } else { + score + }, + } + } +} + +fn compute_matches(selection: &str, commands: &[ExpandedCommand]) -> Vec { + if selection.is_empty() { + commands.iter().enumerate().map(|(idx, _)| idx).collect() + } else { + let matcher = SkimMatcherV2::default(); + + let start = std::time::Instant::now(); + let mut scores: Vec = commands + .iter() + .enumerate() + .filter_map(|(row_idx, entry)| { + let group = entry.menubar.join(" "); + let text = format!("{group}: {}", entry.brief); + matcher + .fuzzy_match(&text, selection) + .map(|score| MatchResult::new(row_idx, score, selection, commands)) + }) + .collect(); + scores.sort_by(|a, b| a.score.cmp(&b.score).reverse()); + log::trace!("matching took {:?}", start.elapsed()); + + scores.iter().map(|result| result.row_idx).collect() + } +} + +impl CommandPalette { + pub fn new(_term_window: &mut TermWindow) -> Self { + let commands = build_commands(); + + Self { + element: RefCell::new(None), + selection: RefCell::new(String::new()), + commands, + matches: RefCell::new(None), + selected_row: RefCell::new(0), + top_row: RefCell::new(0), + max_rows_on_screen: RefCell::new(0), + } + } + + fn compute( + term_window: &mut TermWindow, + selection: &str, + commands: &[ExpandedCommand], + matches: &MatchResults, + max_rows_on_screen: usize, + selected_row: usize, + top_row: usize, + ) -> anyhow::Result> { + let font = term_window + .fonts + .command_palette_font() + .expect("to resolve command palette font"); + let metrics = RenderMetrics::with_font_metrics(&font.metrics()); + + let top_bar_height = if term_window.show_tab_bar && !term_window.config.tab_bar_at_bottom { + term_window.tab_bar_pixel_height().unwrap() + } else { + 0. + }; + let (padding_left, padding_top) = term_window.padding_left_top(); + let border = term_window.get_os_border(); + let top_pixel_y = top_bar_height + padding_top + border.top.get() as f32; + + let mut elements = + vec![ + Element::new(&font, ElementContent::Text(format!("> {selection}_"))) + .colors(ElementColors { + border: BorderColor::default(), + bg: LinearRgba::TRANSPARENT.into(), + text: term_window + .config + .command_palette_fg_color + .to_linear() + .into(), + }) + .display(DisplayType::Block), + ]; + + for (display_idx, command) in matches + .matches + .iter() + .map(|&idx| &commands[idx]) + .enumerate() + .skip(top_row) + .take(max_rows_on_screen) + { + let group = command.menubar.join(" | "); + + let (bg, text) = if display_idx == selected_row { + ( + term_window + .config + .command_palette_fg_color + .to_linear() + .into(), + term_window + .config + .command_palette_bg_color + .to_linear() + .into(), + ) + } else { + ( + LinearRgba::TRANSPARENT.into(), + term_window + .config + .command_palette_fg_color + .to_linear() + .into(), + ) + }; + + // DRY if the brief and doc are the same + let label = if command.brief.to_ascii_lowercase() == command.doc.to_ascii_lowercase() { + format!("{group}: {}", command.brief) + } else { + format!("{group}: {}. {}", command.brief, command.doc) + }; + + elements.push( + Element::new(&font, ElementContent::Text(label)) + .colors(ElementColors { + border: BorderColor::default(), + bg, + text, + }) + .padding(BoxDimension { + left: Dimension::Cells(0.25), + right: Dimension::Cells(0.25), + top: Dimension::Cells(0.), + bottom: Dimension::Cells(0.), + }) + .display(DisplayType::Block), + ); + } + + let element = Element::new(&font, ElementContent::Children(elements)) + .colors(ElementColors { + border: BorderColor::new( + term_window + .config + .command_palette_bg_color + .to_linear() + .into(), + ), + bg: term_window + .config + .command_palette_bg_color + .to_linear() + .into(), + text: term_window + .config + .command_palette_fg_color + .to_linear() + .into(), + }) + .margin(BoxDimension { + left: Dimension::Cells(0.25), + right: Dimension::Cells(0.25), + top: Dimension::Cells(0.25), + bottom: Dimension::Cells(0.25), + }) + .padding(BoxDimension { + left: Dimension::Cells(0.25), + right: Dimension::Cells(0.25), + top: Dimension::Cells(0.25), + bottom: Dimension::Cells(0.25), + }) + .border(BoxDimension::new(Dimension::Pixels(1.))) + .border_corners(Some(Corners { + top_left: SizedPoly { + width: Dimension::Cells(0.25), + height: Dimension::Cells(0.25), + poly: TOP_LEFT_ROUNDED_CORNER, + }, + top_right: SizedPoly { + width: Dimension::Cells(0.25), + height: Dimension::Cells(0.25), + poly: TOP_RIGHT_ROUNDED_CORNER, + }, + bottom_left: SizedPoly { + width: Dimension::Cells(0.25), + height: Dimension::Cells(0.25), + poly: BOTTOM_LEFT_ROUNDED_CORNER, + }, + bottom_right: SizedPoly { + width: Dimension::Cells(0.25), + height: Dimension::Cells(0.25), + poly: BOTTOM_RIGHT_ROUNDED_CORNER, + }, + })); + + let dimensions = term_window.dimensions; + let size = term_window.terminal_size; + + let computed = term_window.compute_element( + &LayoutContext { + height: DimensionContext { + dpi: dimensions.dpi as f32, + pixel_max: dimensions.pixel_height as f32, + pixel_cell: metrics.cell_size.height as f32, + }, + width: DimensionContext { + dpi: dimensions.dpi as f32, + pixel_max: dimensions.pixel_width as f32, + pixel_cell: metrics.cell_size.width as f32, + }, + bounds: euclid::rect( + padding_left, + top_pixel_y, + size.cols as f32 * term_window.render_metrics.cell_size.width as f32, + size.rows as f32 * term_window.render_metrics.cell_size.height as f32, + ), + metrics: &metrics, + gl_state: term_window.render_state.as_ref().unwrap(), + zindex: 100, + }, + &element, + )?; + + Ok(vec![computed]) + } + + fn updated_input(&self) { + *self.selected_row.borrow_mut() = 0; + *self.top_row.borrow_mut() = 0; + } + + fn move_up(&self) { + let mut row = self.selected_row.borrow_mut(); + *row = row.saturating_sub(1); + + let mut top_row = self.top_row.borrow_mut(); + if *row < *top_row { + *top_row = *row; + } + } + + fn move_down(&self) { + let max_rows_on_screen = *self.max_rows_on_screen.borrow(); + let limit = self + .matches + .borrow() + .as_ref() + .map(|m| m.matches.len()) + .unwrap_or_else(|| self.commands.len()) + .saturating_sub(1); + let mut row = self.selected_row.borrow_mut(); + *row = row.saturating_add(1).min(limit); + let mut top_row = self.top_row.borrow_mut(); + if *row + *top_row > max_rows_on_screen - 1 { + *top_row = row.saturating_sub(max_rows_on_screen - 1); + } + } +} + +impl Modal for CommandPalette { + fn perform_assignment( + &self, + _assignment: &KeyAssignment, + _term_window: &mut TermWindow, + ) -> bool { + false + } + + fn mouse_event(&self, _event: MouseEvent, _term_window: &mut TermWindow) -> anyhow::Result<()> { + Ok(()) + } + + fn key_down( + &self, + key: KeyCode, + mods: KeyModifiers, + term_window: &mut TermWindow, + ) -> anyhow::Result<()> { + match (key, mods) { + (KeyCode::Escape, KeyModifiers::NONE) | (KeyCode::Char('g'), KeyModifiers::CTRL) => { + term_window.cancel_modal(); + } + (KeyCode::UpArrow, KeyModifiers::NONE) => { + self.move_up(); + } + (KeyCode::DownArrow, KeyModifiers::NONE) => { + self.move_down(); + } + (KeyCode::Char(c), KeyModifiers::NONE) | (KeyCode::Char(c), KeyModifiers::SHIFT) => { + // Type to add to the selection + let mut selection = self.selection.borrow_mut(); + selection.push(c); + self.updated_input(); + } + (KeyCode::Backspace, KeyModifiers::NONE) => { + // Backspace to edit the selection + let mut selection = self.selection.borrow_mut(); + selection.pop(); + self.updated_input(); + } + (KeyCode::Char('u'), KeyModifiers::CTRL) => { + // CTRL-u to clear the selection + let mut selection = self.selection.borrow_mut(); + selection.clear(); + self.updated_input(); + } + (KeyCode::Enter, KeyModifiers::NONE) => { + // Enter the selected character to the current pane + let selected_idx = *self.selected_row.borrow(); + let alias_idx = match self.matches.borrow().as_ref() { + None => return Ok(()), + Some(results) => match results.matches.get(selected_idx) { + Some(i) => *i, + None => return Ok(()), + }, + }; + let item = &self.commands[alias_idx]; + if let Err(err) = save_recent(item) { + log::error!("Error while saving recents: {err:#}"); + } + term_window.cancel_modal(); + + if let Some(pane) = term_window.get_active_pane_or_overlay() { + if let Err(err) = term_window.perform_key_assignment(&pane, &item.action) { + log::error!("Error while performing {item:?}: {err:#}"); + } + } + return Ok(()); + } + _ => return Ok(()), + } + term_window.invalidate_modal(); + Ok(()) + } + + fn computed_element( + &self, + term_window: &mut TermWindow, + ) -> anyhow::Result> { + let selection = self.selection.borrow(); + let selection = selection.as_str(); + + let mut results = self.matches.borrow_mut(); + + let font = term_window + .fonts + .command_palette_font() + .expect("to resolve char selection font"); + let metrics = RenderMetrics::with_font_metrics(&font.metrics()); + + let max_rows_on_screen = ((term_window.dimensions.pixel_height * 8 / 10) + / metrics.cell_size.height as usize) + - 2; + *self.max_rows_on_screen.borrow_mut() = max_rows_on_screen; + + let rebuild_matches = results + .as_ref() + .map(|m| m.selection != selection) + .unwrap_or(true); + if rebuild_matches { + results.replace(MatchResults { + selection: selection.to_string(), + matches: compute_matches(selection, &self.commands), + }); + }; + let matches = results.as_ref().unwrap(); + + if self.element.borrow().is_none() { + let element = Self::compute( + term_window, + selection, + &self.commands, + matches, + max_rows_on_screen, + *self.selected_row.borrow(), + *self.top_row.borrow(), + )?; + self.element.borrow_mut().replace(element); + } + Ok(Ref::map(self.element.borrow(), |v| { + v.as_ref().unwrap().as_slice() + })) + } + + fn reconfigure(&self, _term_window: &mut TermWindow) { + self.element.borrow_mut().take(); + } +}