Skip to content

Visual Studio Code, rebuilt in Rust

Rust
18.3 KB
Raw Blame
//! The workbench's part of `workspace.applyEdit` (contrib/bulkEdit/browser/bulkTextEdits.ts), and what
//! TextFileEditorModelManager does to the text models when a file operation ran.

use std::path::{Path, PathBuf};

use exthost::main_thread::serialized_error;
use gpui::Context;
use serde_json::{Value, json};

use super::Workbench;
use super::format::more_minimal_edits;
use super::host_requests::{range, snippet_edits, uri_parts};
use crate::editor::edit_stack::{ModelResource, MultiModelEditStackElement, SingleModelEditStackElement, UndoElement};
use crate::editor::{EditReason, Position, SharedModel, TextDocument, expand_snippet, uri_string};
use crate::local_history;

impl Workbench {
    /// `BulkTextEdits.apply`: each resource's edits are one model change, made through the active editor when it shows
    /// the model; nothing applies when a model moved past the version the host edited. The undo joins `undo_group`
    /// under `label`, "Workspace Edit" without one (bulkEditService.ts).
    pub fn apply_workspace_text_edits(&mut self, edits: &Value, provider_files: &Value, undo_group: u64, label: Option<&str>, cx: &mut Context<Self>) -> Result<Value, Value> {
        let mut resources: Vec<(&str, PathBuf, Vec<&Value>)> = Vec::new();
        for edit in edits.as_array().into_iter().flatten() {
            let (scheme, path) = uri_parts(&edit["resource"])?;
            match resources.iter_mut().find(|(known_scheme, known_path, _)| *known_scheme == scheme && *known_path == path) {
                Some((_, _, group)) => group.push(edit),
                None => resources.push((scheme, path, vec![edit])),
            }
        }
        let mut opened = false;
        for (scheme, path, _) in &resources {
            if self.editors.model(scheme, path).is_none() {
                let document = self.resolve_document(scheme, path, provider_files)?;
                self.editors.open_model(document);
                opened = true;
            }
        }
        if opened {
            self.editors_changed(cx);
        }
        for (scheme, path, group) in &resources {
            let version_id = self.editors.model(scheme, path).expect("resolved above").text_model().version_id;
            if group.iter().any(|edit| edit["versionId"].as_u64().is_some_and(|expected| expected != u64::from(version_id))) {
                return Err(serialized_error(&format!("{} has changed in the meantime", uri_string(scheme, path))));
            }
        }
        // `ModelEditTask.addEdit`: (start, end, text, insertAsSnippet, keepWhitespace, has metadata), and the EOL.
        let mut tasks = Vec::new();
        for (scheme, path, group) in resources {
            let model = self.editors.model(scheme, &path).expect("resolved above");
            let mut eol = None;
            let mut replaces = Vec::new();
            for edit in group {
                let text_edit = &edit["textEdit"];
                eol = text_edit["eol"].as_u64().or(eol);
                let text = text_edit["text"].as_str().unwrap_or_default();
                let (start, end) = match text_edit["range"].is_null() {
                    true => (Position::new(0, 0), document_end(&model.document().lines)),
                    false => range(model, &text_edit["range"]),
                };
                if (text_edit["range"].is_null() || start == end) && text.is_empty() {
                    continue;
                }
                replaces.push((start, end, text, text_edit["insertAsSnippet"] == json!(true), text_edit["keepWhitespace"] == json!(true), !edit["metadata"].is_null()));
            }
            tasks.push((scheme, path, replaces, eol));
        }
        let mut elements = Vec::new();
        for (scheme, path, replaces, eol) in &tasks {
            let model = self.editors.model(scheme, path).expect("resolved above");
            let is_no_op = replaces.is_empty() && eol.is_none_or(|sequence| model.document().eol == if sequence == 1 { "\r\n" } else { "\n" });
            if tasks.len() == 1 && is_no_op {
                return Ok(Value::Null);
            }
            elements.push(SingleModelEditStackElement::new(ModelResource::new(model.undo_key(), scheme, path.clone()), model.alternative_version_id(), model.document().eol, model.selections.clone()));
        }
        let Some(first) = elements.first() else { return Ok(Value::Null) };
        let first_key = first.resource.key.clone();
        let element = match elements.len() {
            1 => UndoElement::Model(elements.pop().expect("one element")),
            _ => UndoElement::MultiModel(MultiModelEditStackElement::new(elements)),
        };
        let undo_redo = self.editors.undo_redo.clone();
        undo_redo.borrow_mut().push(label.unwrap_or("Workspace Edit").to_owned(), element.resources(), undo_group, 0, false, element);
        let clipboard = cx.read_from_clipboard().and_then(|item| item.text());
        for (scheme, ref path, replaces, eol) in tasks {
            let in_active_editor = self.editors.active().is_some_and(|editor| editor.document().is(scheme, path));
            let model = self.editors.model_mut(scheme, path).expect("resolved above");
            // `EditorEditTask`: the snippet controller takes every edit when one is a snippet; without the editor a snippet is its text.
            let change = if in_active_editor && replaces.iter().any(|replace| replace.3) {
                let templates: Vec<String> = replaces.iter().map(|&(_, _, text, is_snippet, _, _)| if is_snippet { text.to_string() } else { escape_snippet(text) }).collect();
                let snippets: Vec<_> = replaces.iter().zip(&templates).map(|(&(start, end, _, _, keep_whitespace, _), template)| (start, end, template.as_str(), keep_whitespace)).collect();
                let (edits, selections, _) = snippet_edits(model, &self.languages, &snippets, clipboard.as_deref());
                let pairs = self.languages.rules(&model.document().language_id).map(|rules| rules.auto_closing_pairs.as_slice()).unwrap_or_default();
                model.execute_edits_tracking_pairs(edits, Some(selections), EditReason::Unknown("snippet"), pairs)
            } else if in_active_editor {
                // `_createEditsTasks`: the active editor's edits are made more minimal, in runs split by edits with metadata.
                let mut edits = Vec::new();
                let mut run = Vec::new();
                for &(start, end, text, _, _, has_metadata) in &replaces {
                    if has_metadata {
                        edits.extend(more_minimal_edits(&model.document().lines, std::mem::take(&mut run)));
                        edits.push((start, end, text.to_string()));
                    } else {
                        run.push((start, end, text.to_string()));
                    }
                }
                edits.extend(more_minimal_edits(&model.document().lines, run));
                model.execute_edits(edits.into_iter().map(|(start, end, text)| (start, end, text, true)).collect(), None, EditReason::ApplyEdits)
            } else {
                let indentation = model.document().indentation;
                let edits = replaces
                    .iter()
                    .map(|&(start, end, text, is_snippet, _, _)| {
                        let text = if is_snippet { expand_snippet(text, "", false, indentation, |_| None).text } else { text.to_string() };
                        (start, end, text, true)
                    })
                    .collect();
                model.execute_edits(edits, None, EditReason::ApplyEdits)
            };
            if let Some(change) = change {
                self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);
            }
            if let Some(sequence) = eol
                && let Some(change) = self.editors.model_mut(scheme, path).expect("resolved above").push_eol(sequence)
            {
                self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);
            }
        }
        if let Some(element) = undo_redo.borrow_mut().last_element_mut(&first_key) {
            element.close();
        }
        self.host.send_visible_ranges(&self.editors);
        cx.notify();
        Ok(Value::Null)
    }

    /// `ITextModelService.createModelReference`: a file from disk, or what the session read from an extension's provider.
    pub(super) fn resolve_document(&self, scheme: &str, path: &Path, provider_files: &Value) -> Result<TextDocument, Value> {
        let settings = self.settings.lock().unwrap();
        if scheme == "untitled" {
            return Ok(TextDocument::untitled(path, "", None, &self.languages, &settings));
        }
        if crate::editor::on_disk(scheme) {
            let bytes = std::fs::read(path).map_err(|error| serialized_error(&format!("Unable to read file '{}' ({error})", path.display())))?;
            return Ok(TextDocument::from_bytes(scheme, path, &bytes, None, &self.languages, &settings));
        }
        let file = provider_files.as_array().into_iter().flatten().find(|file| uri_parts(&file["uri"]).is_ok_and(|(file_scheme, file_path)| file_scheme == scheme && file_path == path));
        let Some(file) = file else {
            return Err(serialized_error(&format!("Unable to resolve resource {}", uri_string(scheme, path))));
        };
        let bytes: Vec<u8> = serde_json::from_value(file["bytes"].clone()).expect("bytes from main_thread_bulk_edits.rs");
        Ok(TextDocument::from_bytes(scheme, path, &bytes, None, &self.languages, &settings))
    }

    /// `onDidRunWorkingCopyFileOperation` of TextFileEditorModelManager: the models of a moved resource and its children
    /// continue at the target with their text and dirty state; the model of a created file reverts to its new contents.
    /// workingCopyFileService.ts soft-reverts the dirty models of a deleted resource, so they close or orphan clean.
    pub fn models_after_file_operation(&mut self, operation: u64, pairs: &Value, cx: &mut Context<Self>) {
        let mut changed = false;
        for pair in pairs.as_array().into_iter().flatten() {
            let Ok((scheme, ref target)) = uri_parts(&pair["target"]) else { continue };
            match operation {
                // FileOperation.Create
                0 => {
                    if let Ok(bytes) = serde_json::from_value::<Vec<u8>>(pair["bytes"].clone()) {
                        changed |= self.revert_model(scheme, target, &bytes, cx);
                    }
                }
                // FileOperation.Delete
                1 => {
                    for path in self.model_paths_under(scheme, target) {
                        self.soft_revert_model(scheme, &path);
                    }
                }
                // FileOperation.Copy: workingCopyFileService.ts soft-reverts the target's dirty models, which then
                // reload the copied file.
                3 => {
                    let bytes = serde_json::from_value::<Vec<u8>>(pair["bytes"].clone()).ok();
                    for path in self.model_paths_under(scheme, target) {
                        match bytes.as_deref().filter(|_| path == *target) {
                            Some(bytes) => changed |= self.revert_model(scheme, &path, bytes, cx),
                            None => self.soft_revert_model(scheme, &path),
                        }
                    }
                }
                // FileOperation.Move
                2 => {
                    if let Ok((source_scheme, ref source)) = uri_parts(&pair["source"]) {
                        changed |= self.move_models(source_scheme, source, scheme, target, cx);
                        self.move_custom_editors(source_scheme, source, scheme, target);
                        if source_scheme == "file" && scheme == "file" {
                            self.move_local_history(source, target, cx);
                        }
                    }
                }
                _ => {}
            }
        }
        if changed {
            self.editors_changed(cx);
        }
        self.resolve_custom_editors(cx);
        cx.notify();
    }

    /// The paths of the models of `scheme` at `resource` or inside it (`isEqualOrParent`), each once.
    fn model_paths_under(&self, scheme: &str, resource: &Path) -> Vec<PathBuf> {
        let mut paths: Vec<PathBuf> = Vec::new();
        for model in self.editors.all_editors() {
            let document = model.document();
            if document.scheme == scheme && document.path.starts_with(resource) && !paths.contains(&document.path) {
                paths.push(document.path.clone());
            }
        }
        paths
    }

    /// `revert({ soft: true })`: a dirty model keeps its text and is clean.
    fn soft_revert_model(&mut self, scheme: &str, path: &Path) {
        let model = self.editors.model_mut(scheme, path).expect("the caller found the model");
        if !model.is_dirty() {
            return;
        }
        model.mark_saved();
        let model = self.editors.model(scheme, path).expect("found above");
        self.host.send_dirty_state(&self.editors, model, false);
    }

    fn move_models(&mut self, source_scheme: &str, source: &Path, target_scheme: &str, target: &Path, cx: &mut Context<Self>) -> bool {
        let sources = self.model_paths_under(source_scheme, source);
        for old in &sources {
            let rest = old.strip_prefix(source).expect("model_paths_under");
            let new = if rest.as_os_str().is_empty() { target.to_path_buf() } else { target.join(rest) };
            if self.editors.model(target_scheme, &new).is_some() {
                self.move_onto_open_model(source_scheme, old, target_scheme, &new, cx);
                continue;
            }
            let model = self.editors.model_mut(source_scheme, old).expect("model_paths_under");
            let mut document = model.document_mut();
            document.path = new;
            document.scheme = target_scheme.to_string();
        }
        !sources.is_empty()
    }

    /// A move onto a resource with a model: the source is soft-reverted, the target model takes the source's text
    /// (dirty when the source was, else as on disk), and every group's editors of the source show the target model
    /// (editorService.ts `handleMovedFile`, `replaceEditors`), or close where the group has an editor of it already.
    fn move_onto_open_model(&mut self, source_scheme: &str, source: &Path, target_scheme: &str, target: &Path, cx: &mut Context<Self>) {
        let model = self.editors.model(source_scheme, source).expect("the caller found the model");
        let (text, dirty) = (model.document().lines.join(model.document().eol), model.is_dirty());
        self.soft_revert_model(source_scheme, source);
        self.update_model(target_scheme, target, &text, !dirty, cx);
        let target_model = self.editors.model(target_scheme, target).expect("the caller found the model").model.clone();
        for group in self.editors.group_ids_mru() {
            self.with_group(group, |workbench| workbench.replace_editors_of(source_scheme, source, target_scheme, target, &target_model));
        }
    }

    /// The active group's editors of the source show `target_model`, or close where the group shows the target already.
    fn replace_editors_of(&mut self, source_scheme: &str, source: &Path, target_scheme: &str, target: &Path, target_model: &SharedModel) {
        for index in (0..self.editors.editors.len()).rev() {
            if !self.editors.editors[index].document().is(source_scheme, source) {
                continue;
            }
            match self.editors.editors.iter().position(|editor| editor.document().is(target_scheme, target)) {
                Some(shown) => {
                    let active = self.editors.active_index() == Some(index);
                    self.editors.close(index);
                    if active {
                        self.editors.activate(if shown > index { shown - 1 } else { shown });
                    }
                }
                None => self.editors.replace_model(index, target_model.clone()),
            }
        }
    }

    /// workingCopyHistoryTracker.ts `onDidRunWorkingCopyFileOperation` for a move: the history of the moved files
    /// follows them to `target`.
    fn move_local_history(&self, source: &Path, target: &Path, cx: &mut Context<Self>) {
        let settings = self.settings.clone();
        let history_home = settings.lock().unwrap().user_home().join("History");
        let (source, target) = (source.to_path_buf(), target.to_path_buf());
        let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |since| since.as_millis() as i64);
        let moved = cx.background_executor().spawn(async move {
            let limits = |file: &Path| local_history::limits(&settings.lock().unwrap(), file);
            if let Err(error) = local_history::move_entries(&history_home, &source, &target, timestamp, limits) {
                eprintln!("local history of {}: {error}", source.display());
            }
        });
        cx.spawn(async move |workbench, cx| {
            moved.await;
            let _ = workbench.update(cx, |workbench, cx| workbench.local_history_changed(cx));
        })
        .detach();
    }

    /// `TextFileEditorModel.revert`: the model takes the text of `bytes` and is clean.
    pub(super) fn revert_model(&mut self, scheme: &str, path: &Path, bytes: &[u8], cx: &mut Context<Self>) -> bool {
        let document = TextDocument::from_bytes(scheme, path, bytes, None, &self.languages, &self.settings.lock().unwrap());
        let Some(model) = self.editors.model_mut(scheme, path) else { return false };
        let end = document_end(&model.document().lines);
        model.push_undo_stop();
        let change = model.execute_edits(vec![(Position::new(0, 0), end, document.lines.join("\n"), false)], None, EditReason::ApplyEdits);
        model.push_undo_stop();
        model.mark_saved();
        if let Some(change) = change {
            self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);
        }
        true
    }
}

pub(super) fn document_end(lines: &[String]) -> Position {
    let last = lines.len() - 1;
    Position::new(last, lines[last].chars().count())
}

/// `SnippetParser.escape`: the text inserts as it is.
pub(super) fn escape_snippet(text: &str) -> String {
    text.replace('\\', "\\\\").replace('$', "\\$").replace('}', "\\}")
}

#[cfg(test)]
mod tests;