Skip to content

Visual Studio Code, rebuilt in Rust

Rust
17.4 KB
Raw Blame
//! Injected text (model.ts `InjectedTextOptions`, modelLineProjectionData.ts): text an editor shows between a model
//! line's chars without it being in the model (inlay hints, color boxes, ghost text). It moves every later x of
//! its line right, so every x of a model column goes through `LineLayout`. A cursor head keeps its model position
//! plus how many injections at its column it sits after (upstream's view position).

use super::cursor::Position;
use super::folding::tracked;
use super::{OpenEditor, char_advance, char_columns, edit::end_of};

/// Who injected the text; each owner draws its own.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InjectionOwner {
    InlayHint,
    Color,
    GhostText,
    /// The `before` and `after` content text of an extension's decoration type.
    DecorationContent,
    /// The room of the inline progress widget, which draws itself.
    InlineProgress,
    /// A debug inline value after its line (debugEditorContribution.ts `createInlineValueDecoration`).
    DebugInlineValue,
    /// The arrow before a top stack frame's column (callStackEditorContribution.ts `makeStackFrameColumnDecoration`).
    StackFrameColumn,
    /// An inline breakpoint or candidate's `debug-breakpoint-placeholder` (breakpointEditorContribution.ts).
    InlineBreakpoint,
    /// An inline coverage count badge or missed-branch indicator (codeCoverageDecorations.ts `countBadge`).
    Coverage,
}

