Skip to content

Visual Studio Code, rebuilt in Rust

Rust
25.0 KB
Raw Blame
//! The diff editor's input and view model: diffEditorInput.ts (labels), diffEditorViewModel.ts (the diff of two
//! models, recomputed when either changes) and diffEditorViewZones.ts `computeRangeAlignment` (the whitespace that
//! keeps both sides aligned). Drawn by `workbench/diff_editor_view.rs`.

use std::path::PathBuf;

use diff::{DiffOptions, LineRange, LineRangeMapping, LinesDiff};

use crate::editor::{OpenEditor, Position, Selection, split_query};

pub mod unchanged_regions;

use unchanged_regions::{OutlineSymbol, UnchangedDrag, UnchangedRegion};

/// The scheme of a diff editor's tab entry: the group keeps it as an editor without text, its `DiffInput` names the
/// two models it shows.
pub const DIFF_EDITOR_SCHEME: &str = "diff-editor";

/// One side's model, as `EditorGroup::model` finds it.
#[derive(Clone, Debug, PartialEq)]
pub struct Side {
    pub scheme: String,
    pub path: PathBuf,
}

impl Side {
    pub fn name(&self) -> String {
        split_query(&self.scheme, &self.path).0.file_name().unwrap_or_default().to_string_lossy().into_owned()
    }
}

/// `DiffEditorInput`: the original and modified resources and the preferred label. The preferred description is
/// left out: the port's tabs show no descriptions yet.
pub struct DiffInput {
    pub original: Side,
    pub modified: Side,
    pub label: Option<String>,
    pub diff: Option<ComputedDiff>,
    /// The view mode the editor draws now: inline by setting or below the breakpoint.
    pub inline_now: bool,
    /// The view zones of the current diff and view mode, both sides.
    pub zones: Vec<DiffZone>,
    /// The modified side's zones as placed in its model: view zone id and zone.
    pub placed_zones: Vec<(u32, DiffZone)>,
    /// The collapsed unchanged regions with `diffEditor.hideUnchangedRegions.enabled`, and the diff versions and
    /// minimum and context line counts they were computed for.
    pub unchanged: Vec<UnchangedRegion>,
    pub unchanged_key: Option<((u32, u32), usize, usize)>,
    /// The placeholder view zones of the modified side: view zone id and region index.
    pub placed_unchanged: Vec<(u32, usize)>,
    /// The modified editor's cursor lines the regions last revealed, and the bar being dragged.
    pub unchanged_cursors: Vec<usize>,
    pub unchanged_drag: Option<UnchangedDrag>,
    /// The modified model's document symbols for the breadcrumbs, and the model version they were asked for.
    pub symbols: Vec<OutlineSymbol>,
    pub symbols_version: Option<u32>,
    /// The modified side's code editor: its model's, with its own cursors, scroll and view zones, as
    /// diffEditorWidget.ts creates a CodeEditorWidget per side. `EditorGroup` attaches it on open.
    pub modified_editor: Option<OpenEditor>,
    /// The original side's code editor, attached with the modified one: its own cursor, not a text editor's.
    pub original_editor: Option<OpenEditor>,
    /// The original editor has the focus (`getFocusedCodeEditor`): editor commands, find and the cursor act in it.
    pub original_focused: bool,
    /// Side by side, the original editor's diff zones and unchanged region placeholders as placed in it.
    pub placed_original_zones: Vec<(u32, DiffZone)>,
    pub placed_original_unchanged: Vec<(u32, usize)>,
    /// The scroll both side editors had after the last sync: the side that differs from it scrolled.
    pub synced_scroll: crate::editor::Scroll,
    /// The custom editor showing the diff in place of the text diff editor (customEditors.ts `createDiffEditorInput`).
    pub custom: Option<CustomDiff>,
    /// A diff widget a view embeds with fixed options (testResultsOutput.ts `diffEditorOptions`), not a diff editor.
    pub embedded: bool,
}

/// A custom editor's diff: its view type, and whether it is one `CustomEditorDiffInput` (inline) rather than a
/// `DiffEditorInput` of a webview per side.
#[derive(Clone, PartialEq)]
pub struct CustomDiff {
    pub view_type: String,
    pub inline: bool,
}

