Skip to content

Visual Studio Code, rebuilt in Rust

Rust
10.7 KB
Raw Blame
//! The workbench's runs of undoRedoService.ts: `undo`/`redo` of the active text model or of the Explorer's source,
//! with the confirmations they ask for, the closed models loaded first (modelUndoRedoParticipant.ts), and the file
//! elements of `workspace.applyEdit` and the Explorer (`FileUndoRedoElement`), whose edits reverse on the host thread.

use std::path::Path;

use files::operations::FileUndo;
use gpui::{AsyncWindowContext, Context, PromptLevel, WeakEntity, Window};
use serde_json::Value;

use super::Workbench;
use super::explorer_actions::{confirm, notify_error};
use crate::commands::Outcome;
use crate::editor::edit_stack::{UndoElement, UndoService};
use crate::host_sync::FileJob;
use crate::undo_redo::{Direction, Next, Running};

impl Workbench {
    /// The file edits of `workspace.applyEdit` (`BulkFileEdits` with `UndoRedoSource.None`), on the stack of every
    /// file they touched.
    pub(crate) fn push_file_undo(&mut self, undo: FileUndo) {
        if undo.operations.iter().all(Vec::is_empty) {
            return;
        }
        let group = undo.group;
        let element = UndoElement::File(undo);
        self.editors.undo_redo.borrow_mut().push("Workspace Edit".into(), element.resources(), group, 0, false, element);
    }

    /// `UndoCommand` / `RedoCommand` in a text editor: `undo(model.uri)` / `redo(model.uri)`.
    pub(super) fn text_undo(&mut self, direction: Direction, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        let Some(active) = self.editors.active() else { return Outcome::done() };
        let key = active.undo_key();
        let service = active.text_model().undo_redo.clone();
        let next = match direction {
            Direction::Undo => service.borrow_mut().undo(&key),
            Direction::Redo => service.borrow_mut().redo(&key),
        };
        self.run_undo_steps(service, next, window, cx);
        Outcome::done()
    }

    /// The steps the service asks for: text elements run now, a confirmation, a closed model or a file element goes
    /// on after this update.
    pub(super) fn run_undo_steps(&mut self, service: UndoService, mut next: Next<UndoElement>, window: &mut Window, cx: &mut Context<Self>) {
        let next = loop {
            match next {
                Next::Run(running) if !runs_on_the_host(&running.work) => next = self.run_text_element(&service, running, cx),
                other => break other,
            }
        };
        if matches!(next, Next::Done) && service.borrow().warnings.is_empty() {
            return;
        }
        cx.spawn_in(window, async move |workbench, cx| continue_undo_steps(&workbench, cx, service, next).await).detach();
    }

    /// A text or cells element's `undo()` / `redo()` on each of its models, then the service goes on with its group.
    fn run_text_element(&mut self, service: &UndoService, mut running: Running<UndoElement>, cx: &mut Context<Self>) -> Next<UndoElement> {
        let direction = running.direction;
        if let UndoElement::Cells { notebook, undo, redo } = &running.work {
            if let Err(error) = self.run_cells_element(&crate::notebook::uri_string(notebook), undo, redo, direction, cx) {
                let mut service = service.borrow_mut();
                service.fail(running);
                service.warnings.push(error);
                return Next::Done;
            }
            return service.borrow_mut().finish(running);
        }
        if let UndoElement::MergeHandled { scheme, path, index, input, handled } = &running.work {
            let merge = self.editors.merges.values_mut().find(|merge| merge.result.scheme == *scheme && merge.result.path == *path);
            if let Some(model) = merge.and_then(|merge| merge.model.as_mut()) {
                model.set_input_handled(*index, *input, *handled == (direction == Direction::Redo));
            }
            cx.notify();
            return service.borrow_mut().finish(running);
        }
        let mut elements = running.work.model_elements(direction == Direction::Undo);
        // `SingleModelEditStackElement.undo` throws for a model that went without invalidating its elements.
        if elements.iter().any(|element| self.editors.model(&element.resource.scheme, &element.resource.path).is_none()) {
            drop(elements);
            service.borrow_mut().fail(running);
            return Next::Done;
        }
        let active = self.editors.active().map(|editor| editor.document().uri_string());
        for element in elements.iter_mut() {
            if active.as_ref() == Some(&element.resource.uri) {
                drop(self.run_on_active_editor(|editor| editor.apply_stack_element(element, direction), cx));
                continue;
            }
            let model = self.editors.model_mut(&element.resource.scheme, &element.resource.path).expect("checked above");
            if let Some(change) = model.apply_stack_element(element, direction) {
                self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);
            }
        }
        drop(elements);
        self.host.send_visible_ranges(&self.editors);
        cx.notify();
        service.borrow_mut().finish(running)
    }

    /// `ModelUndoRedoParticipant.prepareUndoRedo`: the closed files' models open again; one that cannot be read
    /// stays closed.
    fn load_missing_models(&mut self, missing: &[(String, String)], cx: &mut Context<Self>) {
        let mut opened = false;
        for (key, path) in missing {
            let path = Path::new(path);
            // The kept schemes the workbench reads itself; `fake-fs` has no provider here.
            let Some(scheme) = ["file", files::user_data::SCHEME].into_iter().find(|scheme| crate::editor::uri_string(scheme, path) == *key) else { continue };
            if self.editors.model(scheme, path).is_some() {
                continue;
            }
            let Ok(document) = self.resolve_document(scheme, path, &Value::Null) else { continue };
            self.editors.open_model(document);
            opened = true;
        }
        if opened {
            self.editors_changed(cx);
        }
    }
}