impl InjectionOwner {
    /// The `InjectedTextCursorStops` of the owner's injections: an inlay hint's last part `Right`, ghost text `Left`,
    /// a color box and the progress room the default `Both`. Decoration content is CSS content upstream, outside
    /// the view positions, so the cursor stays before it.
    fn cursor_stops(self) -> CursorStops {
        match self {
            InjectionOwner::InlayHint => CursorStops::Right,
            // A debug inline value's `InjectedTextCursorStops.None` sits at the line's end, where Left is the one stop.
            InjectionOwner::GhostText | InjectionOwner::DecorationContent | InjectionOwner::DebugInlineValue | InjectionOwner::Coverage => CursorStops::Left,
            InjectionOwner::Color | InjectionOwner::InlineProgress | InjectionOwner::StackFrameColumn | InjectionOwner::InlineBreakpoint => CursorStops::Both,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CursorStops {
    Left,
    Right,
    Both,
}

impl CursorStops {
    fn left(self) -> bool {
        self != CursorStops::Right
    }

    fn right(self) -> bool {
        self != CursorStops::Left
    }
}

/// `normalizeOffsetInInputWithInjectionsAroundInjections` with `PositionAffinity.None` over the injections at one
/// column: a position `past` of them (clamped to all) moves to where a cursor may rest, also as a count.
pub fn cursor_stop(stops: &[CursorStops], past: usize) -> usize {
    let past = past.min(stops.len());
    if stops.is_empty() {
        return 0;
    }
    let index = past.saturating_sub(1);
    if past > 0 && stops[index].right() {
        return past;
    }
    if stops[index].left() {
        return index;
    }
    let mut result = index;
    for previous in (0..index).rev() {
        if stops[previous].right() {
            break;
        }
        result -= 1;
        if stops[previous].left() {
            break;
        }
    }
    result
}

/// How monospaceLineBreaksComputer.ts measures an injected text when wrapping; the drawn width does not count.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WrapWidth {
    /// Each injected char its own column width, whatever font draws it.
    Chars,
    /// `widthInEm`: one piece `columns` wide that never breaks.
    Fixed,
    /// An inlay hint: its label chars between its `paddingLeft` and `paddingRight` whitespace (width-only
    /// injections) of these columns; the `editor.inlayHints.padding` box (`padding` columns each side) and font size
    /// do not count. The box's left side is on the first label part (its chars end at `first_part_end`), its right
    /// side on the last (from `last_part_start`).
    Hint { left: f32, right: f32, padding: f32, first_part_end: usize, last_part_start: usize },
}

impl WrapWidth {
    /// A wrap before label char `index` of a hint cuts its part's span in two, and each piece takes the part's
    /// padding (inlayHintsController.ts `cssProperties.padding`): the right side added to the piece before the wrap
    /// and the left side to the piece after it, in columns.
    pub fn hint_split_padding(&self, index: usize) -> (f32, f32) {
        let WrapWidth::Hint { padding, first_part_end, last_part_start, .. } = *self else { return (0., 0.) };
        let right = if index > last_part_start { padding } else { 0. };
        let left = if index < first_part_end { padding } else { 0. };
        (right, left)
    }
}

/// One injected text before the char at `position` (after the line's last char at its length).
#[derive(Clone, Debug, PartialEq)]
pub struct InjectedText {
    pub position: Position,
    /// The drawn width in editor columns (fractional when the text uses another font size or has padding).
    pub columns: f32,
    /// `InjectedTextOptions.content`: the injected chars, which the tab stops after them count (`_renderLine`).
    pub content: String,
    pub wrap: WrapWidth,
    pub owner: InjectionOwner,
    /// The owner's index of what it drew here.
    pub id: usize,
    /// `AlwaysGrowsWhenTypingAtEdges` on the owner's range: an injection at the range's start keeps to the
    /// char before it when text is typed at it, one at the end moves with the typed text.
    pub at_range_start: bool,
}

/// The x of every model column of one line, in editor columns from the line's start: `column_x`, the injected
/// texts' widths added (`ModelLineProjectionData.translateToOutputPosition`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LineLayout {
    /// The x in columns of each char boundary without the injections (`column_x`), `len + 1` entries.
    text_x: Vec<f32>,
    /// The visible column each char starts at, the injected chars before it counted (`_renderLine`'s `visibleColumn`).
    visible: Vec<usize>,
    /// (char column, width, width of its last char) of each injection, by column.
    injections: Vec<(usize, f32, f32)>,
}

impl LineLayout {
    /// `injections` are (char column, width, content) by column.
    pub fn new<'a>(text: &str, tab_size: usize, injections: impl IntoIterator<Item = (usize, f32, &'a str)>) -> Self {
        let injections: Vec<_> = injections.into_iter().collect();
        let mut text_x = Vec::with_capacity(text.len() + 1);
        let mut visible_at = Vec::with_capacity(text.len());
        let (mut visible, mut x) = (0, 0.);
        let mut pending = injections.iter().peekable();
        text_x.push(0.);
        for (column, c) in text.chars().enumerate() {
            while let Some((_, _, content)) = pending.next_if(|(at, ..)| *at == column) {
                visible = content.chars().fold(visible, |visible, c| visible + char_columns(c, visible, tab_size));
            }
            visible_at.push(visible);
            x += char_advance(c, visible, tab_size);
            visible += char_columns(c, visible, tab_size);
            text_x.push(x);
        }
        LineLayout { text_x, visible: visible_at, injections: injections.into_iter().map(|(column, width, content)| (column, width, width / content.chars().count().max(1) as f32)).collect() }
    }

    /// The visible column char `column` starts at, the injected chars before it counted.
    pub fn visible(&self, column: usize) -> usize {
        self.visible[column]
    }

    fn len(&self) -> usize {
        self.text_x.len() - 1
    }

    fn injected_before(&self, column: usize, including_column: bool) -> f32 {
        self.injections.iter().take_while(|(at, ..)| *at < column || (including_column && *at == column)).map(|(_, width, _)| width).sum()
    }

    /// `PositionAffinity.None`: a position at an injection is before it, as the cursor draws.
    pub fn x(&self, column: usize) -> f32 {
        let column = column.min(self.len());
        self.text_x[column] + self.injected_before(column, false)
    }

    /// A cursor at `column` after `past` of the injections there.
    pub fn cursor_x(&self, column: usize, past: usize) -> f32 {
        let column = column.min(self.len());
        let at_column = self.injections.iter().filter(|(at, ..)| *at == column).take(past).map(|(_, width, _)| width).sum::<f32>();
        self.x(column) + at_column
    }

    /// `PositionAffinity.Right`: where the char at `column` starts, after the injections at it.
    pub fn char_x(&self, column: usize) -> f32 {
        let column = column.min(self.len());
        self.text_x[column] + self.injected_before(column, true)
    }

    /// `convertModelRangeToViewRange`: an empty range sits before the injections at it; a range starts after
    /// the injections at its start and ends before the ones at its end.
    pub fn range(&self, start: usize, end: usize) -> (f32, f32) {
        match start == end {
            true => (self.x(start), self.x(start)),
            false => (self.char_x(start), self.x(end)),
        }
    }

    /// The line's width with the injections after its last char.
    pub fn width(&self) -> f32 {
        self.char_x(self.len())
    }

    /// The model column nearest to `x` for a click: a char takes the clicks up to its middle, a click on an
    /// injection goes to its column.
    pub fn column_at(&self, x: f32) -> usize {
        self.position_at(x).0
    }

    /// The view position nearest to `x` for a click (`caretRangeFromPoint`), as (model column, injections there
    /// it is past): an injection takes the clicks up to the middle of its last char, the char after it the clicks up
    /// to its own middle, both after the injection.
    pub fn position_at(&self, x: f32) -> (usize, usize) {
        let mut injections = self.injections.iter().peekable();
        for column in 0..=self.len() {
            let mut left = self.x(column);
            let mut past = 0;
            while let Some((_, width, last_char)) = injections.next_if(|(at, ..)| *at == column) {
                if x < left + width {
                    return (column, if x > left + width - last_char / 2. { past + 1 } else { past });
                }
                left += width;
                past += 1;
            }
            // `columnFromVisibleColumn`: the left column on a tie.
            if column == self.len() || x <= (left + self.x(column + 1)) / 2. {
                return (column, past);
            }
        }
        unreachable!("the last column returns")
    }

    /// `column_at` as the x of the model text alone, which the click handlers take.
    pub fn model_visible(&self, x: f32) -> f32 {
        self.text_x[self.column_at(x)]
    }

    /// `x` in the model text's x for a hover, which takes the char under the mouse (mouseTarget.ts
    /// `createMouseTargetFromHitTestPosition`'s range): an x on an injection is its column's.
    pub fn model_x(&self, x: f32) -> f32 {
        let mut injected = 0.;
        let mut injections = self.injections.iter().peekable();
        for column in 0..=self.len() {
            while let Some((_, width, _)) = injections.next_if(|(at, ..)| *at == column) {
                if x < self.text_x[column] + injected + width {
                    return self.text_x[column];
                }
                injected += width;
            }
            if column < self.len() && x < self.text_x[column + 1] + injected {
                break;
            }
        }
        x - injected
    }

    pub fn injection_column(&self, index: usize) -> usize {
        self.injections[index].0
    }

    /// The injections of the line with their x, for drawing.
    pub fn injection_x(&self) -> impl Iterator<Item = (usize, f32)> + '_ {
        self.injections.iter().enumerate().map(|(index, &(column, ..))| (index, self.text_x[column.min(self.len())] + self.injections[..index].iter().map(|(_, width, _)| width).sum::<f32>()))
    }
}

