Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

Add UI shape cache and file-preview caching

RoversXf580352f32de
diff --git a/wezterm-gui/src/shapecache.rs b/wezterm-gui/src/shapecache.rs
index da0834a3..134239e7 100644
--- a/wezterm-gui/src/shapecache.rs
+++ b/wezterm-gui/src/shapecache.rs
@@ -25,6 +25,7 @@ pub struct GlyphPosition {
pub struct ShapedInfo {
pub glyph: Rc<CachedGlyph>,
pub pos: GlyphPosition,
+ pub cluster: usize,
pub block_key: Option<BlockKey>,
}
@@ -47,6 +48,7 @@ impl ShapedInfo {
bearing_x: glyph.bearing_x.get() as f32,
},
glyph: Rc::clone(glyph),
+ cluster: info.cluster as usize,
block_key: info.only_char.and_then(BlockKey::from_char),
});
}
@@ -118,6 +120,7 @@ impl<'a> std::hash::Hash for dyn ShapeCacheKeyTrait + 'a {
#[cfg(test)]
mod test {
+ use crate::glyphcache::CachedGlyph;
use crate::glyphcache::GlyphCache;
use crate::shapecache::{GlyphPosition, ShapedInfo};
use crate::utilsprites::RenderMetrics;
@@ -126,7 +129,8 @@ mod test {
use termwiz::cell::CellAttributes;
use termwiz::surface::{Line, SEQ_ZERO};
use wezterm_bidi::Direction;
- use wezterm_font::shaper::PresentationWidth;
+ use wezterm_font::shaper::{GlyphInfo, PresentationWidth};
+ use wezterm_font::units::PixelLength;
use wezterm_font::{FontConfiguration, LoadedFont};
fn cluster_and_shape(
@@ -190,6 +194,55 @@ mod test {
.collect()
}
+ #[test]
+ fn shaped_info_preserves_clusters() {
+ let glyph = Rc::new(CachedGlyph {
+ has_color: false,
+ brightness_adjust: 1.0,
+ x_offset: PixelLength::new(0.0),
+ y_offset: PixelLength::new(0.0),
+ x_advance: PixelLength::new(1.0),
+ bearing_x: PixelLength::new(0.0),
+ bearing_y: PixelLength::new(0.0),
+ texture: None,
+ scale: 1.0,
+ });
+ let infos = vec![
+ GlyphInfo {
+ text: "a".to_string(),
+ only_char: Some('a'),
+ is_space: false,
+ num_cells: 1,
+ cluster: 0,
+ font_idx: 0,
+ glyph_pos: 11,
+ x_advance: PixelLength::new(1.0),
+ y_advance: PixelLength::new(0.0),
+ x_offset: PixelLength::new(0.0),
+ y_offset: PixelLength::new(0.0),
+ },
+ GlyphInfo {
+ text: "你".to_string(),
+ only_char: Some('你'),
+ is_space: false,
+ num_cells: 2,
+ cluster: 3,
+ font_idx: 0,
+ glyph_pos: 12,
+ x_advance: PixelLength::new(2.0),
+ y_advance: PixelLength::new(0.0),
+ x_offset: PixelLength::new(0.0),
+ y_offset: PixelLength::new(0.0),
+ },
+ ];
+ let shaped = ShapedInfo::process(&infos, &[Rc::clone(&glyph), glyph]);
+
+ assert_eq!(
+ shaped.iter().map(|info| info.cluster).collect::<Vec<_>>(),
+ vec![0, 3]
+ );
+ }
+
#[test]
fn ligatures_fira() {
config::use_test_configuration();
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index eee76792..5d7ea6a7 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -57,7 +57,7 @@ use mux_lua::MuxPane;
use smol::channel::Sender;
use smol::Timer;
use std::cell::{RefCell, RefMut};
-use std::collections::{HashMap, HashSet, LinkedList};
+use std::collections::{HashMap, HashSet, LinkedList, VecDeque};
use std::ops::Add;
use std::path::PathBuf;
use std::rc::Rc;
@@ -375,15 +375,39 @@ pub(crate) enum RightSidebarFileIndexStatus {
#[derive(Clone)]
pub(crate) struct RightSidebarFilePreviewSpan {
pub text: String,
+ pub char_count: usize,
pub color: LinearRgba,
}
#[derive(Clone)]
pub(crate) struct RightSidebarFilePreviewLine {
pub plain: String,
+ pub char_count: usize,
pub spans: Vec<RightSidebarFilePreviewSpan>,
}
+#[derive(Clone, Debug, Eq, Hash, PartialEq)]
+pub(crate) struct RightSidebarFilePreviewSliceCacheKey {
+ pub generation: u64,
+ pub line_index: usize,
+ pub horizontal_offset: usize,
+ pub paint_columns: usize,
+ pub highlighted: bool,
+}
+
+#[derive(Clone)]
+pub(crate) struct RightSidebarFilePreviewSliceCacheValue {
+ pub text: String,
+ pub colors: Vec<LinearRgba>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum UiShapeCacheLookup {
+ Hit,
+ Miss,
+ Skipped,
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct RightSidebarFilePreviewSelectionPoint {
pub line: usize,
@@ -942,6 +966,10 @@ pub struct TermWindow {
right_sidebar_file_index_status: RightSidebarFileIndexStatus,
right_sidebar_file_index: Option<Arc<RightSidebarFileIndex>>,
right_sidebar_file_index_cancel: Option<Arc<AtomicBool>>,
+ // Bumped each time the file panel goes idle; a delayed release task only
+ // frees the index/buffers if its captured token still matches (i.e. the
+ // panel was not reopened or re-toggled in the meantime).
+ right_sidebar_file_memory_release_token: u64,
right_sidebar_file_search_generation: u64,
right_sidebar_file_search_cancel: Option<Arc<AtomicBool>>,
right_sidebar_file_search_query: String,
@@ -959,6 +987,16 @@ pub struct TermWindow {
right_sidebar_file_preview_message: Option<String>,
right_sidebar_file_preview_truncated: bool,
right_sidebar_file_preview_selection: Option<RightSidebarFilePreviewSelection>,
+ right_sidebar_file_preview_slice_cache: RefCell<
+ HashMap<RightSidebarFilePreviewSliceCacheKey, RightSidebarFilePreviewSliceCacheValue>,
+ >,
+ right_sidebar_file_preview_slice_cache_order:
+ RefCell<VecDeque<RightSidebarFilePreviewSliceCacheKey>>,
+ // Full-line per-character colours for the horizontal-scroll fast path, keyed
+ // by (preview generation, line index). Built once per line and reused across
+ // every horizontal offset so panning never rebuilds the colour list.
+ right_sidebar_file_preview_line_color_cache: RefCell<HashMap<(u64, usize), Rc<Vec<LinearRgba>>>>,
+ right_sidebar_file_preview_line_color_cache_order: RefCell<VecDeque<(u64, usize)>>,
right_sidebar_file_tree_scroll_offset: f32,
right_sidebar_file_preview_scroll_offset: f32,
right_sidebar_file_preview_horizontal_offset: usize,
@@ -1484,6 +1522,7 @@ impl TermWindow {
right_sidebar_file_index_root: None,
right_sidebar_file_index_project_name: String::new(),
right_sidebar_file_index_status: RightSidebarFileIndexStatus::Empty,
+ right_sidebar_file_memory_release_token: 0,
right_sidebar_file_index: None,
right_sidebar_file_index_cancel: None,
right_sidebar_file_search_generation: 0,
@@ -1503,6 +1542,10 @@ impl TermWindow {
right_sidebar_file_preview_message: None,
right_sidebar_file_preview_truncated: false,
right_sidebar_file_preview_selection: None,
+ right_sidebar_file_preview_slice_cache: RefCell::new(HashMap::new()),
+ right_sidebar_file_preview_slice_cache_order: RefCell::new(VecDeque::new()),
+ right_sidebar_file_preview_line_color_cache: RefCell::new(HashMap::new()),
+ right_sidebar_file_preview_line_color_cache_order: RefCell::new(VecDeque::new()),
right_sidebar_file_tree_scroll_offset: 0.0,
right_sidebar_file_preview_scroll_offset: 0.0,
right_sidebar_file_preview_horizontal_offset: 0,
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index 87d76069..90c559c8 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -571,8 +571,9 @@ impl super::TermWindow {
WMEK::VertWheel(_) | WMEK::HorzWheel(_) => false,
_ => return false,
};
- let _ = changed;
- context.invalidate();
+ if changed {
+ context.invalidate();
+ }
return true;
}
}
@@ -602,12 +603,18 @@ impl super::TermWindow {
}
if self.right_sidebar_mode == super::RightSidebarMode::Chat {
- self.scroll_right_sidebar_files(amount);
+ if self.scroll_right_sidebar_files(amount) {
+ context.invalidate();
+ }
} else {
+ let was_visible = self.right_sidebar_snippet_scrollbar_visible_until;
self.show_right_sidebar_snippet_scrollbar();
- self.scroll_right_sidebar_snippets(amount);
+ if self.scroll_right_sidebar_snippets(amount)
+ || was_visible != self.right_sidebar_snippet_scrollbar_visible_until
+ {
+ context.invalidate();
+ }
}
- context.invalidate();
true
}
@@ -2073,6 +2080,11 @@ impl super::TermWindow {
if event.kind == WMEK::Press(MousePress::Left) {
let previous_width = self.right_sidebar_width();
self.right_sidebar_mode = mode;
+ // Leaving the file view (e.g. switching to Snippets/Tasks) makes the
+ // file index idle; schedule it for release if nothing reopens it.
+ if !self.right_sidebar_file_view_active() {
+ self.schedule_right_sidebar_file_memory_release();
+ }
self.invalidate_or_reflow_right_sidebar(previous_width, context);
}
}
diff --git a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
index 5d4ffb31..229662fb 100644
--- a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
+++ b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs
@@ -1,5 +1,6 @@
use crate::customglyph::BlockKey;
use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
+use crate::shapecache::{BorrowedShapeCacheKey, ShapedInfo};
use crate::tabbar::{TabBarItem, TabEntry};
use crate::termwindow::ui::icons::SvgIcon;
use crate::termwindow::ui::tokens::{
@@ -9,16 +10,16 @@ use crate::termwindow::ui::tokens::{
WINDOW_TAB_LEADING_ACTION_BUTTON_SIZE, WINDOW_TAB_LEADING_ACTION_GAP,
WINDOW_TAB_LEADING_ACTION_ICON_SIZE, WINDOW_TAB_RADIUS, WINDOW_TAB_TOP_SPACER,
};
-use crate::termwindow::{TermWindowNotif, UIItem, UIItemType};
+use crate::termwindow::{TermWindowNotif, UIItem, UIItemType, UiShapeCacheLookup};
use crate::ui::UiPalette;
use crate::utilsprites::RenderMetrics;
-use anyhow::Context;
+use anyhow::{anyhow, Context};
use finl_unicode::grapheme_clusters::Graphemes;
use std::rc::Rc;
use termwiz::cell::grapheme_column_width;
use termwiz::cell::CellAttributes;
use wezterm_bidi::Direction;
-use wezterm_font::LoadedFont;
+use wezterm_font::{ClearShapeCache, LoadedFont};
use wezterm_term::Line;
use window::color::LinearRgba;
use window::WindowOps;
@@ -27,6 +28,7 @@ use window::{IntegratedTitleButton, IntegratedTitleButtonStyle, WindowDecoration
const WINDOW_TAB_INSET: usize = 8;
const WINDOW_TAB_ICON_GAP: usize = 8;
const WINDOW_TAB_MIN_TEXT_COLS: usize = 3;
+const UI_SHAPE_CACHE_FONT_IDENTITY_BIT: u64 = 1u64 << 63;
impl crate::TermWindow {
pub fn invalidate_fancy_tab_bar(&mut self) {
@@ -1235,7 +1237,7 @@ impl crate::TermWindow {
/// per-character colour list. The whole string is shaped **once** instead of
/// once per coloured span; that is what keeps the file preview smooth while
/// scrolling syntax-highlighted code (the shaper does not cache results).
- #[allow(clippy::too_many_arguments)]
+ #[allow(clippy::too_many_arguments, dead_code)]
pub(crate) fn paint_ui_colored_text(
&self,
layers: &mut TripleLayerQuadAllocator,
@@ -1364,6 +1366,284 @@ impl crate::TermWindow {
Ok(())
}
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn paint_ui_title_text_cached(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ font: &Rc<LoadedFont>,
+ metrics: &RenderMetrics,
+ text: &str,
+ x: usize,
+ y: usize,
+ width: usize,
+ foreground: LinearRgba,
+ ) -> anyhow::Result<UiShapeCacheLookup> {
+ self.paint_ui_title_text_cached_with_advance(
+ layers, font, metrics, text, x, y, width, foreground,
+ )
+ .map(|(_, lookup)| lookup)
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn paint_ui_title_text_cached_with_advance(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ font: &Rc<LoadedFont>,
+ metrics: &RenderMetrics,
+ text: &str,
+ x: usize,
+ y: usize,
+ width: usize,
+ foreground: LinearRgba,
+ ) -> anyhow::Result<(f32, UiShapeCacheLookup)> {
+ if text.is_empty() || width == 0 {
+ return Ok((0.0, UiShapeCacheLookup::Skipped));
+ }
+
+ let (shaped, lookup) = self.cached_ui_shape(font, metrics, text)?;
+ let advance =
+ self.paint_cached_ui_shape(layers, metrics, &shaped, x, y, width, |_| foreground)?;
+ Ok((advance, lookup))
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn paint_ui_colored_text_cached(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ font: &Rc<LoadedFont>,
+ metrics: &RenderMetrics,
+ text: &str,
+ char_colors: &[LinearRgba],
+ default_color: LinearRgba,
+ x: usize,
+ y: usize,
+ width: usize,
+ ) -> anyhow::Result<UiShapeCacheLookup> {
+ if text.is_empty() || width == 0 {
+ return Ok(UiShapeCacheLookup::Skipped);
+ }
+
+ let (shaped, lookup) = self.cached_ui_shape(font, metrics, text)?;
+
+ // Map each byte offset to its char index so a glyph's cluster can look
+ // up the colour of the character it came from. This stays outside the
+ // shape cache because colours are applied at paint time.
+ let mut byte_to_char = vec![0usize; text.len() + 1];
+ for (char_idx, (byte_idx, ch)) in text.char_indices().enumerate() {
+ for byte in byte_idx..byte_idx + ch.len_utf8() {
+ byte_to_char[byte] = char_idx;
+ }
+ }
+ if let Some(last) = byte_to_char.last_mut() {
+ *last = char_colors.len().saturating_sub(1);
+ }
+
+ self.paint_cached_ui_shape(layers, metrics, &shaped, x, y, width, |info| {
+ let char_idx = byte_to_char.get(info.cluster).copied().unwrap_or(0);
+ char_colors.get(char_idx).copied().unwrap_or(default_color)
+ })?;
+
+ Ok(lookup)
+ }
+
+ pub(crate) fn cached_ui_shape(
+ &self,
+ font: &Rc<LoadedFont>,
+ metrics: &RenderMetrics,
+ text: &str,
+ ) -> anyhow::Result<(Rc<Vec<ShapedInfo>>, UiShapeCacheLookup)> {
+ let font_identity = UI_SHAPE_CACHE_FONT_IDENTITY_BIT | font.id() as u64;
+ let style = font.style();
+ let key = BorrowedShapeCacheKey {
+ font_identity,
+ style,
+ text,
+ };
+
+ if let Some(cached) = self.lookup_cached_shape(&key) {
+ return cached.map(|shaped| (shaped, UiShapeCacheLookup::Hit));
+ }
+
+ let Some(window) = self.window.as_ref().cloned() else {
+ return Ok((Rc::new(Vec::new()), UiShapeCacheLookup::Skipped));
+ };
+ let Some(gl_state) = self.render_state.as_ref() else {
+ return Ok((Rc::new(Vec::new()), UiShapeCacheLookup::Skipped));
+ };
+
+ let infos = match font.shape(
+ text,
+ move || window.notify(TermWindowNotif::InvalidateShapeCache),
+ BlockKey::filter_out_synthetic,
+ None,
+ Direction::LeftToRight,
+ None,
+ None,
+ ) {
+ Ok(infos) => infos,
+ Err(err) => {
+ if err.root_cause().downcast_ref::<ClearShapeCache>().is_some() {
+ return Err(err);
+ }
+
+ let res = anyhow!("shaper error: {}", err);
+ self.shape_cache.borrow_mut().put(key.to_owned(), Err(err));
+ return Err(res);
+ }
+ };
+
+ let glyphs = {
+ let mut glyph_cache = gl_state.glyph_cache.borrow_mut();
+ self.glyph_infos_to_glyphs(style, &mut glyph_cache, &infos, font, metrics)?
+ };
+ let shaped = Rc::new(ShapedInfo::process(&infos, &glyphs));
+ self.shape_cache
+ .borrow_mut()
+ .put(key.to_owned(), Ok(Rc::clone(&shaped)));
+ Ok((shaped, UiShapeCacheLookup::Miss))
+ }
+
+ /// Total advance width (px) of `text` in `font`, via the shared shape cache.
+ /// Reuses the same cached glyph run as the cached painters, so width queries
+ /// (ellipsize, button sizing) become cache hits after the first shape and
+ /// stay consistent with what is painted.
+ pub(crate) fn cached_ui_text_advance(
+ &self,
+ font: &Rc<LoadedFont>,
+ metrics: &RenderMetrics,
+ text: &str,
+ ) -> anyhow::Result<f32> {
+ if text.is_empty() {
+ return Ok(0.0);
+ }
+ let (shaped, _) = self.cached_ui_shape(font, metrics, text)?;
+ Ok(shaped
+ .iter()
+ .map(|info| info.glyph.x_advance.get() as f32)
+ .sum())
+ }
+
+ fn paint_cached_ui_shape<F>(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ metrics: &RenderMetrics,
+ shaped: &[ShapedInfo],
+ x: usize,
+ y: usize,
+ width: usize,
+ color_for: F,
+ ) -> anyhow::Result<f32>
+ where
+ F: FnMut(&ShapedInfo) -> LinearRgba,
+ {
+ self.paint_cached_ui_shape_clipped(
+ layers,
+ metrics,
+ shaped,
+ x as f32,
+ y as f32,
+ x as f32,
+ (x + width) as f32,
+ color_for,
+ )
+ }
+
+ /// Draw a cached glyph run starting at pixel `start_x` (which may be left of
+ /// `clip_left`, e.g. for a horizontally-scrolled line), clipping to
+ /// `[clip_left, clip_right]`: glyphs fully left of `clip_left` advance the
+ /// pen but draw nothing, and drawing stops at `clip_right`. With
+ /// `start_x == clip_left` this is identical to the previous fixed-origin
+ /// painter, so existing callers are unaffected.
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn paint_cached_ui_shape_clipped<F>(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ metrics: &RenderMetrics,
+ shaped: &[ShapedInfo],
+ start_x: f32,
+ y: f32,
+ clip_left: f32,
+ clip_right: f32,
+ mut color_for: F,
+ ) -> anyhow::Result<f32>
+ where
+ F: FnMut(&ShapedInfo) -> LinearRgba,
+ {
+ if shaped.is_empty() || clip_right <= clip_left {
+ return Ok(0.0);
+ }
+
+ let Some(gl_state) = self.render_state.as_ref() else {
+ return Ok(0.0);
+ };
+ let mut glyph_cache = gl_state.glyph_cache.borrow_mut();
+ let left_offset = self.dimensions.pixel_width as f32 / -2.0;
+ let top_offset = self.dimensions.pixel_height as f32 / -2.0;
+ let baseline = metrics.cell_size.height as f32 + metrics.descender.get() as f32;
+ let mut x_pos = start_x;
+
+ for info in shaped {
+ let advance = info.glyph.x_advance.get() as f32;
+ // Fully left of the viewport: advance the pen, draw nothing.
+ if x_pos + advance <= clip_left {
+ x_pos += advance;
+ continue;
+ }
+ let color = color_for(info);
+
+ if let Some(key) = info.block_key {
+ if x_pos + advance > clip_right {
+ break;
+ }
+ let sprite = glyph_cache.cached_block(key, metrics)?;
+ let mut quad = layers.allocate(2)?;
+ quad.set_position(
+ x_pos + left_offset,
+ y + top_offset,
+ x_pos + left_offset + advance,
+ y + top_offset + metrics.cell_size.height as f32,
+ );
+ quad.set_texture(sprite.texture_coords());
+ quad.set_fg_color(color);
+ quad.set_alt_color_and_mix_value(color, 0.0);
+ quad.set_hsv(None);
+ x_pos += advance;
+ continue;
+ }
+
+ let glyph = &info.glyph;
+ if x_pos + advance > clip_right {
+ break;
+ }
+
+ if let Some(texture) = glyph.texture.as_ref() {
+ let glyph_x = x_pos + (glyph.x_offset + glyph.bearing_x).get() as f32;
+ let glyph_y = y - (glyph.y_offset + glyph.bearing_y).get() as f32 + baseline;
+ let glyph_width = texture.coords.size.width as f32 * glyph.scale as f32;
+ let glyph_height = texture.coords.size.height as f32 * glyph.scale as f32;
+ if glyph_x + glyph_width > clip_right {
+ break;
+ }
+ let mut quad = layers.allocate(2)?;
+ quad.set_position(
+ glyph_x + left_offset,
+ glyph_y + top_offset,
+ glyph_x + left_offset + glyph_width,
+ glyph_y + top_offset + glyph_height,
+ );
+ quad.set_texture(texture.texture_coords());
+ quad.set_fg_color(color);
+ quad.set_alt_color_and_mix_value(color, 0.0);
+ quad.set_has_color(glyph.has_color);
+ quad.set_hsv(None);
+ }
+
+ x_pos += advance;
+ }
+
+ Ok((x_pos - start_x).max(0.0))
+ }
+
fn paint_fancy_tab_icon(
&self,
layers: &mut TripleLayerQuadAllocator,
diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
index b1cef97f..a9c6f498 100644
--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
@@ -11,10 +11,11 @@ use crate::termwindow::{
RightSidebarFileCharBag, RightSidebarFileField, RightSidebarFileIndex,
RightSidebarFileIndexEntry, RightSidebarFileIndexStatus, RightSidebarFilePreviewImage,
RightSidebarFilePreviewLine, RightSidebarFilePreviewSelection,
- RightSidebarFilePreviewSelectionPoint, RightSidebarFilePreviewSpan, RightSidebarFileTreeRow,
+ RightSidebarFilePreviewSelectionPoint, RightSidebarFilePreviewSliceCacheKey,
+ RightSidebarFilePreviewSliceCacheValue, RightSidebarFilePreviewSpan, RightSidebarFileTreeRow,
RightSidebarFileView, RightSidebarInputLayout, RightSidebarMode,
RightSidebarOpenWithCacheEntry, RightSidebarSnippetField, RightSidebarSnippetView,
- TermWindowNotif, UIItem, UIItemType,
+ TermWindowNotif, UIItem, UIItemType, UiShapeCacheLookup,
};
use crate::ui::TextInputState;
use crate::ui::UiPalette;
@@ -31,7 +32,7 @@ use std::io::Read;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
-use std::sync::Arc;
+use std::sync::{Arc, Mutex, OnceLock, Weak};
use std::time::{Duration, Instant};
use syntect::easy::HighlightLines;
use syntect::highlighting::{Color as SyntectColor, Style as SyntectStyle, Theme, ThemeSet};
@@ -78,6 +79,12 @@ const FILE_PREVIEW_HEADER_HEIGHT: usize = 64;
const FILE_PREVIEW_MAX_BYTES: usize = 256 * 1024;
const FILE_PREVIEW_TRUNCATED_LABEL: &str = "Preview truncated to 256 KiB";
const FILE_PREVIEW_IMAGE_MAX_BYTES: usize = 16 * 1024 * 1024;
+// The file-size cap above bounds the *encoded* bytes, but a small encoded image
+// can decode to an enormous RGBA bitmap (`width × height × 4`, ×frames for
+// animations) — a decompression bomb that has spiked RAM to >1 GiB. The preview
+// pane is only a few hundred px wide, so cap the decode at ~16 MP (≈64 MiB
+// RGBA), which still covers 4K/5K screenshots and typical photos.
+const FILE_PREVIEW_IMAGE_MAX_PIXELS: u64 = 16_000_000;
const FILE_PREVIEW_PANE_MIN_WIDTH: usize = 360;
const FILE_PREVIEW_PANE_DEFAULT_WIDTH: usize = 560;
// Per-line we keep the *full* content (bounded only by FILE_PREVIEW_MAX_BYTES
@@ -86,10 +93,19 @@ const FILE_PREVIEW_PANE_DEFAULT_WIDTH: usize = 560;
// point are rendered in the default colour instead of being dropped. This keeps
// syntect cost bounded on pathological single-line files without losing data.
const FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT: usize = 8192;
+const FILE_PREVIEW_SLICE_CACHE_CAPACITY: usize = 256;
+// Lines up to this many columns are shaped whole (once, cached) so horizontal
+// scrolling is pure translation of the cached glyph run instead of re-shaping a
+// new substring per step. Longer lines fall back to the per-window slice path to
+// keep the one-time shaping cost bounded.
+const FILE_PREVIEW_FULL_LINE_SHAPE_MAX_COLS: usize = 4096;
const FILE_PREVIEW_SCROLLBAR_THICKNESS: usize = 4;
const FILE_PREVIEW_SCROLLBAR_HIT_SLOP: usize = 6;
const FILE_TREE_ROW_LIMIT: usize = 2000;
const FILE_INDEX_ENTRY_LIMIT: usize = 100_000;
+// How long the file panel must stay closed/idle before its in-memory index and
+// buffers are released. Reopening within this window keeps everything resident.
+const FILE_INDEX_IDLE_RELEASE_SECS: u64 = 30;
const FILE_FILTER_DEBOUNCE_MS: u64 = 350;
#[derive(Debug, Clone, Copy)]
@@ -133,6 +149,78 @@ pub(crate) struct RightSidebarFilePreviewHorizontalScrollGeometry {
pub max_scroll: usize,
}
+struct FilePreviewPaintProfile {
+ enabled: bool,
+ start: Option<Instant>,
+ line_count: usize,
+ visible_lines: usize,
+ plain_lines: usize,
+ highlighted_lines: usize,
+ slice_requests: usize,
+ shape_requests: usize,
+ shape_cache_hits: usize,
+ shape_cache_misses: usize,
+}
+
+impl FilePreviewPaintProfile {
+ fn new() -> Self {
+ static ENABLED: OnceLock<bool> = OnceLock::new();
+ let enabled =
+ *ENABLED.get_or_init(|| std::env::var_os("THINKTERM_PROFILE_FILE_PREVIEW").is_some());
+ Self {
+ enabled,
+ start: enabled.then(Instant::now),
+ line_count: 0,
+ visible_lines: 0,
+ plain_lines: 0,
+ highlighted_lines: 0,
+ slice_requests: 0,
+ shape_requests: 0,
+ shape_cache_hits: 0,
+ shape_cache_misses: 0,
+ }
+ }
+
+ fn record_shape_lookup(&mut self, lookup: UiShapeCacheLookup) {
+ if !self.enabled {
+ return;
+ }
+ self.shape_requests += 1;
+ match lookup {
+ UiShapeCacheLookup::Hit => self.shape_cache_hits += 1,
+ UiShapeCacheLookup::Miss => self.shape_cache_misses += 1,
+ UiShapeCacheLookup::Skipped => {}
+ }
+ }
+
+ fn finish(&self, scroll_offset: f32, horizontal_offset: usize) {
+ if !self.enabled {
+ return;
+ }
+ let Some(start) = self.start else {
+ return;
+ };
+ let elapsed = start.elapsed();
+ if elapsed < Duration::from_millis(8) {
+ return;
+ }
+ log::info!(
+ "file preview paint: {:?}, lines={}, visible={}, plain={}, highlighted={}, slices={}, shape_requests={}, shape_hits={}, shape_misses={}, scroll={:.1}, hscroll={}",
+ elapsed,
+ self.line_count,
+ self.visible_lines,
+ self.plain_lines,
+ self.highlighted_lines,
+ self.slice_requests,
+ self.shape_requests,
+ self.shape_cache_hits,
+ self.shape_cache_misses,
+ scroll_offset,
+ horizontal_offset
+ );
+ }
+}
+
#[derive(Debug, Clone, Copy)]
struct RightSidebarFilePreviewBodyMetrics {
x: usize,
@@ -363,12 +451,72 @@ impl crate::TermWindow {
pub fn toggle_right_sidebar(&mut self) {
self.right_sidebar_collapsed = !self.right_sidebar_collapsed;
+ if self.right_sidebar_collapsed {
+ self.schedule_right_sidebar_file_memory_release();
+ }
}
pub fn expand_right_sidebar(&mut self) {
self.right_sidebar_collapsed = false;
}
+ /// The file panel (and its in-memory index) is only relevant while the right
+ /// sidebar is open and in `Chat`/File mode.
+ pub(crate) fn right_sidebar_file_view_active(&self) -> bool {
+ !self.right_sidebar_collapsed && self.right_sidebar_mode == RightSidebarMode::Chat
+ }
+
+ /// Schedule a delayed check that frees the file index + buffers if the panel
+ /// stays closed/idle. Bumping the token makes any earlier pending check a
+ /// no-op, so reopening or re-toggling within the window keeps memory warm.
+ pub(crate) fn schedule_right_sidebar_file_memory_release(&mut self) {
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ self.right_sidebar_file_memory_release_token =
+ self.right_sidebar_file_memory_release_token.wrapping_add(1);
+ let token = self.right_sidebar_file_memory_release_token;
+ let target = Instant::now() + Duration::from_secs(FILE_INDEX_IDLE_RELEASE_SECS);
+ promise::spawn::spawn(async move {
+ smol::Timer::at(target).await;
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ term_window.release_right_sidebar_file_memory_if_idle(token);
+ })));
+ })
+ .detach();
+ }
+
+ /// Free the in-memory file index, browse/search rows and preview buffers once
+ /// the panel has been idle long enough. No-op if it was reopened/re-toggled
+ /// since scheduling, or if an index build is still in flight. The root and
+ /// expanded-folder set are kept so reopening rebuilds the same view.
+ fn release_right_sidebar_file_memory_if_idle(&mut self, token: u64) {
+ if token != self.right_sidebar_file_memory_release_token
+ || self.right_sidebar_file_view_active()
+ || matches!(
+ self.right_sidebar_file_index_status,
+ RightSidebarFileIndexStatus::Indexing
+ )
+ {
+ return;
+ }
+
+ if let Some(cancel) = self.right_sidebar_file_index_cancel.take() {
+ cancel.store(true, AtomicOrdering::Relaxed);
+ }
+ self.clear_right_sidebar_file_search();
+ self.close_right_sidebar_file_preview();
+ // `close_right_sidebar_file_preview` only `.clear()`s the preview lines,
+ // which keeps the (potentially large) capacity; drop it outright.
+ self.right_sidebar_file_preview_lines = Vec::new();
+
+ self.right_sidebar_file_index = None;
+ self.right_sidebar_file_index_status = RightSidebarFileIndexStatus::Empty;
+ self.right_sidebar_file_browse_rows = Vec::new();
+ self.right_sidebar_file_browse_cache_key = None;
+ self.invalidate_window();
+ }
+
pub(crate) fn right_sidebar_toggle_icon(&self) -> SvgIcon {
if self.right_sidebar_collapsed {
SvgIcon::PanelRightOpen
@@ -583,6 +731,7 @@ impl crate::TermWindow {
let generation = self.right_sidebar_file_preview_generation;
self.right_sidebar_file_preview_lines.clear();
self.right_sidebar_file_preview_max_columns = 0;
+ self.clear_right_sidebar_file_preview_slice_cache();
self.right_sidebar_file_preview_image = None;
self.right_sidebar_file_preview_message = Some("Loading file preview...".to_string());
self.right_sidebar_file_preview_truncated = false;
@@ -629,6 +778,7 @@ impl crate::TermWindow {
self.right_sidebar_file_preview_generation.wrapping_add(1);
self.right_sidebar_file_preview_lines.clear();
self.right_sidebar_file_preview_max_columns = 0;
+ self.clear_right_sidebar_file_preview_slice_cache();
self.right_sidebar_file_preview_image = None;
self.right_sidebar_file_preview_message = None;
self.right_sidebar_file_preview_truncated = false;
@@ -637,6 +787,94 @@ impl crate::TermWindow {
self.right_sidebar_file_preview_horizontal_offset = 0;
}
+ fn clear_right_sidebar_file_preview_slice_cache(&self) {
+ self.right_sidebar_file_preview_slice_cache
+ .borrow_mut()
+ .clear();
+ self.right_sidebar_file_preview_slice_cache_order
+ .borrow_mut()
+ .clear();
+ self.right_sidebar_file_preview_line_color_cache
+ .borrow_mut()
+ .clear();
+ self.right_sidebar_file_preview_line_color_cache_order
+ .borrow_mut()
+ .clear();
+ }
+
+ /// Per-byte colours for a whole preview line, keyed by (generation, line
+ /// index) so horizontal scrolling reuses the same colour list. Indexed by
+ /// byte offset into `line.plain` so a glyph's `cluster` maps straight to its
+ /// colour without rebuilding a byte→char table every frame.
+ fn cached_full_line_colors(
+ &self,
+ line_index: usize,
+ line: &RightSidebarFilePreviewLine,
+ ) -> Rc<Vec<LinearRgba>> {
+ let key = (self.right_sidebar_file_preview_generation, line_index);
+ if let Some(value) = self
+ .right_sidebar_file_preview_line_color_cache
+ .borrow()
+ .get(&key)
+ .cloned()
+ {
+ return value;
+ }
+ let colors = Rc::new(full_line_colors_by_byte(line));
+ {
+ let mut cache = self.right_sidebar_file_preview_line_color_cache.borrow_mut();
+ let mut order = self
+ .right_sidebar_file_preview_line_color_cache_order
+ .borrow_mut();
+ if !cache.contains_key(&key) {
+ order.push_back(key);
+ }
+ cache.insert(key, Rc::clone(&colors));
+ while order.len() > FILE_PREVIEW_SLICE_CACHE_CAPACITY {
+ if let Some(old_key) = order.pop_front() {
+ cache.remove(&old_key);
+ }
+ }
+ }
+ colors
+ }
+
+ fn cached_right_sidebar_file_preview_slice<F>(
+ &self,
+ key: RightSidebarFilePreviewSliceCacheKey,
+ build: F,
+ ) -> RightSidebarFilePreviewSliceCacheValue
+ where
+ F: FnOnce() -> RightSidebarFilePreviewSliceCacheValue,
+ {
+ if let Some(value) = self
+ .right_sidebar_file_preview_slice_cache
+ .borrow()
+ .get(&key)
+ .cloned()
+ {
+ return value;
+ }
+
+ let value = build();
+ {
+ let mut cache = self.right_sidebar_file_preview_slice_cache.borrow_mut();
+ let mut order = self
+ .right_sidebar_file_preview_slice_cache_order
+ .borrow_mut();
+ if !cache.contains_key(&key) {
+ order.push_back(key.clone());
+ }
+ cache.insert(key, value.clone());
+ while order.len() > FILE_PREVIEW_SLICE_CACHE_CAPACITY {
+ if let Some(old_key) = order.pop_front() {
+ cache.remove(&old_key);
+ }
+ }
+ }
+ value
+ }
+
fn apply_right_sidebar_file_preview_result(
&mut self,
generation: u64,
@@ -653,9 +891,10 @@ impl crate::TermWindow {
self.right_sidebar_file_preview_max_columns = self
.right_sidebar_file_preview_lines
.iter()
- .map(|line| line.plain.chars().count())
+ .map(|line| line.char_count)
.max()
.unwrap_or(0);
+ self.clear_right_sidebar_file_preview_slice_cache();
self.right_sidebar_file_preview_image = result.image;
self.right_sidebar_file_preview_message = result.message;
self.right_sidebar_file_preview_truncated = result.truncated;
@@ -877,7 +1116,7 @@ impl crate::TermWindow {
let line_end = if line_idx == end.line {
end.column
} else {
- line.plain.chars().count()
+ line.char_count
};
if line_end > line_start {
text.push_str(&preview_text_range(&line.plain, line_start, line_end));
@@ -937,7 +1176,7 @@ impl crate::TermWindow {
let line_len = self
.right_sidebar_file_preview_lines
.get(line)
- .map(|line| line.plain.chars().count())
+ .map(|line| line.char_count)
.unwrap_or(0);
let (_, _, text_x, text_width) =
@@ -1114,12 +1353,11 @@ impl crate::TermWindow {
let worker_cancel = index_cancel.clone();
promise::spawn::spawn(async move {
let result = promise::spawn::spawn_into_new_thread(move || {
- Ok(build_right_sidebar_file_index_with_cancel(
+ Ok(build_or_reuse_shared_file_index(
&index_root_path,
&index_project_name,
&worker_cancel,
- )
- .map(Arc::new))
+ ))
})
.await
.unwrap_or_else(|err| Err(format!("Unable to index files: {err}")));
@@ -3534,6 +3772,9 @@ impl crate::TermWindow {
let Some(path) = self.right_sidebar_file_selected.clone() else {
return Ok(());
};
+ let mut profile = FilePreviewPaintProfile::new();
+ let mut profile_scroll_offset = 0.0;
+ let mut profile_horizontal_offset = 0usize;
let Some(metrics) = self.right_sidebar_file_preview_body_metrics(ui_metrics) else {
self.paint_files_preview_header(
@@ -3572,11 +3813,13 @@ impl crate::TermWindow {
let visible_height =
self.right_sidebar_file_preview_effective_visible_height(metrics, ui_metrics);
let line_count = preview_line_count(&self.right_sidebar_file_preview_lines);
+ profile.line_count = line_count;
let max_scroll = metrics.total_height.saturating_sub(visible_height) as f32;
self.right_sidebar_file_preview_scroll_offset = self
.right_sidebar_file_preview_scroll_offset
.clamp(0.0, max_scroll);
let scroll_offset = self.right_sidebar_file_preview_scroll_offset;
+ profile_scroll_offset = scroll_offset;
show_top_fade = max_scroll > 0.0 && scroll_offset > 0.0;
show_scrollbars = true;
@@ -3588,6 +3831,7 @@ impl crate::TermWindow {
self.right_sidebar_file_preview_horizontal_scroll_max_with_metrics(ui_metrics),
);
let horizontal_offset = self.right_sidebar_file_preview_horizontal_offset;
+ profile_horizontal_offset = horizontal_offset;
// Render only the visible horizontal window, never the whole line
// (lines can be tens of thousands of columns wide). The preview font
// is proportional, so `visible_columns` (text_width / cell_width)
@@ -3603,70 +3847,67 @@ impl crate::TermWindow {
});
let first_visible_line = (scroll_offset / line_height as f32).floor().max(0.0) as usize;
let visible_line_count = visible_height / line_height + 3;
- for (idx, line) in preview_visible_lines(
- &self.right_sidebar_file_preview_lines,
+ let visible_range = preview_visible_line_range(
+ self.right_sidebar_file_preview_lines.len(),
first_visible_line,
visible_line_count,
- ) {
- let line_top = body_y as f32 + (idx * line_height) as f32 - scroll_offset;
- let line_bottom = line_top + line_height as f32;
- if line_bottom <= body_y as f32 {
- continue;
- }
- if line_top >= body_bottom as f32 {
- break;
- }
- let line_y = line_top.floor().max(0.0) as usize;
- self.paint_right_sidebar_file_preview_selection_for_line(
+ );
+ if self.right_sidebar_file_preview_lines.is_empty() && first_visible_line == 0 {
+ let empty_line = preview_line_from_plain("");
+ self.paint_right_sidebar_file_preview_text_line(
layers,
+ ui_font,
+ ui_metrics,
chrome,
- line,
- idx,
- horizontal_offset,
- visible_columns,
+ foreground,
+ muted_fg,
+ 0,
+ &empty_line,
+ body_x,
+ body_y,
+ body_bottom,
+ number_width,
text_x,
- line_y,
+ text_width,
line_height,
+ scroll_offset,
+ horizontal_offset,
+ visible_columns,
+ paint_columns,
cell_width,
+ Some(&mut profile),
)?;
- self.paint_ui_title_text(
- layers,
- ui_font,
- &ui_metrics,
- &(idx + 1).to_string(),
- body_x,
- line_y,
- number_width,
- muted_fg.mul_alpha(0.72),
- )?;
- if line.spans.is_empty() {
- let visible_text =
- preview_text_slice(&line.plain, horizontal_offset, paint_columns);
- // Clip at the edge (no "..."); the horizontal scrollbar
- // indicates there is more content off-screen.
- self.paint_ui_title_text(
- layers,
- ui_font,
- &ui_metrics,
- &visible_text,
- text_x,
- line_y,
- text_width,
- foreground,
- )?;
- } else {
- self.paint_highlighted_preview_line(
+ } else {
+ for idx in visible_range {
+ let Some(line) = self.right_sidebar_file_preview_lines.get(idx) else {
+ continue;
+ };
+ let should_break = self.paint_right_sidebar_file_preview_text_line(
layers,
ui_font,
ui_metrics,
+ chrome,
+ foreground,
+ muted_fg,
+ idx,
line,
- horizontal_offset,
- paint_columns,
+ body_x,
+ body_y,
+ body_bottom,
+ number_width,
text_x,
- line_y,
text_width,
- foreground,
+ line_height,
+ scroll_offset,
+ horizontal_offset,
+ visible_columns,
+ paint_columns,
+ cell_width,
+ Some(&mut profile),
)?;
+ if should_break {
+ break;
+ }
}
}
@@ -3726,9 +3967,133 @@ impl crate::TermWindow {
self.paint_right_sidebar_file_preview_scrollbar(layers, chrome)?;
self.paint_right_sidebar_file_preview_horizontal_scrollbar(layers, chrome)?;
}
+ profile.finish(profile_scroll_offset, profile_horizontal_offset);
Ok(())
}
+ #[allow(clippy::too_many_arguments)]
+ fn paint_right_sidebar_file_preview_text_line(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ ui_font: &Rc<LoadedFont>,
+ ui_metrics: RenderMetrics,
+ chrome: UiPalette,
+ foreground: LinearRgba,
+ muted_fg: LinearRgba,
+ idx: usize,
+ line: &RightSidebarFilePreviewLine,
+ body_x: usize,
+ body_y: usize,
+ body_bottom: usize,
+ number_width: usize,
+ text_x: usize,
+ text_width: usize,
+ line_height: usize,
+ scroll_offset: f32,
+ horizontal_offset: usize,
+ visible_columns: usize,
+ paint_columns: usize,
+ cell_width: usize,
+ mut profile: Option<&mut FilePreviewPaintProfile>,
+ ) -> anyhow::Result<bool> {
+ let line_top = body_y as f32 + (idx * line_height) as f32 - scroll_offset;
+ let line_bottom = line_top + line_height as f32;
+ if line_bottom <= body_y as f32 {
+ return Ok(false);
+ }
+ if line_top >= body_bottom as f32 {
+ return Ok(true);
+ }
+ if let Some(profile) = profile.as_deref_mut().filter(|profile| profile.enabled) {
+ profile.visible_lines += 1;
+ profile.slice_requests += 1;
+ if line.spans.is_empty() {
+ profile.plain_lines += 1;
+ } else {
+ profile.highlighted_lines += 1;
+ }
+ }
+
+ let line_y = line_top.floor().max(0.0) as usize;
+ self.paint_right_sidebar_file_preview_selection_for_line(
+ layers,
+ chrome,
+ line,
+ idx,
+ horizontal_offset,
+ visible_columns,
+ text_x,
+ line_y,
+ line_height,
+ cell_width,
+ )?;
+ let line_number_lookup = self.paint_ui_title_text_cached(
+ layers,
+ ui_font,
+ &ui_metrics,
+ &(idx + 1).to_string(),
+ body_x,
+ line_y,
+ number_width,
+ muted_fg.mul_alpha(0.72),
+ )?;
+ if let Some(profile) = profile.as_deref_mut() {
+ profile.record_shape_lookup(line_number_lookup);
+ }
+
+ let text_lookup = if line.char_count <= FILE_PREVIEW_FULL_LINE_SHAPE_MAX_COLS {
+ // Fast path: shape the whole line once (cached) and translate/clip it
+ // for the current horizontal offset, so panning never re-shapes.
+ self.paint_full_line_preview_text(
+ layers,
+ ui_font,
+ ui_metrics,
+ idx,
+ line,
+ horizontal_offset,
+ text_x,
+ line_y,
+ text_width,
+ foreground,
+ )?
+ } else if line.spans.is_empty() {
+ // Fallback for pathological ultra-long lines: render only the visible
+ // window (horizontal scroll re-shapes, but such lines are rare). Clip
+ // at the edge (no "..."); the horizontal scrollbar shows there's more.
+ let visible_text =
+ self.cached_plain_preview_slice(idx, line, horizontal_offset, paint_columns);
+ self.paint_ui_title_text_cached(
+ layers,
+ ui_font,
+ &ui_metrics,
+ &visible_text,
+ text_x,
+ line_y,
+ text_width,
+ foreground,
+ )?
+ } else {
+ self.paint_highlighted_preview_line(
+ layers,
+ ui_font,
+ ui_metrics,
+ idx,
+ line,
+ horizontal_offset,
+ paint_columns,
+ text_x,
+ line_y,
+ text_width,
+ foreground,
+ )?
+ };
+ if let Some(profile) = profile.as_deref_mut() {
+ profile.record_shape_lookup(text_lookup);
+ }
+
+ Ok(false)
+ }
+
#[allow(clippy::too_many_arguments)]
fn paint_right_sidebar_file_preview_selection_for_line(
&self,
@@ -3750,7 +4115,7 @@ impl crate::TermWindow {
return Ok(());
}
- let line_len = line.plain.chars().count();
+ let line_len = line.char_count;
let selection_start = if line_idx == start.line {
start.column
} else {
@@ -3965,6 +4330,7 @@ impl crate::TermWindow {
layers: &mut TripleLayerQuadAllocator,
ui_font: &Rc<LoadedFont>,
ui_metrics: RenderMetrics,
+ line_index: usize,
line: &RightSidebarFilePreviewLine,
horizontal_offset: usize,
visible_columns: usize,
@@ -3972,25 +4338,25 @@ impl crate::TermWindow {
y: usize,
width: usize,
fallback: LinearRgba,
- ) -> anyhow::Result<()> {
+ ) -> anyhow::Result<UiShapeCacheLookup> {
if width == 0 || visible_columns == 0 {
- return Ok(());
+ return Ok(UiShapeCacheLookup::Skipped);
}
// Build the visible window's text + a per-character colour list from the
// spans, then shape it in a single call. Shaping once per line (instead
// of once per coloured span) is what keeps scrolling smooth.
- let (visible_text, colors) =
- preview_visible_colored(line, horizontal_offset, visible_columns);
- if visible_text.is_empty() {
- return Ok(());
+ let visible =
+ self.cached_colored_preview_slice(line_index, line, horizontal_offset, visible_columns);
+ if visible.text.is_empty() {
+ return Ok(UiShapeCacheLookup::Skipped);
}
- self.paint_ui_colored_text(
+ self.paint_ui_colored_text_cached(
layers,
ui_font,
&ui_metrics,
- &visible_text,
- &colors,
+ &visible.text,
+ &visible.colors,
fallback,
x,
y,
@@ -3998,6 +4364,127 @@ impl crate::TermWindow {
)
}
+ /// Horizontal-scroll fast path: shape the whole line once (shared shape
+ /// cache, keyed on the full line text so it is stable across every
+ /// horizontal offset), then translate the cached glyph run left by the pixel
+ /// width of the scrolled-past columns and clip it to the text column. Panning
+ /// only recomputes the translation; it never re-shapes or re-slices.
+ #[allow(clippy::too_many_arguments)]
+ fn paint_full_line_preview_text(
+ &self,
+ layers: &mut TripleLayerQuadAllocator,
+ ui_font: &Rc<LoadedFont>,
+ ui_metrics: RenderMetrics,
+ line_index: usize,
+ line: &RightSidebarFilePreviewLine,
+ horizontal_offset: usize,
+ text_x: usize,
+ line_y: usize,
+ text_width: usize,
+ foreground: LinearRgba,
+ ) -> anyhow::Result<UiShapeCacheLookup> {
+ if line.plain.is_empty() || text_width == 0 {
+ return Ok(UiShapeCacheLookup::Skipped);
+ }
+ let (shaped, lookup) = self.cached_ui_shape(ui_font, &ui_metrics, &line.plain)?;
+ if shaped.is_empty() {
+ return Ok(lookup);
+ }
+
+ // Pixel offset of the first visible column within the cached run. The
+ // glyph at `horizontal_offset` lands exactly on `text_x`, so columns to
+ // its left are fully clipped (no partial glyph bleeds into the gutter).
+ let start_byte = line
+ .plain
+ .char_indices()
+ .nth(horizontal_offset)
+ .map(|(byte, _)| byte)
+ .unwrap_or(line.plain.len());
+ let mut start_px = 0.0f32;
+ for info in shaped.iter() {
+ if info.cluster >= start_byte {
+ break;
+ }
+ start_px += info.glyph.x_advance.get() as f32;
+ }
+
+ let start_x = text_x as f32 - start_px;
+ let clip_left = text_x as f32;
+ let clip_right = (text_x + text_width) as f32;
+ let y = line_y as f32;
+
+ if line.spans.is_empty() {
+ self.paint_cached_ui_shape_clipped(
+ layers,
+ &ui_metrics,
+ &shaped,
+ start_x,
+ y,
+ clip_left,
+ clip_right,
+ |_| foreground,
+ )?;
+ } else {
+ let colors = self.cached_full_line_colors(line_index, line);
+ self.paint_cached_ui_shape_clipped(
+ layers,
+ &ui_metrics,
+ &shaped,
+ start_x,
+ y,
+ clip_left,
+ clip_right,
+ |info| colors.get(info.cluster).copied().unwrap_or(foreground),
+ )?;
+ }
+
+ Ok(lookup)
+ }
+
+ fn cached_plain_preview_slice(
+ &self,
+ line_index: usize,
+ line: &RightSidebarFilePreviewLine,
+ horizontal_offset: usize,
+ paint_columns: usize,
+ ) -> String {
+ let key = RightSidebarFilePreviewSliceCacheKey {
+ generation: self.right_sidebar_file_preview_generation,
+ line_index,
+ horizontal_offset,
+ paint_columns,
+ highlighted: false,
+ };
+ self.cached_right_sidebar_file_preview_slice(key, || {
+ RightSidebarFilePreviewSliceCacheValue {
+ text: preview_text_slice(&line.plain, horizontal_offset, paint_columns)
+ .into_owned(),
+ colors: Vec::new(),
+ }
+ })
+ .text
+ }
+
+ fn cached_colored_preview_slice(
+ &self,
+ line_index: usize,
+ line: &RightSidebarFilePreviewLine,
+ horizontal_offset: usize,
+ paint_columns: usize,
+ ) -> RightSidebarFilePreviewSliceCacheValue {
+ let key = RightSidebarFilePreviewSliceCacheKey {
+ generation: self.right_sidebar_file_preview_generation,
+ line_index,
+ horizontal_offset,
+ paint_columns,
+ highlighted: true,
+ };
+ self.cached_right_sidebar_file_preview_slice(key, || {
+ let (text, colors) = preview_visible_colored(line, horizontal_offset, paint_columns);
+ RightSidebarFilePreviewSliceCacheValue { text, colors }
+ })
+ }
+
#[allow(clippy::too_many_arguments)]
fn paint_snippets_list(
&mut self,
@@ -4718,8 +5205,8 @@ impl crate::TermWindow {
// Selection highlight, behind the glyphs.
if let Some((sel_start, sel_end)) = input.caret_selection_range() {
- let vis_start = sel_start.max(first);
- let vis_end = sel_end.max(first);
+ let vis_start = sel_start.max(first).min(chars.len());
+ let vis_end = sel_end.max(first).min(chars.len());
if vis_end > vis_start {
let start_prefix: String = chars[first..vis_start].iter().collect();
let end_prefix: String = chars[first..vis_end].iter().collect();
@@ -5029,6 +5516,7 @@ fn preview_plain_lines_from_text(text: &str) -> Vec<RightSidebarFilePreviewLine>
fn preview_line_from_plain(line: &str) -> RightSidebarFilePreviewLine {
RightSidebarFilePreviewLine {
plain: line.to_string(),
+ char_count: line.chars().count(),
spans: Vec::new(),
}
}
@@ -5039,6 +5527,7 @@ fn preview_line_from_highlighted_ranges(
default_color: LinearRgba,
) -> RightSidebarFilePreviewLine {
let mut plain = String::new();
+ let mut char_count = 0usize;
let mut spans = Vec::new();
for (style, text) in ranges {
@@ -5046,9 +5535,12 @@ fn preview_line_from_highlighted_ranges(
continue;
}
let color = syntect_color_to_linear(style.foreground);
+ let span_char_count = text.chars().count();
plain.push_str(text);
+ char_count = char_count.saturating_add(span_char_count);
spans.push(RightSidebarFilePreviewSpan {
text: text.to_string(),
+ char_count: span_char_count,
color,
});
}
@@ -5056,14 +5548,21 @@ fn preview_line_from_highlighted_ranges(
// The un-highlighted remainder of a very long line is kept verbatim so no
// content is dropped; it just renders in the editor's default colour.
if !tail.is_empty() {
+ let span_char_count = tail.chars().count();
plain.push_str(tail);
+ char_count = char_count.saturating_add(span_char_count);
spans.push(RightSidebarFilePreviewSpan {
text: tail.to_string(),
+ char_count: span_char_count,
color: default_color,
});
}
- RightSidebarFilePreviewLine { plain, spans }
+ RightSidebarFilePreviewLine {
+ plain,
+ char_count,
+ spans,
+ }
}
fn syntect_color_to_linear(color: SyntectColor) -> LinearRgba {
@@ -5103,6 +5602,23 @@ fn estimated_file_preview_visible_columns(text_width: usize, cell_width: usize)
text_width / cell_width.max(1)
}
+/// Per-byte colours for a whole highlighted line: `colors[b]` is the colour of
+/// the character that byte `b` of `line.plain` belongs to. Spans concatenate to
+/// `line.plain`, so this aligns with a glyph's `cluster` (a byte offset) for the
+/// full-line horizontal-scroll fast path. Plain lines have no spans and use a
+/// uniform foreground instead.
+fn full_line_colors_by_byte(line: &RightSidebarFilePreviewLine) -> Vec<LinearRgba> {
+ let mut colors = Vec::with_capacity(line.plain.len());
+ for span in &line.spans {
+ for ch in span.text.chars() {
+ for _ in 0..ch.len_utf8() {
+ colors.push(span.color);
+ }
+ }
+ }
+ colors
+}
+
/// Collect the visible horizontal window of a highlighted line into a single
/// string plus a parallel per-character colour list, so the whole window can be
/// shaped in one call. `start_column`/`max_columns` are in characters.
@@ -5119,7 +5635,7 @@ fn preview_visible_colored(
if remaining == 0 {
break;
}
- let span_columns = span.text.chars().count();
+ let span_columns = span.char_count;
if skip >= span_columns {
skip -= span_columns;
continue;
@@ -5171,30 +5687,17 @@ fn preview_text_range(text: &str, start_column: usize, end_column: usize) -> Cow
}
}
-fn preview_visible_lines(
- lines: &[RightSidebarFilePreviewLine],
+fn preview_visible_line_range(
+ line_count: usize,
first_line: usize,
max_lines: usize,
-) -> Vec<(usize, &RightSidebarFilePreviewLine)> {
- if max_lines == 0 {
- return vec![];
- }
- if lines.is_empty() {
- return if first_line == 0 {
- static EMPTY_LINE: std::sync::OnceLock<RightSidebarFilePreviewLine> =
- std::sync::OnceLock::new();
- vec![(0, EMPTY_LINE.get_or_init(|| preview_line_from_plain("")))]
- } else {
- vec![]
- };
+) -> std::ops::Range<usize> {
+ if line_count == 0 || max_lines == 0 {
+ return 0..0;
}
-
- lines
- .iter()
- .enumerate()
- .skip(first_line)
- .take(max_lines)
- .collect()
+ let start = first_line.min(line_count);
+ let end = start.saturating_add(max_lines).min(line_count);
+ start..end
}
fn right_sidebar_file_row_metrics(ui_metrics: RenderMetrics) -> RightSidebarFileRowMetrics {
@@ -5344,7 +5847,15 @@ fn load_file_preview_image(path: &Path) -> anyhow::Result<RightSidebarFilePrevie
let bytes = fs::read(path).with_context(|| format!("read {}", path.display()))?;
let image_data = ImageDataType::EncodedFile(bytes);
+ // `dimensions()` only reads the header, so this is cheap and lets us reject
+ // decompression bombs *before* `cached_image` decodes the full RGBA bitmap.
let (width, height) = image_data.dimensions().context("decode image dimensions")?;
+ if !image_pixels_within_preview_budget(width, height) {
+ anyhow::bail!(
+ "image is too large to preview ({width}×{height}, over {} megapixels)",
+ FILE_PREVIEW_IMAGE_MAX_PIXELS / 1_000_000
+ );
+ }
Ok(RightSidebarFilePreviewImage {
data: Arc::new(ImageData::with_data(image_data)),
width,
@@ -5352,6 +5863,13 @@ fn load_file_preview_image(path: &Path) -> anyhow::Result<RightSidebarFilePrevie
})
}
+/// Whether an image of `width × height` is small enough to decode for preview
+/// without risking a huge RGBA allocation. Uses `u64` so the product cannot
+/// overflow for pathological dimensions.
+fn image_pixels_within_preview_budget(width: u32, height: u32) -> bool {
+ (width as u64).saturating_mul(height as u64) <= FILE_PREVIEW_IMAGE_MAX_PIXELS
+}
+
fn load_file_preview(path: &Path) -> (String, Option<String>, bool) {
let file = match fs::File::open(path) {
Ok(file) => file,
@@ -5431,6 +5949,50 @@ impl RightSidebarFileCharBag {
}
}
+/// Process-wide registry of weak references to file indexes, keyed by
+/// (root, project). Lets multiple windows on the same workspace share a single
+/// `Arc<RightSidebarFileIndex>` instead of each scanning and holding its own
+/// copy. Only weak refs live here, so an index is freed the moment the last
+/// window drops its strong ref (e.g. via the idle-release path).
+fn shared_file_index_registry(
+) -> &'static Mutex<HashMap<(PathBuf, String), Weak<RightSidebarFileIndex>>> {
+ static REGISTRY: OnceLock<Mutex<HashMap<(PathBuf, String), Weak<RightSidebarFileIndex>>>> =
+ OnceLock::new();
+ REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+/// Reuse a live shared index for `(root, project)` if one exists, otherwise scan
+/// and register it. The scan runs without holding the registry lock, so two
+/// windows racing on the same root may each scan once (harmless: both produce
+/// equivalent indexes and the last registration wins). A cancelled scan returns
+/// `Err` and is never registered.
+fn build_or_reuse_shared_file_index(
+ root: &Path,
+ project_name: &str,
+ cancel: &AtomicBool,
+) -> Result<Arc<RightSidebarFileIndex>, String> {
+ let key = (root.to_path_buf(), project_name.to_string());
+ if let Some(existing) = shared_file_index_registry()
+ .lock()
+ .ok()
+ .and_then(|registry| registry.get(&key).and_then(Weak::upgrade))
+ {
+ return Ok(existing);
+ }
+
+ let index = Arc::new(build_right_sidebar_file_index_with_cancel(
+ root,
+ project_name,
+ cancel,
+ )?);
+
+ if let Ok(mut registry) = shared_file_index_registry().lock() {
+ registry.insert(key, Arc::downgrade(&index));
+ registry.retain(|_, weak| weak.strong_count() > 0);
+ }
+ Ok(index)
+}
+
#[cfg(test)]
fn build_right_sidebar_file_index(
root: &Path,
@@ -5979,20 +6541,23 @@ fn snippet_cursor_visible(now_ms: u128, blink_ms: u64) -> bool {
#[cfg(test)]
mod tests {
use super::{
- build_right_sidebar_file_index, load_file_preview, load_file_preview_image, naturalish_cmp,
- path_key, preview_line_count, preview_lines_from_text, preview_plain_lines_from_text,
- preview_text_range, preview_visible_lines, right_sidebar_file_browse_rows_from_index,
- right_sidebar_file_row_metrics, right_sidebar_open_with_cache_key,
- search_right_sidebar_file_index, snippet_cursor_visible, snippet_run_buffer,
- sorted_open_with_candidates, visible_file_row_range, wrap_snippet_text_for_width,
- FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT, FILE_PREVIEW_MAX_BYTES,
+ build_right_sidebar_file_index, full_line_colors_by_byte, image_pixels_within_preview_budget,
+ load_file_preview, load_file_preview_image, naturalish_cmp, path_key, preview_line_count,
+ preview_lines_from_text, preview_plain_lines_from_text,
+ preview_text_range, preview_visible_colored, preview_visible_line_range,
+ right_sidebar_file_browse_rows_from_index, right_sidebar_file_row_metrics,
+ right_sidebar_open_with_cache_key, search_right_sidebar_file_index, snippet_cursor_visible,
+ snippet_run_buffer, sorted_open_with_candidates, visible_file_row_range,
+ wrap_snippet_text_for_width, FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT, FILE_PREVIEW_MAX_BYTES,
};
+ use crate::termwindow::{RightSidebarFilePreviewLine, RightSidebarFilePreviewSpan};
use crate::utilsprites::RenderMetrics;
use std::collections::HashSet;
use std::fs;
use std::io::Cursor;
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use wezterm_font::units::PixelLength;
+ use window::color::LinearRgba;
use window::Size;
fn test_render_metrics(cell_height: isize, cell_width: isize) -> RenderMetrics {
@@ -6205,22 +6770,20 @@ mod tests {
}
#[test]
- fn preview_visible_lines_only_returns_requested_window() {
+ fn preview_visible_line_range_only_returns_requested_window() {
let cached_lines = preview_plain_lines_from_text("one\ntwo\nthree\nfour");
- let lines = preview_visible_lines(&cached_lines, 1, 2);
+ let range = preview_visible_line_range(cached_lines.len(), 1, 2);
assert_eq!(preview_line_count(&cached_lines), 4);
- assert_eq!(lines[0].0, 1);
- assert_eq!(lines[0].1.plain, "two");
- assert_eq!(lines[1].0, 2);
- assert_eq!(lines[1].1.plain, "three");
+ assert_eq!(range, 1..3);
+ assert_eq!(cached_lines[range.start].plain, "two");
+ assert_eq!(cached_lines[range.end - 1].plain, "three");
let empty_lines = preview_plain_lines_from_text("");
assert_eq!(preview_line_count(&empty_lines), 1);
- let visible = preview_visible_lines(&empty_lines, 0, 2);
- assert_eq!(visible.len(), 1);
- assert_eq!(visible[0].0, 0);
- assert_eq!(visible[0].1.plain, "");
+ assert_eq!(preview_visible_line_range(empty_lines.len(), 0, 2), 0..1);
+ assert_eq!(empty_lines[0].plain, "");
+ assert_eq!(preview_visible_line_range(0, 0, 2), 0..0);
}
#[test]
@@ -6259,6 +6822,18 @@ mod tests {
assert!(large.chevron_size <= 24);
}
+ #[test]
+ fn preview_image_pixel_budget_rejects_decompression_bombs() {
+ // Typical sizes are allowed.
+ assert!(image_pixels_within_preview_budget(1920, 1080)); // 2 MP
+ assert!(image_pixels_within_preview_budget(4096, 2160)); // ~8.8 MP (4K)
+ assert!(image_pixels_within_preview_budget(4000, 4000)); // 16 MP (== budget)
+ // Bombs are rejected, and the u64 product cannot overflow.
+ assert!(!image_pixels_within_preview_budget(8000, 8000)); // 64 MP
+ assert!(!image_pixels_within_preview_budget(100_000, 100_000));
+ assert!(!image_pixels_within_preview_budget(u32::MAX, u32::MAX));
+ }
+
#[test]
fn open_with_cache_key_uses_extension_when_available() {
assert_eq!(
@@ -6339,6 +6914,86 @@ mod tests {
);
}
+ #[test]
+ fn preview_lines_store_character_counts() {
+ let plain = preview_plain_lines_from_text("ab你好cd");
+ assert_eq!(plain[0].char_count, 6);
+
+ let highlighted =
+ preview_lines_from_text(std::path::Path::new("script.py"), "def 你好():", true);
+ let line = &highlighted[0];
+ assert_eq!(line.char_count, line.plain.chars().count());
+ assert_eq!(
+ line.spans.iter().map(|span| span.char_count).sum::<usize>(),
+ line.char_count
+ );
+ }
+
+ #[test]
+ fn preview_visible_colored_slices_by_character_columns() {
+ let green = LinearRgba::with_components(0.0, 1.0, 0.0, 1.0);
+ let blue = LinearRgba::with_components(0.0, 0.0, 1.0, 1.0);
+ let line = RightSidebarFilePreviewLine {
+ plain: "ab你好cd".to_string(),
+ char_count: 6,
+ spans: vec![
+ RightSidebarFilePreviewSpan {
+ text: "ab".to_string(),
+ char_count: 2,
+ color: green,
+ },
+ RightSidebarFilePreviewSpan {
+ text: "你好cd".to_string(),
+ char_count: 4,
+ color: blue,
+ },
+ ],
+ };
+
+ let (text, colors) = preview_visible_colored(&line, 2, 2);
+ assert_eq!(text, "你好");
+ assert_eq!(colors, vec![blue, blue]);
+ }
+
+ #[test]
+ fn full_line_colors_map_each_byte_to_its_span_color() {
+ let green = LinearRgba::with_components(0.0, 1.0, 0.0, 1.0);
+ let blue = LinearRgba::with_components(0.0, 0.0, 1.0, 1.0);
+ // "ab你好cd": a=0 b=1 你=2..5 好=5..8 c=8 d=9 -> 10 bytes; 你/好 are 3
+ // bytes each. The full-line h-scroll painter indexes this by a glyph's
+ // `cluster` (a byte offset), so each byte must carry its span's colour.
+ let line = RightSidebarFilePreviewLine {
+ plain: "ab你好cd".to_string(),
+ char_count: 6,
+ spans: vec![
+ RightSidebarFilePreviewSpan {
+ text: "ab你".to_string(),
+ char_count: 3,
+ color: green,
+ },
+ RightSidebarFilePreviewSpan {
+ text: "好cd".to_string(),
+ char_count: 3,
+ color: blue,
+ },
+ ],
+ };
+
+ let colors = full_line_colors_by_byte(&line);
+ assert_eq!(colors.len(), line.plain.len());
+ // bytes 0..5 (a, b, 你) -> green; 5..10 (好, c, d) -> blue.
+ for b in 0..5 {
+ assert_eq!(colors[b], green, "byte {b} should be green");
+ }
+ for b in 5..10 {
+ assert_eq!(colors[b], blue, "byte {b} should be blue");
+ }
+ // A multi-byte glyph's cluster maps to the right colour: 你 at byte 2,
+ // 好 at byte 5.
+ assert_eq!(colors[2], green);
+ assert_eq!(colors[5], blue);
+ }
+
#[test]
fn preview_keeps_long_lines_intact() {
// A line far longer than the highlight cap must be preserved verbatim
diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rs
index 60a29cf1..afae942c 100644
--- a/wezterm-gui/src/termwindow/ui/sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs
@@ -1,4 +1,3 @@
-use crate::customglyph::BlockKey;
use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};
use crate::termwindow::render::corners::{
BOTTOM_LEFT_ROUNDED_CORNER, BOTTOM_RIGHT_ROUNDED_CORNER, TOP_LEFT_ROUNDED_CORNER,
@@ -18,14 +17,12 @@ use crate::ui::UiPalette;
use crate::utilsprites::RenderMetrics;
use crate::workspace_threads;
use anyhow::Context;
-use finl_unicode::grapheme_clusters::Graphemes;
use mux::Mux;
use std::borrow::Cow;
use std::rc::Rc;
-use wezterm_bidi::Direction;
use wezterm_font::LoadedFont;
use window::color::LinearRgba;
-use window::{MouseEventKind as WMEK, RectF, WindowOps};
+use window::{MouseEventKind as WMEK, RectF};
const SIDEBAR_SCROLLBAR_VISIBLE_MS: u64 = 900;
const SIDEBAR_SETTINGS_FOOTER_HEIGHT: usize = 72;
@@ -2245,7 +2242,8 @@ impl crate::TermWindow {
return Ok(());
}
- self.paint_ui_title_text(layers, font, &metrics, &text, x, y, width, foreground)
+ self.paint_ui_title_text_cached(layers, font, &metrics, &text, x, y, width, foreground)?;
+ Ok(())
}
fn ellipsize_sidebar_text<'a>(
@@ -2259,33 +2257,46 @@ impl crate::TermWindow {
return Ok(Cow::Borrowed(""));
}
- if self.sidebar_text_width(font, text)? <= max_width {
+ // Shape the whole string ONCE via the shared shape cache, then measure
+ // and cut from the cached glyph run. The previous implementation
+ // re-measured a growing prefix grapheme-by-grapheme, each re-shaping the
+ // string (`sidebar_text_width`), which was O(N^2) harfbuzz work per row
+ // every frame and made the search list (long `display_path` names) crawl.
+ let metrics = RenderMetrics::with_font_metrics(&font.metrics());
+ let (shaped, _) = self.cached_ui_shape(font, &metrics, text)?;
+ let total: f32 = shaped
+ .iter()
+ .map(|info| info.glyph.x_advance.get() as f32)
+ .sum();
+ if total <= max_width {
return Ok(Cow::Borrowed(text));
}
const ELLIPSIS: &str = "...";
- if self.sidebar_text_width(font, ELLIPSIS)? > max_width {
- let mut fallback = String::new();
- for dot_count in 1..=ELLIPSIS.len() {
- let candidate = ".".repeat(dot_count);
- if self.sidebar_text_width(font, &candidate)? > max_width {
- break;
- }
- fallback = candidate;
- }
- return Ok(Cow::Owned(fallback));
+ let ellipsis_w = self.sidebar_text_width(font, ELLIPSIS)?;
+ if ellipsis_w > max_width {
+ // Not even the ellipsis fits; emit as many dots as do (matches the
+ // previous degenerate fallback).
+ let dot_w = self.sidebar_text_width(font, ".")?;
+ let dots = if dot_w > 0.0 {
+ ((max_width / dot_w).floor() as usize).min(ELLIPSIS.len())
+ } else {
+ 0
+ };
+ return Ok(Cow::Owned(".".repeat(dots)));
}
- let mut output = String::new();
- for grapheme in Graphemes::new(text) {
- let mut candidate = output.clone();
- candidate.push_str(grapheme);
- candidate.push_str(ELLIPSIS);
- if self.sidebar_text_width(font, &candidate)? > max_width {
- break;
- }
- output.push_str(grapheme);
- }
+ // Keep the largest prefix (at a glyph-cluster boundary) that still
+ // leaves room for the ellipsis.
+ let budget = max_width - ellipsis_w;
+ let glyphs: Vec<(f32, usize)> = shaped
+ .iter()
+ .map(|info| (info.glyph.x_advance.get() as f32, info.cluster))
+ .collect();
+ let cut_byte = ellipsize_cut_byte(&glyphs, text.len(), budget).min(text.len());
+
+ let mut output = String::with_capacity(cut_byte + ELLIPSIS.len());
+ output.push_str(&text[..cut_byte]);
output.push_str(ELLIPSIS);
Ok(Cow::Owned(output))
}
@@ -2295,19 +2306,13 @@ impl crate::TermWindow {
font: &Rc<LoadedFont>,
text: &str,
) -> anyhow::Result<f32> {
- let Some(window) = self.window.as_ref().cloned() else {
- return Ok(0.0);
- };
- let infos = font.shape(
- text,
- move || window.notify(crate::termwindow::TermWindowNotif::InvalidateShapeCache),
- BlockKey::filter_out_synthetic,
- None,
- Direction::LeftToRight,
- None,
- None,
- )?;
- Ok(infos.iter().map(|info| info.x_advance.get() as f32).sum())
+ // Route through the shared shape cache so repeated width queries (the
+ // ellipsize fit-check, button sizing, etc.) become cache hits and stay
+ // consistent with the cached painters. Metrics are derived from the font
+ // exactly as the sidebar paint path does
+ // (`RenderMetrics::with_font_metrics(&ui_font.metrics())`).
+ let metrics = RenderMetrics::with_font_metrics(&font.metrics());
+ self.cached_ui_text_advance(font, &metrics, text)
}
pub(crate) fn paint_sidebar_icon(
@@ -2410,3 +2415,70 @@ impl crate::TermWindow {
Ok(())
}
}
+
+/// Largest byte prefix (at a glyph-cluster boundary) whose cumulative advance
+/// fits in `budget`. `glyphs` are `(advance_px, cluster)` pairs in visual order,
+/// where `cluster` is the source byte offset of each glyph. Cutting at the
+/// *next* glyph's cluster guarantees we never split a multi-byte character or a
+/// shaped cluster. Used by `ellipsize_sidebar_text` to truncate in a single
+/// shaping pass instead of re-shaping a growing prefix per grapheme.
+fn ellipsize_cut_byte(glyphs: &[(f32, usize)], text_len: usize, budget: f32) -> usize {
+ let mut acc = 0.0f32;
+ let mut cut = 0usize;
+ for idx in 0..glyphs.len() {
+ let advance = glyphs[idx].0;
+ if acc + advance > budget {
+ break;
+ }
+ acc += advance;
+ cut = glyphs.get(idx + 1).map(|next| next.1).unwrap_or(text_len);
+ }
+ cut
+}
+
+#[cfg(test)]
+mod tests {
+ use super::ellipsize_cut_byte;
+
+ // Build (advance, cluster) pairs for an ASCII or per-char string where every
+ // char is one glyph of `advance` px and the cluster is its byte offset.
+ fn glyphs_per_char(text: &str, advance: f32) -> Vec<(f32, usize)> {
+ text.char_indices().map(|(byte, _)| (advance, byte)).collect()
+ }
+
+ #[test]
+ fn cut_keeps_whole_prefix_when_everything_fits() {
+ let text = "abcdef";
+ let glyphs = glyphs_per_char(text, 10.0);
+ // budget large enough for all 6 glyphs.
+ assert_eq!(ellipsize_cut_byte(&glyphs, text.len(), 1000.0), text.len());
+ }
+
+ #[test]
+ fn cut_stops_at_budget() {
+ let text = "abcdef";
+ let glyphs = glyphs_per_char(text, 10.0);
+ // budget for ~3.5 glyphs -> keep 3 (bytes 0..3).
+ assert_eq!(ellipsize_cut_byte(&glyphs, text.len(), 35.0), 3);
+ }
+
+ #[test]
+ fn cut_never_splits_multibyte_chars() {
+ // "ab你好cd": bytes a=0 b=1 你=2..5 好=5..8 c=8 d=9 (你/好 are 3 bytes each).
+ let text = "ab你好cd";
+ let glyphs = glyphs_per_char(text, 10.0);
+ // Budget for 3 glyphs (a, b, 你) -> cut at byte 5 (start of 好), the
+ // boundary AFTER the full multi-byte char, never inside it.
+ let cut = ellipsize_cut_byte(&glyphs, text.len(), 35.0);
+ assert_eq!(cut, 5);
+ assert!(text.is_char_boundary(cut));
+ assert_eq!(&text[..cut], "ab你");
+ }
+
+ #[test]
+ fn cut_is_zero_when_nothing_fits() {
+ let text = "abc";
+ let glyphs = glyphs_per_char(text, 10.0);
+ assert_eq!(ellipsize_cut_byte(&glyphs, text.len(), 5.0), 0);
+ }
+}
diff --git a/wezterm-gui/src/ui/state.rs b/wezterm-gui/src/ui/state.rs
index cfd8e2b2..04742c03 100644
--- a/wezterm-gui/src/ui/state.rs
+++ b/wezterm-gui/src/ui/state.rs
@@ -186,13 +186,15 @@ impl TextInputState {
}
pub(crate) fn caret_selection_range(&self) -> Option<(usize, usize)> {
- let anchor = self.selection_anchor?;
- if anchor == self.cursor {
+ let len = self.char_len();
+ let anchor = self.selection_anchor?.min(len);
+ let cursor = self.cursor.min(len);
+ if anchor == cursor {
None
- } else if anchor < self.cursor {
- Some((anchor, self.cursor))
+ } else if anchor < cursor {
+ Some((anchor, cursor))
} else {
- Some((self.cursor, anchor))
+ Some((cursor, anchor))
}
}
@@ -595,6 +597,16 @@ mod text_input_tests {
assert_eq!(i.text, "hellohi world");
}
+ #[test]
+ fn stale_selection_range_is_clamped_to_current_text() {
+ let mut i = input("abc");
+ i.cursor = 0;
+ i.selection_anchor = Some(4);
+
+ assert_eq!(i.caret_selection_range(), Some((0, 3)));
+ assert_eq!(i.caret_selected_text().as_deref(), Some("abc"));
+ }
+
#[test]
fn plain_move_collapses_selection_to_an_edge() {
let mut i = input("abcd");