Skip to content

Visual Studio Code, rebuilt in Rust

Rust
17.4 KB
Raw Blame
//! Keyboard and text input of the code editor: keys no keybinding took, and the platform text input
//! (IME, dead keys) through GPUI's input handler. Keybindings run before this (workbench/keyboard.rs).

use std::ops::Range;
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;

use gpui::{Bounds, Context, EntityInputHandler, KeyDownEvent, Pixels, UTF16Selection, Window, px};

use config::configuration::Overrides;
use futures::channel::oneshot;

use super::Workbench;
use super::auto_save::SaveReason;
use super::text_files::SaveOptions;
use serde_json::json;

use super::model_events::Cursor;
use crate::editor::Reveal;
use crate::editor::save_participants::SaveParticipants;
use crate::editor::edit_stack::{TYPING_LABEL, UndoElement};
use crate::editor::{Position, Selection, uri_string, utf16_column};
use crate::local_history;

/// The text participants to run: all, or the ones `SaveParticipantsContribution` registers before or after
/// `FormatOnSaveParticipant`.
#[derive(Clone, Copy, PartialEq)]
pub(super) enum SavePhase {
    All,
    BeforeFormat,
    AfterFormat,
}

impl Workbench {
    /// Enter reaches the editor as typed text, the line break the browser's textarea would insert. codeEditorWidget.ts
    /// `trigger` runs `Handler.Type` itself, not through the command service, so typing never waits for an activation.
    pub(super) fn editor_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
        let modifiers = event.keystroke.modifiers;
        if event.keystroke.key != "enter" || modifiers.platform || modifiers.control || modifiers.alt || self.marked_text.is_some() {
            return;
        }
        cx.stop_propagation();
        let typing = self.commands.get("type").expect("editor_commands registers type");
        drop(typing(self, vec![json!({ "text": "\n" })], window, cx));
    }

    /// fileCommands.ts `save`: the editor's model, also when clean (`force`).
    pub(super) fn save_editor(&mut self, index: usize, cx: &mut Context<Self>) -> oneshot::Receiver<bool> {
        let document = self.editors.tab_model(index).document();
        let (scheme, path) = (document.scheme.clone(), document.path.clone());
        drop(document);
        if scheme == crate::notebook::NOTEBOOK_EDITOR_SCHEME {
            return self.save_notebook_editor(&path.to_string_lossy(), cx);
        }
        self.save_model_with(scheme, path, SaveReason::Explicit, SaveOptions { force: true, ..SaveOptions::default() }, cx)
    }

    /// `textFileService.save` of any open model, one without an editor too.
    pub(super) fn save_model(&mut self, scheme: String, path: PathBuf, reason: SaveReason, cx: &mut Context<Self>) -> oneshot::Receiver<bool> {
        self.save_model_with(scheme, path, reason, SaveOptions::default(), cx)
    }

    /// saveParticipants.ts: the text participants of the model's language and resource, their changes sent to the host.
    pub(super) fn run_save_participants(&mut self, scheme: &str, path: &Path, reason: SaveReason, phase: SavePhase, cx: &mut Context<Self>) {
        // `findEditor`: only the group's one code editor, showing the active model, has cursors.
        let shown = self.editors.active().is_some_and(|editor| editor.document().is(scheme, path));
        let model = self.editors.model_mut(scheme, path).expect("saving an open model");
        let spared_cursors = match reason == SaveReason::Auto && shown {
            true => model.selections.iter().map(|selection| selection.head).collect(),
            false => Vec::new(),
        };
        let settings = self.settings.lock().unwrap();
        let language_id = model.document().language_id.clone();
        let overrides = Overrides { resource: Some(path), override_identifier: Some(&language_id) };
        let on = |key: &str| settings.get_value(Some(key), &overrides) == Some(json!(true));
        let participants = SaveParticipants {
            trim_trailing_whitespace: phase != SavePhase::AfterFormat && on("files.trimTrailingWhitespace"),
            trim_in_regex_and_strings: settings.get_value(Some("files.trimTrailingWhitespaceInRegexAndStrings"), &overrides) != Some(json!(false)),
            insert_final_newline: phase != SavePhase::BeforeFormat && on("files.insertFinalNewline"),
            trim_final_newlines: phase != SavePhase::BeforeFormat && on("files.trimFinalNewlines"),
            spared_cursors,
        };
        drop(settings);
        let changes = model.run_save_participants(&participants);
        let changed = !changes.is_empty();
        for change in changes {
            // Only FinalNewLineParticipant edits through the shown editor (`executeEdits`); the others through the model.
            let source = match super::model_events::edit_source(&change.reason) {
                "insertFinalNewLine" => "insertFinalNewLine",
                _ => "modelChange",
            };
            self.model_content_changed(Some(change), Cursor { moved: false, source, reveal: Reveal::Nothing }, cx);
        }
        if changed {
            self.host.send_visible_ranges(&self.editors);
        }
    }

    /// workingCopyHistoryTracker.ts `onDidSave`: the saved file goes into the local history with its modification
    /// time, its source from the undo stack (`resolveSourceFromUndoRedo`).
    pub(super) fn add_local_history_entry(&self, scheme: &str, path: &Path, cx: &mut Context<Self>) {
        let Ok(metadata) = std::fs::metadata(path) else { return };
        let source = self.editors.model(scheme, path).and_then(|model| {
            let undo_redo = model.text_model().undo_redo.clone();
            let undo_redo = undo_redo.borrow();
            let key = model.undo_key();
            match undo_redo.last_element_and_label(&key) {
                // Only typing's elements are `undoredo.textBufferEdit`: a plain save.
                Some((UndoElement::Model(_), TYPING_LABEL)) => None,
                Some((_, label)) => Some(label.to_owned()),
                None if undo_redo.has_elements(&key) => Some("undoRedo.source".to_owned()),
                None => None,
            }
        });
        let settings = self.settings.lock().unwrap();
        let Some(limits) = local_history::tracked(&settings, path, metadata.len()) else { return };
        let history_home = settings.user_home().join("History");
        drop(settings);
        let timestamp = metadata.modified().ok().and_then(|modified| modified.duration_since(UNIX_EPOCH).ok()).map_or(0, |since| since.as_millis() as i64);
        let (resource, path) = (uri_string(scheme, path), path.to_path_buf());
        let added = cx.background_executor().spawn(async move {
            if let Err(error) = local_history::add_entry(&history_home, &resource, &path, source.as_deref(), None, timestamp, &limits) {
                eprintln!("local history of {}: {error}", path.display());
            }
        });
        cx.spawn(async move |workbench, cx| {
            added.await;
            let _ = workbench.update(cx, |workbench, cx| workbench.local_history_changed(cx));
        })
        .detach();
    }

    /// nativeEditContext.ts `_emitTypeEvent`: a UTF-16 range of the edit context's text as the chars it replaces
    /// before and after the primary selection (`replacePrevCharCnt`, `replaceNextCharCnt`); a count past the
    /// selection's line stops at it, as `compositionType` validates its range.
    fn input_range(&self, range: Range<usize>) -> (usize, usize) {
        let editor = self.editors.active().expect("input goes to the active editor");
        let selection = editor.selection();
        let (selection_start, selection_end) = (selection.start(), selection.end());
        let document = editor.document();
        let lines = &document.lines[selection_start.line..=selection_end.line];
        let first = selection_start.line;
        let start = position_at_utf16(lines, document.eol.len(), range.start);
        let end = position_at_utf16(lines, document.eol.len(), range.end);
        let previous = if start.line + first == selection_start.line { selection_start.column.saturating_sub(start.column) } else { selection_start.column };
        let next = match end.line + first == selection_end.line {
            true => end.column,
            false => lines[selection_end.line - first].chars().count(),
        };
        let next = next.saturating_sub(selection_end.column);
        (previous, next)
    }

    /// The edit context's text (`_getNewEditContextState`): the primary selection's lines, from its start line's
    /// start to its end line's end, joined by the model's EOL, with the selection's model position of its start.
    fn edit_context_text(&self) -> Option<(String, Position, Position)> {
        let editor = self.editors.active()?;
        let selection = editor.selection();
        let document = editor.document();
        Some((document.lines[selection.start().line..=selection.end().line].join(document.eol), selection.start(), selection.end()))
    }
}

