Add CharSelect modal for emoji/nerdfont/unicode input

CTRL-SHIFT-U is a new default key assignment for this new modal.
It opens up a fuzzy searchable browser that defaults to showing
emoji/emoticons.  The category can by cycled through the suggested
emoji categories using CTRL-r.  Unlike the system emoji palette,
wezterm includes a category for nerdfont symbols, and another
that is a list of all unicode codepoint names, so you should be
able to browse for pretty much any codepoint you can think of.

The modal also allows fuzzy searching based on:

* The official unicode name
* The github shortcode
* codepoint value in hex

so if you know the codepoint value but not the name, you can
still find a way to input what you're looking for.

Pressing Enter will copy the selected item to the clipboard
send it to the active pane, and cancel the modal. You can therefore
repeat the insert by simply pasting.

I plan to add frecency to this in a later commit: that way the
frequently/recently used selections will show in a category of
their own and make it easier to re-input them.

refs: https://github.com/wez/wezterm/issues/2163
This commit is contained in:
Wez Furlong committed 2022-08-31 18:15:28 -07:00
1 parent ba88bda9eb
commit ed731a0d8d
12 files changed
+135471 -12

No files matched your search

Generated
+7
View File
@@ -1172,6 +1172,12 @@ dependencies = [
"winreg",
]
[[package]]
name = "emojis"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdc0036e5881a30eec779c55ac7b4bf54eedc3c72ddc8d02c2a580c43b1c9ba"
[[package]]
name = "encoding_rs"
version = "0.8.31"
@@ -5422,6 +5428,7 @@ dependencies = [
"dirs-next",
"downcast-rs",
"embed-resource",
"emojis",
"env-bootstrap",
"env_logger",
"euclid",
+7
View File
@@ -97,6 +97,9 @@ pub struct Config {
#[dynamic(default)]
pub window_frame: WindowFrameConfig,
#[dynamic(default = "default_char_select_font_size")]
pub char_select_font_size: f64,
#[dynamic(default = "default_pane_select_font_size")]
pub pane_select_font_size: f64,
@@ -1226,6 +1229,10 @@ fn default_pane_select_font_size() -> f64 {
36.0
}
fn default_char_select_font_size() -> f64 {
18.0
}
fn default_swallow_mouse_click_on_window_focus() -> bool {
cfg!(target_os = "macos")
}
+46
View File
@@ -318,6 +318,51 @@ pub struct PaneSelectArguments {
pub mode: PaneSelectMode,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromDynamic, ToDynamic)]
pub enum CharSelectGroup {
SmileysAndEmotion,
PeopleAndBody,
AnimalsAndNature,
FoodAndDrink,
TravelAndPlaces,
Activities,
Objects,
Symbols,
Flags,
NerdFonts,
UnicodeNames,
}
impl CharSelectGroup {
pub fn next(self) -> Self {
match self {
Self::SmileysAndEmotion => Self::PeopleAndBody,
Self::PeopleAndBody => Self::AnimalsAndNature,
Self::AnimalsAndNature => Self::FoodAndDrink,
Self::FoodAndDrink => Self::TravelAndPlaces,
Self::TravelAndPlaces => Self::Activities,
Self::Activities => Self::Objects,
Self::Objects => Self::Symbols,
Self::Symbols => Self::Flags,
Self::Flags => Self::NerdFonts,
Self::NerdFonts => Self::UnicodeNames,
Self::UnicodeNames => Self::SmileysAndEmotion,
}
}
}
impl Default for CharSelectGroup {
fn default() -> Self {
Self::SmileysAndEmotion
}
}
#[derive(Default, Debug, Clone, PartialEq, Eq, FromDynamic, ToDynamic)]
pub struct CharSelectArguments {
#[dynamic(default)]
pub group: CharSelectGroup,
}
#[derive(Default, Debug, Clone, PartialEq, Eq, FromDynamic, ToDynamic)]
pub struct QuickSelectArguments {
/// Overrides the main quick_select_alphabet config
@@ -434,6 +479,7 @@ pub enum KeyAssignment {
RotatePanes(RotationDirection),
SplitPane(SplitPane),
PaneSelect(PaneSelectArguments),
CharSelect(CharSelectArguments),
}
impl_lua_conversion_dynamic!(KeyAssignment);
+2
View File
@@ -18,6 +18,8 @@ As features stabilize some brief notes about them will accumulate here.
* [CopyMode](copymode.md) now supports selecting and move by semantic zones. [#2346](https://github.com/wez/wezterm/issues/2346)
* [max_fps](config/lua/config/max_fps.md) option to limit maximum frame rate [#2419](https://github.com/wez/wezterm/discussions/2419)
* [`user-var-changed` event](config/lua/window-events/user-var-changed.md) allows triggering lua code in response to user vars being changed
* `CTRL-SHIFT-U` activates a new Emoij/Unicodes/NerdFont character picker modal overlay. Fuzzy search by name or hex unicode codepoint value, or browse with keys. `CTRL-r` to cycle the browser between categories. `Enter` to select an item, copy it to the clipboard and send it to the active pane as input. `Esc` to cancel.
* `CTRL-SHIFT-P` is now a default assignment for [PaneSelect](config/lua/keyassignment/PaneSelect.md)
#### Changed
+23
View File
@@ -460,6 +460,7 @@ struct FontConfigInner {
built_in: RefCell<Arc<FontDatabase>>,
title_font: RefCell<Option<Rc<LoadedFont>>>,
pane_select_font: RefCell<Option<Rc<LoadedFont>>>,
char_select_font: RefCell<Option<Rc<LoadedFont>>>,
fallback_channel: RefCell<Option<Sender<FallbackResolveInfo>>>,
}
@@ -479,6 +480,7 @@ impl FontConfigInner {
metrics: RefCell::new(None),
title_font: RefCell::new(None),
pane_select_font: RefCell::new(None),
char_select_font: RefCell::new(None),
font_scale: RefCell::new(1.0),
dpi: RefCell::new(dpi),
config: RefCell::new(config.clone()),
@@ -495,6 +497,7 @@ impl FontConfigInner {
fonts.clear();
self.title_font.borrow_mut().take();
self.pane_select_font.borrow_mut().take();
self.char_select_font.borrow_mut().take();
self.metrics.borrow_mut().take();
*self.font_dirs.borrow_mut() = Arc::new(FontDatabase::with_font_dirs(config)?);
Ok(())
@@ -634,6 +637,22 @@ impl FontConfigInner {
Ok(loaded)
}
fn char_select_font(&self, myself: &Rc<Self>) -> anyhow::Result<Rc<LoadedFont>> {
let config = self.config.borrow();
let mut char_select_font = self.char_select_font.borrow_mut();
if let Some(entry) = char_select_font.as_ref() {
return Ok(Rc::clone(entry));
}
let loaded = self.make_title_font_impl(myself, Some(config.char_select_font_size))?;
char_select_font.replace(Rc::clone(&loaded));
Ok(loaded)
}
fn pane_select_font(&self, myself: &Rc<Self>) -> anyhow::Result<Rc<LoadedFont>> {
let config = self.config.borrow();
@@ -992,6 +1011,10 @@ impl FontConfiguration {
self.inner.pane_select_font(&self.inner)
}
pub fn char_select_font(&self) -> anyhow::Result<Rc<LoadedFont>> {
self.inner.char_select_font(&self.inner)
}
/// Given a text style, load (with caching) the font that best
/// matches according to the fontconfig pattern.
pub fn resolve_font(&self, style: &TextStyle) -> anyhow::Result<Rc<LoadedFont>> {
+1
View File
@@ -31,6 +31,7 @@ colorgrad = "0.6"
config = { path = "../config" }
downcast-rs = "1.0"
dirs-next = "2.0"
emojis = "0.4"
env-bootstrap = { path = "../env-bootstrap" }
euclid = "0.22"
fastrand = "1.6"
+18
View File
@@ -302,6 +302,24 @@ static DEFS: &[CommandDef] = &[
keys: &[(Modifiers::CTRL.union(Modifiers::SHIFT), "Space")],
args: &[ArgType::ActivePane],
},
CommandDef {
brief: "Enter Emoji / Character selection mode",
doc: "Activates the character selection UI for the current pane",
exp: |exp| {
exp.push(CharSelect(CharSelectArguments::default()));
},
keys: &[(Modifiers::CTRL.union(Modifiers::SHIFT), "u")],
args: &[ArgType::ActivePane],
},
CommandDef {
brief: "Enter Pane selection mode",
doc: "Activates the pane selection UI",
exp: |exp| {
exp.push(PaneSelect(PaneSelectArguments::default()));
},
keys: &[(Modifiers::CTRL.union(Modifiers::SHIFT), "p")],
args: &[ArgType::ActivePane],
},
CommandDef {
brief: "Decrease font size",
doc: "Scales the font size smaller by 10%",
+1
View File
@@ -44,6 +44,7 @@ mod shapecache;
mod stats;
mod tabbar;
mod termwindow;
mod unicode_names;
mod uniforms;
mod update;
mod utilsprites;
+20 -12
View File
@@ -644,11 +644,12 @@ impl super::TermWindow {
})
}
ElementContent::Children(kids) => {
let mut pixel_width: f32 = 0.;
let mut pixel_height: f32 = 0.;
let mut block_pixel_width: f32 = 0.;
let mut block_pixel_height: f32 = 0.;
let mut computed_kids = vec![];
let mut max_x: f32 = 0.;
let mut float_width: f32 = 0.;
let mut y_coord: f32 = 0.;
let max_width = match element.max_width {
Some(w) => w
@@ -659,20 +660,27 @@ impl super::TermWindow {
.min(context.width.pixel_max);
for child in kids {
if child.display == DisplayType::Block {
y_coord += block_pixel_height;
block_pixel_height = 0.;
block_pixel_width = 0.;
}
let kid = self.compute_element(
&LayoutContext {
bounds: match child.float {
Float::None => euclid::rect(
pixel_width,
context.bounds.min_y(),
context.bounds.max_x() - (context.bounds.min_x() + pixel_width),
context.bounds.height(),
block_pixel_width,
y_coord,
context.bounds.max_x()
- (context.bounds.min_x() + block_pixel_width),
context.bounds.max_y() - (context.bounds.min_y() + y_coord),
),
Float::Right => euclid::rect(
0.,
context.bounds.min_y(),
y_coord,
context.bounds.width(),
context.bounds.height(),
context.bounds.max_y() - (context.bounds.min_y() + y_coord),
),
},
gl_state: context.gl_state,
@@ -692,11 +700,11 @@ impl super::TermWindow {
float_width += float_width.max(kid.bounds.width());
}
Float::None => {
pixel_width += kid.bounds.width();
max_x = max_x.max(pixel_width);
block_pixel_width += kid.bounds.width();
max_x = max_x.max(block_pixel_width);
}
}
pixel_height = pixel_height.max(kid.bounds.height());
block_pixel_height = block_pixel_height.max(kid.bounds.height());
computed_kids.push(kid);
}
@@ -706,7 +714,7 @@ impl super::TermWindow {
let mut float_max_x = (max_x + float_width).min(max_width);
let pixel_height = pixel_height.max(min_height);
let pixel_height = (y_coord + block_pixel_height).max(min_height);
for (kid, child) in computed_kids.iter_mut().zip(kids.iter()) {
match child.float {
+579
View File
@@ -0,0 +1,579 @@
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;
use crate::utilsprites::RenderMetrics;
use crate::TermWindow;
use config::keyassignment::{
CharSelectArguments, CharSelectGroup, ClipboardCopyDestination, KeyAssignment,
};
use config::Dimension;
use emojis::{Emoji, Group};
use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher;
use std::borrow::Cow;
use std::cell::{Ref, RefCell};
use wezterm_term::{KeyCode, KeyModifiers, MouseEvent};
use window::color::LinearRgba;
struct MatchResults {
selection: String,
matches: Vec<usize>,
group: CharSelectGroup,
}
pub struct CharSelector {
group: RefCell<CharSelectGroup>,
element: RefCell<Option<Vec<ComputedElement>>>,
selection: RefCell<String>,
aliases: Vec<Alias>,
matches: RefCell<Option<MatchResults>>,
selected_row: RefCell<usize>,
top_row: RefCell<usize>,
max_rows_on_screen: RefCell<usize>,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Character {
Unicode { name: &'static str, value: char },
Emoji(&'static Emoji),
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Alias {
name: Cow<'static, str>,
character: Character,
group: CharSelectGroup,
}
impl Alias {
fn name(&self) -> &str {
&self.name
}
fn glyph(&self) -> String {
match &self.character {
Character::Unicode { value, .. } => value.to_string(),
Character::Emoji(emoji) => emoji.as_str().to_string(),
}
}
fn codepoints(&self) -> String {
let mut res = String::new();
for c in self.glyph().chars() {
if !res.is_empty() {
res.push(' ');
}
res.push_str(&format!("U+{:X}", c as u32));
}
res
}
}
fn build_aliases() -> Vec<Alias> {
let mut aliases = vec![];
let start = std::time::Instant::now();
fn push(aliases: &mut Vec<Alias>, alias: Alias) {
aliases.push(alias);
}
for emoji in emojis::iter() {
let group = match emoji.group() {
Group::SmileysAndEmotion => CharSelectGroup::SmileysAndEmotion,
Group::PeopleAndBody => CharSelectGroup::PeopleAndBody,
Group::AnimalsAndNature => CharSelectGroup::AnimalsAndNature,
Group::FoodAndDrink => CharSelectGroup::FoodAndDrink,
Group::TravelAndPlaces => CharSelectGroup::TravelAndPlaces,
Group::Activities => CharSelectGroup::Activities,
Group::Objects => CharSelectGroup::Objects,
Group::Symbols => CharSelectGroup::Symbols,
Group::Flags => CharSelectGroup::Flags,
};
push(
&mut aliases,
Alias {
name: Cow::Borrowed(emoji.name()),
character: Character::Emoji(emoji),
group,
},
);
if let Some(short) = emoji.shortcode() {
if short != emoji.name() {
push(
&mut aliases,
Alias {
name: Cow::Borrowed(short),
character: Character::Emoji(emoji),
group,
},
);
}
}
}
for (name, value) in crate::unicode_names::NAMES {
push(
&mut aliases,
Alias {
name: Cow::Borrowed(name),
character: Character::Unicode {
name,
value: char::from_u32(*value).unwrap(),
},
group: CharSelectGroup::UnicodeNames,
},
);
}
for (name, value) in termwiz::nerdfonts::NERD_FONT_GLYPHS {
push(
&mut aliases,
Alias {
name: Cow::Borrowed(name),
character: Character::Unicode {
name,
value: *value,
},
group: CharSelectGroup::NerdFonts,
},
);
}
log::trace!(
"Took {:?} to build {} aliases",
start.elapsed(),
aliases.len()
);
aliases
}
#[derive(Debug)]
struct MatchResult {
row_idx: usize,
score: i64,
}
impl MatchResult {
fn new(row_idx: usize, score: i64, selection: &str, aliases: &[Alias]) -> Self {
Self {
row_idx,
score: if aliases[row_idx].name == 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, aliases: &[Alias], group: CharSelectGroup) -> Vec<usize> {
if selection.is_empty() {
aliases
.iter()
.enumerate()
.filter(|(_idx, a)| a.group == group)
.map(|(idx, _a)| idx)
.collect()
} else {
let matcher = SkimMatcherV2::default();
let numeric_selection = if selection.chars().all(|c| c.is_ascii_hexdigit()) {
Some(format!("U+{selection}"))
} else if selection.starts_with("U+") {
Some(selection.to_string())
} else {
None
};
let start = std::time::Instant::now();
let mut scores: Vec<MatchResult> = aliases
.iter()
.enumerate()
.filter_map(|(row_idx, entry)| {
let alias_result = matcher
.fuzzy_match(&entry.name, selection)
.map(|score| MatchResult::new(row_idx, score, selection, aliases));
match &numeric_selection {
Some(sel) => {
let codepoints = entry.codepoints();
if codepoints == *sel {
Some(MatchResult {
row_idx,
score: i64::max_value(),
})
} else {
let number_result = matcher
.fuzzy_match(&codepoints, &sel)
.map(|score| MatchResult::new(row_idx, score, sel, aliases));
match (alias_result, number_result) {
(
Some(MatchResult { score: a, .. }),
Some(MatchResult { score: b, .. }),
) => Some(MatchResult {
row_idx,
score: a.max(b),
}),
(Some(a), None) | (None, Some(a)) => Some(a),
(None, None) => None,
}
}
}
None => alias_result,
}
})
.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 CharSelector {
pub fn new(_term_window: &mut TermWindow, args: &CharSelectArguments) -> Self {
Self {
element: RefCell::new(None),
selection: RefCell::new(String::new()),
group: RefCell::new(args.group),
aliases: build_aliases(),
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,
aliases: &[Alias],
matches: &MatchResults,
max_rows_on_screen: usize,
selected_row: usize,
top_row: usize,
) -> anyhow::Result<Vec<ComputedElement>> {
let font = term_window
.fonts
.char_select_font()
.expect("to resolve char selection 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!("Select: {selection}_")))
.colors(ElementColors {
border: BorderColor::default(),
bg: LinearRgba::TRANSPARENT.into(),
text: term_window.config.pane_select_fg_color.to_linear().into(),
})
.display(DisplayType::Block),
];
for (display_idx, alias) in matches
.matches
.iter()
.map(|&idx| &aliases[idx])
.enumerate()
.skip(top_row)
.take(max_rows_on_screen)
{
let (bg, text) = if display_idx == selected_row {
(
term_window.config.pane_select_fg_color.to_linear().into(),
term_window.config.pane_select_bg_color.to_linear().into(),
)
} else {
(
LinearRgba::TRANSPARENT.into(),
term_window.config.pane_select_fg_color.to_linear().into(),
)
};
elements.push(
Element::new(
&font,
ElementContent::Text(format!(
"{} {} ({})",
alias.glyph(),
alias.name(),
alias.codepoints()
)),
)
.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.pane_select_bg_color.to_linear().into(),
),
bg: term_window.config.pane_select_bg_color.to_linear().into(),
text: term_window.config.pane_select_fg_color.to_linear().into(),
})
.margin(BoxDimension {
left: Dimension::Cells(1.25),
right: Dimension::Cells(1.25),
top: Dimension::Cells(1.25),
bottom: Dimension::Cells(1.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;
}
log::info!("selected_row={} top_row={}", *row, *top_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.aliases.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);
}
log::info!("selected_row={} top_row={}", *row, *top_row);
}
}
impl Modal for CharSelector {
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::Char('r'), KeyModifiers::CTRL) => {
// Cycle the selected group
let mut group = self.group.borrow_mut();
*group = group.next();
self.selection.borrow_mut().clear();
self.updated_input();
}
(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 = self
.matches
.borrow()
.as_ref()
.map_or(selected_idx, |m| m.matches[selected_idx]);
let glyph = self.aliases[alias_idx].glyph();
log::trace!("selected: {glyph}");
term_window.copy_to_clipboard(
ClipboardCopyDestination::ClipboardAndPrimarySelection,
glyph.clone(),
);
if let Some(pane) = term_window.get_active_pane_or_overlay() {
pane.writer().write_all(glyph.as_bytes()).ok();
}
term_window.cancel_modal();
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 group = *self.group.borrow();
let mut results = self.matches.borrow_mut();
let font = term_window
.fonts
.char_select_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 || m.group != group)
.unwrap_or(true);
if rebuild_matches {
results.replace(MatchResults {
selection: selection.to_string(),
matches: compute_matches(selection, &self.aliases, group),
group,
});
};
let matches = results.as_ref().unwrap();
if self.element.borrow().is_none() {
let element = Self::compute(
term_window,
selection,
&self.aliases,
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();
}
}
+8
View File
@@ -66,6 +66,7 @@ use wezterm_term::{Alert, StableRowIndex, TerminalConfiguration, TerminalSize};
pub mod background;
pub mod box_model;
pub mod charselect;
pub mod clipboard;
mod keyevent;
pub mod modal;
@@ -1582,6 +1583,9 @@ impl TermWindow {
fn invalidate_modal(&mut self) {
if let Some(modal) = self.get_modal() {
modal.reconfigure(self);
if let Some(window) = self.window.as_ref() {
window.invalidate();
}
}
}
@@ -2693,6 +2697,10 @@ impl TermWindow {
let modal = crate::termwindow::paneselect::PaneSelector::new(self, args);
self.modal.borrow_mut().replace(Rc::new(modal));
}
CharSelect(args) => {
let modal = crate::termwindow::charselect::CharSelector::new(self, args);
self.modal.borrow_mut().replace(Rc::new(modal));
}
};
Ok(())
}
File diff suppressed because it is too large. Load diff