Skip to content

Visual Studio Code, rebuilt in Rust

Rust
33.7 KB
Raw Blame
//! platform/undoRedo/common/undoRedoService.ts: one past and future per resource. A resource element sits on its
//! resource's stack; a workspace element sits on the stack of every resource it touches and runs only while it is
//! the closest element of all of them, else it splits into resource elements or flushes their stacks. Elements are
//! plain data: `undo`/`redo` return the next step (`Next`), the caller shows its dialog or runs its work and
//! passes the step back. Resources are `(comparison key, label)` pairs, as `getUriComparisonKey` and
//! `getResourceLabel` give them.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::Path;

/// `IWorkspaceUndoRedoElement.split`: one resource element per resource, none when the element cannot split. The
/// parts keep the element's label, as `MultiModelEditStackElement.split` gives them.
pub trait Split: Sized {
    fn split(&self) -> Vec<((String, String), Self)>;
}

/// Whether an element runs its undo or its redo.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Direction {
    Undo,
    Redo,
}

#[derive(Clone, Copy, PartialEq)]
enum RemovedResourceReason {
    ExternalRemoval,
    NoParallelUniverses,
}

/// `ResourceStackElement` (`Resource`) or `WorkspaceStackElement` with its `removedResources` and
/// `invalidatedResources`, each `(comparison key, label, reason)`, empty for null.
enum Kind {
    Resource { is_valid: bool },
    Workspace { removed: Vec<(String, String, RemovedResourceReason)>, invalidated: Vec<(String, String, RemovedResourceReason)> },
}

pub struct StackElement<E> {
    pub id: u64,
    pub label: String,
    pub confirm_before_undo: bool,
    /// `UndoRedoGroup` id, 0 for none.
    pub group: u64,
    /// `UndoRedoSource` id, 0 for none.
    pub source: u64,
    /// `groupOrder` and `sourceOrder`: when it was pushed, in the order of every undo element, 0 for an element split
    /// off a workspace element.
    pub order: u64,
    resources: Vec<(String, String)>,
    kind: Kind,
    /// `None` while the element runs.
    actual: Option<E>,
    /// `actual.split()` taken when it started running: upstream splits a running element too.
    running_parts: Vec<((String, String), E)>,
}

/// `ResourceEditStack`: `past` and `future` hold element ids, the closest last.
struct ResourceEditStack {
    label: String,
    past: Vec<u64>,
    future: Vec<u64>,
    locked: bool,
    version: u64,
}

/// `ResourceEditStackSnapshot`: the element ids of one resource's stack, past first, then the future closest first.
#[derive(Clone, PartialEq, Debug)]
pub struct ResourceEditStackSnapshot {
    pub key: String,
    pub elements: Vec<u64>,
}

/// What the caller does next for an undo or redo.
pub enum Next<E> {
    Done,
    /// `_confirmAndContinueUndo`: "Would you like to undo '{0}'?"; Yes goes on with `confirm_undo`.
    Confirm(ConfirmUndo),
    /// `_confirmAndExecuteWorkspaceUndo`: "Would you like to undo '{0}' across all files?", answered with
    /// `undo_in_all_files`, `undo_this_file`, or nothing for Cancel.
    ConfirmWorkspace(ConfirmWorkspaceUndo),
    /// The element's `undo()` or `redo()`: run `work`, then `finish` it, or `fail` it when it threw.
    Run(Running<E>),
    /// `_invokeWorkspacePrepare` (modelUndoRedoParticipant.ts): load the models of `missing`, then `prepared`.
    Prepare(Preparing),
}

pub struct ConfirmUndo {
    pub label: String,
    key: String,
    source: u64,
}

pub struct ConfirmWorkspaceUndo {
    pub label: String,
    pub files: usize,
    key: String,
    id: u64,
    /// `EditStackSnapshot`: the affected stacks with their versions, `None` for a missing one.
    snapshot: Vec<(String, Option<u64>)>,
}

/// A workspace element waiting for its missing models, its stacks locked meanwhile.
pub struct Preparing {
    /// The `(comparison key, label)` of each resource whose model went (`MultiModelEditStackElement.getMissingModels`).
    pub missing: Vec<(String, String)>,
    key: String,
    id: u64,
    snapshot: Vec<(String, Option<u64>)>,
    direction: Direction,
    undo_confirmed: bool,
}