/// The diff of the models' versions it was computed for.
pub struct ComputedDiff {
    pub versions: (u32, u32),
    pub options: (bool, u64, bool),
    pub diff: LinesDiff,
}

impl DiffInput {
    pub fn new(original: Side, modified: Side, label: Option<String>) -> Self {
        DiffInput { original, modified, label, diff: None, inline_now: false, zones: Vec::new(), placed_zones: Vec::new(), unchanged: Vec::new(), unchanged_key: None, placed_unchanged: Vec::new(), unchanged_cursors: Vec::new(), unchanged_drag: None, symbols: Vec::new(), symbols_version: None, modified_editor: None, original_editor: None, original_focused: false, placed_original_zones: Vec::new(), placed_original_unchanged: Vec::new(), synced_scroll: crate::editor::Scroll::default(), custom: None, embedded: false }
    }

    /// `computeLabels` name: the preferred label, else `original ↔ modified`; customEditorDiffInput.ts `getName`
    /// of an inline custom editor diff: `original - modified`.
    pub fn name(&self) -> String {
        match &self.label {
            Some(label) => label.clone(),
            None if self.custom.as_ref().is_some_and(|custom| custom.inline) => format!("{} - {}", self.original.name(), self.modified.name()),
            None => format!("{} \u{2194} {}", self.original.name(), self.modified.name()),
        }
    }

    /// `computeLabels` title (medium verbosity): the sides' paths joined with ` ↔ `, after the preferred label.
    pub fn title(&self, path_label: impl Fn(&Side) -> String) -> String {
        // customEditorDiffInput.ts `getTitle`: the name, as no description is passed.
        if self.custom.as_ref().is_some_and(|custom| custom.inline) {
            return self.name();
        }
        let (original, modified) = (path_label(&self.original), path_label(&self.modified));
        let title = if original == modified { modified } else { format!("{original} \u{2194} {modified}") };
        match &self.label {
            Some(label) => format!("{label} ({title})"),
            None => title,
        }
    }

    /// Recomputes the diff when either model or an option changed since the last one (diffEditorViewModel.ts
    /// `_diff`, which upstream debounces on a worker).
    /// Answers whether it computed a new diff (`onDidUpdateDiff`).
    pub fn update(&mut self, original: &OpenEditor, modified: &OpenEditor, options: DiffOptions) -> bool {
        let versions = (original.text_model().version_id, modified.text_model().version_id);
        let key = (options.ignore_trim_whitespace, options.max_computation_time_ms, options.compute_moves);
        if self.diff.as_ref().is_some_and(|diff| diff.versions == versions && diff.options == key) {
            return false;
        }
        let (original_lines, modified_lines) = (&original.document().lines, &modified.document().lines);
        let diff = diff::compute_diff(original_lines, modified_lines, options);
        self.diff = Some(ComputedDiff { versions, options: key, diff });
        true
    }

    /// `updateUnchangedRegions` when the diff or the line counts changed; without `hide_unchanged` (minimum and
    /// context line counts) no region, as the view model resets them when the option goes off.
    pub fn update_unchanged(&mut self, original: &crate::editor::TextModel, modified: &crate::editor::TextModel, hide_unchanged: Option<(usize, usize)>) {
        let (original_count, modified_count) = (original.document.lines.len(), modified.document.lines.len());
        let Some((min_hidden, min_context)) = hide_unchanged else {
            self.unchanged.clear();
            self.unchanged_key = None;
            return;
        };
        let computed = self.diff.as_ref().expect("update runs first");
        let key = (computed.versions, min_hidden, min_context);
        if self.unchanged_key == Some(key) {
            return;
        }
        let new = UnchangedRegion::from_diffs(&computed.diff.changes, original_count, modified_count, min_hidden, min_context);
        let last = match self.unchanged_key {
            Some((seen, ..)) => unchanged_regions::track(&self.unchanged, seen, original, modified),
            None => Vec::new(),
        };
        self.unchanged = unchanged_regions::transfer(new, &last, original_count, modified_count);
        // hideUnchangedRegionsFeature.ts: one region covering the whole modified model (no change) shows nothing.
        if let [only] = self.unchanged[..]
            && only.modified_line == 1
            && only.line_count == modified_count
        {
            self.unchanged.clear();
        }
        self.unchanged_key = Some(key);
    }
}