impl OpenEditor {
    /// The injected texts on model line `line`, by column.
    pub fn injected_text_on(&self, line: usize) -> &[InjectedText] {
        let first = self.injected_text.partition_point(|injection| injection.position.line < line);
        let count = self.injected_text[first..].partition_point(|injection| injection.position.line == line);
        &self.injected_text[first..first + count]
    }

    /// How many injections at cursor `index`'s head it sits after: set by the last cursor move while the cursors
    /// stay where it left them, the injections there since then counted again.
    pub fn head_past_injections(&self, index: usize) -> usize {
        let head = self.selections[index].head;
        let Some((selections, heads)) = &self.past_injections else { return 0 };
        let past = if *selections == self.selections { heads.iter().find(|(at, _)| *at == head).map_or(0, |(_, past)| *past) } else { 0 };
        cursor_stop(&self.cursor_stops(head), past)
    }

    /// After a cursor move: each head (position, injections past it, `usize::MAX` for all) at its cursor stop.
    pub(super) fn set_heads_past_injections(&mut self, heads: impl IntoIterator<Item = (Position, usize)>) {
        let heads: Vec<_> = heads.into_iter().map(|(head, past)| (head, cursor_stop(&self.cursor_stops(head), past))).filter(|(_, past)| *past > 0).collect();
        self.past_injections = (!heads.is_empty()).then(|| (self.selections.clone(), heads));
    }

