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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
use crate::Position;
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use unicode_segmentation::UnicodeSegmentation;

const TIME_AFTER_WHICH_OPERATION_COMMITS: u64 = 1; // in seconds
const HISTORY_SIZE: usize = 8;

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum OperationType {
    Insert,
    Delete,
}

impl OperationType {
    fn reversed(self) -> Self {
        match self {
            OperationType::Insert => OperationType::Delete,
            OperationType::Delete => OperationType::Insert,
        }
    }
}
/// An Operation describe a text edition at a specific start position.
///
/// An Operation can be of 2 types: either Insert or Delete, testifying of the fact
/// that we either inserted or deleted the provided text content, starting at a given
/// x/y position.
#[derive(Debug, PartialEq)]
pub struct Operation {
    pub content: String,
    pub start_position: Position,
    pub op_type: OperationType,
}

impl Operation {
    /// Append the argument string to the Operation content
    fn mut_push(&mut self, text: &str) {
        self.content.push_str(text);
    }

    /// Return the position the cursor would be at the end of the Operation.
    ///
    /// Examples:
    /// - an insert of "rust" starting at {0, 0} would return an end position of {3, 0}
    /// - an insert of "rust\nrocks" starting at {0, 0} would return an end position of {4, 1}
    /// - a deletion of "tsur" starting at {3, 0} would return an end position of {0, 0}
    /// - a deletion of "skcor\ntsur" starting at {1, 4} would return an end position of {0, 0}
    ///
    /// Note: this one took a long time to get right but seems to work. Check unit tests in doubt!
    #[must_use]
    pub fn end_position(&self, document_rows_length: &[usize]) -> Position {
        let mut x: usize = self.start_position.x;
        let mut y: usize = self.start_position.y;
        match self.op_type {
            OperationType::Insert => {
                for grapheme in self.content.graphemes(true) {
                    if grapheme == "\n" {
                        x = 0;
                        y += 1;
                    } else {
                        x += 1;
                    }
                }
                Position {
                    x: x.saturating_sub(1),
                    y,
                }
            }
            OperationType::Delete => {
                for grapheme in self.content.graphemes(true) {
                    if grapheme == "\n" {
                        y = y.saturating_sub(1);
                        x = *document_rows_length.get(y).unwrap_or(&0);
                    } else {
                        x = x.saturating_sub(1);
                    }
                }
                Position { x, y }
            }
        }
    }

    #[must_use]
    pub fn reversed(&self, document_rows_length: &[usize]) -> Self {
        Self {
            content: self.content.graphemes(true).rev().collect(),
            op_type: self.op_type.reversed(),
            start_position: self.end_position(document_rows_length),
        }
    }
}

/// History is a bounded double-ended ``Vec`` of ``Operations``. Every-time a new change is
/// registered, it is added to the history. If the time elapsed since the last change is
/// greater than ``TIME_AFTER_WHICH_OPERATION_COMMITS``, a new operation is added to the
/// ``operations`` ``VecDeque``. If not, the content of the back (last) operation is
/// mutated in place.
#[derive(Debug)]
pub struct History {
    pub operations: VecDeque<Operation>,
    pub last_edit_time: Instant,
}

impl Default for History {
    fn default() -> Self {
        Self {
            operations: VecDeque::with_capacity(HISTORY_SIZE),
            last_edit_time: Instant::now(),
        }
    }
}

impl History {
    fn set_last_edit_time_to_now(&mut self) {
        self.last_edit_time = Instant::now();
    }

    fn push(&mut self, text: &str, position: Position, operation_type: OperationType) {
        // maintain the history to its max size, to bound memory usage
        if self.operations.len() == HISTORY_SIZE {
            self.operations.pop_front();
        }
        self.operations.push_back(Operation {
            content: text.to_string(),
            start_position: position,
            op_type: operation_type,
        });
        self.set_last_edit_time_to_now();
    }
    /// Push (by either creating a new Operation or mutating the last one) an
    /// Insert operation in history based on the provided inserted text and position.
    fn push_insert(&mut self, text: &str, position: Position) {
        self.push(text, position, OperationType::Insert);
    }

    /// Push (by either creating a new Operation or mutating the last one) a
    /// Delete operation in history based on the provided deleted text and position.
    fn push_delete(&mut self, text: &str, position: Position) {
        self.push(text, position, OperationType::Delete);
    }

    /// Register that an insertion of provided text occured at the provided position.
    ///
    /// Either register that as a whole new ``Operation``, or mutate the back ``Operation``
    /// depending whether the elapsed time since the last operation is greater than
    /// ``TIME_AFTER_WHICH_OPERATION_COMMITS``.
    /// However, if the back operation was a Delee, push a new Insert ``Operation``
    /// in the history.
    pub fn register_insertion(&mut self, text: &str, position: Position) {
        if Instant::elapsed(&self.last_edit_time)
            >= Duration::new(TIME_AFTER_WHICH_OPERATION_COMMITS, 0)
            || self.operations.is_empty()
        {
            self.push_insert(text, position);
        } else if let Some(op) = self.operations.back_mut() {
            match op.op_type {
                OperationType::Insert => {
                    op.mut_push(text);
                    self.set_last_edit_time_to_now();
                }
                OperationType::Delete => self.push_insert(text, position),
            }
        }
    }

    /// Register that a deletion of provided text occured at the provided position.
    ///
    /// Either register that as a whole new ``Operation``, or mutate the back ``Operation``
    /// depending whether the elapsed time since the last operation is greater than
    /// ``TIME_AFTER_WHICH_OPERATION_COMMITS``.
    ///  However, if the back operation was an Insert, push a new Delete ``Operation``
    /// in the history.
    pub fn register_deletion(&mut self, text: &str, position: Position) {
        if Instant::elapsed(&self.last_edit_time)
            >= Duration::new(TIME_AFTER_WHICH_OPERATION_COMMITS, 0)
            || self.operations.is_empty()
        {
            self.push_delete(text, position);
        } else if let Some(op) = self.operations.back_mut() {
            match op.op_type {
                OperationType::Insert => self.push_delete(text, position),
                OperationType::Delete => {
                    op.mut_push(text);
                    self.set_last_edit_time_to_now();
                }
            }
        }
    }

    /// If any Operation is in the history, pop it and returm its reversed Operation.
    #[must_use]
    pub fn last_operation_reversed(&mut self, document_rows_length: &[usize]) -> Option<Operation> {
        self.operations
            .pop_back()
            .map(|op| op.reversed(document_rows_length))
    }
}

#[cfg(test)]
#[path = "./history_test.rs"]
mod history_test;