async fn continue_undo_steps(workbench: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, service: UndoService, mut next: Next<UndoElement>) {
    loop {
        let warnings = std::mem::take(&mut service.borrow_mut().warnings);
        for warning in warnings {
            notify_error(workbench, cx, warning).await;
        }
        next = match next {
            Next::Done => return,
            Next::Confirm(prompt) => {
                if !confirm(workbench, cx, PromptLevel::Info, format!("Would you like to undo '{}'?", prompt.label), None, "Yes").await {
                    return;
                }
                service.borrow_mut().confirm_undo(prompt)
            }
            Next::ConfirmWorkspace(prompt) => {
                let message = format!("Would you like to undo '{}' across all files?", prompt.label);
                let all_files = format!("Undo in {} Files", prompt.files);
                let buttons = [all_files.as_str(), "Undo this File", "Cancel"];
                let Ok(answer) = workbench.update_in(cx, |_, window, cx| crate::dialog::show_message_box(window, crate::dialog::InTests::Refuse, PromptLevel::Info, &message, None, &buttons, None, cx)) else { return };
                match answer.await {
                    Ok((0, _)) => service.borrow_mut().undo_in_all_files(prompt),
                    Ok((1, _)) => service.borrow_mut().undo_this_file(prompt),
                    _ => return,
                }
            }
            Next::Prepare(preparing) => {
                if workbench.update(cx, |workbench, cx| workbench.load_missing_models(&preparing.missing, cx)).is_err() {
                    return;
                }
                service.borrow_mut().prepared(preparing)
            }
            Next::Run(running) => {
                let Some(next) = run_element(workbench, cx, &service, running).await else { return };
                next
            }
        };
    }
}

/// File elements and custom document edits finish on another thread.
fn runs_on_the_host(element: &UndoElement) -> bool {
    matches!(element, UndoElement::File(_) | UndoElement::CustomEdit { .. })
}

/// A file element reverses on the host thread while the models follow its moves, a custom document edit waits for
/// the extension's `$undo` / `$redo`; a text element runs at once. `None` when the workbench went or the element
/// failed, its error shown.
async fn run_element(workbench: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, service: &UndoService, mut running: Running<UndoElement>) -> Option<Next<UndoElement>> {
    if !runs_on_the_host(&running.work) {
        return workbench.update(cx, |workbench, cx| workbench.run_text_element(service, running, cx)).ok();
    }
    if let UndoElement::CustomEdit { resource, view_type } = &running.work {
        let redo = running.direction == Direction::Redo;
        let receiver = workbench.update(cx, |workbench, cx| workbench.run_custom_document_edit(resource, view_type, redo, cx)).ok()?;
        let result = match receiver {
            Some(receiver) => receiver.await.unwrap_or(Ok(Value::Null)),
            None => Ok(Value::Null),
        };
        let next = workbench.update(cx, |_, _| match result {
            Ok(_) => Ok(service.borrow_mut().finish(running)),
            Err(error) => {
                service.borrow_mut().fail(running);
                Err(error["message"].as_str().unwrap_or("Error").to_owned())
            }
        });
        return match next.ok()? {
            Ok(next) => Some(next),
            Err(error) => {
                notify_error(workbench, cx, error).await;
                None
            }
        };
    }
    let UndoElement::File(undo) = &mut running.work else { unreachable!("checked above") };
    let undo = std::mem::take(undo);
    let receiver = workbench.update(cx, |workbench, _| workbench.host.run_files(FileJob::Reverse(undo))).ok()?;
    let result = receiver.await.unwrap_or_else(|_| Err(files::FileError { name: "Error".into(), message: "Canceled".into(), operation: None }));
    let next = workbench
        .update(cx, |workbench, cx| {
            cx.notify();
            match result {
                Ok(undo) => {
                    workbench.follow_explorer_moves(&undo);
                    running.work = UndoElement::File(undo);
                    Ok(service.borrow_mut().finish(running))
                }
                Err(error) => {
                    service.borrow_mut().fail(running);
                    Err(error.message)
                }
            }
        })
        .ok()?;
    match next {
        Ok(next) => Some(next),
        Err(error) => {
            notify_error(workbench, cx, error).await;
            None
        }
    }
}

#[cfg(test)]
mod tests;