/// `diffEditor.*` settings the view reads, with diffEditor.ts defaults.
pub fn diff_options(setting: impl Fn(&str) -> serde_json::Value) -> DiffOptions {
    DiffOptions {
        ignore_trim_whitespace: setting("diffEditor.ignoreTrimWhitespace").as_bool().unwrap_or(true),
        max_computation_time_ms: setting("diffEditor.maxComputationTime").as_u64().unwrap_or(5000),
        compute_moves: setting("diffEditor.experimental.showMoves").as_bool().unwrap_or(false),
        extend_to_subwords: false,
    }
}

/// `ILineRangeAlignment`: lines of both sides drawn at the same height; `changed` when they belong to a change.
#[derive(Clone, Debug, PartialEq)]
pub struct Alignment {
    pub original: LineRange,
    pub modified: LineRange,
    pub original_height: f32,
    pub modified_height: f32,
    pub changed: bool,
}

/// `getAdditionalLineHeights` without wrapped lines: the other view zones' heights by the 1-based line they follow
/// (0 above the first line), sorted, the zones of one line together.
pub fn additional_heights(zones: impl Iterator<Item = (usize, f32)>) -> Vec<(usize, f32)> {
    let mut zones: Vec<(usize, f32)> = zones.collect();
    zones.sort_by_key(|zone| zone.0);
    let mut joined: Vec<(usize, f32)> = Vec::new();
    for (line, height) in zones {
        match joined.last_mut() {
            Some(last) if last.0 == line => last.1 += height,
            _ => joined.push((line, height)),
        }
    }
    joined
}

/// `computeRangeAlignment` without wrapped lines: per change, the stretches the inner changes break it into when
/// `inner_hunk_alignment` (side by side), else the whole change; outside the changes, one line of each side per other
/// view zone (`additional_heights`), so the zones of one side leave room in the other.
pub fn range_alignment(diff: &LinesDiff, original_lines: &[String], inner_hunk_alignment: bool, original_zones: &[(usize, f32)], modified_zones: &[(usize, f32)], line_height: f32) -> Vec<Alignment> {
    let mut queues = ZoneQueues { original: original_zones, modified: modified_zones, line_height };
    let mut result = Vec::new();
    let (mut last_original_line, mut last_modified_line) = (0, 0);
    for change in &diff.changes {
        queues.align_outside(change.original.start, change.modified.start, last_original_line, last_modified_line, &mut result);
        let mut first = true;
        let mut last_original = change.original.start;
        let mut last_modified = change.modified.start;
        let mut emit = |original_end: usize, modified_end: usize, force: bool, queues: &mut ZoneQueues, result: &mut Vec<Alignment>| {
            if original_end < last_original || modified_end < last_modified {
                return;
            }
            if first {
                first = false;
            } else if !force && (original_end == last_original || modified_end == last_modified) {
                return;
            }
            let original = LineRange::new(last_original, original_end);
            let modified = LineRange::new(last_modified, modified_end);
            if original.is_empty() && modified.is_empty() {
                return;
            }
            let original_height = original.len() as f32 * line_height + take_before(&mut queues.original, original_end);
            let modified_height = modified.len() as f32 * line_height + take_before(&mut queues.modified, modified_end);
            result.push(Alignment { original, modified, original_height, modified_height, changed: true });
            last_original = original_end;
            last_modified = modified_end;
        };
        if inner_hunk_alignment {
            for inner in change.inner_changes.iter().flatten() {
                if inner.original.start.column > 1 && inner.modified.start.column > 1 {
                    emit(inner.original.start.line, inner.modified.start.line, false, &mut queues, &mut result);
                }
                let max_column = original_lines.get(inner.original.end.line - 1).map_or(usize::MAX, |line| line.chars().count() + 1);
                if inner.original.end.column < max_column {
                    emit(inner.original.end.line, inner.modified.end.line, false, &mut queues, &mut result);
                }
            }
        }
        emit(change.original.end, change.modified.end, true, &mut queues, &mut result);
        (last_original_line, last_modified_line) = (change.original.end, change.modified.end);
    }
    queues.align_outside(usize::MAX, usize::MAX, last_original_line, last_modified_line, &mut result);
    result
}