pub struct Running<E> {
    pub id: u64,
    pub direction: Direction,
    pub work: E,
    group: u64,
    undo_confirmed: bool,
    locked: Vec<String>,
}

pub struct UndoRedoService<E> {
    /// Boxed: a tree node keeps room for 11 values, and a 376 byte element left half of each empty.
    elements: BTreeMap<u64, Box<StackElement<E>>>,
    stacks: BTreeMap<String, ResourceEditStack>,
    next_id: u64,
    next_order: u64,
    uri_comparison_key_computers: HashMap<String, fn(&Path) -> String>,
    /// `notificationService.warn` messages, for the caller to show.
    pub warnings: Vec<String>,
}

impl<E> Default for UndoRedoService<E> {
    fn default() -> Self {
        UndoRedoService { elements: BTreeMap::new(), stacks: BTreeMap::new(), next_id: 1, next_order: 1, uri_comparison_key_computers: HashMap::new(), warnings: Vec::new() }
    }
}

impl<E> UndoRedoService<E> {
    /// `registerUriComparisonKeyComputer`: the resources of `scheme` share the stack `computer` names for their path.
    pub fn register_uri_comparison_key_computer(&mut self, scheme: &str, computer: fn(&Path) -> String) {
        self.uri_comparison_key_computers.insert(scheme.to_owned(), computer);
    }

    pub fn unregister_uri_comparison_key_computer(&mut self, scheme: &str) {
        self.uri_comparison_key_computers.remove(scheme);
    }

    /// `getUriComparisonKey`: the URI string, unless a computer is registered for the scheme.
    pub fn get_uri_comparison_key(&self, scheme: &str, path: &Path) -> String {
        match self.uri_comparison_key_computers.get(scheme) {
            Some(computer) => computer(path),
            None => crate::editor::uri_string(scheme, path),
        }
    }
}

impl<E: Split> UndoRedoService<E> {
    /// `pushElement`: an element of one distinct resource is a resource element, of more a workspace element.
    pub fn push(&mut self, label: String, resources: Vec<(String, String)>, group: u64, source: u64, confirm_before_undo: bool, actual: E) -> u64 {
        let mut seen = HashSet::new();
        let resources: Vec<(String, String)> = resources.into_iter().filter(|(key, _)| seen.insert(key.clone())).collect();
        let kind = match resources.len() {
            1 => Kind::Resource { is_valid: true },
            _ => Kind::Workspace { removed: Vec::new(), invalidated: Vec::new() },
        };
        let order = self.next_order;
        self.next_order += 1;
        let id = self.insert(StackElement { id: 0, label, confirm_before_undo, group, source, order, resources, kind, actual: Some(actual), running_parts: Vec::new() });
        let resources = self.elements[&id].resources.clone();
        let mut dropped_future = false;
        for (key, label) in resources {
            let stack = self.stacks.entry(key.clone()).or_insert_with(|| ResourceEditStack { label, past: Vec::new(), future: Vec::new(), locked: false, version: 1 });
            let future = std::mem::take(&mut stack.future);
            dropped_future |= !future.is_empty();
            stack.past.push(id);
            stack.version += 1;
            let label = stack.label.clone();
            for future in future {
                self.remove_resource(future, &key, &label, RemovedResourceReason::NoParallelUniverses);
            }
        }
        // Only a dropped future can leave an element on no stack; the scan visits every element, each keystroke.
        if dropped_future {
            self.collect_garbage();
        }
        id
    }

    /// `getLastElement`: the closest past element, none while the stack has a future.
    pub fn last_element(&self, key: &str) -> Option<&E> {
        self.last_element_and_label(key).map(|(element, _)| element)
    }

    pub fn last_element_and_label(&self, key: &str) -> Option<(&E, &str)> {
        let stack = self.stacks.get(key)?;
        if !stack.future.is_empty() {
            return None;
        }
        let element = &self.elements[stack.past.last()?];
        Some((element.actual.as_ref()?, &element.label))
    }

