1use std::collections::HashSet;
7
8use anyhow::Result;
9
10use crate::link::Link;
11use crate::link_storage::ChangeObserver;
12use crate::named_type_links::NamedTypeLinks;
13
14pub type LinkChange = (Option<Link>, Option<Link>);
17
18fn present(link: Link) -> Option<Link> {
19 (!link.is_null()).then_some(link)
20}
21
22#[derive(Debug, Default, Clone)]
32pub struct LinksUndoLog {
33 changes: Vec<LinkChange>,
34 names: Vec<(u32, Option<String>)>,
35 named: HashSet<u32>,
36}
37
38impl LinksUndoLog {
39 pub fn new() -> Self {
40 Self::default()
41 }
42
43 pub fn is_empty(&self) -> bool {
45 self.changes.is_empty() && self.names.is_empty()
46 }
47
48 pub fn changes(&self) -> &[LinkChange] {
50 &self.changes
51 }
52
53 pub fn record(&mut self, before: Option<Link>, after: Option<Link>) {
55 if before.is_some() && before == after {
56 return;
57 }
58 self.changes.push((before, after));
59 }
60
61 pub fn record_observed(&mut self, before: Link, after: Link) {
64 self.record(present(before), present(after));
65 }
66
67 pub fn keep_name<L: NamedTypeLinks + ?Sized>(
69 &mut self,
70 names: &mut L,
71 link: u32,
72 ) -> Result<()> {
73 if self.named.insert(link) {
74 let name = names.get_name(link)?;
75 self.names.push((link, name));
76 }
77 Ok(())
78 }
79
80 pub fn keep_holder_of<L: NamedTypeLinks + ?Sized>(
82 &mut self,
83 links: &mut L,
84 name: &str,
85 ) -> Result<()> {
86 match links.get_by_name(name)? {
87 Some(holder) if holder != 0 => self.keep_name(links, holder),
88 _ => Ok(()),
89 }
90 }
91
92 pub fn keep_names_of_usages<L: NamedTypeLinks + ?Sized>(
95 &mut self,
96 links: &mut L,
97 link: u32,
98 ) -> Result<()> {
99 for usage in usages_of(links, link) {
100 self.keep_name(links, usage)?;
101 }
102 Ok(())
103 }
104
105 pub fn clear(&mut self) {
107 self.changes.clear();
108 self.names.clear();
109 self.named.clear();
110 }
111
112 pub fn undo<L: NamedTypeLinks + ?Sized>(&mut self, links: &mut L) -> Result<Vec<u32>> {
117 let mut created = Vec::new();
118 for &(before, after) in self.changes.iter().rev() {
119 match (before, after) {
120 (None, Some(made)) => {
121 if links.exists(made.index) {
122 links.delete(made.index)?;
124 }
125 created.push(made.index);
126 }
127 (Some(was), None) => {
128 if !links.exists(was.index) {
129 links.try_ensure_created(was.index)?;
130 }
131 if was.source != 0 || was.target != 0 {
132 links.update(was.index, was.source, was.target)?;
133 }
134 }
135 (Some(old), Some(_)) => {
136 if links.exists(old.index) {
137 links.update(old.index, old.source, old.target)?;
138 }
139 }
140 (None, None) => {}
141 }
142 }
143 for (link, name) in &self.names {
145 if *name != links.get_name(*link)? && (name.is_none() || !links.exists(*link)) {
146 links.remove_name(*link)?;
147 }
148 }
149 for (link, name) in &self.names {
150 if let Some(name) = name {
151 if links.exists(*link) && Some(name) != links.get_name(*link)?.as_ref() {
152 links.set_name(*link, name)?;
153 }
154 }
155 }
156 self.clear();
157 Ok(created)
158 }
159}
160
161pub fn usages_of<L: NamedTypeLinks + ?Sized>(links: &mut L, link: u32) -> Vec<u32> {
163 let mut found = vec![link];
164 let mut seen = HashSet::from([link]);
165 let mut i = 0;
166 while i < found.len() {
167 let at = found[i];
168 let usages = links
169 .query_links(None, Some(at), None)
170 .into_iter()
171 .chain(links.query_links(None, None, Some(at)));
172 for usage in usages {
173 if seen.insert(usage.index) {
174 found.push(usage.index);
175 }
176 }
177 i += 1;
178 }
179 found
180}
181
182pub fn keep_names_before_update<L: NamedTypeLinks + ?Sized>(
186 log: &mut LinksUndoLog,
187 links: &mut L,
188 index: u32,
189 source: u32,
190 target: u32,
191) -> Result<()> {
192 match links.search(source, target) {
193 Some(equal) if equal != 0 && equal != index => log.keep_names_of_usages(links, index),
194 _ => log.keep_name(links, index),
195 }
196}
197
198pub struct UndoableLinksDecorator<L: NamedTypeLinks> {
202 links: L,
203 log: LinksUndoLog,
204 recording: bool,
205}
206
207impl<L: NamedTypeLinks> UndoableLinksDecorator<L> {
208 pub fn new(links: L) -> Self {
209 Self {
210 links,
211 log: LinksUndoLog::new(),
212 recording: false,
213 }
214 }
215
216 pub fn log(&self) -> &LinksUndoLog {
218 &self.log
219 }
220
221 pub fn recording(&self) -> bool {
223 self.recording
224 }
225
226 pub fn begin(&mut self) {
228 self.log.clear();
229 self.recording = true;
230 }
231
232 pub fn commit(&mut self) {
234 self.recording = false;
235 self.log.clear();
236 }
237
238 pub fn rollback(&mut self) -> Result<Vec<u32>> {
242 self.recording = false;
243 self.log.undo(&mut self.links)
244 }
245
246 pub fn inner(&self) -> &L {
247 &self.links
248 }
249
250 pub fn inner_mut(&mut self) -> &mut L {
251 &mut self.links
252 }
253
254 pub fn into_inner(self) -> L {
255 self.links
256 }
257
258 fn created(&mut self, id: u32) -> u32 {
259 if self.recording {
260 let link = self.links.get_link(id).unwrap_or(Link::new(id, 0, 0));
261 self.log.record(None, Some(link));
262 }
263 id
264 }
265}
266
267impl<L: NamedTypeLinks> NamedTypeLinks for UndoableLinksDecorator<L> {
268 fn query_limits(&self) -> Option<crate::query_options::QueryLimits> {
269 self.links.query_limits()
270 }
271
272 fn reserve_query_allocations(
273 &mut self,
274 processor: &crate::query_processor::QueryProcessor,
275 restriction: &crate::lino_link::LinoLink,
276 substitution: &crate::lino_link::LinoLink,
277 ) -> Result<Option<std::collections::HashSet<u32>>> {
278 self.links
279 .reserve_query_allocations(processor, restriction, substitution)
280 }
281
282 fn create(&mut self, source: u32, target: u32) -> u32 {
283 let id = self.links.create(source, target);
284 self.created(id)
285 }
286
287 fn ensure_created(&mut self, id: u32) -> u32 {
288 if id == 0 || self.links.exists(id) {
289 return id;
290 }
291 let id = self.links.ensure_created(id);
292 self.created(id)
293 }
294
295 fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
296 if id != 0 && self.links.exists(id) {
297 return Ok(id);
298 }
299 let id = self.links.try_ensure_created(id)?;
300 Ok(self.created(id))
301 }
302
303 fn get_link(&mut self, id: u32) -> Option<Link> {
304 self.links.get_link(id)
305 }
306
307 fn exists(&mut self, id: u32) -> bool {
308 self.links.exists(id)
309 }
310
311 fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
312 let id = self.links.try_create(source, target)?;
313 Ok(self.created(id))
314 }
315
316 fn reference_exists(&mut self, id: u32) -> bool {
317 self.links.reference_exists(id)
318 }
319
320 fn next_created_addresses(&mut self, count: usize) -> Result<Vec<u32>> {
321 self.links.next_created_addresses(count)
323 }
324
325 fn update_observed(
326 &mut self,
327 id: u32,
328 source: u32,
329 target: u32,
330 observer: ChangeObserver<'_>,
331 ) -> Result<Link> {
332 if !self.recording {
333 return self.links.update_observed(id, source, target, observer);
334 }
335 keep_names_before_update(&mut self.log, &mut self.links, id, source, target)?;
336 let log = &mut self.log;
337 self.links
338 .update_observed(id, source, target, &mut |before, after| {
339 log.record_observed(before, after);
340 observer(before, after);
341 })
342 }
343
344 fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
345 if !self.recording {
346 return self.links.delete_observed(id, observer);
347 }
348 self.log.keep_names_of_usages(&mut self.links, id)?;
349 let log = &mut self.log;
350 self.links.delete_observed(id, &mut |before, after| {
351 log.record_observed(before, after);
352 observer(before, after);
353 })
354 }
355
356 fn all_links(&mut self) -> Vec<Link> {
357 self.links.all_links()
358 }
359
360 fn query_links(
361 &mut self,
362 index: Option<u32>,
363 source: Option<u32>,
364 target: Option<u32>,
365 ) -> Vec<Link> {
366 self.links.query_links(index, source, target)
367 }
368
369 fn search(&mut self, source: u32, target: u32) -> Option<u32> {
370 self.links.search(source, target)
371 }
372
373 fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
374 match self.links.search(source, target) {
375 Some(found) => found,
376 None => self.create(source, target),
377 }
378 }
379
380 fn get_name(&mut self, id: u32) -> Result<Option<String>> {
381 self.links.get_name(id)
382 }
383
384 fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
385 if self.recording {
386 self.log.keep_name(&mut self.links, id)?;
387 self.log.keep_holder_of(&mut self.links, name)?;
388 }
389 self.links.set_name(id, name)
390 }
391
392 fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
393 self.links.get_by_name(name)
394 }
395
396 fn remove_name(&mut self, id: u32) -> Result<()> {
397 if self.recording {
398 self.log.keep_name(&mut self.links, id)?;
399 }
400 self.links.remove_name(id)
401 }
402
403 fn save(&mut self) -> Result<()> {
404 self.links.save()
405 }
406}