/// The platform's text input sees the primary selection's lines (nativeEditContext.ts, the EditContext API that
/// VS Code uses on Electron), offsets in UTF-16 units.
impl EntityInputHandler for Workbench {
    fn text_for_range(&mut self, range: Range<usize>, adjusted_range: &mut Option<Range<usize>>, window: &mut Window, _: &mut Context<Self>) -> Option<String> {
        if let Some(id) = self.focused_input(window) {
            return self.input_text_for_range(id, range, adjusted_range);
        }
        let (text, _, _) = self.edit_context_text()?;
        let units: Vec<u16> = text.encode_utf16().collect();
        let range = range.start.min(units.len())..range.end.min(units.len());
        *adjusted_range = Some(range.clone());
        Some(String::from_utf16_lossy(&units[range]))
    }

    fn selected_text_range(&mut self, _: bool, window: &mut Window, _: &mut Context<Self>) -> Option<UTF16Selection> {
        if let Some(id) = self.focused_input(window) {
            return self.input_selected_range(id);
        }
        let editor = self.editors.active()?;
        let selection = editor.selection();
        let document = editor.document();
        let first = selection.start().line;
        let lines = &document.lines[first..=selection.end().line];
        let offset = |position: Position| utf16_offset(lines, document.eol.len(), Position::new(position.line - first, position.column));
        let (anchor, head) = (offset(selection.anchor), offset(selection.head));
        Some(UTF16Selection { range: anchor.min(head)..anchor.max(head), reversed: head < anchor })
    }

