summaryrefslogtreecommitdiff
path: root/rust/crates/commands/src/batch_command.rs
blob: bd928d3381776335f4b6a1c8c290e5005b6fb6ff (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use scene::Project;

use crate::command::{Command, CommandError, CommandResult};

pub struct BatchCommand {
    commands: Vec<Box<dyn Command>>,
}

impl BatchCommand {
    pub fn new(commands: Vec<Box<dyn Command>>) -> Self {
        Self { commands }
    }

    pub fn len(&self) -> usize {
        self.commands.len()
    }

    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }
}

impl Command for BatchCommand {
    fn execute(
        &mut self,
        project: &mut Project,
    ) -> Result<Option<CommandResult>, CommandError> {
        let mut latest_selection_result = None;

        for command in &mut self.commands {
            let result = command.execute(project)?;
            if result.as_ref().and_then(|r| r.selection.as_ref()).is_some() {
                latest_selection_result = result;
            }
        }

        Ok(latest_selection_result)
    }

    fn undo(&mut self, project: &mut Project) {
        for command in self.commands.iter_mut().rev() {
            command.undo(project);
        }
    }

    fn redo(
        &mut self,
        project: &mut Project,
    ) -> Result<Option<CommandResult>, CommandError> {
        let mut latest_selection_result = None;

        for command in &mut self.commands {
            let result = command.redo(project)?;
            if result.as_ref().and_then(|r| r.selection.as_ref()).is_some() {
                latest_selection_result = result;
            }
        }

        Ok(latest_selection_result)
    }
}