Skip to content

Visual Studio Code, rebuilt in Rust

Rust
12.5 KB
Raw Blame
//! The browser's text selection over text drawn with `user-select: text`: the Test Results markdown message and the
//! Debug Console (repl.css). One selection per window, as the browser's; each surface keeps its own texts, so a part
//! that redraws alone (part_view.rs) replaces only its own.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use gpui::{Bounds, Context, InteractiveElement, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, Point, SharedString, Styled, TextLayout, canvas, point, px};

use super::Workbench;

/// A surface whose texts can be selected.
pub(super) type TextSurface = &'static str;

/// The texts of each surface in document order as last drawn, and the selection's surface, anchor and head as
/// (text, byte offset).
#[derive(Default)]
pub(super) struct TextSelection {
    surfaces: RefCell<Vec<(TextSurface, Vec<SelectableText>)>>,
    surface: TextSurface,
    anchor: (usize, usize),
    head: (usize, usize),
    selecting: bool,
}

struct SelectableText {
    layout: TextLayout,
    text: SharedString,
    /// Its bounds as last drawn; none for a text not drawn yet.
    bounds: Rc<Cell<Option<Bounds<Pixels>>>>,
    /// What a copy puts between it and the text before it, as Chrome's selection `toString`: nothing inside a
    /// paragraph drawn word by word, `\n` between a code block's lines or the console's rows, `\n\n` between blocks.
    /// shortcut: list items take `\n\n` where Chrome's tight `li` gives `\n`, refine when a list message needs it.
    separator: &'static str,
}

impl TextSelection {
    /// The selection's start and end, the anchor or the head first.
    fn ordered(&self) -> ((usize, usize), (usize, usize)) {
        (self.anchor.min(self.head), self.anchor.max(self.head))
    }

    pub(super) fn is_collapsed(&self) -> bool {
        self.anchor == self.head
    }

    /// Drops the selection when it is in `surface`, whose content changed under it.
    pub(super) fn collapse_in(&mut self, surface: TextSurface) {
        if self.surface == surface {
            self.head = self.anchor;
        }
    }

    /// Starts drawing `surface` again: its texts are the ones taken from here on.
    pub(super) fn begin(&self, surface: TextSurface) {
        let mut surfaces = self.surfaces.borrow_mut();
        match surfaces.iter_mut().find(|(drawn, _)| *drawn == surface) {
            Some((_, texts)) => texts.clear(),
            None => surfaces.push((surface, Vec::new())),
        }
    }

    fn with_texts<R>(&self, surface: TextSurface, read: impl FnOnce(&[SelectableText]) -> R) -> R {
        let surfaces = self.surfaces.borrow();
        let texts = surfaces.iter().find(|(drawn, _)| *drawn == surface).map_or(&[][..], |(_, texts)| texts.as_slice());
        read(texts)
    }

    /// The selected text: each text after the separator it takes.
    pub(super) fn to_text(&self) -> String {
        let mut selected = String::new();
        if self.is_collapsed() {
            return selected;
        }
        let (start, end) = self.ordered();
        self.with_texts(self.surface, |texts| {
            for (index, text) in texts.iter().enumerate().take(end.0 + 1).skip(start.0) {
                let from = if index == start.0 { start.1 } else { 0 };
                let to = if index == end.0 { end.1 } else { text.text.len() };
                if index > start.0 {
                    selected.push_str(text.separator);
                }
                selected.push_str(&text.text[from..to]);
            }
        });
        selected
    }
}

