command palette: first pass
This commit introduces a rough first pass at a command palette modal. It is an adaptation of the emoji character selector and needs refinement. Importantly, the default pane selector key assignment now calls into this new command palette instead. refs: https://github.com/wez/wezterm/issues/1485
This commit is contained in:
7 files changed
+590
-7
No files matched your search
@@ -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")
|
||||
}
|
||||
|
||||
@@ -533,6 +533,7 @@ pub enum KeyAssignment {
|
||||
|
||||
ResetTerminal,
|
||||
OpenUri(String),
|
||||
ActivateCommandPalette,
|
||||
}
|
||||
impl_lua_conversion_dynamic!(KeyAssignment);
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
+36
-6
@@ -459,6 +459,7 @@ struct FontConfigInner {
|
||||
title_font: RefCell<Option<Rc<LoadedFont>>>,
|
||||
pane_select_font: RefCell<Option<Rc<LoadedFont>>>,
|
||||
char_select_font: RefCell<Option<Rc<LoadedFont>>>,
|
||||
command_palette_font: RefCell<Option<Rc<LoadedFont>>>,
|
||||
fallback_channel: RefCell<Option<Sender<FallbackResolveInfo>>>,
|
||||
}
|
||||
|
||||
@@ -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<Self>,
|
||||
pref_size: Option<f64>,
|
||||
make_bold: bool,
|
||||
) -> anyhow::Result<Rc<LoadedFont>> {
|
||||
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<Self>) -> anyhow::Result<Rc<LoadedFont>> {
|
||||
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<Self>) -> anyhow::Result<Rc<LoadedFont>> {
|
||||
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<Rc<LoadedFont>> {
|
||||
self.inner.command_palette_font(&self.inner)
|
||||
}
|
||||
|
||||
pub fn pane_select_font(&self) -> anyhow::Result<Rc<LoadedFont>> {
|
||||
self.inner.pane_select_font(&self.inner)
|
||||
}
|
||||
|
||||
@@ -412,7 +412,7 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Comm
|
||||
PaneSelect(_) => 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<Comm
|
||||
args: &[ArgType::ActivePane],
|
||||
menubar: &["Shell"],
|
||||
},
|
||||
ActivateCommandPalette => 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<KeyAssignment> {
|
||||
CharSelect(CharSelectArguments::default()),
|
||||
ActivateCopyMode,
|
||||
ClearKeyTableStack,
|
||||
ActivateCommandPalette,
|
||||
// ----------------- View
|
||||
DecreaseFontSize,
|
||||
IncreaseFontSize,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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<usize>,
|
||||
}
|
||||
|
||||
pub struct CommandPalette {
|
||||
element: RefCell<Option<Vec<ComputedElement>>>,
|
||||
selection: RefCell<String>,
|
||||
matches: RefCell<Option<MatchResults>>,
|
||||
selected_row: RefCell<usize>,
|
||||
top_row: RefCell<usize>,
|
||||
max_rows_on_screen: RefCell<usize>,
|
||||
commands: Vec<ExpandedCommand>,
|
||||
}
|
||||
|
||||
#[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<Vec<Recent>> {
|
||||
let file_name = recent_file_name();
|
||||
let f = std::fs::File::open(&file_name)?;
|
||||
let mut recents: Vec<Recent> = 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<ExpandedCommand> {
|
||||
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<usize> {
|
||||
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<MatchResult> = 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<Vec<ComputedElement>> {
|
||||
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<Ref<[ComputedElement]>> {
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user