use super::command::{Command, CompositeCommand};
use crate::buffer::TextBuffer;
use crate::canvas_editor::CodeEditor;
use std::collections::VecDeque;
use std::sync::{Arc, Mutex, MutexGuard};
#[derive(Debug, Clone)]
pub struct CommandHistory {
inner: Arc<Mutex<HistoryInner>>,
}
#[derive(Debug)]
struct HistoryInner {
undo_stack: VecDeque<Box<dyn Command>>,
redo_stack: Vec<Box<dyn Command>>,
max_size: usize,
save_point: Option<usize>,
current_group: Option<CompositeCommand>,
}
impl HistoryInner {
fn enforce_size_limit(&mut self) {
while self.undo_stack.len() > self.max_size {
self.undo_stack.pop_front();
if let Some(ref mut sp) = self.save_point {
if *sp > 0 {
*sp -= 1;
} else {
self.save_point = None;
}
}
}
}
}
impl CommandHistory {
fn lock_inner(&self) -> MutexGuard<'_, HistoryInner> {
self.inner.lock().unwrap_or_else(|error| error.into_inner())
}
pub fn new(max_size: usize) -> Self {
Self {
inner: Arc::new(Mutex::new(HistoryInner {
undo_stack: VecDeque::with_capacity(max_size.min(100)),
redo_stack: Vec::with_capacity(max_size.min(100)),
max_size,
save_point: None,
current_group: None,
})),
}
}
pub fn push(&self, command: Box<dyn Command>) {
let mut inner = self.lock_inner();
if let Some(ref mut group) = inner.current_group {
group.add(command);
return;
}
if inner.save_point.is_some_and(|sp| sp > inner.undo_stack.len()) {
inner.save_point = None;
}
inner.redo_stack.clear();
inner.undo_stack.push_back(command);
inner.enforce_size_limit();
}
pub fn undo(
&self,
buffer: &mut TextBuffer,
cursor: &mut (usize, usize),
) -> bool {
let mut inner = self.lock_inner();
if inner.current_group.is_some() {
Self::end_group_internal(&mut inner);
}
if let Some(mut command) = inner.undo_stack.pop_back() {
command.undo(buffer, cursor);
inner.redo_stack.push(command);
true
} else {
false
}
}
pub fn redo(
&self,
buffer: &mut TextBuffer,
cursor: &mut (usize, usize),
) -> bool {
let mut inner = self.lock_inner();
if let Some(mut command) = inner.redo_stack.pop() {
command.execute(buffer, cursor);
inner.undo_stack.push_back(command);
true
} else {
false
}
}
#[must_use]
pub fn can_undo(&self) -> bool {
let inner = self.lock_inner();
!inner.undo_stack.is_empty() || inner.current_group.is_some()
}
#[must_use]
pub fn can_redo(&self) -> bool {
let inner = self.lock_inner();
!inner.redo_stack.is_empty()
}
pub fn mark_saved(&self) {
let mut inner = self.lock_inner();
inner.save_point = Some(inner.undo_stack.len());
}
#[must_use]
pub fn is_modified(&self) -> bool {
let inner = self.lock_inner();
if inner.current_group.is_some() {
return true;
}
match inner.save_point {
None => !inner.undo_stack.is_empty(),
Some(sp) => sp != inner.undo_stack.len(),
}
}
pub fn clear(&self) {
let mut inner = self.lock_inner();
inner.undo_stack.clear();
inner.redo_stack.clear();
inner.save_point = None;
inner.current_group = None;
}
pub fn begin_group(&self) {
let mut inner = self.lock_inner();
if inner.current_group.is_none() {
inner.current_group = Some(CompositeCommand::new());
}
}
pub fn end_group(&self) {
let mut inner = self.lock_inner();
Self::end_group_internal(&mut inner);
}
fn end_group_internal(inner: &mut HistoryInner) {
if let Some(group) = inner.current_group.take()
&& !group.is_empty()
{
if inner.save_point.is_some_and(|sp| sp > inner.undo_stack.len()) {
inner.save_point = None;
}
inner.redo_stack.clear();
inner.undo_stack.push_back(Box::new(group));
inner.enforce_size_limit();
}
}
#[must_use]
pub fn max_size(&self) -> usize {
let inner = self.lock_inner();
inner.max_size
}
pub fn set_max_size(&self, max_size: usize) {
let mut inner = self.lock_inner();
inner.max_size = max_size;
inner.enforce_size_limit();
}
#[must_use]
pub fn undo_count(&self) -> usize {
let inner = self.lock_inner();
inner.undo_stack.len()
}
#[must_use]
pub fn redo_count(&self) -> usize {
let inner = self.lock_inner();
inner.redo_stack.len()
}
}
impl Default for CommandHistory {
fn default() -> Self {
Self::new(100)
}
}
impl CodeEditor {
pub fn is_modified(&self) -> bool {
self.history.is_modified()
}
pub fn mark_saved(&mut self) {
self.history.mark_saved();
}
pub fn can_undo(&self) -> bool {
self.history.can_undo()
}
pub fn can_redo(&self) -> bool {
self.history.can_redo()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::canvas_editor::editing::command::InsertCharCommand;
#[test]
fn test_new_history() {
let history = CommandHistory::new(50);
assert_eq!(history.max_size(), 50);
assert!(!history.can_undo());
assert!(!history.can_redo());
}
#[test]
fn test_push_and_undo() {
let mut buffer = TextBuffer::new("hello");
let mut cursor = (0, 5);
let history = CommandHistory::new(10);
let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
cmd.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd));
assert!(history.can_undo());
assert_eq!(buffer.line(0), "hello!");
history.undo(&mut buffer, &mut cursor);
assert_eq!(buffer.line(0), "hello");
assert_eq!(cursor, (0, 5));
}
#[test]
fn test_redo() {
let mut buffer = TextBuffer::new("hello");
let mut cursor = (0, 5);
let history = CommandHistory::new(10);
let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
cmd.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd));
history.undo(&mut buffer, &mut cursor);
assert_eq!(buffer.line(0), "hello");
assert!(history.can_redo());
history.redo(&mut buffer, &mut cursor);
assert_eq!(buffer.line(0), "hello!");
assert_eq!(cursor, (0, 6));
}
#[test]
fn test_save_point() {
let mut buffer = TextBuffer::new("hello");
let mut cursor = (0, 5);
let history = CommandHistory::new(10);
assert!(!history.is_modified());
let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
cmd.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd));
assert!(history.is_modified());
history.mark_saved();
assert!(!history.is_modified());
let mut cmd2 = InsertCharCommand::new(0, 6, '?', cursor);
cmd2.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd2));
assert!(history.is_modified()); }
#[test]
fn test_save_point_invalidated_after_undo_then_diverging_edit() {
let mut buffer = TextBuffer::new("hello");
let mut cursor = (0, 5);
let history = CommandHistory::new(10);
let mut cmd_a = InsertCharCommand::new(0, 5, 'A', cursor);
cmd_a.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd_a));
history.mark_saved();
assert!(!history.is_modified());
history.undo(&mut buffer, &mut cursor);
assert!(history.is_modified());
let mut cmd_b = InsertCharCommand::new(0, 5, 'B', cursor);
cmd_b.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd_b));
assert_eq!(buffer.line(0), "helloB");
assert!(history.is_modified());
}
#[test]
fn test_save_point_invalidated_after_undo_then_group_diverges() {
let mut buffer = TextBuffer::new("hello");
let mut cursor = (0, 5);
let history = CommandHistory::new(10);
history.begin_group();
let mut cmd_a = InsertCharCommand::new(0, 5, 'A', cursor);
cmd_a.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd_a));
history.end_group();
history.mark_saved();
assert!(!history.is_modified());
history.undo(&mut buffer, &mut cursor);
assert!(history.is_modified());
history.begin_group();
let mut cmd_b = InsertCharCommand::new(0, 5, 'B', cursor);
cmd_b.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd_b));
history.end_group();
assert_eq!(buffer.line(0), "helloB");
assert!(history.is_modified());
}
#[test]
fn test_clear() {
let mut buffer = TextBuffer::new("hello");
let mut cursor = (0, 5);
let history = CommandHistory::new(10);
let mut cmd = InsertCharCommand::new(0, 5, '!', cursor);
cmd.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd));
assert!(history.can_undo());
history.clear();
assert!(!history.can_undo());
assert!(!history.is_modified());
}
#[test]
fn test_size_limit() {
let mut buffer = TextBuffer::new("a");
let mut cursor = (0, 1);
let history = CommandHistory::new(3);
for i in 0..5 {
let mut cmd = InsertCharCommand::new(0, 1 + i, 'x', cursor);
cmd.execute(&mut buffer, &mut cursor);
cursor.1 += 1;
history.push(Box::new(cmd));
}
assert_eq!(history.undo_count(), 3);
}
#[test]
fn test_grouping() {
let mut buffer = TextBuffer::new("hello");
let mut cursor = (0, 5);
let history = CommandHistory::new(10);
history.begin_group();
for ch in "!!!".chars() {
let mut cmd = InsertCharCommand::new(0, cursor.1, ch, cursor);
cmd.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd));
}
history.end_group();
assert_eq!(buffer.line(0), "hello!!!");
assert_eq!(history.undo_count(), 1);
history.undo(&mut buffer, &mut cursor);
assert_eq!(buffer.line(0), "hello");
assert_eq!(cursor, (0, 5));
}
#[test]
fn test_enforce_size_limit_adjusts_save_point() {
let mut buffer = TextBuffer::new("a");
let mut cursor = (0, 1);
let history = CommandHistory::new(3);
for i in 0..3 {
let mut cmd = InsertCharCommand::new(0, 1 + i, 'x', cursor);
cmd.execute(&mut buffer, &mut cursor);
cursor.1 += 1;
history.push(Box::new(cmd));
}
history.mark_saved();
assert!(!history.is_modified());
let mut cmd = InsertCharCommand::new(0, cursor.1, 'x', cursor);
cmd.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd));
assert_eq!(history.undo_count(), 3);
assert!(history.is_modified());
history.undo(&mut buffer, &mut cursor);
assert!(!history.is_modified());
}
#[test]
fn test_enforce_size_limit_clears_save_point_when_trimmed_away() {
let mut buffer = TextBuffer::new("a");
let mut cursor = (0, 1);
let history = CommandHistory::new(3);
let mut cmd = InsertCharCommand::new(0, 1, 'x', cursor);
cmd.execute(&mut buffer, &mut cursor);
cursor.1 += 1;
history.push(Box::new(cmd));
history.mark_saved();
for i in 0..3 {
let mut cmd = InsertCharCommand::new(0, cursor.1 + i, 'x', cursor);
cmd.execute(&mut buffer, &mut cursor);
cursor.1 += 1;
history.push(Box::new(cmd));
}
assert!(history.is_modified());
}
#[test]
fn test_set_max_size_trims_multiple_entries_in_one_call() {
let mut buffer = TextBuffer::new("a");
let mut cursor = (0, 1);
let history = CommandHistory::new(10);
for i in 0..5 {
let mut cmd = InsertCharCommand::new(0, 1 + i, 'x', cursor);
cmd.execute(&mut buffer, &mut cursor);
cursor.1 += 1;
history.push(Box::new(cmd));
}
assert_eq!(history.undo_count(), 5);
history.set_max_size(2);
assert_eq!(history.undo_count(), 2);
}
#[test]
fn test_push_clears_redo() {
let mut buffer = TextBuffer::new("hello");
let mut cursor = (0, 5);
let history = CommandHistory::new(10);
let mut cmd1 = InsertCharCommand::new(0, 5, '!', cursor);
cmd1.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd1));
history.undo(&mut buffer, &mut cursor);
assert!(history.can_redo());
let mut cmd2 = InsertCharCommand::new(0, 5, '?', cursor);
cmd2.execute(&mut buffer, &mut cursor);
history.push(Box::new(cmd2));
assert!(!history.can_redo());
}
#[derive(Debug)]
struct PanickingUndoCommand;
impl Command for PanickingUndoCommand {
fn execute(
&mut self,
_buffer: &mut TextBuffer,
_cursor: &mut (usize, usize),
) {
}
fn undo(
&mut self,
_buffer: &mut TextBuffer,
_cursor: &mut (usize, usize),
) {
let empty: Vec<u8> = Vec::new();
let _ = empty[0];
}
}
#[test]
#[cfg(panic = "unwind")]
fn test_history_survives_a_panicking_command() {
let mut buffer = TextBuffer::new("hello");
let mut cursor = (0, 5);
let history = CommandHistory::new(10);
history.push(Box::new(PanickingUndoCommand));
assert_eq!(history.undo_count(), 1);
let previous_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let outcome =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
history.undo(&mut buffer, &mut cursor)
}));
std::panic::set_hook(previous_hook);
assert!(outcome.is_err(), "the command under test must panic");
assert!(!history.can_undo());
assert!(!history.can_redo());
assert_eq!(history.undo_count(), 0);
assert_eq!(history.redo_count(), 0);
assert!(!history.is_modified());
history.clear();
let mut command = InsertCharCommand::new(0, 5, '!', cursor);
command.execute(&mut buffer, &mut cursor);
history.push(Box::new(command));
assert!(history.undo(&mut buffer, &mut cursor));
assert_eq!(buffer.to_string(), "hello");
}
}