91 lines
1.8 KiB
Rust
Raw Normal View History

2021-08-06 08:40:45 +08:00
use crate::core::Delta;
2021-08-05 20:05:40 +08:00
const MAX_UNDOS: usize = 20;
2021-08-05 22:52:19 +08:00
#[derive(Debug, Clone)]
2021-08-06 23:06:27 +08:00
pub struct RevId(pub usize);
2021-08-05 22:52:19 +08:00
2021-08-05 20:05:40 +08:00
#[derive(Debug, Clone)]
pub struct Revision {
2021-08-05 22:52:19 +08:00
rev_id: RevId,
pub delta: Delta,
}
impl Revision {
pub fn new(rev_id: RevId, delta: Delta) -> Revision { Self { rev_id, delta } }
2021-08-05 20:05:40 +08:00
}
#[derive(Debug, Clone)]
pub struct UndoResult {
success: bool,
2021-08-06 23:06:27 +08:00
len: usize,
2021-08-05 20:05:40 +08:00
}
2021-08-05 22:52:19 +08:00
impl UndoResult {
pub fn fail() -> Self {
UndoResult {
success: false,
len: 0,
}
}
2021-08-06 23:06:27 +08:00
pub fn success(len: usize) -> Self { UndoResult { success: true, len } }
2021-08-05 22:52:19 +08:00
}
2021-08-05 20:05:40 +08:00
#[derive(Debug, Clone)]
pub struct History {
cur_undo: usize,
2021-08-05 22:52:19 +08:00
undos: Vec<Delta>,
redoes: Vec<Delta>,
2021-08-06 08:40:45 +08:00
capacity: usize,
2021-08-05 20:05:40 +08:00
}
impl History {
pub fn new() -> Self {
History {
cur_undo: 1,
undos: Vec::new(),
redoes: Vec::new(),
2021-08-14 16:44:39 +08:00
capacity: MAX_UNDOS,
2021-08-05 20:05:40 +08:00
}
}
pub fn can_undo(&self) -> bool { !self.undos.is_empty() }
pub fn can_redo(&self) -> bool { !self.redoes.is_empty() }
2021-08-05 20:05:40 +08:00
2021-08-05 22:52:19 +08:00
pub fn add_undo(&mut self, delta: Delta) { self.undos.push(delta); }
2021-08-05 20:05:40 +08:00
pub fn add_redo(&mut self, delta: Delta) { self.redoes.push(delta); }
2021-08-05 22:52:19 +08:00
2021-08-06 08:40:45 +08:00
pub fn record(&mut self, delta: Delta) {
if delta.ops.is_empty() {
return;
}
self.redoes.clear();
2021-08-06 08:40:45 +08:00
self.add_undo(delta);
if self.undos.len() > self.capacity {
self.undos.remove(0);
}
}
2021-08-05 22:52:19 +08:00
pub fn undo(&mut self) -> Option<Delta> {
2021-08-05 20:05:40 +08:00
if !self.can_undo() {
return None;
}
2021-08-05 22:52:19 +08:00
let delta = self.undos.pop().unwrap();
Some(delta)
}
2021-08-05 20:05:40 +08:00
2021-08-05 22:52:19 +08:00
pub fn redo(&mut self) -> Option<Delta> {
if !self.can_redo() {
return None;
}
2021-08-05 20:05:40 +08:00
let delta = self.redoes.pop().unwrap();
2021-08-05 22:52:19 +08:00
Some(delta)
2021-08-05 20:05:40 +08:00
}
}