    /// `getLastElement(resource).label`.
    #[cfg(test)]
    pub fn last_label(&self, key: &str) -> Option<&str> {
        Some(&self.elements[self.stacks.get(key)?.past.last()?].label)
    }
    /// `getLastElement` to append to (`EditStack._getOrCreateEditStackElement`).
    pub fn last_element_mut(&mut self, key: &str) -> Option<&mut E> {
        let stack = self.stacks.get(key)?;
        if !stack.future.is_empty() {
            return None;
        }
        let id = *stack.past.last()?;
        self.elements.get_mut(&id)?.actual.as_mut()
    }

    /// `getElements`: the past and future of the resource, a running element left out.
    pub fn elements(&self, key: &str) -> (Vec<&E>, Vec<&E>) {
        let Some(stack) = self.stacks.get(key) else { return (Vec::new(), Vec::new()) };
        let actual = |ids: &Vec<u64>| ids.iter().filter_map(|id| self.elements[id].actual.as_ref()).collect();
        (actual(&stack.past), actual(&stack.future))
    }

    pub fn has_elements(&self, key: &str) -> bool {
        self.stacks.get(key).is_some_and(|stack| !stack.past.is_empty() || !stack.future.is_empty())
    }

    pub fn can_undo(&self, key: &str) -> bool {
        self.stacks.get(key).is_some_and(|stack| !stack.past.is_empty())
    }

    pub fn can_redo(&self, key: &str) -> bool {
        self.stacks.get(key).is_some_and(|stack| !stack.future.is_empty())
    }

    pub fn can_undo_source(&self, source: u64) -> bool {
        self.closest_with_source(source, Direction::Undo).is_some()
    }

    pub fn can_redo_source(&self, source: u64) -> bool {
        self.closest_with_source(source, Direction::Redo).is_some()
    }

    /// `getClosestPastElement` / `getClosestFutureElement` of one resource's stack.
    fn closest(&self, key: &str, direction: Direction) -> Option<&StackElement<E>> {
        let stack = self.stacks.get(key)?;
        let id = match direction {
            Direction::Undo => stack.past.last(),
            Direction::Redo => stack.future.last(),
        };
        id.map(|id| &*self.elements[id])
    }

    /// `_findClosestUndoElementInGroup` / `_findClosestRedoElementInGroup`: of the group's elements next on some
    /// stack, the one pushed last for undo, first for redo, with its resource's key.
    fn closest_in_group(&self, group: u64, direction: Direction) -> Option<(String, &StackElement<E>)> {
        if group == 0 {
            return None;
        }
        let mut matched: Option<(String, &StackElement<E>)> = None;
        for key in self.stacks.keys() {
            let Some(candidate) = self.closest(key, direction).filter(|candidate| candidate.group == group) else { continue };
            let better = match direction {
                Direction::Undo => matched.as_ref().is_none_or(|(_, matched)| candidate.order > matched.order),
                Direction::Redo => matched.as_ref().is_none_or(|(_, matched)| candidate.order < matched.order),
            };
            if better {
                matched = Some((key.clone(), candidate));
            }
        }
        matched
    }

    /// `removeElements`: the resource's stack goes; the workspace elements on it can no longer run in it.
    pub fn remove_elements(&mut self, key: &str) {
        let Some(stack) = self.stacks.remove(key) else { return };
        for id in stack.past.iter().chain(&stack.future) {
            self.remove_resource(*id, key, &stack.label, RemovedResourceReason::ExternalRemoval);
        }
        self.collect_garbage();
    }

    /// `setElementsValidFlag`: marks the resource's elements that pass `filter`.
    pub fn set_elements_valid_flag(&mut self, key: &str, is_valid: bool, filter: impl Fn(&E) -> bool) {
        let Some(stack) = self.stacks.get(key) else { return };
        for id in stack.past.iter().chain(&stack.future) {
            let element = self.elements.get_mut(id).expect("a stack's elements exist");
            if !element.actual.as_ref().is_some_and(&filter) {
                continue;
            }
            match &mut element.kind {
                Kind::Resource { is_valid: valid } => *valid = is_valid,
                Kind::Workspace { invalidated, .. } if is_valid => invalidated.retain(|(invalid, _, _)| invalid != key),
                Kind::Workspace { invalidated, .. } => {
                    if !invalidated.iter().any(|(invalid, _, _)| invalid == key) {
                        invalidated.push((key.to_owned(), stack.label.clone(), RemovedResourceReason::ExternalRemoval));
                    }
                }
            }
        }
    }

