history.rs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. use crate::core::Delta;
  2. const MAX_UNDOS: usize = 20;
  3. #[derive(Debug, Clone)]
  4. pub struct RevId(pub u64);
  5. #[derive(Debug, Clone)]
  6. pub struct Revision {
  7. rev_id: RevId,
  8. pub delta: Delta,
  9. }
  10. impl Revision {
  11. pub fn new(rev_id: RevId, delta: Delta) -> Revision { Self { rev_id, delta } }
  12. }
  13. #[derive(Debug, Clone)]
  14. pub struct UndoResult {
  15. success: bool,
  16. len: u64,
  17. }
  18. impl UndoResult {
  19. pub fn fail() -> Self {
  20. UndoResult {
  21. success: false,
  22. len: 0,
  23. }
  24. }
  25. pub fn success(len: u64) -> Self { UndoResult { success: true, len } }
  26. }
  27. #[derive(Debug, Clone)]
  28. pub struct History {
  29. cur_undo: usize,
  30. undos: Vec<Delta>,
  31. redos: Vec<Delta>,
  32. capacity: usize,
  33. }
  34. impl History {
  35. pub fn new() -> Self {
  36. History {
  37. cur_undo: 1,
  38. undos: Vec::new(),
  39. redos: Vec::new(),
  40. capacity: 20,
  41. }
  42. }
  43. pub fn can_undo(&self) -> bool { !self.undos.is_empty() }
  44. pub fn can_redo(&self) -> bool { !self.redos.is_empty() }
  45. pub fn add_undo(&mut self, delta: Delta) { self.undos.push(delta); }
  46. pub fn add_redo(&mut self, delta: Delta) { self.redos.push(delta); }
  47. pub fn record(&mut self, delta: Delta) {
  48. if delta.ops.is_empty() {
  49. return;
  50. }
  51. self.redos.clear();
  52. self.add_undo(delta);
  53. if self.undos.len() > self.capacity {
  54. self.undos.remove(0);
  55. }
  56. }
  57. pub fn undo(&mut self) -> Option<Delta> {
  58. if !self.can_undo() {
  59. return None;
  60. }
  61. let delta = self.undos.pop().unwrap();
  62. Some(delta)
  63. }
  64. pub fn redo(&mut self) -> Option<Delta> {
  65. if !self.can_redo() {
  66. return None;
  67. }
  68. let delta = self.redos.pop().unwrap();
  69. Some(delta)
  70. }
  71. }