Skip to main content

xrack_layout/
history.rs

1use crate::{
2    EditAction, Target,
3    edit::{AppliedEdit, SelectionState},
4};
5use std::{
6    collections::VecDeque,
7    time::{Duration, Instant},
8};
9use xrack_runtime::{Node, RowKey};
10
11const EDITORS: usize = 16;
12const EDIT_GROUPS: usize = 128;
13const EDIT_BYTES: usize = 1024 * 1024;
14const GROUP_INTERVAL: Duration = Duration::from_millis(750);
15
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub(crate) struct EditorKey {
18    path: Vec<usize>,
19    row: Option<(usize, RowKey)>,
20}
21
22impl EditorKey {
23    pub(crate) fn new(scene: &Node, target: &Target) -> Self {
24        let mut path = target.path.clone();
25        let row = target.row_key.and_then(|key| {
26            (1..=path.len()).rev().find_map(|depth| {
27                let node = scene.at_path(&path[..depth])?;
28                (node.kind == "ListRow" && node.routing_row_key() == Some(key))
29                    .then_some((depth - 1, key))
30            })
31        });
32        if let Some((slot, key)) = row {
33            if key.has_view_scope() {
34                path.drain(..=slot);
35            } else {
36                path[slot] = 0;
37            }
38        }
39        Self { path, row }
40    }
41}
42
43/// The source of an edit determines whether it can merge with preceding typing.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum EditSource {
46    Keyboard,
47    Ime,
48    Atomic,
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub(crate) enum Group {
53    Insert,
54    Overwrite,
55    Backspace,
56    Delete,
57    Atomic,
58}
59
60impl Group {
61    pub(crate) fn for_edit(
62        source: EditSource,
63        action: EditAction<'_>,
64        before: SelectionState,
65        edit: &AppliedEdit,
66    ) -> Self {
67        if source != EditSource::Keyboard || !before.collapsed() {
68            return Self::Atomic;
69        }
70        match action {
71            EditAction::Insert(_) if !edit.inserted.contains('\n') => {
72                if edit.removed.is_empty() {
73                    Self::Insert
74                } else {
75                    Self::Overwrite
76                }
77            }
78            EditAction::Backspace => Self::Backspace,
79            EditAction::Delete => Self::Delete,
80            _ => Self::Atomic,
81        }
82    }
83}
84
85#[derive(Clone, Debug)]
86pub(crate) struct Record {
87    start: usize,
88    removed: String,
89    inserted: String,
90    before: SelectionState,
91    after: SelectionState,
92}
93
94impl Record {
95    pub(crate) fn new(
96        edit: AppliedEdit,
97        before: SelectionState,
98        after: SelectionState,
99    ) -> (String, Self) {
100        (
101            edit.text,
102            Self {
103                start: edit.start,
104                removed: edit.removed,
105                inserted: edit.inserted,
106                before,
107                after,
108            },
109        )
110    }
111
112    fn bytes(&self) -> usize {
113        self.removed.len() + self.inserted.len()
114    }
115
116    fn merge(&mut self, next: &Self, group: Group) -> bool {
117        if self.after != next.before {
118            return false;
119        }
120        match group {
121            Group::Insert if self.start + self.inserted.len() == next.start => {
122                self.inserted.push_str(&next.inserted)
123            }
124            Group::Overwrite if self.start + self.inserted.len() == next.start => {
125                self.removed.push_str(&next.removed);
126                self.inserted.push_str(&next.inserted);
127            }
128            Group::Delete if self.start == next.start => self.removed.push_str(&next.removed),
129            Group::Backspace if next.start + next.removed.len() == self.start => {
130                self.removed.insert_str(0, &next.removed);
131                self.start = next.start;
132            }
133            _ => return false,
134        }
135        self.after = next.after;
136        true
137    }
138
139    fn apply(&self, current: &str, redo: bool) -> (String, SelectionState) {
140        let (remove, insert, selection) = if redo {
141            (&self.removed, &self.inserted, self.after)
142        } else {
143            (&self.inserted, &self.removed, self.before)
144        };
145        let range = self.start..self.start + remove.len();
146        debug_assert_eq!(&current[range.clone()], remove);
147        let mut text = current.to_owned();
148        text.replace_range(range, insert);
149        (text, selection)
150    }
151}
152
153#[derive(Clone, Debug, Default)]
154pub(crate) struct TextHistory {
155    expected: String,
156    undo: VecDeque<Record>,
157    redo: Vec<Record>,
158    group: Option<(Group, Instant)>,
159}
160
161impl TextHistory {
162    pub(crate) fn break_group(&mut self) {
163        self.group = None;
164    }
165    pub(crate) fn observe(&mut self, current: &str) {
166        if self.expected != current {
167            self.undo.clear();
168            self.redo.clear();
169            self.group = None;
170            self.expected.clear();
171            self.expected.push_str(current);
172        }
173    }
174
175    pub(crate) fn push(&mut self, next: String, record: Record, group: Group, now: Instant) {
176        let merged = group != Group::Atomic
177            && self.group.is_some_and(|(previous, when)| {
178                previous == group && now.saturating_duration_since(when) <= GROUP_INTERVAL
179            })
180            && self
181                .undo
182                .back_mut()
183                .is_some_and(|last| last.merge(&record, group));
184        if !merged {
185            self.undo.push_back(record);
186        }
187        self.expected = next;
188        self.group = Some((group, now));
189        self.redo.clear();
190        let mut bytes: usize = self.undo.iter().map(Record::bytes).sum();
191        while (self.undo.len() > EDIT_GROUPS || bytes > EDIT_BYTES)
192            && let Some(oldest) = self.undo.pop_front()
193        {
194            bytes -= oldest.bytes();
195        }
196    }
197
198    pub(crate) fn replay(&self, redo: bool) -> Option<(String, SelectionState)> {
199        let record = if redo {
200            self.redo.last()
201        } else {
202            self.undo.back()
203        }?;
204        Some(record.apply(&self.expected, redo))
205    }
206
207    pub(crate) fn availability(&self, current: &str) -> (bool, bool) {
208        let (undo, redo) = (!self.undo.is_empty(), !self.redo.is_empty());
209        if (undo || redo) && self.expected == current {
210            (undo, redo)
211        } else {
212            (false, false)
213        }
214    }
215
216    pub(crate) fn commit_replay(&mut self, text: String, redo: bool) {
217        if redo {
218            let Some(record) = self.redo.pop() else {
219                return;
220            };
221            self.undo.push_back(record);
222        } else {
223            let Some(record) = self.undo.pop_back() else {
224                return;
225            };
226            self.redo.push(record);
227        }
228        self.expected = text;
229        self.group = None;
230    }
231}
232
233#[derive(Clone, Debug, Default)]
234pub(crate) struct EditHistories(VecDeque<(EditorKey, TextHistory)>);
235
236impl EditHistories {
237    pub(crate) fn get(&self, key: &EditorKey) -> Option<&TextHistory> {
238        self.0
239            .iter()
240            .find(|(stored, _)| stored == key)
241            .map(|(_, history)| history)
242    }
243
244    #[expect(
245        clippy::expect_used,
246        reason = "the deque is appended immediately before returning the new last value"
247    )]
248    pub(crate) fn entry(&mut self, key: EditorKey) -> &mut TextHistory {
249        let old = self
250            .0
251            .iter()
252            .position(|(stored, _)| *stored == key)
253            .and_then(|index| self.0.remove(index));
254        if self.0.len() == EDITORS {
255            self.0.pop_front();
256        }
257        self.0
258            .push_back(old.unwrap_or_else(|| (key, TextHistory::default())));
259        &mut self.0.back_mut().expect("inserted editor history").1
260    }
261
262    pub(crate) fn get_mut(&mut self, key: &EditorKey) -> Option<&mut TextHistory> {
263        self.0
264            .iter_mut()
265            .find(|(stored, _)| stored == key)
266            .map(|(_, history)| history)
267    }
268
269    pub(crate) fn break_group(&mut self) {
270        for (_, history) in &mut self.0 {
271            history.break_group();
272        }
273    }
274}