    pub fn create_snapshot(&self, key: &str) -> ResourceEditStackSnapshot {
        let elements = match self.stacks.get(key) {
            Some(stack) => stack.past.iter().chain(stack.future.iter().rev()).copied().collect(),
            None => Vec::new(),
        };
        ResourceEditStackSnapshot { key: key.to_owned(), elements }
    }

    /// `restoreSnapshot`: the stack keeps the elements up to the first that differs from the snapshot; a stack
    /// left empty goes.
    pub fn restore_snapshot(&mut self, snapshot: &ResourceEditStackSnapshot) {
        let Some(stack) = self.stacks.get_mut(&snapshot.key) else { return };
        let mut is_ok = true;
        let mut index = 0;
        let mut remove_past_after = None;
        let mut removed = Vec::new();
        for (i, id) in stack.past.iter().enumerate() {
            if is_ok && snapshot.elements.get(index) != Some(id) {
                is_ok = false;
                remove_past_after = Some(i);
            }
            if !is_ok {
                removed.push(*id);
            }
            index += 1;
        }
        let mut remove_future_before = None;
        for (i, id) in stack.future.iter().enumerate().rev() {
            if is_ok && snapshot.elements.get(index) != Some(id) {
                is_ok = false;
                remove_future_before = Some(i);
            }
            if !is_ok {
                removed.push(*id);
            }
            index += 1;
        }
        if let Some(after) = remove_past_after {
            stack.past.truncate(after);
        }
        if let Some(before) = remove_future_before {
            stack.future.drain(..=before);
        }
        stack.version += 1;
        let label = stack.label.clone();
        for id in removed {
            self.remove_resource(id, &snapshot.key, &label, RemovedResourceReason::ExternalRemoval);
        }
        if !self.has_elements(&snapshot.key) {
            self.remove_elements(&snapshot.key);
        }
        self.collect_garbage();
    }

    /// `undo(resource)`.
    pub fn undo(&mut self, key: &str) -> Next<E> {
        self.undo_with(key, 0, false)
    }

    /// `undo(source)`: the source's element pushed last.
    pub fn undo_source(&mut self, source: u64) -> Next<E> {
        match self.closest_with_source(source, Direction::Undo) {
            Some(key) => self.undo_with(&key, source, false),
            None => Next::Done,
        }
    }

    /// The Yes of `_confirmAndContinueUndo`.
    pub fn confirm_undo(&mut self, prompt: ConfirmUndo) -> Next<E> {
        self.undo_with(&prompt.key, prompt.source, true)
    }

    /// "Undo in {0} Files": the element is checked again, the dialog may have taken a while.
    pub fn undo_in_all_files(&mut self, prompt: ConfirmWorkspaceUndo) -> Next<E> {
        let Some(element) = self.elements.get(&prompt.id) else { return Next::Done };
        if let Some(error) = self.check_workspace(&prompt.key, element.id, &prompt.snapshot, Direction::Undo, false) {
            return error;
        }
        self.execute_workspace(&prompt.key, prompt.id, &prompt.snapshot, Direction::Undo, true)
    }

    /// "Undo this File": the element splits, this resource's part runs.
    pub fn undo_this_file(&mut self, prompt: ConfirmWorkspaceUndo) -> Next<E> {
        if self.elements.contains_key(&prompt.id) {
            self.split_workspace_element(prompt.id, Direction::Undo, &[]);
        }
        self.undo_with(&prompt.key, 0, true)
    }

    /// `redo(resource)`.
    pub fn redo(&mut self, key: &str) -> Next<E> {
        let Some(id) = self.stacks.get(key).and_then(|stack| stack.future.last().copied()) else { return Next::Done };
        let group = self.elements[&id].group;
        if let Some((matched_key, matched)) = self.closest_in_group(group, Direction::Redo)
            && matched.id != id
        {
            return self.redo(&matched_key);
        }
        match self.elements[&id].kind {
            Kind::Workspace { .. } => self.workspace_run(key, id, Direction::Redo, false),
            Kind::Resource { .. } => self.resource_run(key, id, Direction::Redo, false),
        }
    }

