Skip to main content

cimview/
refresh.rs

1//! The model decoded from a set of files, brought up to date with an edit of them by decoding again
2//! only the objects the edit touched. Decoding RealGrid's 117 MB anew takes some 0.9 s, and an edit
3//! in an editor touches a handful of objects.
4//!
5//! In each file that changed, the elements of its index before and after are compared in document
6//! order: those that differ, came or went write the objects touched. Each is removed from the model
7//! and decoded again from what every file writes of it (an EQ file's element and an SSH file's),
8//! the files in their order, merged as a load merges them: the model is the one a full decode
9//! gives.
10
11use std::collections::BTreeSet;
12
13use cimmodel::CimDataset;
14
15use crate::edit::File;
16use crate::index::Element;
17
18/// `model`, decoded from the files as they were, brought up to date with `files` as they are now
19/// (in the order the model was decoded from them); `before` holds each file that changed as it
20/// was, with its index. The number of objects decoded again.
21///
22/// An error says why the model can't be patched: a file gone or new, an edit of what is written
23/// around the objects (the XML declaration, the root element), an object without an mRID, objects
24/// of classes no table knows, or a difference model. The model may then be partly changed: decode
25/// it anew. A model with difference models applied ([`CimDataset::apply`]) is the caller's to decode
26/// anew.
27pub fn refresh(model: &mut CimDataset, before: &[File], files: &[File]) -> Result<usize, String> {
28    let mut ids: BTreeSet<&str> = BTreeSet::new();
29    for old in before {
30        let new = files
31            .iter()
32            .find(|f| f.name == old.name)
33            .ok_or_else(|| format!("`{}` is no longer in the set", old.name))?;
34        if old.text == new.text {
35            continue;
36        }
37        touched(old, new, &mut ids)?;
38    }
39    let ids: BTreeSet<String> = ids.into_iter().map(str::to_string).collect();
40    refresh_objects(model, &ids, files)
41}
42
43/// `model` with the objects `ids` decoded again from `files` as they are now (in the order the
44/// model was decoded from them): for an edit that knows the objects it touched, as
45/// [`crate::index::Index::edited`] tells. The number of objects. An error as [`refresh`]'s.
46pub fn refresh_objects(
47    model: &mut CimDataset,
48    ids: &BTreeSet<String>,
49    files: &[File],
50) -> Result<usize, String> {
51    if ids.contains("") {
52        return Err("an object without an mRID".into());
53    }
54    for id in ids {
55        model.remove(id);
56    }
57    for file in files {
58        let mut spans: Vec<(usize, usize)> = ids
59            .iter()
60            .flat_map(|id| file.index.of(id))
61            .map(|e| span(file, e))
62            .collect();
63        if spans.is_empty() {
64            continue;
65        }
66        spans.sort_unstable();
67        let body: Vec<&str> = spans.iter().map(|&(s, e)| &file.text[s..e]).collect();
68        model.merge(decode(file, &body.join("\n"))?);
69    }
70    Ok(ids.len())
71}
72
73/// Where `e` is written in `file`, as byte offsets.
74fn span(file: &File, e: &Element) -> (usize, usize) {
75    (
76        file.lines.offset(file.text, e.full.start),
77        file.lines.offset(file.text, e.full.end),
78    )
79}
80
81/// The objects whose elements differ between `old` and `new`, two states of one file, added to
82/// `ids`.
83fn touched<'a>(old: &File<'a>, new: &File<'a>, ids: &mut BTreeSet<&'a str>) -> Result<(), String> {
84    let (was, is) = (&old.index.elements, &new.index.elements);
85    let (Some(first), Some(last)) = (was.first().zip(is.first()), was.last().zip(is.last())) else {
86        return Err("a file without objects".into());
87    };
88    // Around the objects, the file is written as it was.
89    let head = (span(old, first.0).0, span(new, first.1).0);
90    let tail = (span(old, last.0).1, span(new, last.1).1);
91    if old.text[..head.0] != new.text[..head.1] || old.text[tail.0..] != new.text[tail.1..] {
92        return Err("an edit around the objects: the XML declaration or the root element".into());
93    }
94    let text = |f: &File<'a>, e: &Element| {
95        let (s, e) = span(f, e);
96        &f.text[s..e]
97    };
98    // Whether the object of `e` is written in `f` at `from` or after.
99    let later = |f: &File, e: &Element, from: usize| {
100        f.index
101            .places_of(&e.mrid)
102            .iter()
103            .any(|&k| k as usize >= from)
104    };
105    let mut mark = |e: &'a Element| {
106        if e.mrid.is_empty() {
107            Err("an object without an mRID".to_string())
108        } else {
109            ids.insert(e.mrid.as_str());
110            Ok(())
111        }
112    };
113    let (mut i, mut j) = (0, 0);
114    while i < was.len() && j < is.len() {
115        let (a, b) = (&was[i], &is[j]);
116        if a.mrid == b.mrid {
117            if text(old, a) != text(new, b) {
118                mark(b)?;
119            }
120            i += 1;
121            j += 1;
122            continue;
123        }
124        match (later(new, a, j), later(old, b, i)) {
125            // `b` came.
126            (true, false) => {
127                mark(b)?;
128                j += 1;
129            }
130            // `a` went.
131            (false, _) => {
132                mark(a)?;
133                i += 1;
134            }
135            // Both moved.
136            (true, true) => {
137                mark(a)?;
138                mark(b)?;
139                i += 1;
140                j += 1;
141            }
142        }
143    }
144    was[i..].iter().try_for_each(&mut mark)?;
145    is[j..].iter().try_for_each(&mut mark)?;
146    Ok(())
147}
148
149/// `body`, whole elements of `file`, decoded as a document of its own: with what `file` writes
150/// before its objects (the XML declaration, the root's start tag) and after them.
151fn decode(file: &File, body: &str) -> Result<CimDataset, String> {
152    let text = file.text;
153    let head = file
154        .index
155        .elements
156        .first()
157        .map_or(0, |e| file.lines.offset(text, e.full.start));
158    let tail = text.rfind("</").unwrap_or(text.len());
159    let doc = format!("{}{body}\n{}", &text[..head], &text[tail..]);
160    let found = CimDataset::decode_str(&doc).map_err(|e| e.to_string())?;
161    if !found.foreign.is_empty() {
162        return Err("objects of classes no table knows".into());
163    }
164    if !found.differences.is_empty() {
165        return Err("a difference model".into());
166    }
167    Ok(found)
168}
169
170#[cfg(test)]
171mod tests {
172    use std::collections::{BTreeMap, HashSet};
173
174    use super::*;
175    use crate::edit::{self, Edits};
176    use crate::grid::{self, Model};
177    use crate::index::Index;
178    use crate::text::Range;
179    use crate::text::{LineIndex, apply};
180    use crate::tree;
181
182    fn micro_grid() -> Vec<(String, String)> {
183        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(
184            "../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged",
185        );
186        let mut names: Vec<_> = std::fs::read_dir(&dir)
187            .unwrap()
188            .map(|e| e.unwrap().file_name().into_string().unwrap())
189            .filter(|n| n.ends_with(".xml"))
190            .collect();
191        names.sort();
192        names
193            .into_iter()
194            .map(|n| {
195                let text = std::fs::read_to_string(dir.join(&n)).unwrap();
196                (n, text)
197            })
198            .collect()
199    }
200
201    fn decode_all(texts: &[(String, String)]) -> CimDataset {
202        let mut model = CimDataset::default();
203        for (_, t) in texts {
204            model.merge(CimDataset::decode_str(t).unwrap());
205        }
206        model
207    }
208
209    /// Each object as written: its class, whether only described, its fields sorted; and each
210    /// class's objects, sorted.
211    fn snapshot(model: &CimDataset) -> (BTreeMap<String, String>, BTreeMap<String, Vec<String>>) {
212        let objects = model
213            .entries
214            .iter()
215            .map(|(id, e)| {
216                let mut fields: Vec<String> = e
217                    .fields()
218                    .iter()
219                    .map(|(k, v)| format!("{k}={v:?}"))
220                    .collect();
221                fields.sort();
222                let types: Vec<&str> = e.types().map(|t| t.qualified).collect();
223                (id.clone(), format!("{types:?} {} {fields:?}", e.defined()))
224            })
225            .collect();
226        let by_type = model
227            .by_type
228            .iter()
229            .filter(|(_, ids)| !ids.is_empty())
230            .map(|(t, ids)| {
231                let mut ids = ids.clone();
232                ids.sort();
233                (t.clone(), ids)
234            })
235            .collect();
236        (objects, by_type)
237    }
238
239    /// `edit` made of the files `texts`: the model patched, and decoded anew, alike.
240    fn patched_as_decoded(
241        texts: &[(String, String)],
242        edit: impl for<'a> FnOnce(&[File<'a>]) -> Edits<'a>,
243    ) -> usize {
244        let lines: Vec<LineIndex> = texts.iter().map(|(_, t)| LineIndex::new(t)).collect();
245        let indexes: Vec<Index> = texts.iter().map(|(_, t)| Index::build(t)).collect();
246        let files: Vec<File> = texts
247            .iter()
248            .zip(&lines)
249            .zip(&indexes)
250            .map(|(((n, t), l), i)| File {
251                name: n,
252                text: t,
253                lines: l,
254                index: i,
255            })
256            .collect();
257        let edits: Vec<(String, Vec<_>)> = edit(&files)
258            .into_iter()
259            .map(|(n, e)| (n.to_string(), e))
260            .collect();
261        assert!(!edits.is_empty(), "the edit changes nothing");
262        let after: Vec<(String, String)> = texts
263            .iter()
264            .map(|(n, t)| match edits.iter().find(|(m, _)| m == n) {
265                Some((_, e)) => (n.clone(), apply(t, e)),
266                None => (n.clone(), t.clone()),
267            })
268            .collect();
269
270        let mut model = decode_all(texts);
271        let changed: Vec<&File> = files
272            .iter()
273            .filter(|f| edits.iter().any(|(n, _)| n == f.name))
274            .collect();
275        let before: Vec<File> = changed
276            .iter()
277            .map(|f| File {
278                name: f.name,
279                text: f.text,
280                lines: f.lines,
281                index: f.index,
282            })
283            .collect();
284        let lines: Vec<LineIndex> = after.iter().map(|(_, t)| LineIndex::new(t)).collect();
285        let indexes: Vec<Index> = after.iter().map(|(_, t)| Index::build(t)).collect();
286        let files: Vec<File> = after
287            .iter()
288            .zip(&lines)
289            .zip(&indexes)
290            .map(|(((n, t), l), i)| File {
291                name: n,
292                text: t,
293                lines: l,
294                index: i,
295            })
296            .collect();
297        let count = refresh(&mut model, &before, &files).unwrap();
298        assert_eq!(snapshot(&model), snapshot(&decode_all(&after)));
299        count
300    }
301
302    #[test]
303    fn a_rename_patched_as_decoded() {
304        let texts = micro_grid();
305        let model = decode_all(&texts);
306        let line = model.by_type["ACLineSegment"][0].clone();
307        let n = patched_as_decoded(&texts, |files| {
308            edit::rename(files, &line, "_renamed").unwrap()
309        });
310        // The line under both names, its terminals and what else refers to it.
311        assert!(n >= 4, "{n}");
312    }
313
314    #[test]
315    fn a_deletion_patched_as_decoded() {
316        let texts = micro_grid();
317        let model = decode_all(&texts);
318        let line = model.by_type["ACLineSegment"][1].clone();
319        patched_as_decoded(&texts, |files| {
320            edit::delete(files, &HashSet::from([line.as_str()])).edits
321        });
322    }
323
324    #[test]
325    fn a_field_set_patched_as_decoded() {
326        let texts = micro_grid();
327        let model = decode_all(&texts);
328        let line = model.by_type["ACLineSegment"][0].clone();
329        let n = patched_as_decoded(&texts, |files| {
330            edit::set_field(files, "", &line, "IdentifiedObject.name", "renamed").unwrap()
331        });
332        assert_eq!(n, 1);
333    }
334
335    #[test]
336    fn a_breaker_added_patched_as_decoded() {
337        let texts = micro_grid();
338        let model = decode_all(&texts);
339        let datasets = [model];
340        let m = Model::new(&datasets);
341        let g = grid::build(&m);
342        let t = tree::build(&m);
343        let (sub, inside) = g
344            .nodes
345            .iter()
346            .filter(|n| n.kind == "Substation")
347            .find_map(|n| Some((n.id.clone(), g.inside_of(&n.id)?)))
348            .unwrap();
349        let level = inside.groups[0].id.clone();
350        let mut k = 0u8;
351        let n = patched_as_decoded(&texts, |files| {
352            let op = serde_json::json!({ "op": "add", "class": "Breaker", "level": level });
353            let mut random = || {
354                k += 1;
355                [k; 16]
356            };
357            crate::topology::apply(files, &t, inside, &op, &mut random)
358                .unwrap_or_else(|e| panic!("{sub}: {e}"))
359                .edits
360        });
361        // The breaker, its terminals and connectivity nodes at least.
362        assert!(n >= 3, "{n}");
363    }
364
365    /// `edits` of the files `texts`, each file's index edited as read anew.
366    fn indexes_edited_as_read(
367        texts: &[(String, String)],
368        edits: &[(String, Vec<crate::text::TextEdit>)],
369    ) -> usize {
370        let mut all = 0;
371        assert!(
372            edits.iter().any(|(_, e)| !e.is_empty()),
373            "the edit changes nothing"
374        );
375        for (name, changes) in edits {
376            let old = &texts.iter().find(|(n, _)| n == name).unwrap().1;
377            let new = apply(old, changes);
378            let (old_lines, new_lines) = (LineIndex::new(old), LineIndex::new(&new));
379            let (edited, touched) = Index::build(old)
380                .edited(old, &old_lines, &new, &new_lines, changes)
381                .unwrap_or_else(|_| panic!("{name}: refused"));
382            let read = Index::build(&new);
383            assert_eq!(
384                format!("{:?}", edited.elements),
385                format!("{:?}", read.elements),
386                "{name}"
387            );
388            // What differs is among what it touched.
389            let was = Index::build(old);
390            let before: BTreeMap<&str, String> = was
391                .elements
392                .iter()
393                .map(|e| (e.mrid.as_str(), slice(old, &old_lines, e).to_string()))
394                .collect();
395            for e in &read.elements {
396                if before.get(e.mrid.as_str()).map(String::as_str)
397                    != Some(slice(&new, &new_lines, e))
398                {
399                    assert!(touched.contains(&e.mrid), "{name}: {} not touched", e.mrid);
400                }
401            }
402            all += touched.len();
403        }
404        all
405    }
406
407    fn slice<'t>(text: &'t str, lines: &LineIndex, e: &crate::index::Element) -> &'t str {
408        &text[lines.offset(text, e.full.start)..lines.offset(text, e.full.end)]
409    }
410
411    /// The edits `edit` makes of the MicroGrid files, by file.
412    fn edits_of(
413        texts: &[(String, String)],
414        edit: impl for<'a> FnOnce(&[File<'a>]) -> Edits<'a>,
415    ) -> Vec<(String, Vec<crate::text::TextEdit>)> {
416        let lines: Vec<LineIndex> = texts.iter().map(|(_, t)| LineIndex::new(t)).collect();
417        let indexes: Vec<Index> = texts.iter().map(|(_, t)| Index::build(t)).collect();
418        let files: Vec<File> = texts
419            .iter()
420            .zip(&lines)
421            .zip(&indexes)
422            .map(|(((n, t), l), i)| File {
423                name: n,
424                text: t,
425                lines: l,
426                index: i,
427            })
428            .collect();
429        edit(&files)
430            .into_iter()
431            .map(|(n, e)| (n.to_string(), e))
432            .collect()
433    }
434
435    #[test]
436    fn indexes_are_edited_as_read_anew() {
437        let texts = micro_grid();
438        let model = decode_all(&texts);
439        let line = model.by_type["ACLineSegment"][0].clone();
440        let other = model.by_type["ACLineSegment"][1].clone();
441        indexes_edited_as_read(
442            &texts,
443            &edits_of(&texts, |f| edit::rename(f, &line, "_renamed").unwrap()),
444        );
445        indexes_edited_as_read(
446            &texts,
447            &edits_of(&texts, |f| {
448                edit::delete(f, &HashSet::from([other.as_str()])).edits
449            }),
450        );
451        indexes_edited_as_read(
452            &texts,
453            &edits_of(&texts, |f| {
454                edit::set_field(f, "", &line, "IdentifiedObject.name", "a\nname").unwrap()
455            }),
456        );
457        // Objects added before the root's end, and one taken from the start.
458        let (name, text) = &texts[4];
459        let lines = LineIndex::new(text);
460        let ix = Index::build(text);
461        let end = text.rfind("</").unwrap();
462        let at = |o: usize| lines.position(text, o);
463        let first = &ix.elements[1];
464        let added = "  <cim:Breaker rdf:ID=\"_new\">\n    <cim:IdentifiedObject.name>New</cim:IdentifiedObject.name>\n  </cim:Breaker>\n";
465        let changes = vec![
466            crate::text::TextEdit::new(Range::new(first.full.start, first.full.end), String::new()),
467            crate::text::TextEdit::new(Range::new(at(end), at(end)), added.to_string()),
468        ];
469        // The two objects, and those written on the lines they meet: no more is read again.
470        let touched = indexes_edited_as_read(&texts, &[(name.clone(), changes)]);
471        assert!(touched <= 6, "{touched}");
472    }
473
474    /// The grid of `texts` laid out as it is built anew, given that of `before`.
475    fn laid_out_as_anew(before: &[(String, String)], texts: &[(String, String)]) -> bool {
476        let previous = [decode_all(before)];
477        let previous = grid::build(&Model::new(&previous));
478        let now = [decode_all(texts)];
479        let m = Model::new(&now);
480        let kept = format!("{:?}", grid::build_like(&m, Some(previous)).auto);
481        kept == format!("{:?}", grid::build(&m).auto)
482    }
483
484    /// The automatic layout of the grid of `texts`, built given `previous`, and that grid.
485    fn auto_after(texts: &[(String, String)], previous: Option<grid::Grid>) -> grid::Grid {
486        let now = [decode_all(texts)];
487        grid::build_like(&Model::new(&now), previous)
488    }
489
490    /// Where `g`'s automatic layout puts each substation, and routes each line, by their ids.
491    fn places(
492        g: &grid::Grid,
493    ) -> (
494        BTreeMap<String, (f64, f64)>,
495        BTreeMap<String, crate::schematic::Route>,
496    ) {
497        let auto = g.auto.as_ref().unwrap();
498        let nodes = g
499            .nodes
500            .iter()
501            .enumerate()
502            .map(|(i, n)| (n.id.clone(), auto.nodes[&i]))
503            .collect();
504        let edges = g
505            .edges
506            .iter()
507            .enumerate()
508            .filter_map(|(k, e)| {
509                let route = auto.edges.get(&k)?.clone();
510                Some((
511                    e.id.clone(),
512                    (route, auto.tracks.get(&k).copied().unwrap_or(0)),
513                ))
514            })
515            .collect();
516        (nodes, edges)
517    }
518
519    #[test]
520    fn a_grid_keeps_its_layout_as_it_would_come_out() {
521        let texts = micro_grid();
522        let after = |edits: Vec<(String, Vec<crate::text::TextEdit>)>| -> Vec<(String, String)> {
523            texts
524                .iter()
525                .map(|(n, t)| match edits.iter().find(|(m, _)| m == n) {
526                    Some((_, e)) => (n.clone(), apply(t, e)),
527                    None => (n.clone(), t.clone()),
528                })
529                .collect()
530        };
531        // A field set: the same substations and lines.
532        let model = decode_all(&texts);
533        let line = model.by_type["ACLineSegment"][0].clone();
534        let named = after(edits_of(&texts, |f| {
535            edit::set_field(f, "", &line, "IdentifiedObject.name", "renamed").unwrap()
536        }));
537        assert!(laid_out_as_anew(&texts, &named));
538    }
539
540    #[test]
541    fn a_grid_keeps_its_layout_as_lines_come_and_go() {
542        let texts = micro_grid();
543        let model = decode_all(&texts);
544        let line = model.by_type["ACLineSegment"][0].clone();
545        let edits = edits_of(&texts, |f| {
546            edit::delete(f, &HashSet::from([line.as_str()])).edits
547        });
548        let gone: Vec<(String, String)> = texts
549            .iter()
550            .map(|(n, t)| match edits.iter().find(|(m, _)| m == n) {
551                Some((_, e)) => (n.clone(), apply(t, e)),
552                None => (n.clone(), t.clone()),
553            })
554            .collect();
555        let first = auto_after(&texts, None);
556        let (nodes, edges) = places(&first);
557        // A line gone: every substation where it was, every other line along its route.
558        let without = auto_after(&gone, Some(auto_after(&texts, None)));
559        let (kept, routes) = places(&without);
560        assert_eq!(kept, nodes);
561        assert!(!routes.is_empty());
562        for (id, route) in &routes {
563            assert_eq!(Some(route), edges.get(id), "{id}");
564        }
565        assert!(routes.keys().all(|id| !id.starts_with(line.as_str())));
566        // The line back: routed between where its substations are; gone again, the layout of
567        // before it came, as an addition undone gives back.
568        let back = auto_after(
569            &texts,
570            Some(auto_after(&gone, Some(auto_after(&texts, None)))),
571        );
572        let (again, back_routes) = places(&back);
573        assert_eq!(again, nodes);
574        assert_eq!(back_routes.len(), edges.len());
575        let undone = auto_after(&gone, Some(back));
576        assert_eq!(places(&undone), places(&without));
577        // Another model: laid out anew.
578        assert_eq!(
579            format!("{:?}", auto_after(&texts, Some(grid::Grid::default())).auto),
580            format!("{:?}", first.auto)
581        );
582    }
583
584    /// The grid of the files `edit` makes of `texts`, from that of `texts` with a finding on
585    /// each object (as cimlens keeps it, validated) and what the edit touched: as [`grid::build`]
586    /// gives it. Whether it was brought up to date, rather than built anew.
587    fn rebuilt_as_built(
588        texts: &[(String, String)],
589        edit: impl for<'a> FnOnce(&[File<'a>]) -> Edits<'a>,
590    ) -> bool {
591        let edits = edits_of(texts, edit);
592        let mut touched = BTreeSet::new();
593        let after: Vec<(String, String)> = texts
594            .iter()
595            .map(|(n, t)| match edits.iter().find(|(m, _)| m == n) {
596                Some((_, e)) => {
597                    let new = apply(t, e);
598                    let (_, ids) = Index::build(t)
599                        .edited(t, &LineIndex::new(t), &new, &LineIndex::new(&new), e)
600                        .unwrap_or_else(|_| panic!("{n}: refused"));
601                    touched.extend(ids);
602                    (n.clone(), new)
603                }
604                None => (n.clone(), t.clone()),
605            })
606            .collect();
607        let before = [decode_all(texts)];
608        let found: Vec<(Option<usize>, cimvalidation::Violation)> = before[0]
609            .entries
610            .keys()
611            .map(|id| {
612                let v = cimvalidation::Violation {
613                    object_id: id.clone(),
614                    rule_id: String::new(),
615                    class: String::new(),
616                    property: String::new(),
617                    message: String::new(),
618                    severity: "sh:Violation".into(),
619                    name: String::new(),
620                    description: String::new(),
621                };
622                (None, v)
623            })
624            .collect();
625        let previous = || {
626            let mut g = grid::build(&Model::new(&before));
627            g.add_findings(&found);
628            g
629        };
630        let now = [decode_all(&after)];
631        let m = Model::new(&now);
632        let updated = grid::update(&m, &mut previous(), &touched).is_some();
633        // As built given the grid before: its automatic layout carried over.
634        let built = grid::build_like(&m, Some(grid::build(&Model::new(&before))));
635        assert_eq!(
636            grid::rebuild(&m, previous(), &touched).snapshot(),
637            built.snapshot()
638        );
639        updated
640    }
641
642    /// The edits of topology operation `op` inside the substation `inside`.
643    fn operated<'a>(
644        files: &[File<'a>],
645        tree: &tree::Tree,
646        inside: &crate::grid::Inside,
647        op: &serde_json::Value,
648    ) -> Edits<'a> {
649        let mut k = 0u8;
650        let mut random = || {
651            k += 1;
652            [k; 16]
653        };
654        crate::topology::apply(files, tree, inside, op, &mut random)
655            .unwrap()
656            .edits
657    }
658
659    #[test]
660    fn a_grid_is_rebuilt_as_built() {
661        // In Anvers: a breaker added, then switched, renamed and deleted; a load deleted.
662        let texts = micro_grid();
663        let datasets = [decode_all(&texts)];
664        let m = Model::new(&datasets);
665        let (g, t) = (grid::build(&m), tree::build(&m));
666        fn anvers(g: &grid::Grid) -> &crate::grid::Inside {
667            let id = &g.nodes.iter().find(|n| n.label == "Anvers").unwrap().id;
668            g.inside_of(id).unwrap()
669        }
670        let inside = anvers(&g);
671        let level = inside.groups[0].id.clone();
672        let add = serde_json::json!({ "op": "add", "class": "Breaker", "level": level });
673        assert!(rebuilt_as_built(&texts, |f| operated(f, &t, inside, &add)));
674        let load = inside
675            .items
676            .iter()
677            .find(|it| it.class == "ConformLoad")
678            .unwrap()
679            .id
680            .clone();
681        let delete = serde_json::json!({ "op": "delete", "ids": [load] });
682        assert!(rebuilt_as_built(&texts, |f| operated(
683            f, &t, inside, &delete
684        )));
685
686        let edits = edits_of(&texts, |f| operated(f, &t, inside, &add));
687        let added: Vec<(String, String)> = texts
688            .iter()
689            .map(|(n, text)| match edits.iter().find(|(m, _)| m == n) {
690                Some((_, e)) => (n.clone(), apply(text, e)),
691                None => (n.clone(), text.clone()),
692            })
693            .collect();
694        let datasets = [decode_all(&added)];
695        let m = Model::new(&datasets);
696        let (g, t) = (grid::build(&m), tree::build(&m));
697        let inside = anvers(&g);
698        let breaker = inside
699            .items
700            .iter()
701            .find(|it| it.class == "Breaker")
702            .unwrap()
703            .id
704            .clone();
705        let open = serde_json::json!({ "op": "switch", "id": breaker, "open": true });
706        assert!(rebuilt_as_built(&added, |f| operated(f, &t, inside, &open)));
707        assert!(rebuilt_as_built(&added, |f| {
708            edit::set_field(f, "", &breaker, "IdentifiedObject.name", "renamed").unwrap()
709        }));
710        let delete = serde_json::json!({ "op": "delete", "ids": [breaker] });
711        assert!(rebuilt_as_built(&added, |f| operated(
712            f, &t, inside, &delete
713        )));
714        // Nothing edited: as it was, its findings gone.
715        assert!(rebuilt_as_built(&texts, |_| Vec::new()));
716
717        // A line, or a substation: built anew.
718        let line = datasets[0].by_type["ACLineSegment"][0].clone();
719        assert!(!rebuilt_as_built(&texts, |f| {
720            edit::set_field(f, "", &line, "IdentifiedObject.name", "renamed").unwrap()
721        }));
722        assert!(!rebuilt_as_built(&texts, |f| {
723            edit::delete(f, &HashSet::from([line.as_str()])).edits
724        }));
725        let sub = datasets[0].by_type["Substation"][0].clone();
726        assert!(!rebuilt_as_built(&texts, |f| {
727            edit::set_field(f, "", &sub, "IdentifiedObject.name", "renamed").unwrap()
728        }));
729    }
730
731    #[test]
732    fn an_edit_of_the_root_is_refused() {
733        let texts = micro_grid();
734        let (name, text) = &texts[1];
735        let after = text.replacen("xmlns:cim=", "xmlns:x=\"urn:x\" xmlns:cim=", 1);
736        let (lines, index) = (LineIndex::new(&after), Index::build(&after));
737        let files = [File {
738            name,
739            text: &after,
740            lines: &lines,
741            index: &index,
742        }];
743        let (old_lines, old_index) = (LineIndex::new(text), Index::build(text));
744        let before = [File {
745            name,
746            text,
747            lines: &old_lines,
748            index: &old_index,
749        }];
750        let mut model = decode_all(&texts);
751        assert!(refresh(&mut model, &before, &files).is_err());
752    }
753}