/// The other view zones of both sides not aligned yet.
struct ZoneQueues<'a> {
    original: &'a [(usize, f32)],
    modified: &'a [(usize, f32)],
    line_height: f32,
}

impl ZoneQueues<'_> {
    /// `handleAlignmentsOutsideOfDiffs`: each zone before the lines, nearest first, aligned with the line of the other
    /// side as far from the last change (zones on both lines at once together).
    fn align_outside(&mut self, until_original: usize, until_modified: usize, last_original: usize, last_modified: usize, result: &mut Vec<Alignment>) {
        loop {
            let original = self.original.first().copied().filter(|zone| zone.0 < until_original);
            let modified = self.modified.first().copied().filter(|zone| zone.0 < until_modified);
            let distance = |zone: Option<(usize, f32)>, last: usize| zone.map_or(usize::MAX, |zone| zone.0 - last);
            let (original_distance, modified_distance) = (distance(original, last_original), distance(modified, last_modified));
            let (original, modified) = match (original, modified) {
                (None, None) => break,
                _ if original_distance < modified_distance => {
                    let original = original.expect("nearer than none");
                    self.original = &self.original[1..];
                    (original, (original.0 - last_original + last_modified, 0.))
                }
                _ if original_distance > modified_distance => {
                    let modified = modified.expect("nearer than none");
                    self.modified = &self.modified[1..];
                    ((modified.0 - last_modified + last_original, 0.), modified)
                }
                (Some(original), Some(modified)) => {
                    (self.original, self.modified) = (&self.original[1..], &self.modified[1..]);
                    (original, modified)
                }
                _ => unreachable!("equal distances are of two zones"),
            };
            result.push(Alignment {
                original: LineRange::new(original.0, original.0 + 1),
                modified: LineRange::new(modified.0, modified.0 + 1),
                original_height: self.line_height + original.1,
                modified_height: self.line_height + modified.1,
                changed: false,
            });
        }
    }
}

/// `takeWhile(v => v.lineNumber < end)`: the heights of the zones before `end`, taken off the queue.
fn take_before(queue: &mut &[(usize, f32)], end: usize) -> f32 {
    let count = queue.iter().take_while(|zone| zone.0 < end).count();
    let height = queue[..count].iter().map(|zone| zone.1).sum();
    *queue = &queue[count..];
    height
}

/// Which editor a view zone goes in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ZoneSide {
    Original,
    Modified,
}

/// What a diff view zone shows.
#[derive(Clone, Debug, PartialEq)]
pub enum ZoneContent {
    /// `createFakeLinesDiv`: the diagonal fill of the side with fewer lines.
    Fill,
    /// The inline view's deleted lines (`line-delete`), with the change they belong to.
    Deleted { original: LineRange, change: usize },
}

/// A view zone of the diff: below `after_line` (1-based, 0 above the first line), `height` pixels tall.
#[derive(Clone, Debug, PartialEq)]
pub struct DiffZone {
    pub side: ZoneSide,
    pub after_line: usize,
    pub height: f32,
    pub content: ZoneContent,
}

/// The view zones of `diffEditorViewZones.ts` for `alignments`: the diagonal fill under the shorter side of each
/// stretch; inline, a change shows its deleted lines above it in the modified editor, and the original editor, which
/// shows only its line numbers, the space of the modified lines below it.
pub fn view_zones(diff: &LinesDiff, alignments: &[Alignment], side_by_side: bool, line_height: f32) -> Vec<DiffZone> {
    let mut zones = Vec::new();
    for alignment in alignments {
        if alignment.changed && !side_by_side {
            if !alignment.original.is_empty() {
                let change = diff.changes.iter().position(|change| change.original.start <= alignment.original.start && alignment.original.end <= change.original.end).unwrap_or(0);
                let height = alignment.original.len() as f32 * line_height;
                zones.push(DiffZone { side: ZoneSide::Modified, after_line: alignment.modified.start - 1, height, content: ZoneContent::Deleted { original: alignment.original, change } });
            }
            if alignment.modified_height > 0. {
                zones.push(DiffZone { side: ZoneSide::Original, after_line: alignment.original.end - 1, height: alignment.modified_height, content: ZoneContent::Fill });
            }
            continue;
        }
        let delta = alignment.modified_height - alignment.original_height;
        if delta > 0. {
            zones.push(DiffZone { side: ZoneSide::Original, after_line: alignment.original.end - 1, height: delta, content: ZoneContent::Fill });
        } else if delta < 0. {
            zones.push(DiffZone { side: ZoneSide::Modified, after_line: alignment.modified.end - 1, height: -delta, content: ZoneContent::Fill });
        }
    }
    zones
}

