Skip to content

Visual Studio Code, rebuilt in Rust

Rust

perf(minimap): copy unchanged minimap rows from the last frame

rokartur6baca3e42aaf
diff --git a/native/crates/app/src/editor/minimap.rs b/native/crates/app/src/editor/minimap.rs
index 890e1bd3481..6539379c123 100644
--- a/native/crates/app/src/editor/minimap.rs
+++ b/native/crates/app/src/editor/minimap.rs
@@ -572,6 +572,7 @@ pub fn x_offset_for_column(text: &str, column: usize, tab_size: usize, char_widt
}
/// What `MinimapOptions` reads from the theme for the text canvas.
+#[derive(Clone, PartialEq)]
pub struct LinesColors {
/// `minimap.background`, else the editor background.
pub background: [u8; 4],
@@ -583,9 +584,23 @@ pub struct LinesColors {
pub use_lighter_font: bool,
}
-/// `InnerMinimap.renderLines` drawn whole, without reusing the rows of the last frame: the lines of `layout`, 1-based
-/// view lines, below `top_padding_line_count` empty rows. `line` gives a line's text and its color runs.
-pub fn render_lines<'a>(info: &MinimapLayoutInfo, layout: &MinimapLayout, renderer: &CharRenderer, colors: &LinesColors, tab_size: usize, line: impl Fn(usize) -> (std::borrow::Cow<'a, str>, Vec<(usize, [u8; 3])>)) -> MinimapImage {
+/// A line's text and color runs: with the style, all its pixels depend on.
+type LineKey = (String, Vec<(usize, [u8; 3])>);
+
+/// `RenderData`: the last `render_lines` image with the style it was drawn in, and from `start_line_number` on each
+/// line with its first row, `None` for a line the image cuts.
+pub struct RenderedLines {
+ pub image: MinimapImage,
+ style: (MinimapLayoutInfo, LinesColors, usize),
+ start_line_number: usize,
+ lines: Vec<(LineKey, Option<usize>)>,
+}
+
+/// `InnerMinimap.renderLines`: the lines of `layout`, 1-based view lines, below `top_padding_line_count` empty rows.
+/// `line` gives a line's text and its color runs. As `_renderUntouchedLines`, a line `previous` drew in the same
+/// style with the same text and colors is copied from it; upstream drops a changed line from it on its change events.
+pub fn render_lines<'a>(info: &MinimapLayoutInfo, layout: &MinimapLayout, renderer: &CharRenderer, colors: &LinesColors, tab_size: usize, previous: Option<&RenderedLines>, line: impl Fn(usize) -> (std::borrow::Cow<'a, str>, Vec<(usize, [u8; 3])>)) -> RenderedLines {
+ let style_key = (*info, colors.clone(), tab_size);
let mut image = MinimapImage::new(info.canvas_inner_width as usize, info.canvas_inner_height as usize, colors.background);
let base_char_height = if info.render_characters { BASE_CHAR_HEIGHT } else { BASE_CHAR_HEIGHT + 1 };
let render_line_height = (base_char_height * info.scale) as f64;
@@ -608,13 +623,28 @@ pub fn render_lines<'a>(info: &MinimapLayoutInfo, layout: &MinimapLayout, render
tab_size,
};
let line_height = info.line_height as usize;
+ // A glyph taller than its line (blocks at line height 2) draws into the next line's rows, which a copy would miss.
+ let previous = previous.filter(|previous| previous.style == style_key && render_line_height <= info.line_height);
+ let row_bytes = line_height * image.width * 4;
+ let mut lines = Vec::new();
let mut dy = layout.top_padding_line_count * line_height;
for line_number in layout.start_line_number..=layout.end_line_number {
let (text, runs) = line(line_number);
- render_line(&mut image, &style, dy + inner_line_padding, &text, &runs);
+ let key = (text.into_owned(), runs);
+ let whole = dy + line_height <= image.height;
+ let start = dy * image.width * 4;
+ let drawn = previous.and_then(|previous| {
+ let (drawn_key, source) = previous.lines.get(line_number.checked_sub(previous.start_line_number)?)?;
+ Some((previous, (*source)? * image.width * 4)).filter(|_| *drawn_key == key)
+ });
+ match drawn {
+ Some((previous, source)) if whole => image.data[start..start + row_bytes].copy_from_slice(&previous.image.data[source..source + row_bytes]),
+ _ => render_line(&mut image, &style, dy + inner_line_padding, &key.0, &key.1),
+ }
+ lines.push((key, whole.then_some(dy)));
dy += line_height;
}
- image
+ RenderedLines { image, style: style_key, start_line_number: layout.start_line_number, lines }
}
/// A range of view lines (1-based) and char columns (0-based), start before end.
@@ -880,4 +910,22 @@ mod tests {
assert_eq!(painted, [12, 14]);
assert_eq!(&image.data[48..52], &[100, 50, 25, 255]);
}
+
+ #[test]
+ fn rows_copied_from_the_last_frame_match_a_whole_redraw() {
+ let info = info(0., 60., true, false, 1, 2., (60., 40.));
+ let renderer = CharRenderer::create(1);
+ let colors = LinesColors { background: [30, 30, 30, 255], default_background: [30, 30, 30], foreground_alpha: 255, use_lighter_font: false };
+ let lines = ["const a = 1;", "\tlet b = a + 2;", "", "return b;", "// done", "x"];
+ let layout = |start: usize| MinimapLayout { scroll_top: 0., scroll_height: 0., slider_needed: false, computed_slider_ratio: 1., slider_top: 0., slider_height: 0., top_padding_line_count: 1, start_line_number: start, end_line_number: start + 3 };
+ let line = |edited: bool| move |number: usize| {
+ let text = if edited && number == 4 { "return c;" } else { lines[number - 1] };
+ (std::borrow::Cow::Borrowed(text), vec![(4, [200, 100, 50]), (text.len(), [90, 180, 240])])
+ };
+ let first = render_lines(&info, &layout(1), &renderer, &colors, 4, None, line(false));
+ let scrolled = render_lines(&info, &layout(2), &renderer, &colors, 4, Some(&first), line(true));
+ let whole = render_lines(&info, &layout(2), &renderer, &colors, 4, None, line(true));
+ assert!(scrolled.image.data == whole.image.data);
+ assert!(first.image.data != whole.image.data);
+ }
}
diff --git a/native/crates/app/src/workbench/minimap_view.rs b/native/crates/app/src/workbench/minimap_view.rs
index 4a02c16608d..0731e943a4a 100644
--- a/native/crates/app/src/workbench/minimap_view.rs
+++ b/native/crates/app/src/workbench/minimap_view.rs
@@ -16,7 +16,7 @@ use serde_json::json;
use super::Workbench;
use crate::editor::minimap::{
- CharRenderer, LinesColors, MINIMAP_GUTTER_WIDTH, MinimapLayout, MinimapLayoutInfo, MinimapLayoutInput, MinimapOptions, MinimapRange, MinimapSampling, MinimapSide, MinimapSize,
+ CharRenderer, LinesColors, MINIMAP_GUTTER_WIDTH, MinimapLayout, MinimapLayoutInfo, MinimapLayoutInput, MinimapOptions, MinimapRange, MinimapSampling, MinimapSide, MinimapSize, RenderedLines,
SliderOptions, compute_minimap_layout, contained_minimap_line_count, decoration_fills, render_lines,
};
use crate::editor::folding::FoldDecoration;
@@ -42,6 +42,8 @@ pub(super) struct Minimap {
/// `_lastRenderData.renderedLayout` with the model it showed: the next layout keeps the lines from jumping back.
rendered: Cell<Option<(u32, MinimapLayout)>>,
image: RefCell<Option<Arc<RenderImage>>>,
+ /// The RGBA lines behind `image`, whose unchanged rows the next frame copies.
+ lines: RefCell<Option<RenderedLines>>,
/// Replaced images, dropped from the sprite atlas at the next paint.
stale: Rc<RefCell<Vec<Arc<RenderImage>>>>,
/// Window y of the minimap, recorded at paint, to turn a press into a minimap row.
@@ -339,20 +341,23 @@ impl Workbench {
let tab_size = document.indentation.tab_size;
let renderer = CharRenderer::create(info.scale);
let token_colors = crate::syntax::Tokenization::minimap_colors(&self.theme);
- let mut image = render_lines(info, layout, &renderer, &colors, tab_size, |minimap_line| {
+ let mut lines = self.minimap.lines.borrow_mut();
+ let rendered = render_lines(info, layout, &renderer, &colors, tab_size, lines.as_ref(), |minimap_line| {
let view_line = sampled_view_line(sampling, minimap_line);
let index = editor.model_line(view_line - 1);
editor.view_line_minimap_data(view_line - 1, document.tokens.minimap_runs(&self.theme, &token_colors, &document.lines, index))
});
+ let (width, height, mut data) = (rendered.image.width, rendered.image.height, rendered.image.data.clone());
+ *lines = Some(rendered);
// RenderImage holds BGRA.
- for pixel in image.data.chunks_exact_mut(4) {
+ for pixel in data.chunks_exact_mut(4) {
pixel.swap(0, 2);
}
let mut current = self.minimap.image.borrow_mut();
- if let Some(previous) = current.as_ref().filter(|previous| previous.as_bytes(0) == Some(image.data.as_slice())) {
+ if let Some(previous) = current.as_ref().filter(|previous| previous.as_bytes(0) == Some(data.as_slice())) {
return previous.clone();
}
- let buffer = RgbaImage::from_raw(image.width as u32, image.height as u32, image.data).expect("the buffer holds width * height pixels");
+ let buffer = RgbaImage::from_raw(width as u32, height as u32, data).expect("the buffer holds width * height pixels");
let next = Arc::new(RenderImage::new([Frame::new(buffer)]));
if let Some(previous) = current.replace(next.clone()) {
self.minimap.stale.borrow_mut().push(previous);
diff --git a/native/crates/textmate/src/theme.rs b/native/crates/textmate/src/theme.rs
index f515d3707e7..1211b855b70 100644
--- a/native/crates/textmate/src/theme.rs
+++ b/native/crates/textmate/src/theme.rs
@@ -3,6 +3,7 @@
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
+use std::hash::{BuildHasherDefault, Hasher};
use std::rc::{Rc, Weak};
use serde_json::Value;
@@ -29,12 +30,31 @@ pub struct Theme {
defaults: Style,
root: TrieElement,
match_cache: RefCell<HashMap<String, Rc<Vec<TrieRule>>>>,
- style_cache: RefCell<HashMap<*const ScopeStack, (Weak<ScopeStack>, Style)>>,
+ style_cache: RefCell<HashMap<*const ScopeStack, (Weak<ScopeStack>, Style), BuildHasherDefault<AddressHasher>>>,
/// The size at which `style_cache` drops the entries of dropped stacks.
style_cache_limit: Cell<usize>,
rules: Vec<Value>,
}
+/// Hashes an address with one multiply: every line's every token asks `style` each frame, where SipHash took a
+/// third of the lookup.
+#[derive(Default)]
+struct AddressHasher(u64);
+
+impl Hasher for AddressHasher {
+ fn write(&mut self, _: &[u8]) {
+ unreachable!("only addresses are hashed");
+ }
+
+ fn write_usize(&mut self, address: usize) {
+ self.0 = (address as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
+ }
+
+ fn finish(&self) -> u64 {
+ self.0
+ }
+}
+
struct ParsedRule {
scope: String,
parent_scopes: Option<Vec<String>>,