Visual Studio Code, rebuilt in Rust
Rust
//! editStack.ts: the undo elements text models push into the workbench's one `UndoRedoService`, next to the file
//! elements of the Explorer and of `workspace.applyEdit` (`FileUndoRedoElement`).
use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc;
use files::operations::FileUndo;
use serde_json::Value;
use super::cursor::{Position, Selection};
use crate::undo_redo::{Split, UndoRedoService};
/// The workbench's `IUndoRedoService`, which every text model holds.
pub type UndoService = Rc<RefCell<UndoRedoService<UndoElement>>>;
/// editStack.ts: the label of the `undoredo.textBufferEdit` elements that model edits open.
pub const TYPING_LABEL: &str = "Typing";
pub enum UndoElement {
Model(SingleModelEditStackElement),
MultiModel(MultiModelEditStackElement),
File(FileUndo),
/// notebookTextModel.ts `StackOperation` of cell edits: the edits that revert them and the ones that apply them again.
Cells { notebook: Value, undo: Vec<Value>, redo: Vec<Value> },
/// mainThreadCustomEditors.ts `pushEdit`: the custom document's current edit goes back or forth.
CustomEdit { resource: Value, view_type: String },
/// mergeEditorModel.ts `setInputHandled`: an input of a merge editor's range marked handled, on its result's stack.
MergeHandled { scheme: String, path: PathBuf, index: usize, input: crate::merge_editor::Input, handled: bool },
}
/// One replace an element took back: where it starts in the text after it, the text it removed and the text it
/// inserted (`TextChange`).
#[derive(Clone, Debug)]
pub(super) struct AppliedEdit {
pub start: Position,
pub removed: String,
pub inserted: String,
}
/// `SingleModelEditStackElement` with its `SingleModelEditStackData`; open until `close` (upstream serializes it).
#[derive(Clone)]
pub struct SingleModelEditStackElement {
/// Shared by the model's elements: a typing session holds thousands (issue 116).
pub resource: Rc<ModelResource>,
pub(super) is_open: bool,
pub(super) before_version_id: u32,
pub(super) after_version_id: u32,
pub(super) before_eol: &'static str,
pub(super) after_eol: &'static str,
pub(super) before_cursor_state: Vec<Selection>,
pub(super) after_cursor_state: Vec<Selection>,
pub(super) changes: Vec<AppliedEdit>,
}
/// `MultiModelEditStackElement`: one model's element per edited model, undone and redone together.
pub struct MultiModelEditStackElement {
is_open: bool,
pub elements: Vec<SingleModelEditStackElement>,
}
/// The model an element edits.
pub struct ModelResource {
/// The stack it is on: `getUriComparisonKey` of the model's URI.
pub key: String,
/// The model's URI string (`matchesResource`, `canAppend`).
pub uri: String,
pub scheme: String,
pub path: PathBuf,
}
impl ModelResource {
pub fn new(key: String, scheme: &str, path: PathBuf) -> Rc<Self> {
Rc::new(ModelResource { key, uri: super::uri_string(scheme, &path), scheme: scheme.to_owned(), path })
}
}
impl SingleModelEditStackElement {
/// `SingleModelEditStackData.create`: the model's alternative version, EOL and cursors before the first change.
pub fn new(resource: Rc<ModelResource>, alternative_version_id: u32, eol: &'static str, before_cursor_state: Vec<Selection>) -> Self {
SingleModelEditStackElement {
resource,
is_open: true,
before_version_id: alternative_version_id,
after_version_id: alternative_version_id,
before_eol: eol,
after_eol: eol,
after_cursor_state: before_cursor_state.clone(),
before_cursor_state,
changes: Vec::new(),
}
}
/// The `(comparison key, label)` the service keeps its stack under.
pub fn resource(&self) -> (String, String) {
(self.resource.key.clone(), self.resource.path.to_string_lossy().into_owned())
}
pub(super) fn append(&mut self, changes: Vec<AppliedEdit>, after_eol: &'static str, after_version_id: u32, after_cursor_state: Vec<Selection>) {
self.changes.extend(changes);
self.after_eol = after_eol;
self.after_version_id = after_version_id;
self.after_cursor_state = after_cursor_state;
}
/// `heapSize`: the length of the serialized data (strings as UTF-16) and the heap overhead.
pub fn heap_size(&self) -> usize {
let selections = |selections: &[Selection]| 4 + 4 * 4 * selections.len();
let string = |text: &str| 4 + 2 * text.encode_utf16().count();
let changes: usize = self.changes.iter().map(|change| 4 + 4 + string(&change.removed) + string(&change.inserted)).sum();
4 + 4 + 1 + 1 + selections(&self.before_cursor_state) + selections(&self.after_cursor_state) + 4 + changes + 168
}
}
impl MultiModelEditStackElement {
pub fn new(elements: Vec<SingleModelEditStackElement>) -> Self {
MultiModelEditStackElement { is_open: true, elements }
}
pub fn resources(&self) -> Vec<(String, String)> {
self.elements.iter().map(SingleModelEditStackElement::resource).collect()
}
}
impl UndoElement {
/// The `(comparison key, label)` of every model or file the element changed.
pub fn resources(&self) -> Vec<(String, String)> {
match self {
UndoElement::Model(element) => vec![element.resource()],
UndoElement::MultiModel(multi) => multi.resources(),
UndoElement::File(undo) => undo.resources().into_iter().map(|resource| (super::uri_string("file", std::path::Path::new(&resource.path)), resource.path)).collect(),
UndoElement::Cells { notebook: uri, .. } | UndoElement::CustomEdit { resource: uri, .. } => vec![(crate::notebook::uri_string(uri), uri["path"].as_str().unwrap_or_default().to_owned())],
UndoElement::MergeHandled { scheme, path, .. } => vec![(super::uri_string(scheme, path), path.to_string_lossy().into_owned())],
}
}
/// `canAppend`: the open element of the model `uri` that the model's next change joins.
pub(super) fn append_target(&mut self, uri: &str) -> Option<&mut SingleModelEditStackElement> {
match self {
UndoElement::Model(element) => (element.is_open && element.resource.uri == uri).then_some(element),
UndoElement::MultiModel(multi) if multi.is_open => multi.elements.iter_mut().find(|element| element.resource.uri == uri),
_ => None,
}
}
/// `pushStackElement`: the model's next change starts a new element.
pub fn close(&mut self) {
match self {
UndoElement::Model(element) => element.is_open = false,
UndoElement::MultiModel(multi) => multi.is_open = false,
UndoElement::File(_) | UndoElement::Cells { .. } | UndoElement::CustomEdit { .. } | UndoElement::MergeHandled { .. } => {}
}
}
/// `popStackElement`: a model's own element takes changes again, a multi-model one stays closed.
pub(super) fn open(&mut self) {
if let UndoElement::Model(element) = self {
element.is_open = true;
}
}
/// `isEditStackElement(element) && element.matchesResource(resource)`.
pub fn is_edit_stack_element_of(&self, uri: &str) -> bool {
self.edit_stack_heap_size(uri).is_some()
}
/// `heapSize(resource)` of an edit stack element of the model `uri`; `None` for another element.
pub fn edit_stack_heap_size(&self, uri: &str) -> Option<usize> {
match self {
UndoElement::Model(element) => (element.resource.uri == uri).then(|| element.heap_size()),
UndoElement::MultiModel(multi) => multi.elements.iter().find(|element| element.resource.uri == uri).map(SingleModelEditStackElement::heap_size),
UndoElement::File(_) | UndoElement::Cells { .. } | UndoElement::CustomEdit { .. } | UndoElement::MergeHandled { .. } => None,
}
}
/// The models of a text element, the multi-model element marked closed by its undo.
pub(crate) fn model_elements(&mut self, undo: bool) -> Vec<&mut SingleModelEditStackElement> {
match self {
UndoElement::Model(element) => vec![element],
UndoElement::MultiModel(multi) => {
if undo {
multi.is_open = false;
}
multi.elements.iter_mut().collect()
}
UndoElement::File(_) | UndoElement::Cells { .. } | UndoElement::CustomEdit { .. } | UndoElement::MergeHandled { .. } => Vec::new(),
}
}
}
/// `MultiModelEditStackElement.split`; the other elements do not split.
impl Split for UndoElement {
fn split(&self) -> Vec<((String, String), Self)> {
let UndoElement::MultiModel(multi) = self else { return Vec::new() };
multi.elements.iter().map(|element| (element.resource(), UndoElement::Model(element.clone()))).collect()
}
}
#[cfg(test)]
mod tests;