Skip to content

Visual Studio Code, rebuilt in Rust

Rust

perf(editor): keep token styles per scope stack, minimap colors per frame

rokartur17f9b6d5e47a
diff --git a/native/crates/app/src/syntax.rs b/native/crates/app/src/syntax.rs
index ea310260aaf..cb3cbb82ccb 100644
--- a/native/crates/app/src/syntax.rs
+++ b/native/crates/app/src/syntax.rs
@@ -173,15 +173,11 @@ impl Tokenization {
}
/// The minimap's view of line `index` (`getMinimapLinesRenderingData`): each token's end byte offset with
- /// its foreground. Bracket pair colors are decorations upstream, so the minimap does not show them.
- pub fn minimap_runs(&self, theme: &Theme, lines: &[String], index: usize) -> Vec<(usize, [u8; 3])> {
- let color_map = theme.tokens.color_map();
- let color = |id: usize| {
- let color = Rgba::try_from(color_map[id].as_str()).expect("the token color map holds hex colors");
- [color.r, color.g, color.b].map(|channel| (channel * 255.).round() as u8)
- };
+ /// its foreground. Bracket pair colors are decorations upstream, so the minimap does not show them. `colors` is
+ /// `theme.tokens.color_map()` as `minimap_colors` parses it.
+ pub fn minimap_runs(&self, theme: &Theme, colors: &[[u8; 3]], lines: &[String], index: usize) -> Vec<(usize, [u8; 3])> {
let text = &lines[index];
- let default_run = vec![(text.len(), color(1))];
+ let default_run = vec![(text.len(), colors[1])];
if self.grammar.is_none() {
return default_run;
}
@@ -191,7 +187,18 @@ impl Tokenization {
if tokens.is_empty() {
return default_run;
}
- tokens.iter().map(|token| (token.end.min(text.len()), color(theme.tokens.style(&token.scopes).foreground))).collect()
+ tokens.iter().map(|token| (token.end.min(text.len()), colors[theme.tokens.style(&token.scopes).foreground])).collect()
+ }
+
+ /// The token color map as the RGB bytes `minimap_runs` takes; index 0, "not set", is black.
+ pub fn minimap_colors(theme: &Theme) -> Vec<[u8; 3]> {
+ let color_map = theme.tokens.color_map();
+ let mut colors = vec![[0; 3]];
+ for hex in &color_map[1..] {
+ let color = Rgba::try_from(hex.as_str()).expect("the token color map holds hex colors");
+ colors.push([color.r, color.g, color.b].map(|channel| (channel * 255.).round() as u8));
+ }
+ colors
}
/// The byte offsets where `renderViewLine` starts a span on line `index`: a token whose style differs from the
diff --git a/native/crates/app/src/workbench/minimap_view.rs b/native/crates/app/src/workbench/minimap_view.rs
index e9fb1f11bf7..4a02c16608d 100644
--- a/native/crates/app/src/workbench/minimap_view.rs
+++ b/native/crates/app/src/workbench/minimap_view.rs
@@ -338,10 +338,11 @@ impl Workbench {
let document = &editor.document();
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 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, &document.lines, index))
+ editor.view_line_minimap_data(view_line - 1, document.tokens.minimap_runs(&self.theme, &token_colors, &document.lines, index))
});
// RenderImage holds BGRA.
for pixel in image.data.chunks_exact_mut(4) {
@@ -378,8 +379,13 @@ impl Workbench {
let mut selections: Vec<MinimapRange> = cursor_selections.iter().map(|selection| MinimapRange { start: view(selection.start().line, selection.start().column), end: view(selection.end().line, selection.end().column) }).collect();
selections.sort_by_key(|range| range.start);
let mut decorations = Vec::new();
+ // `_getMinimapDecorationsInViewport`: a word highlighted all over a long file costs a view column per line.
+ let in_viewport = |line: usize| {
+ let view_line = editor.view_line(line) + 1;
+ (layout.start_line_number..=layout.end_line_number).contains(&sampling.map_or(view_line, |sampling| sampling.minimap_line(view_line)))
+ };
if let Some(color) = self.theme.color("minimap.selectionOccurrenceHighlight") {
- for (line, columns) in &editor.highlights {
+ for (line, columns) in editor.highlights.iter().filter(|(line, _)| in_viewport(*line)) {
decorations.push((MinimapRange { start: view(*line, columns.start), end: view(*line, columns.end) }, color));
}
}
diff --git a/native/crates/textmate/src/theme.rs b/native/crates/textmate/src/theme.rs
index cb140ba1a08..f515d3707e7 100644
--- a/native/crates/textmate/src/theme.rs
+++ b/native/crates/textmate/src/theme.rs
@@ -1,9 +1,9 @@
//! Token colors as vscode-textmate's theme.ts resolves them: the theme's `tokenColors` rules in a
//! trie by scope segment, the most specific rule (longest scope, then parent scopes) winning.
-use std::cell::RefCell;
+use std::cell::{Cell, RefCell};
use std::collections::HashMap;
-use std::rc::Rc;
+use std::rc::{Rc, Weak};
use serde_json::Value;
@@ -29,6 +29,9 @@ pub struct Theme {
defaults: Style,
root: TrieElement,
match_cache: RefCell<HashMap<String, Rc<Vec<TrieRule>>>>,
+ style_cache: RefCell<HashMap<*const ScopeStack, (Weak<ScopeStack>, Style)>>,
+ /// The size at which `style_cache` drops the entries of dropped stacks.
+ style_cache_limit: Cell<usize>,
rules: Vec<Value>,
}
@@ -67,7 +70,7 @@ impl Theme {
let style = Style { font_style: rule.font_style, foreground: color_id(&mut color_map, rule.foreground.as_deref()), background: color_id(&mut color_map, rule.background.as_deref()) };
root.insert(0, &rule.scope, rule.parent_scopes.as_deref(), style);
}
- Theme { color_map, defaults, root, match_cache: RefCell::default(), rules: rules.to_vec() }
+ Theme { color_map, defaults, root, match_cache: RefCell::default(), style_cache: RefCell::default(), style_cache_limit: Cell::new(4096), rules: rules.to_vec() }
}
pub fn color_map(&self) -> &[String] {
@@ -91,8 +94,25 @@ impl Theme {
}
/// The style a token with these scopes gets: each scope's match merged over its parent's, as
- /// `AttributedScopeStack.pushAttributed` merges token attributes.
- pub fn style(&self, path: &ScopeStack) -> Style {
+ /// `AttributedScopeStack.pushAttributed` merges token attributes. Kept per stack while it lives, as vscode-textmate
+ /// keeps it in the stack's token metadata.
+ pub fn style(&self, path: &Rc<ScopeStack>) -> Style {
+ let key = Rc::as_ptr(path);
+ if let Some((_, style)) = self.style_cache.borrow().get(&key) {
+ return *style;
+ }
+ let style = self.resolve_style(path);
+ let mut cache = self.style_cache.borrow_mut();
+ if cache.len() >= self.style_cache_limit.get() {
+ cache.retain(|_, (stack, _)| stack.strong_count() > 0);
+ self.style_cache_limit.set((cache.len() * 2).max(4096));
+ }
+ // The Weak keeps the allocation, so no other stack takes this address while the entry lives.
+ cache.insert(key, (Rc::downgrade(path), style));
+ style
+ }
+
+ fn resolve_style(&self, path: &ScopeStack) -> Style {
let mut style = match &path.parent {
Some(parent) => self.style(parent),
None => self.defaults,
@@ -336,7 +356,7 @@ mod tests {
json!({ "scope": "meta.tag string", "settings": { "foreground": "#aaaaaa", "fontStyle": "italic" } }),
json!({ "scope": ["string.quoted"], "settings": { "fontStyle": "bold" } }),
]);
- let color = |path: &ScopeStack| theme.color_map()[theme.style(path).foreground].clone();
+ let color = |path: &Rc<ScopeStack>| theme.color_map()[theme.style(path).foreground].clone();
let plain = ScopeStack::from_names(&["source.js", "string.quoted.double"]);
assert_eq!(color(&plain), "#E6DB74");
assert_eq!(theme.style(&plain).font_style, BOLD);
@@ -346,4 +366,15 @@ mod tests {
assert_eq!(color(&ScopeStack::from_names(&["source.js", "meta.tag", "string.quoted.double"])), "#E6DB74");
assert_eq!(color(&ScopeStack::from_names(&["source.js"])), "#F8F8F2");
}
+
+ #[test]
+ fn style_cache_drops_dropped_stacks_and_keeps_styles_right() {
+ let theme = Theme::new(&[json!({ "settings": { "foreground": "#F8F8F2" } }), json!({ "scope": "string", "settings": { "foreground": "#E6DB74" } })]);
+ let color = |path: &Rc<ScopeStack>| theme.color_map()[theme.style(path).foreground].clone();
+ for index in 0..10_000 {
+ let names = if index % 2 == 0 { ["source.js", "string"] } else { ["source.js", "comment"] };
+ assert_eq!(color(&ScopeStack::from_names(&names)), if index % 2 == 0 { "#E6DB74" } else { "#F8F8F2" });
+ }
+ assert!(theme.style_cache.borrow().len() <= 4096, "{}", theme.style_cache.borrow().len());
+ }
}