    /// A press at x `layout_x` of model line `line` that put the last cursor at its column: it rests past the
    /// injections the press was past (`normalizePosition` with `PositionAffinity.None`).
    pub fn click_past_injections(&mut self, line: usize, layout_x: f32) {
        let (column, past) = self.line_layout(line).position_at(layout_x);
        let head = self.selections.last().expect("an editor has a cursor").head;
        if head == Position::new(line, column) {
            let heads: Vec<_> = self.selections.iter().map(|selection| (selection.head, if selection.head == head { past } else { 0 })).collect();
            self.set_heads_past_injections(heads);
        }
    }

    /// The x range of cursor `index`'s selection over columns `start..end` of `layout`'s model line `line`: `range`,
    /// its head's edge at the head's view position (`viewState.selection`), past the injections it moved over.
    pub fn selection_x(&self, index: usize, layout: &LineLayout, line: usize, start: usize, end: usize) -> (f32, f32) {
        let selection = self.selections[index];
        let (mut left, mut right) = layout.range(start, end);
        if selection.head == Position::new(line, end) && selection.head > selection.anchor {
            right = layout.cursor_x(end, self.head_past_injections(index));
        }
        if selection.head == Position::new(line, start) && selection.head < selection.anchor {
            left = layout.cursor_x(start, self.head_past_injections(index));
        }
        (left, right)
    }

    fn cursor_stops(&self, position: Position) -> Vec<CursorStops> {
        self.injected_text_on(position.line).iter().filter(|injection| injection.position.column == position.column).map(|injection| injection.owner.cursor_stops()).collect()
    }

    /// The x of every column of model line `line`.
    pub fn line_layout(&self, line: usize) -> LineLayout {
        let document = self.document();
        let splits = self.hint_splits(line);
        let columns = |index: usize, injection: &InjectedText| {
            let split_padding = |(_, char): &(usize, usize)| -> f32 {
                let (right, left) = injection.wrap.hint_split_padding(*char);
                right + left
            };
            injection.columns + splits.iter().filter(|(split, _)| *split == index).map(split_padding).sum::<f32>()
        };
        LineLayout::new(&document.lines[line], document.indentation.tab_size, self.injected_text_on(line).iter().enumerate().map(|(index, injection)| (injection.position.column, columns(index, injection), injection.content.as_str())))
    }

    /// `changeDecorations` of one owner's injected text: replaces what it injected before; the lines with
    /// changed injections break again.
    pub fn set_injected_text(&mut self, owner: InjectionOwner, mut injections: Vec<InjectedText>) {
        let mut lines: Vec<usize> = self.injected_text.iter().filter(|injection| injection.owner == owner).map(|injection| injection.position.line).collect();
        lines.extend(injections.iter().map(|injection| injection.position.line));
        self.injected_text.retain(|injection| injection.owner != owner);
        self.injected_text.append(&mut injections);
        // Stable, so the owner's order holds among the injections at one position.
        self.injected_text.sort_by_key(|injection| injection.position);
        lines.sort_unstable();
        lines.dedup();
        let document = self.model.borrow();
        for line in lines.into_iter().filter(|line| *line < document.document.lines.len()) {
            self.word_wrap.line_injections_changed(&document.document.lines, line, &self.injected_text);
        }
    }

    /// The injections follow an edit like their owner's decorations (intervalTree.ts `nodeAcceptEdit`).
    pub(super) fn track_injected_text(&mut self, start: Position, end: Position, text: &str) {
        let new_end = end_of(start, text);
        for injection in &mut self.injected_text {
            injection.position = tracked(injection.position, start, end, new_end, injection.at_range_start);
        }
        self.injected_text.sort_by_key(|injection| injection.position);
    }
}

#[cfg(test)]
mod tests;