/// diffEditorWidget.ts `mapToOtherSide`: `selection` of the side `mappings` map from, on the other side: the hull
/// (`Range.plusRange`) of where its start and its end land.
pub fn map_to_other_side(selection: Selection, mappings: &[LineRangeMapping]) -> Selection {
    let one_based = |position: Position| diff::Position { line: position.line + 1, column: position.column + 1 };
    let zero_based = |position: diff::Position| Position::new(position.line - 1, position.column - 1);
    let (start_from, start_to) = translate_position(one_based(selection.start()), mappings);
    let (end_from, end_to) = translate_position(one_based(selection.end()), mappings);
    Selection { anchor: zero_based(start_from.min(end_from)), head: zero_based(start_to.max(end_to)) }
}

/// utils.ts `translatePosition`: the range on the mappings' modified side that 1-based `position` of their original
/// side lands on.
fn translate_position(position: diff::Position, mappings: &[LineRangeMapping]) -> (diff::Position, diff::Position) {
    let at = |line, column| (diff::Position { line, column }, diff::Position { line, column });
    let Some(mapping) = mappings.iter().rfind(|mapping| mapping.original.start <= position.line) else {
        return (position, position);
    };
    if mapping.original.end <= position.line {
        return at(position.line + mapping.modified.end - mapping.original.end, position.column);
    }
    let Some(inner_changes) = &mapping.inner_changes else {
        return at(mapping.modified.start, 1);
    };
    let Some(inner) = inner_changes.iter().rfind(|inner| inner.original.start <= position) else {
        return at(position.line + mapping.modified.start - mapping.original.start, position.column);
    };
    if inner.original.start <= position && position <= inner.original.end {
        return (inner.modified.start, inner.modified.end);
    }
    // `lengthBetweenPositions(original end, position).addToPosition(modified end)`.
    let (from, to) = (inner.original.end, inner.modified.end);
    match from.line == position.line {
        true => at(to.line, to.column + position.column - from.column),
        false => at(to.line + position.line - from.line, position.column),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn lines(text: &str) -> Vec<String> {
        text.split('\n').map(str::to_string).collect()
    }

    #[test]
    fn a_selection_maps_through_the_changes_to_the_other_side() {
        // "a", "b", "abc", "d" against "a", "X", "b", "aXYZbc", "d": a line inserted, then "XYZ" inserted into a line.
        let inner = diff::RangeMapping { original: diff::Range::new(3, 2, 3, 2), modified: diff::Range::new(4, 2, 4, 5) };
        let mappings = [LineRangeMapping::new(LineRange::new(2, 2), LineRange::new(2, 3)), LineRangeMapping { inner_changes: Some(vec![inner]), ..LineRangeMapping::new(LineRange::new(3, 4), LineRange::new(4, 5)) }];
        let caret = |line, column| Selection::caret(Position::new(line, column));
        assert_eq!(map_to_other_side(caret(0, 1), &mappings), caret(0, 1), "before every change");
        assert_eq!(map_to_other_side(caret(1, 0), &mappings), caret(2, 0), "after the inserted line");
        assert_eq!(map_to_other_side(caret(2, 2), &mappings), caret(3, 5), "after the inserted text");
        assert_eq!(map_to_other_side(caret(2, 1), &mappings), Selection { anchor: Position::new(3, 1), head: Position::new(3, 4) }, "at the inserted text");
        assert_eq!(map_to_other_side(caret(3, 0), &mappings), caret(4, 0), "after the changed line");
    }

    fn aligned(diff: &LinesDiff, original: &[String]) -> Vec<Alignment> {
        range_alignment(diff, original, true, &[], &[], 1.)
    }

    #[test]
    fn an_insertion_fills_the_original_side_both_side_by_side_and_inline() {
        let (original, modified) = (lines("a\nb\nc"), lines("a\nx\ny\nb\nc"));
        let diff = diff::compute_diff(&original, &modified, DiffOptions::default());
        let alignments = aligned(&diff, &original);
        assert_eq!(alignments, vec![Alignment { original: LineRange::new(2, 2), modified: LineRange::new(2, 4), original_height: 0., modified_height: 2., changed: true }]);
        assert_eq!(view_zones(&diff, &alignments, true, 1.), vec![DiffZone { side: ZoneSide::Original, after_line: 1, height: 2., content: ZoneContent::Fill }]);
        assert_eq!(view_zones(&diff, &alignments, false, 1.), vec![DiffZone { side: ZoneSide::Original, after_line: 1, height: 2., content: ZoneContent::Fill }]);
    }

    #[test]
    fn a_deletion_fills_the_modified_side_and_inline_shows_the_deleted_lines_above() {
        let (original, modified) = (lines("a\nb\nc\nd"), lines("a\nd"));
        let diff = diff::compute_diff(&original, &modified, DiffOptions::default());
        let alignments = aligned(&diff, &original);
        assert_eq!(view_zones(&diff, &alignments, true, 1.), vec![DiffZone { side: ZoneSide::Modified, after_line: 1, height: 2., content: ZoneContent::Fill }]);
        assert_eq!(
            view_zones(&diff, &alignments, false, 1.),
            vec![DiffZone { side: ZoneSide::Modified, after_line: 1, height: 2., content: ZoneContent::Deleted { original: LineRange::new(2, 4), change: 0 } }]
        );
    }

    #[test]
    fn inner_changes_split_a_change_into_aligned_stretches() {
        // Two changed lines, each with unchanged text after its change: one stretch per line, the fill under line 2.
        let (original, modified) = (lines("let a = 1;\nlet b = 1;\nz"), lines("let a = 2;\nlet b = 2;\nnew one\nnew two\nz"));
        let diff = diff::compute_diff(&original, &modified, DiffOptions::default());
        let alignments = aligned(&diff, &original);
        assert_eq!(alignments.first().map(|a| (a.original, a.modified)), Some((LineRange::new(1, 2), LineRange::new(1, 2))));
        assert_eq!(view_zones(&diff, &alignments, true, 1.).iter().map(|zone| (zone.side, zone.after_line, zone.height)).collect::<Vec<_>>(), vec![(ZoneSide::Original, 2, 2.)]);
    }

    #[test]
    fn another_view_zone_of_one_side_fills_the_other() {
        // A 50px zone below unchanged modified line 1 and a 30px one in the change (below modified line 3); line height 10.
        let (original, modified) = (lines("a\nb\nc"), lines("a\nb\nx\nc"));
        let diff = diff::compute_diff(&original, &modified, DiffOptions::default());
        let zones = additional_heights([(3, 20.), (1, 50.), (3, 10.)].into_iter());
        assert_eq!(zones, vec![(1, 50.), (3, 30.)]);
        let alignments = range_alignment(&diff, &original, true, &[], &zones, 10.);
        assert_eq!(view_zones(&diff, &alignments, true, 10.).iter().map(|zone| (zone.side, zone.after_line, zone.height)).collect::<Vec<_>>(), vec![(ZoneSide::Original, 1, 50.), (ZoneSide::Original, 2, 40.)]);
        // The original side's zone below line 1 fills the modified side instead.
        let alignments = range_alignment(&diff, &original, true, &[(1, 50.)], &[], 10.);
        assert_eq!(view_zones(&diff, &alignments, true, 10.).iter().map(|zone| (zone.side, zone.after_line, zone.height)).collect::<Vec<_>>(), vec![(ZoneSide::Modified, 1, 50.), (ZoneSide::Original, 2, 10.)]);
    }
}