impl Workbench {
    /// `root` as the box of `surface`'s texts: a press places the selection, two select the word and three the text, a
    /// drag or a shift press moves its head, a press elsewhere clears it.
    pub(super) fn text_selection_root<E: ParentElement + InteractiveElement>(&self, surface: TextSurface, root: E, cx: &mut Context<Self>) -> E {
        let workbench = cx.entity();
        let selecting = self.text_selection.selecting && self.text_selection.surface == surface;
        // The drag goes on outside the text, as the browser's.
        let drag = canvas(
            |_, _, _| (),
            move |_, _, window, _| {
                if !selecting {
                    return;
                }
                let moved = workbench.clone();
                window.on_mouse_event(move |event: &MouseMoveEvent, phase, _, cx| {
                    if phase == gpui::DispatchPhase::Capture && event.pressed_button == Some(MouseButton::Left) {
                        moved.update(cx, |workbench, cx| workbench.move_text_selection(event.position, cx));
                    }
                });
                let released = workbench.clone();
                window.on_mouse_event(move |_: &gpui::MouseUpEvent, phase, _, cx| {
                    if phase == gpui::DispatchPhase::Capture {
                        released.update(cx, |workbench, _| workbench.text_selection.selecting = false);
                    }
                });
            },
        )
        .absolute()
        .size_0();
        root.child(drag)
            .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, event: &MouseDownEvent, _, cx| {
                workbench.press_text_selection(surface, event.position, event.click_count, event.modifiers.shift, cx);
            }))
            .on_mouse_down_out(cx.listener(move |workbench, _: &MouseDownEvent, _, cx| {
                // A press in a context menu opened on the text keeps the selection, as the browser's native menu does.
                let selection = &mut workbench.text_selection;
                if selection.surface == surface && !selection.is_collapsed() && workbench.context_menu.is_none() {
                    selection.anchor = selection.head;
                    cx.notify();
                }
            }))
    }

    fn press_text_selection(&mut self, surface: TextSurface, position: Point<Pixels>, click_count: usize, shift: bool, cx: &mut Context<Self>) {
        let Some(at) = self.text_selection_at(surface, position) else { return };
        let same_surface = self.text_selection.surface == surface;
        let (anchor, head) = self.text_selection.with_texts(surface, |texts| {
            let text = &texts[at.0].text;
            match click_count {
                1 if shift && same_surface => (self.text_selection.anchor, at),
                1 => (at, at),
                2 => {
                    let word = word_at(text, at.1);
                    ((at.0, word.start), (at.0, word.end))
                }
                _ => ((at.0, 0), (at.0, text.len())),
            }
        });
        let selection = &mut self.text_selection;
        (selection.surface, selection.anchor, selection.head, selection.selecting) = (surface, anchor, head, true);
        cx.notify();
    }

    fn move_text_selection(&mut self, position: Point<Pixels>, cx: &mut Context<Self>) {
        let Some(at) = self.text_selection_at(self.text_selection.surface, position).filter(|at| *at != self.text_selection.head) else { return };
        self.text_selection.head = at;
        cx.notify();
    }

    /// The text and the character boundary at `position`: the drawn text nearest to it, vertically first.
    fn text_selection_at(&self, surface: TextSurface, position: Point<Pixels>) -> Option<(usize, usize)> {
        let distance = |bounds: Bounds<Pixels>| {
            let away = |low: Pixels, high: Pixels, at: Pixels| (low - at).max(at - high).max(px(0.));
            (away(bounds.top(), bounds.bottom(), position.y), away(bounds.left(), bounds.right(), position.x))
        };
        self.text_selection.with_texts(surface, |texts| {
            let mut nearest: Option<(usize, (Pixels, Pixels))> = None;
            for (index, text) in texts.iter().enumerate() {
                let Some(bounds) = text.bounds.get() else { continue };
                if nearest.is_none_or(|(_, best)| distance(bounds) < best) {
                    nearest = Some((index, distance(bounds)));
                }
            }
            let (index, _) = nearest?;
            Some((index, closest_index(&texts[index].layout, position)))
        })
    }

    /// Takes `layout` into `surface` as its next text, and paints the selection's part of it behind it in
    /// `selection.background`, else Chrome's `::selection` default as measured with the blue accent: #B0D4FB light, #567BA1 dark.
    pub(super) fn selectable_text(&self, surface: TextSurface, layout: &TextLayout, text: SharedString, separator: &'static str) -> gpui::Canvas<()> {
        let bounds = Rc::new(Cell::new(None));
        let mut surfaces = self.text_selection.surfaces.borrow_mut();
        let texts = &mut surfaces.iter_mut().find(|(drawn, _)| *drawn == surface).expect("`TextSelection::begin` starts the surface").1;
        let index = texts.len();
        texts.push(SelectableText { layout: layout.clone(), text, bounds: bounds.clone(), separator });
        let selection = &self.text_selection;
        let (start, end) = selection.ordered();
        let painted = selection.surface == surface && !selection.is_collapsed() && (start.0..=end.0).contains(&index);
        let color = match self.theme.color("selection.background") {
            Some(_) => self.color("selection.background"),
            None if self.theme.kind.is_light() => gpui::rgb(0xb0d4fb),
            None => gpui::rgb(0x567ba1),
        };
        let layout = layout.clone();
        canvas(
            move |drawn, _, _| bounds.set(Some(drawn)),
            move |_, _, window, _| {
                if !painted {
                    return;
                }
                let from = if index == start.0 { start.1 } else { 0 };
                let to = if index == end.0 { end.1 } else { layout.len() };
                for row in text_rows(&layout, from..to) {
                    window.paint_quad(gpui::fill(row, color));
                }
            },
        )
        .absolute()
        .inset_0()
    }
}