    /// `redo(source)`: the source's element undone first.
    pub fn redo_source(&mut self, source: u64) -> Next<E> {
        match self.closest_with_source(source, Direction::Redo) {
            Some(key) => self.redo(&key),
            None => Next::Done,
        }
    }

    /// The element ran: its work, ready to run the other way, goes back on it, the locks go, and the next element of
    /// its group follows (`_continueUndoInGroup` / `_continueRedoInGroup`).
    pub fn finish(&mut self, running: Running<E>) -> Next<E> {
        self.release(&running.locked);
        if let Some(element) = self.elements.get_mut(&running.id) {
            element.actual = Some(running.work);
            element.running_parts.clear();
        }
        self.collect_garbage();
        let Some((key, _)) = self.closest_in_group(running.group, running.direction) else { return Next::Done };
        match running.direction {
            Direction::Undo => self.undo_with(&key, 0, running.undo_confirmed),
            Direction::Redo => self.redo(&key),
        }
    }

    /// `_onError`: an element that failed drops the stacks of all its resources; the caller shows the error.
    pub fn fail(&mut self, running: Running<E>) {
        self.release(&running.locked);
        let keys: Vec<String> = self.elements[&running.id].resources.iter().map(|(key, _)| key.clone()).collect();
        self.elements.remove(&running.id);
        for key in &keys {
            self.remove_elements(key);
        }
    }

