Skip to main content

UndoRedoCommand

Trait UndoRedoCommand 

Source
pub trait UndoRedoCommand: Send {
    // Required methods
    fn undo(&mut self) -> Result<()>;
    fn redo(&mut self) -> Result<()>;
    fn as_any(&self) -> &dyn Any;

    // Provided methods
    fn can_merge(&self, _other: &dyn UndoRedoCommand) -> bool { ... }
    fn merge(&mut self, _other: &dyn UndoRedoCommand) -> bool { ... }
}
Expand description

Trait for commands that can be undone and redone.

Implementors can optionally support command merging by overriding the can_merge and merge methods. This allows the UndoRedoManager to combine multiple commands of the same type into a single command, which is useful for operations like continuous typing or dragging.

Required Methods§

Source

fn undo(&mut self) -> Result<()>

Undoes the command, reverting its effects

Source

fn redo(&mut self) -> Result<()>

Redoes the command, reapplying its effects

Source

fn as_any(&self) -> &dyn Any

Returns the type ID of this command for type checking.

This is used for downcasting in the can_merge and merge methods.

§Example
fn as_any(&self) -> &dyn Any {
    self
}

Provided Methods§

Source

fn can_merge(&self, _other: &dyn UndoRedoCommand) -> bool

Returns true if this command can be merged with the other command.

By default, commands cannot be merged. Override this method to enable merging for specific command types.

§Example
fn can_merge(&self, other: &dyn UndoRedoCommand) -> bool {
    // Check if the other command is of the same type
    if let Some(_) = other.as_any().downcast_ref::<Self>() {
        return true;
    }
    false
}
Source

fn merge(&mut self, _other: &dyn UndoRedoCommand) -> bool

Merges this command with the other command. Returns true if the merge was successful.

This method is called only if can_merge returns true.

§Example
use common::undo_redo::UndoRedoCommand;

fn merge(&mut self, other: &dyn UndoRedoCommand) -> bool {
    if let Some(other_cmd) = other.as_any().downcast_ref::<Self>() {
        // Merge the commands
        self.value += other_cmd.value;
        return true;
    }
    false
}

Implementors§