/// The box of `range` on each row of the laid out text. `position_for_index` puts a wrap boundary at the end of the
/// row before it, so a row ends where the next index moves down.
pub(super) fn text_rows(layout: &TextLayout, range: std::ops::Range<usize>) -> Vec<Bounds<Pixels>> {
    let line_height = layout.line_height();
    let left = layout.bounds().origin.x;
    let text = layout.text();
    let indices = text[range.clone()].char_indices().map(|(index, _)| range.start + index).chain([range.end]);
    let mut rows = Vec::new();
    let mut row: Option<(gpui::Point<Pixels>, Pixels)> = None;
    for index in indices {
        let Some(position) = layout.position_for_index(index) else { continue };
        row = match row {
            Some((start, _)) if start.y == position.y => Some((start, position.x)),
            Some((start, right)) => {
                rows.push(Bounds::from_corners(start, point(right, start.y + line_height)));
                Some((point(left, position.y), position.x))
            }
            None => Some((position, position.x)),
        };
    }
    rows.extend(row.map(|(start, right)| Bounds::from_corners(start, point(right, start.y + line_height))));
    rows.retain(|bounds| bounds.size.width > px(0.));
    rows
}

/// The character boundary of the drawn text nearest to `position`: on its row, or the row it is level with.
fn closest_index(layout: &TextLayout, position: Point<Pixels>) -> usize {
    let line_height = layout.line_height();
    let mut origin = layout.bounds().origin;
    let mut start = 0;
    for line in layout.line_layouts() {
        let bottom = origin.y + line.size(line_height).height;
        if position.y < bottom {
            let within = point(position.x - origin.x, (position.y - origin.y).max(px(0.)));
            return start + line.closest_index_for_position(within, line_height).unwrap_or_else(|index| index);
        }
        origin.y = bottom;
        start += line.len() + 1;
    }
    layout.len()
}

/// The word around the boundary `at` for a double click: a run of letters, digits and `_`, else the character there.
fn word_at(text: &str, at: usize) -> std::ops::Range<usize> {
    let is_word = |c: char| c.is_alphanumeric() || c == '_';
    let Some(here) = text[at..].chars().next().or_else(|| text[..at].chars().next_back()) else { return at..at };
    if !is_word(here) {
        let start = if at == text.len() { at - here.len_utf8() } else { at };
        return start..start + here.len_utf8();
    }
    let start = text[..at].char_indices().rev().take_while(|(_, c)| is_word(*c)).last().map_or(at, |(index, _)| index);
    let end = text[at..].char_indices().find(|(_, c)| !is_word(*c)).map_or(text.len(), |(index, _)| at + index);
    start..end
}