    fn insert(&mut self, mut element: StackElement<E>) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        element.id = id;
        self.elements.insert(id, Box::new(element));
        id
    }

    /// `_undo`: an element of a group waits for the group's later ones; one of another source, or one that asks,
    /// asks first unless `undo_confirmed`.
    fn undo_with(&mut self, key: &str, source: u64, undo_confirmed: bool) -> Next<E> {
        let Some(id) = self.stacks.get(key).and_then(|stack| stack.past.last().copied()) else { return Next::Done };
        let element = &self.elements[&id];
        if let Some((matched_key, matched)) = self.closest_in_group(element.group, Direction::Undo)
            && matched.id != id
        {
            return self.undo_with(&matched_key, source, undo_confirmed);
        }
        if (element.source != source || element.confirm_before_undo) && !undo_confirmed {
            return Next::Confirm(ConfirmUndo { label: element.label.clone(), key: key.to_owned(), source });
        }
        match element.kind {
            Kind::Workspace { .. } => self.workspace_run(key, id, Direction::Undo, undo_confirmed),
            Kind::Resource { .. } => self.resource_run(key, id, Direction::Undo, undo_confirmed),
        }
    }

    /// `_workspaceUndo` / `_workspaceRedo`; an undo that can split and is alone in its group asks first.
    fn workspace_run(&mut self, key: &str, id: u64, direction: Direction, undo_confirmed: bool) -> Next<E> {
        let snapshot: Vec<(String, Option<u64>)> = self.elements[&id].resources.iter().map(|(key, _)| (key.clone(), self.stacks.get(key).map(|stack| stack.version))).collect();
        if let Some(error) = self.check_workspace(key, id, &snapshot, direction, false) {
            return error;
        }
        if direction == Direction::Undo && self.can_split(id) && !self.is_part_of_undo_group(id) {
            let element = &self.elements[&id];
            return Next::ConfirmWorkspace(ConfirmWorkspaceUndo { label: element.label.clone(), files: snapshot.len(), key: key.to_owned(), id, snapshot });
        }
        self.execute_workspace(key, id, &snapshot, direction, undo_confirmed)
    }

    /// The end of `_confirmAndExecuteWorkspaceUndo` / `_executeWorkspaceRedo`: the missing models are loaded with the
    /// stacks locked, then it is checked again with the invalidated resources, moved on every stack, locked while it runs.
    fn execute_workspace(&mut self, key: &str, id: u64, snapshot: &[(String, Option<u64>)], direction: Direction, undo_confirmed: bool) -> Next<E> {
        // modelService.ts invalidates a resource of an edit stack element exactly when it disposes its model.
        let Kind::Workspace { invalidated, .. } = &self.elements[&id].kind else { unreachable!("a workspace element") };
        if !invalidated.is_empty() {
            let missing = invalidated.iter().map(|(key, label, _)| (key.clone(), label.clone())).collect();
            let keys: Vec<String> = snapshot.iter().map(|(key, _)| key.clone()).collect();
            self.lock(&keys);
            return Next::Prepare(Preparing { missing, key: key.to_owned(), id, snapshot: snapshot.to_vec(), direction, undo_confirmed });
        }
        self.execute_prepared(key, id, snapshot, direction, undo_confirmed)
    }

    /// The models of `missing` are loaded (or could not be): the element goes on.
    pub fn prepared(&mut self, preparing: Preparing) -> Next<E> {
        let keys: Vec<String> = preparing.snapshot.iter().map(|(key, _)| key.clone()).collect();
        self.release(&keys);
        if !self.elements.contains_key(&preparing.id) {
            return Next::Done;
        }
        self.execute_prepared(&preparing.key, preparing.id, &preparing.snapshot, preparing.direction, preparing.undo_confirmed)
    }

    fn execute_prepared(&mut self, key: &str, id: u64, snapshot: &[(String, Option<u64>)], direction: Direction, undo_confirmed: bool) -> Next<E> {
        if let Some(error) = self.check_workspace(key, id, snapshot, direction, true) {
            return error;
        }
        let keys: Vec<String> = snapshot.iter().map(|(key, _)| key.clone()).collect();
        for key in &keys {
            self.move_element(key, id, direction);
        }
        self.run(id, direction, keys, undo_confirmed)
    }

    /// `_resourceUndo` / `_resourceRedo`: an invalid element flushes its stack, a locked stack warns.
    fn resource_run(&mut self, key: &str, id: u64, direction: Direction, undo_confirmed: bool) -> Next<E> {
        let element = &self.elements[&id];
        if let Kind::Resource { is_valid: false } = element.kind {
            let stack = self.stacks.get_mut(key).expect("the element is on it");
            stack.past.clear();
            stack.future.clear();
            stack.version += 1;
            self.collect_garbage();
            return Next::Done;
        }
        if self.stacks[key].locked {
            self.warnings.push(format!("Could not {} '{}' because there is already an undo or redo operation running.", verb(direction), element.label));
            return Next::Done;
        }
        self.move_element(key, id, direction);
        self.run(id, direction, vec![key.to_owned()], undo_confirmed)
    }

    /// `_safeInvokeWithLocks` up to the invoke: the element's work goes to the caller.
    fn run(&mut self, id: u64, direction: Direction, keys: Vec<String>, undo_confirmed: bool) -> Next<E> {
        self.lock(&keys);
        let element = self.elements.get_mut(&id).expect("checked by the caller");
        let work = element.actual.take().expect("an element on a stack top is not running");
        if matches!(element.kind, Kind::Workspace { .. }) {
            element.running_parts = work.split();
        }
        Next::Run(Running { id, direction, work, group: element.group, undo_confirmed, locked: keys })
    }

    fn lock(&mut self, keys: &[String]) {
        for key in keys {
            if let Some(stack) = self.stacks.get_mut(key) {
                stack.locked = true;
            }
        }
    }

    fn release(&mut self, keys: &[String]) {
        for key in keys {
            if let Some(stack) = self.stacks.get_mut(key) {
                stack.locked = false;
            }
        }
    }

    /// `moveBackward` / `moveForward`.
    fn move_element(&mut self, key: &str, id: u64, direction: Direction) {
        let stack = self.stacks.get_mut(key).expect("checked: the element is the closest on it");
        let (from, to) = match direction {
            Direction::Undo => (&mut stack.past, &mut stack.future),
            Direction::Redo => (&mut stack.future, &mut stack.past),
        };
        from.pop();
        to.push(id);
        stack.version += 1;
    }

    /// `_checkWorkspaceUndo` / `_checkWorkspaceRedo`: `None` when the element can run in every resource, else
    /// what `_tryToSplitAndUndo` makes of it.
    fn check_workspace(&mut self, key: &str, id: u64, snapshot: &[(String, Option<u64>)], direction: Direction, check_invalidated: bool) -> Option<Next<E>> {
        let element = &self.elements[&id];
        let Kind::Workspace { removed, invalidated } = &element.kind else { unreachable!("a resource element is not checked across files") };
        let (verb, label) = (verb(direction), element.label.clone());
        if !removed.is_empty() {
            let (message, ignore) = (format!("Could not {verb} '{label}' across all files. {}", removed_message(removed)), removed.iter().map(|(key, _, _)| key.clone()).collect::<Vec<_>>());
            return Some(self.try_to_split(key, id, direction, &ignore, message));
        }
        if check_invalidated && !invalidated.is_empty() {
            let (message, ignore) = (format!("Could not {verb} '{label}' across all files. {}", removed_message(invalidated)), invalidated.iter().map(|(key, _, _)| key.clone()).collect::<Vec<_>>());
            return Some(self.try_to_split(key, id, direction, &ignore, message));
        }
        // `missingEditStack`: a stack that went is locked and has no label.
        let stacks: Vec<Option<&ResourceEditStack>> = snapshot.iter().map(|(key, _)| self.stacks.get(key)).collect();
        let closest = |stack: &ResourceEditStack| match direction {
            Direction::Undo => stack.past.last().copied(),
            Direction::Redo => stack.future.last().copied(),
        };
        let stack_label = |stack: &Option<&ResourceEditStack>| stack.map(|stack| stack.label.clone()).unwrap_or_default();
        let changed: Vec<String> = stacks.iter().filter(|stack| stack.and_then(closest) != Some(id)).map(stack_label).collect();
        if !changed.is_empty() {
            let message = format!("Could not {verb} '{label}' across all files because changes were made to {}", changed.join(", "));
            return Some(self.try_to_split(key, id, direction, &[], message));
        }
        let locked: Vec<String> = stacks.iter().filter(|stack| stack.is_none_or(|stack| stack.locked)).map(stack_label).collect();
        if !locked.is_empty() {
            let message = format!("Could not {verb} '{label}' across all files because there is already an undo or redo operation running on {}", locked.join(", "));
            return Some(self.try_to_split(key, id, direction, &[], message));
        }
        let changed_meanwhile = snapshot.iter().any(|(key, version)| version.is_some() && self.stacks.get(key).map(|stack| stack.version) != *version);
        if changed_meanwhile {
            let message = format!("Could not {verb} '{label}' across all files because an undo or redo operation occurred in the meantime");
            return Some(self.try_to_split(key, id, direction, &[], message));
        }
        None
    }

    /// `_tryToSplitAndUndo` / `_tryToSplitAndRedo`: the element splits and this resource's part runs, or, when it
    /// cannot split, the stacks of all its resources are flushed.
    fn try_to_split(&mut self, key: &str, id: u64, direction: Direction, ignore: &[String], message: String) -> Next<E> {
        self.warnings.push(message);
        if self.can_split(id) {
            self.split_workspace_element(id, direction, ignore);
            return match direction {
                Direction::Undo => self.undo_with(key, 0, true),
                Direction::Redo => self.redo(key),
            };
        }
        let keys: Vec<String> = self.elements[&id].resources.iter().map(|(key, _)| key.clone()).collect();
        for key in &keys {
            self.remove_elements(key);
        }
        Next::Done
    }

    fn can_split(&self, id: u64) -> bool {
        let element = &self.elements[&id];
        match &element.actual {
            Some(actual) => !actual.split().is_empty(),
            None => !element.running_parts.is_empty(),
        }
    }

    /// `_splitPastWorkspaceElement` / `_splitFutureWorkspaceElement`: on each stack but the ignored ones, the
    /// element's part for that resource takes its place, or it goes when there is none.
    fn split_workspace_element(&mut self, id: u64, direction: Direction, ignore: &[String]) {
        let element = self.elements.get_mut(&id).expect("checked by can_split");
        let parts = match &element.actual {
            Some(actual) => actual.split(),
            None => std::mem::take(&mut element.running_parts),
        };
        let label = element.label.clone();
        let resources = element.resources.clone();
        let mut individual = BTreeMap::new();
        for ((key, resource_label), actual) in parts {
            let part = StackElement { id: 0, label: label.clone(), confirm_before_undo: false, group: 0, source: 0, order: 0, resources: vec![(key.clone(), resource_label)], kind: Kind::Resource { is_valid: true }, actual: Some(actual), running_parts: Vec::new() };
            individual.insert(key, part);
        }
        for (key, _) in resources {
            if ignore.contains(&key) {
                continue;
            }
            let replacement = individual.remove(&key).map(|part| self.insert(part));
            let stack = self.stacks.get_mut(&key).expect("a workspace element's stacks exist");
            let ids = match direction {
                Direction::Undo => &mut stack.past,
                Direction::Redo => &mut stack.future,
            };
            if let Some(j) = ids.iter().rposition(|element| *element == id) {
                match replacement {
                    Some(replacement) => ids[j] = replacement,
                    None => drop(ids.remove(j)),
                }
            }
            stack.version += 1;
        }
        self.collect_garbage();
    }

    /// `_isPartOfUndoGroup`: another element of the element's group is ready to be undone.
    fn is_part_of_undo_group(&self, id: u64) -> bool {
        let group = self.elements[&id].group;
        if group == 0 {
            return false;
        }
        for stack in self.stacks.values() {
            let Some(past) = stack.past.last() else { continue };
            if *past == id && stack.past.len() >= 2 && self.elements[&stack.past[stack.past.len() - 2]].group == group {
                return true;
            }
            if *past != id && self.elements[past].group == group {
                return true;
            }
        }
        false
    }

    /// `_findClosestUndoElementWithSource` / `_findClosestRedoElementWithSource`: the resource whose closest
    /// element of `source` was pushed last for undo, first for redo.
    fn closest_with_source(&self, source: u64, direction: Direction) -> Option<String> {
        if source == 0 {
            return None;
        }
        let mut matched: Option<(&String, u64)> = None;
        for key in self.stacks.keys() {
            let Some(candidate) = self.closest(key, direction).filter(|candidate| candidate.source == source) else { continue };
            let better = match direction {
                Direction::Undo => matched.is_none_or(|(_, order)| candidate.order > order),
                Direction::Redo => matched.is_none_or(|(_, order)| candidate.order < order),
            };
            if better {
                matched = Some((key, candidate.order));
            }
        }
        matched.map(|(key, _)| key.clone())
    }

    /// `WorkspaceStackElement.removeResource`; resource elements ignore it.
    fn remove_resource(&mut self, id: u64, key: &str, label: &str, reason: RemovedResourceReason) {
        let Some(StackElement { kind: Kind::Workspace { removed, .. }, .. }) = self.elements.get_mut(&id).map(|element| &mut **element) else { return };
        if !removed.iter().any(|(removed, _, _)| removed == key) {
            removed.push((key.to_owned(), label.to_owned(), reason));
        }
    }

    /// Elements no stack holds any more are gone; a running one stays until it finishes or fails.
    fn collect_garbage(&mut self) {
        let held: HashSet<u64> = self.stacks.values().flat_map(|stack| stack.past.iter().chain(&stack.future)).copied().collect();
        self.elements.retain(|id, element| held.contains(id) || element.actual.is_none());
    }
}

fn verb(direction: Direction) -> &'static str {
    match direction {
        Direction::Undo => "undo",
        Direction::Redo => "redo",
    }
}

/// `RemovedResources.createMessage`.
fn removed_message(removed: &[(String, String, RemovedResourceReason)]) -> String {
    let labels = |reason: RemovedResourceReason| removed.iter().filter(|(_, _, removed)| *removed == reason).map(|(_, label, _)| label.as_str()).collect::<Vec<_>>().join(", ");
    let (external, no_parallel) = (labels(RemovedResourceReason::ExternalRemoval), labels(RemovedResourceReason::NoParallelUniverses));
    let mut messages = Vec::new();
    if !external.is_empty() {
        messages.push(format!("The following files have been closed and modified on disk: {external}."));
    }
    if !no_parallel.is_empty() {
        messages.push(format!("The following files have been modified in an incompatible way: {no_parallel}."));
    }
    messages.join("\n")
}

#[cfg(test)]
mod tests;