Visual Studio Code, rebuilt in Rust
Rust
feat(minimap): keep the sampled lines and section headers through edits
rokartur01800eb95e8d
diff --git a/native/crates/app/src/editor/minimap.rs b/native/crates/app/src/editor/minimap.rsindex 6539379c123..9b860ceee9b 100644--- a/native/crates/app/src/editor/minimap.rs+++ b/native/crates/app/src/editor/minimap.rs@@ -84,8 +84,7 @@ impl MinimapLayoutInfo {/// minimap.ts `MinimapSamplingState`: with `fill` or `fit` and more view lines than the canvas has rows, each/// minimap line shows one sampled view line.-// shortcut: sampled afresh each frame, where upstream keeps the mapping sticky through `onLinesDeleted` and-// `onLinesInserted`; upgrade if the sampled lines visibly jump while typing in a long file.+#[derive(Clone)]pub struct MinimapSampling {ratio: f64,/// The 1-based view line of each minimap line.@@ -93,17 +92,63 @@ pub struct MinimapSampling {}impl MinimapSampling {- /// `MinimapSamplingState.compute` without a previous state.- pub fn new(view_line_count: usize, minimap_line_count: usize) -> Self {+ /// `MinimapSamplingState.compute`: an old state's sampled lines are kept where they still fall in their+ /// minimap line's view lines.+ pub fn compute(view_line_count: usize, minimap_line_count: usize, old: Option<&MinimapSampling>) -> Self {let ratio = view_line_count as f64 / minimap_line_count as f64;- let mut lines = vec![1];- if minimap_line_count > 1 {- lines = (0..minimap_line_count - 1).map(|i| (i as f64 * ratio + ratio / 2.).round() as usize).collect();- lines.push(view_line_count);+ let half_ratio = ratio / 2.;+ let Some(old) = old.filter(|old| !old.lines.is_empty()) else {+ let mut lines = vec![1];+ if minimap_line_count > 1 {+ lines = (0..minimap_line_count - 1).map(|i| (i as f64 * ratio + half_ratio).round() as usize).collect();+ lines.push(view_line_count);+ }+ return MinimapSampling { ratio, lines };+ };+ let mut lines = Vec::with_capacity(minimap_line_count);+ let (mut old_index, mut min_view_line) = (0, 1);+ for i in 0..minimap_line_count {+ let from = min_view_line.max((i as f64 * ratio).round() as usize);+ let to = from.max(((i + 1) as f64 * ratio).round() as usize);+ while old_index < old.lines.len() && old.lines[old_index] < from {+ old_index += 1;+ }+ let selected = if old_index < old.lines.len() && old.lines[old_index] <= to {+ old_index += 1;+ old.lines[old_index - 1]+ } else if i == 0 {+ 1+ } else if i + 1 == minimap_line_count {+ view_line_count+ } else {+ (i as f64 * ratio + half_ratio).round() as usize+ };+ lines.push(selected);+ min_view_line = selected;}MinimapSampling { ratio, lines }}+ /// `MinimapSamplingState.onLinesDeleted`: sampled lines in `from..=to` move to the line before, later ones up.+ pub fn on_lines_deleted(&mut self, from: usize, to: usize) {+ for line in self.lines.iter_mut().rev() {+ if *line < from {+ break;+ }+ *line = if *line <= to { 1.max(from - 1) } else { *line - (to - from + 1) };+ }+ }++ /// `MinimapSamplingState.onLinesInserted`: sampled lines from `from` move down.+ pub fn on_lines_inserted(&mut self, from: usize, to: usize) {+ for line in self.lines.iter_mut().rev() {+ if *line < from {+ break;+ }+ *line += to - from + 1;+ }+ }+/// `modelLineToMinimapLine`, both 1-based.pub fn minimap_line(&self, view_line: usize) -> usize {((view_line as f64 / self.ratio).round() as usize).max(1).min(self.lines.len())@@ -830,12 +875,23 @@ mod tests {#[test]fn sampling_maps_view_lines_to_minimap_lines() {- let sampling = MinimapSampling::new(10, 4);+ let sampling = MinimapSampling::compute(10, 4, None);assert_eq!(sampling.lines, [1, 4, 6, 10]);assert_eq!((1..=10).map(|line| sampling.minimap_line(line)).collect::<Vec<_>>(), [1, 1, 1, 2, 2, 2, 3, 3, 4, 4]);assert_eq!(sampling.decoration_lines(1, 2), (1, 2));assert_eq!(sampling.decoration_lines(9, 10), (3, 4));- assert_eq!(MinimapSampling::new(5, 1).lines, [1]);+ assert_eq!(MinimapSampling::compute(5, 1, None).lines, [1]);+ }++ #[test]+ fn sampling_stays_on_the_same_lines_through_edits() {+ let mut sampling = MinimapSampling::compute(10, 4, None);+ sampling.on_lines_inserted(2, 2);+ assert_eq!(MinimapSampling::compute(11, 4, Some(&sampling)).lines, [1, 5, 7, 11]);+ assert_eq!(MinimapSampling::compute(11, 4, None).lines, [1, 4, 7, 11]);+ sampling.on_lines_deleted(4, 5);+ assert_eq!(sampling.lines, [1, 3, 5, 9]);+ assert_eq!(MinimapSampling::compute(9, 4, Some(&sampling)).lines, [1, 3, 5, 9]);}#[test]diff --git a/native/crates/app/src/workbench/minimap_view.rs b/native/crates/app/src/workbench/minimap_view.rsindex 0731e943a4a..c33931a5c34 100644--- a/native/crates/app/src/workbench/minimap_view.rs+++ b/native/crates/app/src/workbench/minimap_view.rs@@ -21,7 +21,7 @@ use crate::editor::minimap::{};use crate::editor::folding::FoldDecoration;use crate::editor::section_headers::{FindOptions, MARK_SECTION_HEADER_REGEX, SectionHeader, find_section_headers, fit_section_header};-use crate::editor::{OpenEditor, Position, VERTICAL_SCROLLBAR_WIDTH, Viewport};+use crate::editor::{OpenEditor, Position, TextModel, VERTICAL_SCROLLBAR_WIDTH, Viewport};use crate::theme::relative_luminance;/// minimap.css `.minimap-slider` opacity transition, and `_hideSliderAfterScrollScheduler`.@@ -34,6 +34,8 @@ const MINIMAP_HIDE_DELAY: Duration = Duration::from_millis(500);const SHADOW_STRIP_WIDTH: f32 = 6.;const SHADOW_ALPHA: f32 = 0.08;const SHADOW_SIGMA: f32 = 3.;+/// sectionHeaders.ts `onDidChangeModelTokens`: `computeSectionHeaders.schedule(1000)`.+const TOKENS_CHANGED_DELAY: Duration = Duration::from_millis(1000);#[derive(Default)]pub(super) struct Minimap {@@ -41,6 +43,8 @@ pub(super) struct Minimap {pub info: Option<(MinimapLayoutInfo, f64)>,/// `_lastRenderData.renderedLayout` with the model it showed: the next layout keeps the lines from jumping back.rendered: Cell<Option<(u32, MinimapLayout)>>,+ /// `_samplingState` with the model, its version and whether its view lines were its model lines.+ sampling: RefCell<Option<(u32, u32, bool, MinimapSampling)>>,image: RefCell<Option<Arc<RenderImage>>>,/// The RGBA lines behind `image`, whose unchanged rows the next frame copies.lines: RefCell<Option<RenderedLines>>,@@ -59,7 +63,7 @@ pub(super) struct Minimap {/// `active` of `autohide: scroll`: shown after a scroll until 500ms pass without the pointer over it.active: Option<Task<()>>,/// The section headers of a model version and the find options they were found with.- section_headers: RefCell<Option<(SectionHeaderKey, Rc<Vec<SectionHeader>>)>>,+ section_headers: RefCell<Option<FoundSectionHeaders>>,}/// A section header in the minimap's lines: its view line (1-based), label and separator line.@@ -163,10 +167,30 @@ fn layout_input(outer_width: f32, outer_height: f32, content_left: f32, char_wid}}-/// `MinimapSamplingState.compute` for the editor's view lines; only the heights count, the widths are 0.-fn minimap_sampling(editor: &OpenEditor, viewport: Viewport, pixel_ratio: f64, options: MinimapOptions) -> MinimapSampling {+/// `MinimapSamplingState.compute` for the editor's view lines from `old`; only the heights count, the widths are 0.+fn minimap_sampling(editor: &OpenEditor, viewport: Viewport, pixel_ratio: f64, options: MinimapOptions, old: Option<&MinimapSampling>) -> MinimapSampling {let input = layout_input(0., viewport.height, 0., viewport.char_width, viewport.line_height, editor.view_line_count(), pixel_ratio as f32, options);- MinimapSampling::new(editor.view_line_count(), contained_minimap_line_count(&input).minimap_line_count as usize)+ MinimapSampling::compute(editor.view_line_count(), contained_minimap_line_count(&input).minimap_line_count as usize, old)+}++/// `MinimapSamplingState.onLinesDeleted` and `onLinesInserted` for the model's replaces since `version`, as+/// textModel.ts `_doApplyEdits` reports them: the lines past the edited ones are deleted or inserted.+// shortcut: replayed only while view lines are model lines; with word wrap or folds the state is kept as after+// `onFlushed`, upgrade when the port keeps the view line events of wrapped and folded lines.+fn follow_edits(sampling: &mut MinimapSampling, model: &TextModel, version: u32) {+ if !model.edits.first().is_some_and(|(first, ..)| *first <= version) {+ return;+ }+ for &(_, start, end, new_end, _) in model.edits.iter().filter(|(edit_version, ..)| *edit_version >= version) {+ let (deleting, inserting) = (end.line - start.line, new_end.line - start.line);+ let splice = start.line + 1 + deleting.min(inserting);+ if deleting > inserting {+ sampling.on_lines_deleted(splice + 1, start.line + 1 + deleting);+ }+ if inserting > deleting {+ sampling.on_lines_inserted(splice + 1, start.line + 1 + inserting);+ }+ }}/// The 1-based view line a 1-based minimap line shows.@@ -175,6 +199,24 @@ fn sampled_view_line(sampling: Option<&MinimapSampling>, minimap_line: usize) ->}impl Workbench {+ /// `_recreateLineSampling` from the last frame's state, moved through the edits since.+ fn sticky_minimap_sampling(&self, editor: &OpenEditor, viewport: Viewport, pixel_ratio: f64, options: MinimapOptions) -> MinimapSampling {+ let model = editor.text_model();+ let view_is_model = editor.view_line_count() == model.document.lines.len();+ let mut cached = self.minimap.sampling.borrow_mut();+ let mut old = cached.take().filter(|(model_id, ..)| *model_id == editor.model_id);+ if let Some((_, version, old_view_is_model, sampling)) = &mut old+ && *version != model.version_id+ && *old_view_is_model+ && view_is_model+ {+ follow_edits(sampling, &model, *version);+ }+ let sampling = minimap_sampling(editor, viewport, pixel_ratio, options, old.as_ref().map(|(.., sampling)| sampling));+ *cached = Some((editor.model_id, model.version_id, view_is_model, sampling.clone()));+ sampling+ }+/// `InnerMinimap.render`: the slider's layout, the lines and decorations of the lines it covers.pub(super) fn minimap(&self, editor: &OpenEditor, cx: &mut Context<Self>) -> Option<Stateful<gpui::Div>> {let (info, pixel_ratio) = self.minimap.info?;@@ -183,7 +225,7 @@ impl Workbench {}let viewport = self.editors.viewport;let settings = self.minimap_settings();- let sampling = info.is_sampling.then(|| Rc::new(minimap_sampling(editor, viewport, pixel_ratio, settings.layout)));+ let sampling = info.is_sampling.then(|| Rc::new(self.sticky_minimap_sampling(editor, viewport, pixel_ratio, settings.layout)));let layout = self.minimap_layout(editor, info, pixel_ratio, viewport, sampling.as_deref());let image = self.minimap_image(editor, &info, &layout, sampling.as_deref());let fills = self.minimap_decorations(editor, &info, &layout, sampling.as_deref());@@ -440,17 +482,24 @@ impl Workbench {/// sectionHeaders.ts `SectionHeaderDetector` and `getSectionHeaderDecorationsInViewport`: the headers from a font/// size above the first line to the last.- // shortcut: found again on the UI thread for each new model version, where upstream asks the editor worker 250ms- // after the last edit and moves the old headers with the text meanwhile; upgrade when large files lag on typing.+ /// Found again for each model version, on the UI thread rather than in the worker: port/notes.md "Scheduling+ /// differences". New tokens find them again at most once a second (`onDidChangeModelTokens`), and once all are in.#[allow(clippy::too_many_arguments)]fn minimap_section_labels(&self, editor: &OpenEditor, info: &MinimapLayoutInfo, pixel_ratio: f64, layout: &MinimapLayout, options: &SectionHeaderOptions, sampling: Option<&MinimapSampling>) -> Vec<SectionLabel> {let key = (editor.model_id, editor.text_model().version_id, options.show_region, options.mark_regex.clone());+ let first_untrusted = {+ let document = editor.document();+ document.tokens.first_untrusted_line(&document.lines)+ };let mut cached = self.minimap.section_headers.borrow_mut();- let headers = match cached.as_ref().filter(|(cached_key, _)| *cached_key == key) {- Some((_, headers)) => headers.clone(),+ let fresh = cached.as_ref().filter(|(cached_key, tokens_at, found, _)| {+ *cached_key == key && (*tokens_at == first_untrusted || (first_untrusted.is_some() && found.elapsed() < TOKENS_CHANGED_DELAY))+ });+ let headers = match fresh {+ Some((.., headers)) => headers.clone(),None => {let headers = Rc::new(section_headers(editor, options));- *cached = Some((key, headers.clone()));+ *cached = Some((key, first_untrusted, Instant::now(), headers.clone()));headers}};@@ -578,6 +627,9 @@ impl Workbench {type SectionHeaderKey = (u32, u32, bool, Option<String>);+/// Section headers with their key, the first line then waiting for tokens, and when they were found.+type FoundSectionHeaders = (SectionHeaderKey, Option<usize>, Instant, Rc<Vec<SectionHeader>>);+/// The `editor.minimap` section header options as editorOptions.ts `EditorMinimap.validate` reads them.pub(super) struct SectionHeaderOptions {show_region: bool,@@ -641,7 +693,7 @@ fn section_headers(editor: &OpenEditor, options: &SectionHeaderOptions) -> Vec<Sheaders.retain(|header| {let text = &document.lines[header.start.line];let offset = text.char_indices().nth(header.start.column).map_or(text.len(), |(offset, _)| offset);- !header.should_be_in_comments || document.tokens.token_type_at(&document.lines, header.start.line, offset) == textmate::StandardTokenType::Comment+ !header.should_be_in_comments || document.tokens.stored_token_type_at(&document.lines, header.start.line, offset) == textmate::StandardTokenType::Comment});headers}@@ -696,3 +748,28 @@ fn bytes(color: Rgba) -> [u8; 4] {[color.r, color.g, color.b, color.a].map(byte)}+#[cfg(test)]+mod tests {+ use super::*;+ use crate::editor::test_editor;++ #[test]+ fn sampling_follows_the_lines_each_edit_inserts_and_deletes() {+ let mut editor = test_editor("0\n1\n2\n3\n4\n5\n6\n7\n8\n9", "\n");+ let version = editor.text_model().version_id;+ let sampled = MinimapSampling::compute(10, 4, None);+ editor.move_to(Position::new(1, 0), false);+ editor.type_text("\n");+ editor.move_to(Position::new(5, 0), false);+ editor.move_to(Position::new(7, 0), true);+ editor.type_text("x");+ let mut followed = sampled.clone();+ follow_edits(&mut followed, &editor.text_model(), version);+ // textModel.ts `_doApplyEdits`: the newline inserts line 3, the two-line replace deletes lines 7 to 8.+ let mut expected = sampled.clone();+ expected.on_lines_inserted(3, 3);+ expected.on_lines_deleted(7, 8);+ assert_ne!(followed.lines, sampled.lines);+ assert_eq!(followed.lines, expected.lines);+ }+}diff --git a/port/ledger.md b/port/ledger.mdindex 35c8f538f1b..2ea2f8019ec 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -339,7 +339,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| platform/windows | src/vs/platform | M11 | verified | | windows_state.rs: cargo test -p app windows_state; ui-pair hot-exit.json `restored` (port/results/windows.md, milestone 11 verification). The default size stays 1024x768, the capture size of port/tools/ref-screenshot, where upstream takes 1200x800 or 1440x900 || platform/workspace | src/vs/platform | M12 | verified | | virtual workspaces (non-file folders): milestone 25; config/src/workspace.rs: folders, getFolder, toWorkspaceFolders, workspace label; cargo test -p config workspace (workspace.test.ts cases); api-workspace 4/4; verified: api-tests MOCHA_GREP="vscode API - (workspace|file system|env|types|tasks)" at 44a309311e1: every workspace, workspace-fs, workspace events, workspace-watcher and file system test passes, api-workspace 4/0/0 (port/results/api-tests.md "M12 verification"), api-workspace 4/4 || platform/workspaces | src/vs/platform | M12 | verified | | session.rs, recently_opened.rs, config/src/workspace.rs, workbench/workspace_editing.rs: cargo test -p exthost (workspaces.test.ts stable id case); cargo test -p config workspace:: 5/5; cargo test -p app recently_opened workspace_editing; ui-pair port/fixtures/ui-pair/m12/workspace-folders.json (Remove Folder from Workspace enters Untitled (Workspace)) |-| editor/browser | src/vs/editor | M8 | ported | [scheduling L] minimap.rs:87; minimap_view.rs:432; unicode_highlight.rs:63; indentation.rs:43; comment.rs:45; smart_select.rs:292: sticky minimap sampling, worker section headers and unicode highlights, tokenizeIfCheap, the 30 ms smart select yield. Accepted as "Scheduling differences" only with a measured same result and typing on a 50k-line TS file under 16 ms per edit; otherwise class 3. Audit inputs at 5e5b1b0a915. | editor/view.rs, editor/folding.rs, editor/minimap.rs, editor/word_wrap.rs, editor/smooth_scroll.rs, editor/mouse_selection.rs, workbench/editor_view.rs, workbench/gutter_mouse.rs, workbench/editor_view/text_decorations.rs: cargo test -p app editor::view::tests editor::folding minimap section_headers editor_menus selection_corners whitespace control_characters gutter_presses word_wrap smooth_scroll diff_editor diff_gutter switch_side bracket_pair_guide wrapping_indent_repeats without_a_wrapping_indent file_compare char_ranges a_click_without_a_move mouse_selection text_clicks_select a_selecting_drag_below a_drag_into_the_vertical the_bottom_edge_hit a_drag_below_a_comment text_input:: outline_and_border_follow_the_css_cascade a_decoration_outline_is_drawn_outside_its_range decoration_types_set_and_remove_editor_decorations wrapping_a_padded_inlay_hint_skips_its_padding_box a_selection_over_changes_shows_the_selection_toolbar; ui-pair m12/compare.json, port/fixtures/ui-pair/menus/diff-gutter-selection.json, port/fixtures/ui-pair/m8/inlay-hint-wrap.json (port/notes.md milestones 8 and 14) |+| editor/browser | src/vs/editor | M8 | ported | [3 S] minimap_view.rs:179: with word wrap or folds the sticky minimap sampling is not moved through edits, where upstream follows the view line events of wrapped and folded lines. | editor/view.rs, editor/folding.rs, editor/minimap.rs, editor/word_wrap.rs, editor/smooth_scroll.rs, editor/mouse_selection.rs, workbench/editor_view.rs, workbench/gutter_mouse.rs, workbench/editor_view/text_decorations.rs: cargo test -p app editor::view::tests editor::folding minimap section_headers editor_menus selection_corners whitespace control_characters gutter_presses word_wrap smooth_scroll diff_editor diff_gutter switch_side bracket_pair_guide wrapping_indent_repeats without_a_wrapping_indent file_compare char_ranges a_click_without_a_move mouse_selection text_clicks_select a_selecting_drag_below a_drag_into_the_vertical the_bottom_edge_hit a_drag_below_a_comment text_input:: outline_and_border_follow_the_css_cascade a_decoration_outline_is_drawn_outside_its_range decoration_types_set_and_remove_editor_decorations wrapping_a_padded_inlay_hint_skips_its_padding_box a_selection_over_changes_shows_the_selection_toolbar; ui-pair m12/compare.json, port/fixtures/ui-pair/menus/diff-gutter-selection.json, port/fixtures/ui-pair/m8/inlay-hint-wrap.json (port/notes.md milestones 8 and 14) || editor/common | src/vs/editor | M8 | ported | [scheduling L] minimap.rs:87; minimap_view.rs:432; unicode_highlight.rs:63; indentation.rs:43; comment.rs:45; smart_select.rs:292: sticky minimap sampling, worker section headers and unicode highlights, tokenizeIfCheap, the 30 ms smart select yield. Accepted as "Scheduling differences" only with a measured same result and typing on a 50k-line TS file under 16 ms per edit; otherwise class 3. Audit inputs at 5e5b1b0a915. | app/src/editor, decorations.rs, link_computer.rs, syntax.rs, brackets/tree.rs, the diff crate: cargo test -p app editor:: decorations:: link_computer syntax:: auto_closing brackets lines_in_view_past_the_tokenized_ones the_word_at_a_column full_width_chars_take moving_down_keeps a_hyphen_next_to_a_class_escape_is_literal (13 ignored: upstream's `test.skip` cases); cargo test -p diff; typing on the 52k-line TS file under 2.3 ms median per edit: cargo test --release -p app -- --ignored typing_latency_on_a_large_file. By design: the piece tree text buffer is a vector of lines (large files through workbench/large_file.rs) || editor/standalone | src/vs/editor | | removed | | Artur: internal infrastructure or developer tool with no 1:1 counterpart in the native port || editor/test | src/vs/editor | M6 | n/a | | upstream test infrastructure; the port tests with cargo test and port/tools |