    fn marked_text_range(&self, window: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {
        if let Some(id) = self.focused_input(window) {
            return self.input_view(id).marked.clone();
        }
        self.marked_text.clone()
    }

    fn unmark_text(&mut self, window: &mut Window, _: &mut Context<Self>) {
        if let Some(id) = self.focused_input(window) {
            self.input_view_mut(id).marked = None;
            return;
        }
        self.marked_text = None;
    }

    fn replace_text_in_range(&mut self, range: Option<Range<usize>>, text: &str, window: &mut Window, cx: &mut Context<Self>) {
        if let Some(id) = self.focused_input(window) {
            return self.input_replace(id, range, text, false, window, cx);
        }
        if self.edit_blocked(true, cx) {
            self.marked_text = None;
            return;
        }
        let range = range.or(self.marked_text.take()).map(|range| self.input_range(range));
        // An insert at the cursor is typing: the `type` command runs auto-closing and the typed-character triggers
        // (suggest, signature help, format on type), as the textarea's input event does upstream.
        let Some((previous, next)) = range.filter(|range| *range != (0, 0)) else {
            let typing = self.commands.get("type").expect("editor_commands registers type");
            drop(typing(self, vec![json!({ "text": text })], window, cx));
            return;
        };
        let editor = self.editors.active_mut().expect("input goes to the active editor");
        let change = editor.type_replacing(text, previous, next, "type");
        self.model_content_changed(change, Cursor { moved: false, source: "keyboard", reveal: Reveal::All }, cx);
        if self.overtype {
            let editor = self.editors.active_mut().expect("input goes to the active editor");
            let change = editor.overtype_composed(text);
            self.model_content_changed(change, Cursor { moved: false, source: "keyboard", reveal: Reveal::All }, cx);
        }
    }

    /// IME composition: the marked text replaces the previous one and stays marked; the IME's caret inside it
    /// moves each cursor back from the marked text's end (`positionDelta` of `compositionType`).
    fn replace_and_mark_text_in_range(&mut self, range: Option<Range<usize>>, new_text: &str, new_selected_range: Option<Range<usize>>, window: &mut Window, cx: &mut Context<Self>) {
        if let Some(id) = self.focused_input(window) {
            return self.input_replace(id, range, new_text, true, window, cx);
        }
        if self.edit_blocked(true, cx) {
            return;
        }
        let (previous, next) = range.or(self.marked_text.clone()).map_or((0, 0), |range| self.input_range(range));
        let editor = self.editors.active_mut().expect("input goes to the active editor");
        let primary = editor.selection();
        let start = if primary.is_empty() { Position::new(primary.head.line, primary.head.column.saturating_sub(previous)) } else { primary.start() };
        let change = editor.type_replacing(new_text, previous, next, "compositionType");
        let caret = new_selected_range.filter(|selected| primary.is_empty() && selected.is_empty()).map(|selected| column_at_utf16(new_text, selected.end));
        let back = caret.map_or(0, |caret| new_text.chars().count().saturating_sub(caret));
        if back > 0 {
            let selections = editor.selections.iter().map(|selection| Selection::caret(Position::new(selection.head.line, selection.head.column.saturating_sub(back)))).collect();
            editor.set_selections(selections);
        }
        let marked_start = utf16_column(&editor.document().lines[start.line], start.column);
        self.marked_text = (!new_text.is_empty()).then(|| marked_start..marked_start + new_text.encode_utf16().count());
        self.model_content_changed(change, Cursor { moved: false, source: "keyboard", reveal: Reveal::All }, cx);
    }

    /// `_updateCharacterBounds`: where the chars of `range` draw, so the IME's candidate window opens below them.
    fn bounds_for_range(&mut self, range: Range<usize>, _: Bounds<Pixels>, window: &mut Window, _: &mut Context<Self>) -> Option<Bounds<Pixels>> {
        if self.focused_input(window).is_some() {
            return None;
        }
        let editor = self.editors.active()?;
        let metrics = self.editor_metrics(editor, window);
        let document = editor.document();
        let first = editor.selection().start().line;
        let lines = &document.lines[first..=editor.selection().end().line];
        let position = |offset: usize| {
            let position = position_at_utf16(lines, document.eol.len(), offset);
            Position::new(position.line + first, position.column)
        };
        let (start, end) = (position(range.start), position(range.end));
        drop(document);
        let view_line = editor.position_view_line(start, false);
        let segment = editor.segment(view_line);
        let x = |column: usize| metrics.content_left() + editor.segment_visible_column(segment, column) * metrics.char_width - editor.scroll.left;
        let left = x(start.column);
        let width = if end.line == start.line && editor.position_view_line(end, true) == view_line && end.column > start.column { x(end.column) - left } else { metrics.char_width };
        let top = editor.line_top(view_line, self.editors.viewport) - editor.scroll.top;
        let origin = self.text_area_bounds.get().origin;
        Some(Bounds::new(gpui::point(px(origin.x + left), px(origin.y + top)), gpui::size(px(width), px(metrics.line_height))))
    }

    fn character_index_for_point(&mut self, _: gpui::Point<Pixels>, _: &mut Window, _: &mut Context<Self>) -> Option<usize> {
        None
    }
}

#[cfg(test)]
mod tests;

/// The UTF-16 offset of `position` in `lines` joined by an EOL of `eol` units.
fn utf16_offset(lines: &[String], eol: usize, position: Position) -> usize {
    lines[..position.line].iter().map(|line| line.encode_utf16().count() + eol).sum::<usize>() + utf16_column(&lines[position.line], position.column)
}

/// The position of a UTF-16 offset in `lines` joined by an EOL of `eol` units; an offset inside an EOL is its line's end.
fn position_at_utf16(lines: &[String], eol: usize, mut offset: usize) -> Position {
    for (line, text) in lines.iter().enumerate() {
        let units = text.encode_utf16().count();
        if offset <= units || line + 1 == lines.len() {
            return Position::new(line, column_at_utf16(text, offset));
        }
        if offset < units + eol {
            return Position::new(line, text.chars().count());
        }
        offset -= units + eol;
    }
    Position::new(0, 0)
}

/// The char column at a UTF-16 offset of the line; an offset inside a surrogate pair rounds up.
fn column_at_utf16(line: &str, offset: usize) -> usize {
    let mut units = 0;
    for (column, c) in line.chars().enumerate() {
        if units >= offset {
            return column;
        }
        units += c.len_utf16();
    }
    line.chars().count()
}