Skip to main content

cimview/
edit.rs

1//! Edits across a model set, as text edits for whoever holds the files to
2//! apply: renaming an mRID, deleting objects and adding a field a finding
3//! says is missing; and the objects a reference can name, the likeliest
4//! first; adding an object in a container. They change the files as
5//! written, keeping everything else of them, and reach every file of the
6//! set: an object's EQ, SSH and SV elements and every reference to it.
7//!
8//! The caller gives the files as they are now, each named as it likes (a
9//! URL, a file name), with its [`Index`]; the edits come back by that name.
10
11use std::collections::{HashMap, HashSet};
12
13use cimmodel::base::AttrKind;
14use cimmodel::registry::type_registry;
15
16use crate::index::{IdKind, Index, local};
17use crate::text::{LineIndex, Position, Range, TextEdit, contains};
18use crate::tree::{CONTAINED, Tree};
19
20/// One file of the set, as it is now.
21pub struct File<'a> {
22    /// Whatever names it for the caller.
23    pub name: &'a str,
24    pub text: &'a str,
25    pub lines: &'a LineIndex,
26    pub index: &'a Index,
27}
28
29/// Edits by file, in the order the files were given; only files that change.
30pub type Edits<'a> = Vec<(&'a str, Vec<TextEdit>)>;
31
32impl File<'_> {
33    /// The last `len` bytes of `r`: an mRID at the end of the value written
34    /// (after `#`, or the whole of `_x` or `urn:uuid:x`).
35    fn suffix(&self, r: Range, len: usize) -> Range {
36        let end = self.lines.offset(self.text, r.end);
37        Range::new(self.lines.position(self.text, end.saturating_sub(len)), r.end)
38    }
39
40    /// `r` widened to whole lines when nothing else is written on them.
41    pub(crate) fn lines_of(&self, r: Range) -> Range {
42        let (text, start, end) = (self.text, self.lines.offset(self.text, r.start), self.lines.offset(self.text, r.end));
43        let line_start = text[..start].rfind('\n').map_or(0, |i| i + 1);
44        let line_end = text[end..].find('\n').map_or(text.len(), |i| end + i + 1);
45        if text[line_start..start].trim().is_empty() && text[end..line_end].trim().is_empty() {
46            self.lines.range(text, line_start, line_end)
47        } else {
48            r
49        }
50    }
51
52    /// The text of a field written `<q>text</q>`, and its range.
53    fn field_text(&self, head: Range, full: Range, qname: &str) -> Option<(&str, Range)> {
54        let start = self.lines.offset(self.text, head.end);
55        let end = self.lines.offset(self.text, full.end).checked_sub(qname.len() + 3)?;
56        let value = self.text.get(start..end)?;
57        (!value.contains('<')).then(|| (value, self.lines.range(self.text, start, end)))
58    }
59}
60
61/// The mRID at `pos` in the file `name` — an element's `rdf:ID`/`rdf:about`,
62/// or an `rdf:resource` — and the range of it as written; anywhere else in an
63/// element's start tag, that element's.
64pub fn prepare_rename(files: &[File], name: &str, pos: Position) -> Option<(Range, String)> {
65    let file = files.iter().find(|f| f.name == name)?;
66    let el = file.index.element_at(pos)?;
67    if let Some((mrid, r)) = el.fields.iter().filter_map(|f| f.resource.as_ref()).find(|(_, r)| contains(*r, pos)) {
68        return Some((file.suffix(*r, mrid.len()), mrid.clone()));
69    }
70    let id = el.id_range?;
71    (contains(el.head, pos) && !el.mrid.is_empty()).then(|| (file.suffix(id, el.mrid.len()), el.mrid.clone()))
72}
73
74/// Rename mRID `old` to `new` in every file: each element's `rdf:ID` or
75/// `rdf:about`, each `rdf:resource` to it, and an `IdentifiedObject.mRID`
76/// (or a class's own `….mRID`) that writes it (without its leading `_`, as
77/// CGMES 3 does, if so).
78pub fn rename<'a>(files: &[File<'a>], old: &str, new: &str) -> Result<Edits<'a>, String> {
79    let new = new.trim();
80    if new.is_empty() || new.contains(|c: char| c.is_whitespace() || "\"'<>&#".contains(c)) {
81        return Err(format!("`{new}` cannot be an mRID: no spaces, quotes, `<`, `>`, `&` or `#`"));
82    }
83    let defined = files.iter().flat_map(|f| &f.index.elements).any(|e| e.mrid == old && e.id_kind == Some(IdKind::Id));
84    let ncname = new.starts_with(|c: char| c.is_alphabetic() || c == '_') && !new.contains(':');
85    if defined && !ncname {
86        return Err(format!("`{new}` cannot be an `rdf:ID`: it must start with a letter or `_` and hold no `:`"));
87    }
88    if files.iter().flat_map(|f| &f.index.elements).any(|e| e.mrid == new) {
89        return Err(format!("the model set already has an object `{new}`"));
90    }
91    let mut changes = Vec::new();
92    for file in files {
93        let mut edits = Vec::new();
94        for el in &file.index.elements {
95            if el.mrid == old
96                && let Some(id) = el.id_range
97            {
98                edits.push(TextEdit::new(file.suffix(id, old.len()), new.into()));
99                for f in el.fields.iter().filter(|f| f.key().ends_with(".mRID")) {
100                    let Some((text, r)) = file.field_text(f.head, f.full, &f.qname) else { continue };
101                    let bare = |s: &str| s.strip_prefix('_').unwrap_or(s).to_string();
102                    if text.trim() == old {
103                        edits.push(TextEdit::new(r, new.into()));
104                    } else if text.trim() == bare(old) {
105                        edits.push(TextEdit::new(r, bare(new)));
106                    }
107                }
108            }
109            for (mrid, r) in el.fields.iter().filter_map(|f| f.resource.as_ref()) {
110                if mrid == old {
111                    edits.push(TextEdit::new(file.suffix(*r, old.len()), new.into()));
112                }
113            }
114        }
115        if !edits.is_empty() {
116            changes.push((file.name, edits));
117        }
118    }
119    Ok(changes)
120}
121
122/// What deleting objects changes: the elements writing them, in every file,
123/// and the fields referring to them from what stays. Whole lines go, so a
124/// client should show it before applying it.
125pub struct Deletion<'a> {
126    pub edits: Edits<'a>,
127    pub objects: usize,
128    pub references: usize,
129}
130
131/// Delete objects `ids`.
132pub fn delete<'a>(files: &[File<'a>], ids: &HashSet<&str>) -> Deletion<'a> {
133    let mut changes = Vec::new();
134    let (mut objects, mut references) = (HashSet::new(), 0);
135    for file in files {
136        let mut edits: Vec<TextEdit> = Vec::new();
137        let mut edit = |r: Range| edits.push(TextEdit::new(file.lines_of(r), String::new()));
138        for el in &file.index.elements {
139            if ids.contains(el.mrid.as_str()) {
140                objects.insert(el.mrid.as_str());
141                edit(el.full);
142                continue;
143            }
144            for f in &el.fields {
145                if f.resource.as_ref().is_some_and(|(m, _)| ids.contains(m.as_str())) {
146                    references += 1;
147                    edit(f.full);
148                }
149            }
150        }
151        if !edits.is_empty() {
152            changes.push((file.name, edits));
153        }
154    }
155    Deletion { edits: changes, objects: objects.len(), references }
156}
157
158/// A field to add: where, and where its value is once added.
159pub struct Addition {
160    /// The file it goes in, by its name.
161    pub file: String,
162    pub edit: TextEdit,
163    /// The inserted value (or where it goes), to select after the edit.
164    pub value: Range,
165    /// A reference, inserted empty: `rdf:resource="#"`.
166    pub reference: bool,
167}
168
169impl Addition {
170    /// The edit with the reference to `c` filled in.
171    pub fn naming(&self, c: &Candidate) -> TextEdit {
172        TextEdit::new(self.edit.range, self.edit.new_text.replacen("rdf:resource=\"#\"", &format!("rdf:resource=\"{}\"", c.reference()), 1))
173    }
174}
175
176/// The profile codes `file`'s header declares (`md:Model.profile`,
177/// `dcterms:conformsTo`), by the schemas' profile tables.
178pub(crate) fn profiles(file: &File) -> Vec<&'static str> {
179    let reg = type_registry();
180    let tables: Vec<&[(&str, &str)]> = ["cgmes", "nc"].iter().filter_map(|f| reg.schema(f)).map(|s| s.profiles).collect();
181    let Some(header) = file.index.elements.iter().find(|e| matches!(local(&e.qname), "FullModel" | "Dataset" | "DifferenceModel")) else { return Vec::new() };
182    header
183        .fields
184        .iter()
185        .filter(|f| matches!(f.key(), "Model.profile" | "conformsTo"))
186        .filter_map(|f| match &f.resource {
187            Some((uri, _)) => Some(uri.as_str()),
188            None => file.field_text(f.head, f.full, &f.qname).map(|(t, _)| t.trim()),
189        })
190        .filter_map(|uri| tables.iter().flat_map(|t| t.iter()).find(|(_, u)| *u == uri).map(|(code, _)| *code))
191        .collect()
192}
193
194/// Add field `key` to object `id`, which writes it nowhere: in the file
195/// (`prefer` first) whose profile carries it and that writes the object,
196/// after its last field, with a value to type over — the object's mRID for
197/// `IdentifiedObject.mRID`, `false`, `0`, an enumeration's first value, or
198/// none. `None` if a file writes it already, its class does not declare
199/// it, or no file fits.
200pub fn add_missing(files: &[File], prefer: &str, id: &str, key: &str) -> Option<Addition> {
201    addition(files, prefer, id, key, None)
202}
203
204/// [`add_missing`], with `given` as the value written (as [`set_field`] takes it) rather than
205/// one to type over.
206fn addition(files: &[File], prefer: &str, id: &str, key: &str, given: Option<&str>) -> Option<Addition> {
207    let reg = type_registry();
208    let sites: Vec<(&File, &crate::index::Element)> =
209        files.iter().flat_map(|f| f.index.elements.iter().filter(|e| e.mrid == id).map(move |e| (f, e))).collect();
210    if sites.iter().any(|(_, e)| e.fields.iter().any(|f| f.key() == key)) {
211        return None;
212    }
213    let (def_file, def) = sites.iter().max_by_key(|(_, e)| e.id_kind == Some(IdKind::Id))?;
214    let class = def_file.index.class_of(&def.qname)?;
215    let attr = reg.attr(class, key).filter(|a| a.used)?;
216    let fits = |f: &File| {
217        let declared = profiles(f);
218        declared.is_empty() || attr.origins.is_empty() || declared.iter().any(|p| attr.origins.contains(p))
219    };
220    let (file, el) = sites
221        .iter()
222        .filter(|(f, _)| fits(f))
223        .min_by_key(|(f, e)| (f.name != prefer, e.id_kind != Some(IdKind::Id)))?;
224    let tag = format!("{}:{}", file.index.prefix_of(attr.ns)?, attr.id);
225    let (open, value, close) = match attr.kind {
226        AttrKind::Literal => {
227            let value = match (attr.id, attr.xsd) {
228                _ if given.is_some() => escape(given.unwrap_or_default()),
229                ("IdentifiedObject.mRID", _) => id.strip_prefix('_').unwrap_or(id).to_string(),
230                (_, "boolean") => "false".into(),
231                (_, "double" | "float" | "decimal" | "integer" | "int" | "long" | "short") => "0".into(),
232                _ => String::new(),
233            };
234            (format!("<{tag}>"), value, format!("</{tag}>"))
235        }
236        AttrKind::Association => match given {
237            Some(target) => (format!("<{tag} rdf:resource=\""), reference(target), "\" />".into()),
238            None => (format!("<{tag} rdf:resource=\"#"), String::new(), "\" />".into()),
239        },
240        AttrKind::Enum => {
241            let first = reg.family_of(class.qualified).and_then(|f| reg.schema(f)).and_then(|s| s.enumeration(attr.range)).and_then(|e| e.values.first());
242            let value = given.map_or_else(|| first.map_or(String::new(), |v| v.id.to_string()), |v| enum_value(attr.range, v).to_string());
243            (format!("<{tag} rdf:resource=\"{}", attr.value_ns), value, "\" />".into())
244        }
245    };
246    // On a line of its own after the last field, indented as it is; else
247    // inside the element, a step in from it.
248    let (text, lines) = (file.text, file.lines);
249    let indent_of = |r: Range| {
250        let start = lines.offset(text, Position::new(r.start.line, 0));
251        let at = lines.offset(text, r.start);
252        text[start..at].chars().take_while(|c| c.is_whitespace()).collect::<String>()
253    };
254    let (at, indent) = match el.fields.last() {
255        Some(f) => (f.full.end, indent_of(f.head)),
256        None => {
257            let end = lines.offset(text, el.full.end);
258            let closing = end.checked_sub(el.qname.len() + 3).filter(|&c| text.get(c..end) == Some(&format!("</{}>", el.qname)))?;
259            (lines.position(text, closing), format!("{}  ", indent_of(el.head)))
260        }
261    };
262    // Lines end as the file's do.
263    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
264    let new_text = if el.fields.is_empty() {
265        format!("  {open}{value}{close}{eol}{}", indent_of(el.head))
266    } else {
267        format!("{eol}{indent}{open}{value}{close}")
268    };
269    let utf16 = |s: &str| s.encode_utf16().count() as u32;
270    let start = if el.fields.is_empty() { Position::new(at.line, at.character + 2 + utf16(&open)) } else { Position::new(at.line + 1, utf16(&indent) + utf16(&open)) };
271    let value_range = Range::new(start, Position::new(start.line, start.character + utf16(&value)));
272    let reference = attr.kind == AttrKind::Association && given.is_none();
273    Some(Addition { file: file.name.to_string(), edit: TextEdit::new(Range::new(at, at), new_text), value: value_range, reference })
274}
275
276/// `text` as XML character data.
277fn escape(text: &str) -> String {
278    text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
279}
280
281/// A reference to object `target` as written: `#_id`, or an IRI as it is.
282fn reference(target: &str) -> String {
283    if target.contains(':') { target.to_string() } else { format!("#{target}") }
284}
285
286/// An enumeration's value as its IRI ends: `WindingConnection.D`, from `D` or the whole name.
287fn enum_value<'v>(range: &str, value: &'v str) -> std::borrow::Cow<'v, str> {
288    let value = value.rsplit_once('#').map_or(value, |(_, v)| v);
289    if value.contains('.') { value.into() } else { format!("{range}.{value}").into() }
290}
291
292/// Set field `key` of object `id` to `value`: a literal's text (escaped here), a reference's
293/// object (its mRID, or an IRI), or an enumeration's value (`D`, or `WindingConnection.D`).
294/// Wherever a file writes the field, its value is replaced; where none does, it is added as
295/// [`add_missing`] adds it, `prefer` first. An error if the object's class does not declare it.
296pub fn set_field<'a>(files: &[File<'a>], prefer: &str, id: &str, key: &str, value: &str) -> Result<Edits<'a>, String> {
297    let reg = type_registry();
298    let (def_file, def) = files
299        .iter()
300        .flat_map(|f| f.index.elements.iter().filter(|e| e.mrid == id).map(move |e| (f, e)))
301        .max_by_key(|(_, e)| e.id_kind == Some(IdKind::Id))
302        .ok_or_else(|| format!("no file writes `{id}`"))?;
303    let class = def_file.index.class_of(&def.qname).ok_or_else(|| format!("`{}` is no class of the tables", def.qname))?;
304    let attr = reg.attr(class, key).ok_or_else(|| format!("{} has no field {key}", class.local))?;
305    let mut changes: Edits<'a> = Vec::new();
306    for file in files {
307        let mut edits = Vec::new();
308        for el in file.index.elements.iter().filter(|e| e.mrid == id) {
309            for f in el.fields.iter().filter(|f| f.key() == key) {
310                let edit = match (attr.kind, &f.resource) {
311                    (AttrKind::Literal, None) => match file.field_text(f.head, f.full, &f.qname) {
312                        Some((_, r)) => TextEdit::new(r, escape(value)),
313                        // `<x/>`: written anew.
314                        None => TextEdit::new(f.full, format!("<{q}>{}</{q}>", escape(value), q = f.qname)),
315                    },
316                    (AttrKind::Association, Some((_, r))) => TextEdit::new(*r, reference(value)),
317                    (AttrKind::Enum, Some((_, r))) => {
318                        let start = file.lines.offset(file.text, r.start);
319                        let end = file.lines.offset(file.text, r.end);
320                        let written = &file.text[start..end];
321                        // Its namespace as written, else the attribute's.
322                        let ns = written.rsplit_once('#').map_or(attr.value_ns.to_string(), |(ns, _)| format!("{ns}#"));
323                        TextEdit::new(*r, format!("{ns}{}", enum_value(attr.range, value)))
324                    }
325                    _ => return Err(format!("{key} is written in {} as it cannot be set", file.name)),
326                };
327                edits.push(edit);
328            }
329        }
330        if !edits.is_empty() {
331            changes.push((file.name, edits));
332        }
333    }
334    if changes.is_empty() {
335        let added = addition(files, prefer, id, key, Some(value)).ok_or_else(|| format!("no file of the set takes {key} for `{id}`"))?;
336        let name = files.iter().find(|f| f.name == added.file).map(|f| f.name).expect("one of the files");
337        changes.push((name, vec![added.edit]));
338    }
339    Ok(changes)
340}
341
342/// Remove field `key` from object `id` in every file writing it, its lines with it.
343pub fn remove_field<'a>(files: &[File<'a>], id: &str, key: &str) -> Edits<'a> {
344    let mut changes = Vec::new();
345    for file in files {
346        let edits: Vec<TextEdit> = file
347            .index
348            .elements
349            .iter()
350            .filter(|e| e.mrid == id)
351            .flat_map(|e| e.fields.iter().filter(|f| f.key() == key))
352            .map(|f| TextEdit::new(file.lines_of(f.full), String::new()))
353            .collect();
354        if !edits.is_empty() {
355            changes.push((file.name, edits));
356        }
357    }
358    changes
359}
360
361/// A field of `class` written as an element of `file`, its value as [`set_field`] takes it.
362pub(crate) fn field_element(file: &File, class: &'static cimmodel::base::ClassDef, key: &str, value: &str) -> Result<String, String> {
363    let attr = type_registry().attr(class, key).ok_or_else(|| format!("{} has no field {key}", class.local))?;
364    let prefix = file.index.prefix_of(attr.ns).ok_or_else(|| format!("{} binds no prefix to {}", file.name, attr.ns))?;
365    let tag = format!("{prefix}:{}", attr.id);
366    Ok(match attr.kind {
367        AttrKind::Literal => format!("<{tag}>{}</{tag}>", escape(value)),
368        AttrKind::Association => format!("<{tag} rdf:resource=\"{}\" />", reference(value)),
369        AttrKind::Enum => format!("<{tag} rdf:resource=\"{}{}\" />", attr.value_ns, enum_value(attr.range, value)),
370    })
371}
372
373/// `lines` (an element, unindented) inserted before the end tag of `file`'s root, indented as its
374/// elements are, in its line endings.
375pub(crate) fn at_end(file: &File, lines: &[String]) -> Result<TextEdit, String> {
376    let text = file.text;
377    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
378    let root_end = text.rfind("</").ok_or("the file has no root end tag")?;
379    let line_start = text[..root_end].rfind('\n').map_or(0, |i| i + 1);
380    let indent = file.index.elements.last().map_or("  ".to_string(), |el| {
381        let head = file.lines.offset(text, el.head.start);
382        text[text[..head].rfind('\n').map_or(0, |i| i + 1)..head].to_string()
383    });
384    let at = file.lines.position(text, line_start);
385    let body: String = lines.iter().map(|l| format!("{indent}{l}{eol}")).collect();
386    Ok(TextEdit::new(Range::new(at, at), body))
387}
388
389/// A fresh mRID, `_` and a UUID from `random`, that the set does not have yet nor `taken`.
390pub(crate) fn fresh(files: &[File], taken: &HashSet<String>, random: &mut dyn FnMut() -> [u8; 16]) -> String {
391    loop {
392        let id = format!("_{}", uuid(random()));
393        if !taken.contains(&id) && !files.iter().any(|f| f.index.elements.iter().any(|e| e.mrid == id)) {
394            return id;
395        }
396    }
397}
398
399/// A new object of `class`, with `values` (field, value as [`set_field`] takes it) and its
400/// mRID as text where the class has a field for it (`IdentifiedObject.mRID`, or its own), written at the end of the file `into`, with an
401/// `rdf:ID` whose UUID is drawn from `random`. For objects in no container, which [`add`] cannot
402/// place: a response, a dependency.
403pub fn create<'a>(
404    files: &[File<'a>],
405    into: &str,
406    class: &str,
407    values: &[(&str, &str)],
408    random: &mut dyn FnMut() -> [u8; 16],
409) -> Result<Added<'a>, String> {
410    let reg = type_registry();
411    let file = files.iter().find(|f| f.name == into).ok_or_else(|| format!("no file {into}"))?;
412    // The class by the namespaces the file binds: CGMES's or NC's, whichever has it.
413    let found = file
414        .index
415        .namespaces
416        .iter()
417        .filter_map(|(_, ns)| reg.ns_table(ns)?.get(class).copied())
418        .next()
419        .ok_or_else(|| format!("{into} binds no namespace with a class {class}"))?;
420    let prefix = file.index.prefix_of(found.ns).ok_or("no prefix")?;
421    let id = fresh(files, &HashSet::new(), random);
422    let mut lines = vec![format!("<{prefix}:{} rdf:ID=\"{id}\">", found.local)];
423    // Its mRID as text: `IdentifiedObject.mRID`, or a class's own (`…Response.mRID`).
424    let mrid_key = reg.attrs(found).map(|a| a.id).find(|k| k.ends_with(".mRID"));
425    if let Some(key) = mrid_key.filter(|k| !values.iter().any(|(v, _)| v == k)) {
426        lines.push(format!("  {}", field_element(file, found, key, &id[1..])?));
427    }
428    for (key, value) in values {
429        lines.push(format!("  {}", field_element(file, found, key, value)?));
430    }
431    lines.push(format!("</{prefix}:{}>", found.local));
432    let edit = at_end(file, &lines)?;
433    let first = edit.range.start.line;
434    let select = Range::new(Position::new(first, 0), Position::new(first, 0));
435    Ok(Added { edits: vec![(file.name, vec![edit])], file: file.name.to_string(), select, id })
436}
437
438/// The text of a new file of profile `code` (`DL`) beside `like`: its
439/// prolog and root, with their namespaces, and a FullModel header under the
440/// model id `urn:uuid:{id}` dependent on `like`'s model, with its times,
441/// version and modelling authority set.
442pub fn companion(like: &File, code: &str, id: &str) -> Result<String, String> {
443    let profile = type_registry()
444        .schema("cgmes")
445        .and_then(|s| s.profiles.iter().find(|(c, _)| *c == code))
446        .map(|(_, uri)| *uri)
447        .ok_or_else(|| format!("no profile {code}"))?;
448    let text = like.text;
449    let root_end = text
450        .find("<rdf:RDF")
451        .and_then(|s| text[s..].find('>').map(|e| s + e + 1))
452        .ok_or_else(|| format!("{} has no rdf:RDF root", like.name))?;
453    let header = like
454        .index
455        .elements
456        .iter()
457        .find(|e| local(&e.qname) == "FullModel")
458        .ok_or_else(|| format!("{} has no FullModel header", like.name))?;
459    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
460    let start = like.lines.offset(text, header.full.start);
461    let indent = text[..start].rsplit_once('\n').map_or("", |(_, i)| i);
462    let prefix = header.qname.split_once(':').map_or("md", |(p, _)| p);
463    let model = if header.mrid.contains(':') { header.mrid.clone() } else { format!("#{}", header.mrid) };
464    let mut lines = vec![format!("<{prefix}:FullModel rdf:about=\"urn:uuid:{id}\">")];
465    for f in &header.fields {
466        if matches!(f.key(), "Model.created" | "Model.scenarioTime" | "Model.version" | "Model.modelingAuthoritySet") {
467            lines.push(format!("  {}", &text[like.lines.offset(text, f.full.start)..like.lines.offset(text, f.full.end)]));
468        }
469    }
470    lines.push(format!("  <{prefix}:Model.profile>{profile}</{prefix}:Model.profile>"));
471    lines.push(format!("  <{prefix}:Model.DependentOn rdf:resource=\"{model}\" />"));
472    lines.push(format!("</{prefix}:FullModel>"));
473    let body: String = lines.iter().map(|l| format!("{indent}{l}{eol}")).collect();
474    Ok(format!("{}{eol}{body}</rdf:RDF>{eol}", &text[..root_end]))
475}
476
477/// An object a diagram draws: the mRID it shows, its name, and its points.
478pub type Drawn<'a> = (&'a str, &'a str, Vec<(f64, f64)>);
479
480/// A DL diagram written into `into`: a new `Diagram` named `name` (y
481/// downwards), or in `existing` (in the file defining it, whatever `into`
482/// says), its drawing of what `objects` show replaced and the rest kept. Each of `objects` (the mRID it shows, its name,
483/// its points) a `DiagramObject` with its `DiagramObjectPoint`s, numbered
484/// from 1. UUIDs from `random`. The diagram's mRID is the result's `id`.
485pub fn diagram<'a>(
486    files: &[File<'a>],
487    into: &str,
488    existing: Option<&str>,
489    name: &str,
490    objects: &[Drawn],
491    random: &mut dyn FnMut() -> [u8; 16],
492) -> Result<Added<'a>, String> {
493    let defines = |f: &&File, id: &str| f.index.elements.iter().any(|e| e.mrid == id && e.id_kind == Some(IdKind::Id));
494    let file = match existing {
495        Some(d) => files.iter().find(|f| defines(f, d)).ok_or_else(|| format!("no file defines the diagram {d}"))?,
496        None => files.iter().find(|f| f.name == into).ok_or_else(|| format!("no file {into}"))?,
497    };
498    let reg = type_registry();
499    let class = |local: &str| {
500        file.index
501            .namespaces
502            .iter()
503            .filter_map(|(_, ns)| reg.ns_table(ns)?.get(local).copied())
504            .next()
505            .ok_or_else(|| format!("{} binds no namespace with a class {local}", file.name))
506    };
507    let (diagram_class, object_class, point_class) = (class("Diagram")?, class("DiagramObject")?, class("DiagramObjectPoint")?);
508    let mut taken = HashSet::new();
509    let mut fresh_id = |random: &mut dyn FnMut() -> [u8; 16]| {
510        let id = fresh(files, &taken, random);
511        taken.insert(id.clone());
512        id
513    };
514    let mut edits: Edits<'a> = Vec::new();
515    let mut lines = Vec::new();
516    let diagram = match existing {
517        Some(d) => {
518            // Its objects of what is drawn anew go, with their points; the
519            // diagram stays, with its name and the rest.
520            let anew: HashSet<&str> = objects.iter().map(|(m, _, _)| *m).collect();
521            let shows = |e: &crate::index::Element| {
522                e.fields.iter().any(|f| f.key() == "DiagramObject.IdentifiedObject" && f.resource.as_ref().is_some_and(|(m, _)| anew.contains(m.as_str())))
523            };
524            let shown: HashSet<&str> = file
525                .index
526                .elements
527                .iter()
528                .filter(|e| local(&e.qname) == "DiagramObject")
529                .filter(|e| e.fields.iter().any(|f| f.key() == "DiagramObject.Diagram" && f.resource.as_ref().is_some_and(|(m, _)| m == d)))
530                .filter(|e| shows(e))
531                .map(|e| e.mrid.as_str())
532                .collect();
533            let mut gone: HashSet<&str> = shown.clone();
534            for e in files.iter().flat_map(|f| &f.index.elements) {
535                if local(&e.qname) == "DiagramObjectPoint"
536                    && e.fields.iter().any(|f| f.resource.as_ref().is_some_and(|(m, _)| shown.contains(m.as_str())))
537                {
538                    gone.insert(e.mrid.as_str());
539                }
540            }
541            edits = delete(files, &gone).edits;
542            d.to_string()
543        }
544        None => {
545            let id = fresh_id(random);
546            lines.extend(element(file, diagram_class, &id, &[("IdentifiedObject.name", name), ("Diagram.orientation", "negative")])?);
547            id
548        }
549    };
550    for (shown, label, points) in objects {
551        let id = fresh_id(random);
552        let mut values = vec![("DiagramObject.Diagram", diagram.as_str()), ("DiagramObject.IdentifiedObject", *shown), ("DiagramObject.rotation", "0")];
553        if !label.is_empty() {
554            values.insert(0, ("IdentifiedObject.name", *label));
555        }
556        lines.extend(element(file, object_class, &id, &values)?);
557        for (k, (x, y)) in points.iter().enumerate() {
558            let point = fresh_id(random);
559            let (k, x, y) = ((k + 1).to_string(), number(*x), number(*y));
560            lines.extend(element(
561                file,
562                point_class,
563                &point,
564                &[("DiagramObjectPoint.sequenceNumber", &k), ("DiagramObjectPoint.xPosition", &x), ("DiagramObjectPoint.yPosition", &y), ("DiagramObjectPoint.DiagramObject", &id)],
565            )?);
566        }
567    }
568    let edit = at_end(file, &lines)?;
569    let first = edit.range.start.line;
570    match edits.iter_mut().find(|(n, _)| *n == file.name) {
571        Some((_, es)) => es.push(edit),
572        None => edits.push((file.name, vec![edit])),
573    }
574    let select = Range::new(Position::new(first, 0), Position::new(first, 0));
575    Ok(Added { edits, file: file.name.to_string(), select, id: diagram })
576}
577
578/// A coordinate as DL writes it: to a hundredth, without trailing zeros.
579fn number(x: f64) -> String {
580    let s = format!("{:.2}", (x * 100.0).round() / 100.0);
581    let s = s.trim_end_matches('0').trim_end_matches('.');
582    if s == "-0" { "0".into() } else { s.into() }
583}
584
585/// An object's element, unindented: its `rdf:ID`, its mRID as text where the class has a field for
586/// it, and `values` as [`set_field`] takes them.
587pub(crate) fn element(file: &File, class: &'static cimmodel::base::ClassDef, id: &str, values: &[(&str, &str)]) -> Result<Vec<String>, String> {
588    let prefix = file.index.prefix_of(class.ns).ok_or("no prefix")?;
589    let mut lines = vec![format!("<{prefix}:{} rdf:ID=\"{id}\">", class.local)];
590    let mrid_key = type_registry().attrs(class).map(|a| a.id).find(|k| k.ends_with(".mRID"));
591    if let Some(key) = mrid_key.filter(|k| !values.iter().any(|(v, _)| v == k)) {
592        lines.push(format!("  {}", field_element(file, class, key, &id[1..])?));
593    }
594    for (key, value) in values {
595        lines.push(format!("  {}", field_element(file, class, key, value)?));
596    }
597    lines.push(format!("</{prefix}:{}>", class.local));
598    Ok(lines)
599}
600
601/// Objects copied: the edits, and each object's new mRID.
602pub struct Copied<'a> {
603    pub edits: Edits<'a>,
604    /// (original, copy), in the order given.
605    pub ids: Vec<(String, String)>,
606}
607
608/// Copy objects `ids` with new mRIDs (`_` and a UUID from `random`): every element writing each
609/// of them, in every file or only in `from`, its `rdf:ID` or `rdf:about`, its mRID field, and its
610/// references to the objects copied, rewritten to the copies; references to anything else stay.
611/// Each copy goes after its original, or with `into`, at the end of that file, which must bind
612/// the prefixes the copies use as their files do. `from` matters where two files define the same
613/// objects (a proposal and what was agreed of it): their copies would be one object written twice.
614pub fn copy<'a>(
615    files: &[File<'a>],
616    ids: &[&str],
617    from: Option<&str>,
618    into: Option<&str>,
619    random: &mut dyn FnMut() -> [u8; 16],
620) -> Result<Copied<'a>, String> {
621    let sources = |f: &&File| from.is_none_or(|n| f.name == n);
622    let target = match into {
623        Some(name) => Some(files.iter().find(|f| f.name == name).ok_or_else(|| format!("no file {name}"))?),
624        None => None,
625    };
626    let mut taken = HashSet::new();
627    let mut renamed: Vec<(String, String)> = Vec::new();
628    for id in ids {
629        if !files.iter().filter(sources).any(|f| f.index.elements.iter().any(|e| e.mrid == *id)) {
630            return Err(format!("no file {}writes `{id}`", from.map_or(String::new(), |n| format!("but {n} "))));
631        }
632        let new = fresh(files, &taken, random);
633        taken.insert(new.clone());
634        renamed.push((id.to_string(), new));
635    }
636    let to: HashMap<&str, &str> = renamed.iter().map(|(o, n)| (o.as_str(), n.as_str())).collect();
637    let mut changes: Edits<'a> = Vec::new();
638    let mut moved: Vec<String> = Vec::new();
639    for file in files.iter().filter(sources) {
640        let text = file.text;
641        let mut edits = Vec::new();
642        for el in file.index.elements.iter().filter(|e| to.contains_key(e.mrid.as_str())) {
643            if let Some(t) = target.filter(|t| t.name != file.name) {
644                // The copy's prefixes, bound as they are here.
645                let qnames = std::iter::once(&el.qname).chain(el.fields.iter().map(|f| &f.qname));
646                for q in qnames {
647                    let p = crate::index::prefix(q);
648                    if t.index.namespace(p) != file.index.namespace(p) {
649                        return Err(format!("{} binds `{p}` otherwise than {}", t.name, file.name));
650                    }
651                }
652            }
653            let block = file.lines_of(el.full);
654            let (start, end) = (file.lines.offset(text, block.start), file.lines.offset(text, block.end));
655            // Replacements within the block, by offset.
656            let mut swaps: Vec<(usize, usize, String)> = Vec::new();
657            // An mRID at the end of the value written at `r`.
658            let suffix = |r: Range, old: &str, new: &str| {
659                let at = file.lines.offset(text, r.end);
660                (at - old.len(), at, new.to_string())
661            };
662            let old = el.mrid.as_str();
663            let new = to[old];
664            if let Some(r) = el.id_range {
665                swaps.push(suffix(r, old, new));
666            }
667            for f in &el.fields {
668                if let Some((target_id, r)) = &f.resource
669                    && let Some(n) = to.get(target_id.as_str())
670                {
671                    swaps.push(suffix(*r, target_id, n));
672                }
673                if f.key().ends_with(".mRID")
674                    && let Some((value, r)) = file.field_text(f.head, f.full, &f.qname)
675                {
676                    let bare = |s: &str| s.strip_prefix('_').unwrap_or(s).to_string();
677                    let (vs, ve) = (file.lines.offset(text, r.start), file.lines.offset(text, r.end));
678                    if value.trim() == old {
679                        swaps.push((vs, ve, new.to_string()));
680                    } else if value.trim() == bare(old) {
681                        swaps.push((vs, ve, bare(new)));
682                    }
683                }
684            }
685            swaps.sort_by_key(|s| std::cmp::Reverse(s.0));
686            let mut copied = text[start..end].to_string();
687            for (s, e, with) in swaps {
688                copied.replace_range(s - start..e - start, &with);
689            }
690            if !copied.ends_with('\n') {
691                copied.push_str(if text.contains("\r\n") { "\r\n" } else { "\n" });
692            }
693            match target {
694                Some(_) => moved.push(copied),
695                None => edits.push(TextEdit::new(Range::new(block.end, block.end), copied)),
696            }
697        }
698        if !edits.is_empty() {
699            changes.push((file.name, edits));
700        }
701    }
702    if let Some(t) = target {
703        let root_end = t.text.rfind("</").ok_or("the file has no root end tag")?;
704        let line_start = t.text[..root_end].rfind('\n').map_or(0, |i| i + 1);
705        let at = t.lines.position(t.text, line_start);
706        let edit = TextEdit::new(Range::new(at, at), moved.concat());
707        match changes.iter_mut().find(|(n, _)| *n == t.name) {
708            Some((_, e)) => e.push(edit),
709            None => changes.push((t.name, vec![edit])),
710        }
711    }
712    Ok(Copied { edits: changes, ids: renamed })
713}
714
715/// An object a reference can name.
716pub struct Candidate {
717    pub id: String,
718    pub label: String,
719    pub class: &'static str,
720    /// Its containers' labels, as the outline shows them.
721    pub place: String,
722}
723
724impl Candidate {
725    /// The reference to it as written: `#_id`, or an IRI as it is.
726    pub fn reference(&self) -> String {
727        if self.id.contains(':') { self.id.clone() } else { format!("#{}", self.id) }
728    }
729}
730
731/// The objects field `key` of object `id` can name — of the class it ranges
732/// over, or below — at most `limit`, the likeliest first: those linked to
733/// the object, naming what it names with its other fields or named by it
734/// (a terminal's connectivity node, of its topological node; equipment's
735/// base voltage, its voltage level's); then those that share the most
736/// containers with it, by where they are or by where the objects are that
737/// name them with the same field (a line's base voltage is the one the
738/// equipment of its voltage level names); then the most named.
739/// Empty if `key` is not a reference of the object's class.
740pub fn candidates(indexes: &[&Index], tree: &Tree, id: &str, key: &str, limit: usize) -> Vec<Candidate> {
741    let reg = type_registry();
742    let class = indexes
743        .iter()
744        .flat_map(|ix| ix.elements.iter().filter(|e| e.mrid == id).map(move |e| (ix, e)))
745        .max_by_key(|(_, e)| e.id_kind == Some(IdKind::Id))
746        .and_then(|(ix, e)| ix.class_of(&e.qname));
747    let Some(attr) = class.and_then(|c| reg.attr(c, key)).filter(|a| a.kind == AttrKind::Association) else { return Vec::new() };
748    // What the object names with its other fields.
749    let own: HashSet<&str> = indexes
750        .iter()
751        .flat_map(|ix| ix.elements.iter().filter(|e| e.mrid == id))
752        .flat_map(|e| e.fields.iter().filter(|f| f.key() != key).filter_map(|f| f.resource.as_ref().map(|(t, _)| t.as_str())))
753        .filter(|t| !t.is_empty())
754        .collect();
755    let mut linked: HashSet<&str> = HashSet::new();
756    let mut found: HashMap<&str, (Option<&str>, &'static str)> = HashMap::new();
757    let mut named: HashMap<&str, Vec<&str>> = HashMap::new();
758    for ix in indexes {
759        for el in &ix.elements {
760            let targets = || el.fields.iter().filter_map(|f| f.resource.as_ref().map(|(t, _)| t.as_str()));
761            if own.contains(el.mrid.as_str()) {
762                linked.extend(targets());
763            } else if targets().any(|t| own.contains(t)) {
764                linked.insert(el.mrid.as_str());
765            }
766            for f in el.fields.iter().filter(|f| f.key() == key && el.mrid != id) {
767                if let Some((target, _)) = &f.resource {
768                    named.entry(target.as_str()).or_default().push(el.mrid.as_str());
769                }
770            }
771            if el.mrid.is_empty() || el.mrid == id {
772                continue;
773            }
774            let Some(c) = ix.class_of(&el.qname).filter(|c| reg.chain(c).iter().any(|a| a.local == attr.range)) else { continue };
775            let entry = found.entry(el.mrid.as_str()).or_insert((None, c.local));
776            if entry.0.is_none() {
777                entry.0 = el.name.as_deref().filter(|n| !n.is_empty());
778            }
779        }
780    }
781    let here = {
782        let mut chain = tree.chain(id);
783        chain.pop();
784        chain
785    };
786    let shared = |chain: &[u32]| here.iter().zip(chain).take_while(|(a, b)| a == b).count();
787    let mut ranked: Vec<(bool, usize, usize, String, &str, &'static str)> = found
788        .into_iter()
789        .map(|(c, (name, class))| {
790            let by = named.get(c).map_or(&[][..], Vec::as_slice);
791            let near = by.iter().map(|r| {
792                let mut chain = tree.chain(r);
793                chain.pop();
794                shared(&chain)
795            });
796            let score = near.chain(std::iter::once(shared(&tree.chain(c)))).max().unwrap_or(0);
797            (linked.contains(c), score, by.len(), name.unwrap_or(c).to_string(), c, class)
798        })
799        .collect();
800    ranked.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(b.2.cmp(&a.2)).then_with(|| a.3.to_lowercase().cmp(&b.3.to_lowercase())));
801    ranked
802        .into_iter()
803        .take(limit)
804        .map(|(_, _, _, label, c, class)| Candidate { id: c.to_string(), label, class, place: tree.containers(c).join(" › ") })
805        .collect()
806}
807
808/// A class that can be added in an object, and the field naming it there.
809pub struct Addable {
810    pub class: &'static cimmodel::base::ClassDef,
811    pub key: &'static str,
812}
813
814/// The class of object `id` as the file defining it writes it.
815fn class_in(files: &[File], id: &str) -> Option<&'static cimmodel::base::ClassDef> {
816    let (file, el) = files
817        .iter()
818        .flat_map(|f| f.index.elements.iter().filter(|e| e.mrid == id).map(move |e| (f, e)))
819        .max_by_key(|(_, e)| e.id_kind == Some(IdKind::Id))?;
820    file.index.class_of(&el.qname)
821}
822
823/// The concrete classes of `parent`'s family whose objects the containment
824/// puts in it: the first of [`CONTAINED`] they declare that
825/// ranges over its class. Only classes of the profiles the set's files
826/// declare (all, if none declares one).
827pub fn addable(files: &[File], parent: &str) -> Vec<Addable> {
828    let reg = type_registry();
829    let Some(class) = class_in(files, parent) else { return Vec::new() };
830    let Some(schema) = reg.family_of(class.qualified).and_then(|f| reg.schema(f)) else { return Vec::new() };
831    let is = |range: &str| reg.chain(class).iter().any(|c| c.local == range);
832    let declared: HashSet<&str> = files.iter().flat_map(profiles).collect();
833    let mut out: Vec<Addable> = schema
834        .classes
835        .iter()
836        .filter(|c| c.concrete && (declared.is_empty() || c.origins.iter().any(|o| declared.contains(o))))
837        .filter_map(|c| {
838            let key = CONTAINED.iter().find_map(|k| reg.attr(c, k).filter(|a| a.used && a.kind == AttrKind::Association))?;
839            is(key.range).then_some(Addable { class: c, key: key.id })
840        })
841        .collect();
842    out.sort_by_key(|a| a.class.local);
843    out
844}
845
846/// A version 4 UUID from 16 random bytes, which the caller draws: the standard
847/// library has no randomness on every target this runs on.
848pub fn uuid(mut b: [u8; 16]) -> String {
849    b[6] = (b[6] & 0x0f) | 0x40;
850    b[8] = (b[8] & 0x3f) | 0x80;
851    let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
852    format!("{}-{}-{}-{}-{}", &hex[..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..])
853}
854
855/// An object added: the edits, and where its name (else its start tag) is.
856pub struct Added<'a> {
857    pub edits: Edits<'a>,
858    /// The file its element is in, by its name.
859    pub file: String,
860    pub select: Range,
861    pub id: String,
862}
863
864/// Add an object of `class` in `parent`, named `name` if given: an
865/// `rdf:ID`, its mRID, name and the field naming `parent`, in the file
866/// whose profile carries the class (the parent's own first), after the last
867/// of the parent's objects there, else after the parent, else at the end;
868/// and where the set has an SSH file and the class SSH attributes, an empty
869/// `rdf:about` there for them. What else it needs, validation asks for. Its
870/// mRID is `_` and a UUID from `random` ([`uuid`]), drawn again while the set
871/// has it.
872pub fn add<'a>(
873    files: &[File<'a>],
874    tree: &Tree,
875    parent: &str,
876    class: &str,
877    name: Option<&str>,
878    random: &mut dyn FnMut() -> [u8; 16],
879) -> Result<Added<'a>, String> {
880    let reg = type_registry();
881    let found = addable(files, parent);
882    let Addable { class, key } = found.into_iter().find(|a| a.class.local == class).ok_or_else(|| format!("a {class} cannot be added there"))?;
883    let fits = |f: &File| {
884        let declared = profiles(f);
885        declared.is_empty() || declared.iter().any(|p| class.origins.contains(p))
886    };
887    let defines = |f: &File, id: &str| f.index.elements.iter().any(|e| e.mrid == id && e.id_kind == Some(IdKind::Id));
888    let main = files
889        .iter()
890        .filter(|f| fits(f) && !profiles(f).contains(&"SSH"))
891        .max_by_key(|f| defines(f, parent))
892        .ok_or_else(|| format!("no file of the model set has a profile for {}", class.local))?;
893    let mut id = format!("_{}", uuid(random()));
894    while files.iter().any(|f| f.index.elements.iter().any(|e| e.mrid == id)) {
895        id = format!("_{}", uuid(random()));
896    }
897
898    let prefix = |f: &File, ns: &str| f.index.prefix_of(ns).map(str::to_string);
899    let tag = format!("{}:{}", prefix(main, class.ns).ok_or("the file binds no prefix to the class's namespace")?, class.local);
900    let field = |f: &File, key: &str| reg.attr(class, key).and_then(|a| Some((a, format!("{}:{}", prefix(f, a.ns)?, a.id))));
901    let carries = |f: &File, key: &str| {
902        let declared = profiles(f);
903        reg.attr(class, key).is_some_and(|a| declared.is_empty() || a.origins.iter().any(|o| declared.contains(o)))
904    };
905    let mut lines = vec![format!("<{tag} rdf:ID=\"{id}\">")];
906    let mut select_line = None;
907    if carries(main, "IdentifiedObject.mRID")
908        && let Some((_, t)) = field(main, "IdentifiedObject.mRID")
909    {
910        lines.push(format!("  <{t}>{}</{t}>", &id[1..]));
911    }
912    if let Some(name) = name.map(str::trim).filter(|n| !n.is_empty())
913        && let Some((_, t)) = field(main, "IdentifiedObject.name")
914    {
915        select_line = Some((lines.len(), t.len() + 4, name.encode_utf16().count()));
916        let escaped = name.replace('&', "&amp;").replace('<', "&lt;");
917        lines.push(format!("  <{t}>{escaped}</{t}>"));
918    }
919    let (_, container) = field(main, key).ok_or("the file binds no prefix to the field's namespace")?;
920    let target = if parent.contains(':') { parent.to_string() } else { format!("#{parent}") };
921    lines.push(format!("  <{container} rdf:resource=\"{target}\" />"));
922    lines.push(format!("</{tag}>"));
923
924    let mut changes: Edits<'a> = Vec::new();
925    let (at, line_no) = insertion(main, tree, parent, &lines)?;
926    let select = match select_line {
927        Some((l, col, len)) => {
928            let start = Position::new(line_no + l as u32, at.1 + col as u32);
929            Range::new(start, Position::new(start.line, start.character + len as u32))
930        }
931        None => Range::new(Position::new(line_no, at.1), Position::new(line_no, at.1)),
932    };
933    changes.push((main.name, vec![at.0]));
934    // Its steady-state part.
935    if class.origins.contains(&"SSH")
936        && let Some(ssh) = files.iter().find(|f| profiles(f).contains(&"SSH"))
937        && let Some(p) = prefix(ssh, class.ns)
938    {
939        let tag = format!("{p}:{}", class.local);
940        let ssh_lines = vec![format!("<{tag} rdf:about=\"#{id}\">"), format!("</{tag}>")];
941        let (edit, _) = insertion(ssh, tree, parent, &ssh_lines)?;
942        changes.push((ssh.name, vec![edit.0]));
943    }
944    Ok(Added { edits: changes, file: main.name.to_string(), select, id })
945}
946
947/// Where to insert `lines` (an element, unindented) in `file`: after the
948/// last element there of an object `parent` holds, else after `parent`'s,
949/// else before the root's end tag; indented as the elements are, in the
950/// file's line endings. The edit with the indent's width, and the line the
951/// element starts on.
952pub(crate) fn insertion(file: &File, tree: &Tree, parent: &str, lines: &[String]) -> Result<((TextEdit, u32), u32), String> {
953    let (text, li) = (file.text, file.lines);
954    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
955    let siblings: HashSet<&str> = tree.children(parent).into_iter().collect();
956    let anchor = file.index.elements.iter().rev().find(|e| siblings.contains(e.mrid.as_str()))
957        .or_else(|| file.index.elements.iter().rev().find(|e| e.mrid == parent));
958    let (offset, indent) = match anchor {
959        Some(el) => {
960            let end = li.offset(text, el.full.end);
961            let line_end = text[end..].find('\n').map_or(text.len(), |i| end + i + 1);
962            let head = li.offset(text, el.head.start);
963            let line_start = text[..head].rfind('\n').map_or(0, |i| i + 1);
964            (line_end, text[line_start..head].to_string())
965        }
966        None => {
967            let root_end = text.rfind("</").ok_or("the file has no root end tag")?;
968            let line_start = text[..root_end].rfind('\n').map_or(0, |i| i + 1);
969            let indent = file.index.elements.last().map_or("  ".to_string(), |el| {
970                let head = li.offset(text, el.head.start);
971                text[text[..head].rfind('\n').map_or(0, |i| i + 1)..head].to_string()
972            });
973            (line_start, indent)
974        }
975    };
976    // An anchor ending the file without a newline: start a line first.
977    let lead = if offset == text.len() && !text.ends_with('\n') { eol } else { "" };
978    let body: String = lines.iter().map(|l| format!("{indent}{l}{eol}")).collect();
979    let at = li.position(text, offset);
980    let first = if lead.is_empty() { at.line } else { at.line + 1 };
981    Ok(((TextEdit::new(Range::new(at, at), format!("{lead}{body}")), indent.encode_utf16().count() as u32), first))
982}
983
984/// A fix for a reference to nothing (`rdf:resource="#"`) or to an object the
985/// set lacks: name one of the likeliest objects instead.
986pub struct ReferenceFix {
987    pub key: String,
988    /// The file it is in, by its name.
989    pub file: String,
990    pub edit: TextEdit,
991    pub title: String,
992    /// It names nothing; else something the set does not have.
993    pub empty: bool,
994}
995
996/// The fixes for object `id`'s references to nothing or to objects the set
997/// lacks, in every file that writes it, or only the field at `at`: each the
998/// five likeliest objects ([`candidates`]); `at` names a file and a place in
999/// it. An enumeration value is not a reference to an object, so it has none.
1000pub fn reference_fixes(files: &[File], tree: &Tree, id: &str, at: Option<(&str, Position)>) -> Vec<ReferenceFix> {
1001    let sites: Vec<(&File, &crate::index::Field, &str, Range)> = files
1002        .iter()
1003        .filter(|f| at.is_none_or(|(n, _)| f.name == n))
1004        .flat_map(|f| f.index.elements.iter().filter(|e| e.mrid == id).map(move |e| (f, e)))
1005        .flat_map(|(f, e)| e.fields.iter().map(move |x| (f, x)))
1006        .filter(|(_, x)| at.is_none_or(|(_, pos)| contains(x.full, pos)))
1007        .filter_map(|(f, x)| x.resource.as_ref().map(|(t, r)| (f, x, t.as_str(), *r)))
1008        .collect();
1009    if sites.is_empty() {
1010        return Vec::new();
1011    }
1012    let known: HashSet<&str> = files.iter().flat_map(|f| f.index.elements.iter().map(|e| e.mrid.as_str())).collect();
1013    let indexes: Vec<&Index> = files.iter().map(|f| f.index).collect();
1014    let mut out = Vec::new();
1015    for (file, field, target, value) in sites {
1016        if !target.is_empty() && known.contains(target) {
1017            continue;
1018        }
1019        for c in candidates(&indexes, tree, id, field.key(), 5) {
1020            let place = if c.place.is_empty() { String::new() } else { format!(" in {}", c.place) };
1021            out.push(ReferenceFix {
1022                key: field.key().to_string(),
1023                file: file.name.to_string(),
1024                edit: TextEdit::new(value, c.reference()),
1025                title: format!("Set {} to {} {}{place}", field.key(), c.class, c.label),
1026                empty: target.is_empty(),
1027            });
1028        }
1029    }
1030    out
1031}
1032
1033/// The objects that refer to object `id`, and by which field, as the files
1034/// write them: (referrer, field), each once.
1035pub fn referrers<'a>(files: &[File<'a>], id: &str) -> Vec<(&'a str, &'a str)> {
1036    let mut out: Vec<(&str, &str)> = files
1037        .iter()
1038        .flat_map(|f| f.index.elements.iter())
1039        .flat_map(|e| e.fields.iter().filter(|x| x.resource.as_ref().is_some_and(|(t, _)| t == id)).map(move |x| (e.mrid.as_str(), x.key())))
1040        .filter(|(r, _)| !r.is_empty() && *r != id)
1041        .collect();
1042    out.sort_unstable();
1043    out.dedup();
1044    out
1045}
1046
1047/// How an object is named in a title: its class and name, else mRID.
1048pub fn describe(files: &[File], id: &str) -> String {
1049    let el = files.iter().flat_map(|f| &f.index.elements).filter(|e| e.mrid == id).max_by_key(|e| e.id_kind == Some(IdKind::Id));
1050    match el {
1051        Some(el) => format!("{} {}", local(&el.qname), el.name.as_deref().filter(|n| !n.is_empty()).unwrap_or(id)),
1052        None => id.to_string(),
1053    }
1054}
1055
1056#[cfg(test)]
1057mod tests {
1058    use super::*;
1059
1060    fn micro_grid() -> std::path::PathBuf {
1061        std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1062            .join("../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged")
1063    }
1064
1065    #[test]
1066    fn a_uuid_is_version_4() {
1067        let id = uuid([0xff; 16]);
1068        assert_eq!(id.len(), 36);
1069        assert_eq!(&id[14..15], "4");
1070        assert!(matches!(&id[19..20], "8" | "9" | "a" | "b"), "{id}");
1071    }
1072
1073    const EQ: &str = r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
1074  <cim:Breaker rdf:ID="_b1">
1075    <cim:IdentifiedObject.mRID>b1</cim:IdentifiedObject.mRID>
1076    <cim:IdentifiedObject.name>B1</cim:IdentifiedObject.name>
1077  </cim:Breaker>
1078  <cim:Terminal rdf:ID="_t1">
1079    <cim:Terminal.ConductingEquipment rdf:resource="#_b1" />
1080    <cim:IdentifiedObject.name>T1</cim:IdentifiedObject.name>
1081  </cim:Terminal>
1082</rdf:RDF>"##;
1083    const SSH: &str = r##"<rdf:RDF xmlns:cim="http://iec.ch/TC57/CIM100#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
1084  <cim:Breaker rdf:about="#_b1">
1085    <cim:Switch.open>false</cim:Switch.open>
1086  </cim:Breaker>
1087</rdf:RDF>"##;
1088
1089    fn apply(text: &str, edits: Vec<TextEdit>) -> String {
1090        crate::text::apply(text, &edits)
1091    }
1092
1093    /// The edits of the file `name`.
1094    fn of<'a>(edits: &Edits<'a>, name: &str) -> Vec<TextEdit> {
1095        edits.iter().find(|(n, _)| *n == name).map(|(_, e)| e.clone()).unwrap_or_default()
1096    }
1097
1098    fn with_files<R>(f: impl FnOnce(&[File]) -> R) -> R {
1099        let names = ["EQ.xml", "SSH.xml"];
1100        let texts = [EQ, SSH];
1101        let lines: Vec<LineIndex> = texts.iter().map(|t| LineIndex::new(t)).collect();
1102        let indexes: Vec<Index> = texts.iter().map(|t| Index::build(t)).collect();
1103        let files: Vec<File> = (0..2).map(|i| File { name: names[i], text: texts[i], lines: &lines[i], index: &indexes[i] }).collect();
1104        f(&files)
1105    }
1106
1107    #[test]
1108    fn renames_an_mrid_everywhere() {
1109        with_files(|files| {
1110            // On the reference, and on the start tag.
1111            let (r, old) = prepare_rename(files, "EQ.xml", Position::new(6, 55)).unwrap();
1112            assert_eq!((old.as_str(), r), ("_b1", Range::new(Position::new(6, 53), Position::new(6, 56))));
1113            assert_eq!(prepare_rename(files, "SSH.xml", Position::new(1, 4)).unwrap().1, "_b1");
1114            assert!(prepare_rename(files, "EQ.xml", Position::new(2, 10)).is_none());
1115
1116            let changes = rename(files, "_b1", "_b2").unwrap();
1117            let eq = apply(EQ, of(&changes, "EQ.xml"));
1118            assert!(eq.contains(r#"rdf:ID="_b2""#) && eq.contains(">b2</") && eq.contains(r##"rdf:resource="#_b2""##), "{eq}");
1119            assert!(!eq.contains("b1"), "{eq}");
1120            assert_eq!(apply(SSH, of(&changes, "SSH.xml")), SSH.replace("#_b1", "#_b2"));
1121
1122            assert!(rename(files, "_b1", "_t1").is_err());
1123            assert!(rename(files, "_b1", "a b").is_err());
1124            assert!(rename(files, "_b1", "1b").is_err());
1125        });
1126    }
1127
1128    #[test]
1129    fn adds_a_missing_field_where_its_profile_is() {
1130        let header = |p: &str| format!(r#"  <md:FullModel rdf:about="urn:uuid:{p}">
1131    <md:Model.profile>http://iec.ch/TC57/ns/CIM/{p}/3.0</md:Model.profile>
1132  </md:FullModel>
1133"#);
1134        let with_header = |text: &str, p: &str| {
1135            text.replacen(r#"xmlns:rdf"#, r#"xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#" xmlns:rdf"#, 1)
1136                .replacen(">\n", &format!(">\n{}", header(p)), 1)
1137        };
1138        let texts = [with_header(EQ, "CoreEquipment-EU"), with_header(SSH, "SteadyStateHypothesis-EU")];
1139        let names = ["EQ.xml", "SSH.xml"];
1140        let lines: Vec<LineIndex> = texts.iter().map(|t| LineIndex::new(t)).collect();
1141        let indexes: Vec<Index> = texts.iter().map(|t| Index::build(t)).collect();
1142        let files: Vec<File> = (0..2).map(|i| File { name: names[i], text: &texts[i], lines: &lines[i], index: &indexes[i] }).collect();
1143        let added = |id: &str, key: &str| {
1144            let a = add_missing(&files, names[0], id, key)?;
1145            let i = names.iter().position(|n| *n == a.file).unwrap();
1146            let out = apply(&texts[i], vec![a.edit.clone()]);
1147            let selected = apply(&out, vec![TextEdit::new(a.value, "|".into())]);
1148            Some((i, out, selected))
1149        };
1150
1151        // An SSH attribute goes to the SSH file, though asked from the EQ one.
1152        let (i, out, selected) = added("_b1", "Equipment.inService").unwrap();
1153        assert_eq!(i, 1);
1154        assert!(out.contains("<cim:Switch.open>false</cim:Switch.open>\n    <cim:Equipment.inService>false</cim:Equipment.inService>\n  </cim:Breaker>"), "{out}");
1155        assert!(selected.contains("<cim:Equipment.inService>|</cim:Equipment.inService>"), "{selected}");
1156        // An EQ one to the EQ file; a reference left to fill in, an enumeration its first value.
1157        let (i, _, selected) = added("_t1", "Terminal.ConnectivityNode").unwrap();
1158        assert_eq!(i, 0);
1159        assert!(selected.contains(r##"<cim:Terminal.ConnectivityNode rdf:resource="#|" />"##), "{selected}");
1160        let (_, out, _) = added("_t1", "Terminal.phases").unwrap();
1161        assert!(out.contains(r#"<cim:Terminal.phases rdf:resource="http://iec.ch/TC57/CIM100#PhaseCode."#), "{out}");
1162        // Written already, or not the class's.
1163        assert!(added("_b1", "Switch.open").is_none());
1164        assert!(added("_b1", "ACLineSegment.r").is_none());
1165    }
1166
1167    #[test]
1168    fn sets_and_removes_a_field_wherever_it_is_written() {
1169        with_files(|files| {
1170            // A literal, escaped; written in the SSH file.
1171            let set = set_field(files, "EQ.xml", "_b1", "Switch.open", "true").unwrap();
1172            assert_eq!(apply(SSH, of(&set, "SSH.xml")), SSH.replace(">false<", ">true<"));
1173            let named = set_field(files, "EQ.xml", "_b1", "IdentifiedObject.name", "B & 1").unwrap();
1174            assert!(apply(EQ, of(&named, "EQ.xml")).contains("<cim:IdentifiedObject.name>B &amp; 1</cim:IdentifiedObject.name>"));
1175            // A reference, to an mRID.
1176            let to = set_field(files, "EQ.xml", "_t1", "Terminal.ConductingEquipment", "_b2").unwrap();
1177            assert!(apply(EQ, of(&to, "EQ.xml")).contains(r##"<cim:Terminal.ConductingEquipment rdf:resource="#_b2" />"##));
1178            // Written nowhere: added, with the value given.
1179            let added = set_field(files, "EQ.xml", "_t1", "Terminal.phases", "ABC").unwrap();
1180            assert!(apply(EQ, of(&added, "EQ.xml")).contains(r#"<cim:Terminal.phases rdf:resource="http://iec.ch/TC57/CIM100#PhaseCode.ABC" />"#));
1181            assert!(set_field(files, "EQ.xml", "_b1", "ACLineSegment.r", "1").is_err());
1182
1183            let removed = remove_field(files, "_t1", "Terminal.ConductingEquipment");
1184            let eq = apply(EQ, of(&removed, "EQ.xml"));
1185            assert!(!eq.contains("ConductingEquipment") && eq.contains("<cim:Terminal rdf:ID=\"_t1\">\n    <cim:IdentifiedObject.name>T1"), "{eq}");
1186        });
1187    }
1188
1189    fn counting() -> impl FnMut() -> [u8; 16] {
1190        let mut n = 0u8;
1191        move || {
1192            n += 1;
1193            [n; 16]
1194        }
1195    }
1196
1197    #[test]
1198    fn copies_objects_with_new_mrids_and_their_references_among_them() {
1199        with_files(|files| {
1200            let mut random = counting();
1201            let copied = copy(files, &["_b1", "_t1"], None, None, &mut random).unwrap();
1202            let (b2, t2) = (format!("_{}", uuid([1; 16])), format!("_{}", uuid([2; 16])));
1203            assert_eq!(copied.ids, [("_b1".to_string(), b2.clone()), ("_t1".to_string(), t2.clone())]);
1204            let eq = apply(EQ, of(&copied.edits, "EQ.xml"));
1205            // The originals stay; the copies follow them, naming each other.
1206            assert!(eq.contains(r#"<cim:Breaker rdf:ID="_b1">"#) && eq.contains(&format!(r#"<cim:Breaker rdf:ID="{b2}">"#)), "{eq}");
1207            assert!(eq.contains(&format!("<cim:IdentifiedObject.mRID>{}</cim:IdentifiedObject.mRID>", &b2[1..])), "{eq}");
1208            assert!(eq.contains(&format!(r##"<cim:Terminal.ConductingEquipment rdf:resource="#{b2}" />"##)), "{eq}");
1209            assert_eq!(eq.matches(r##"rdf:resource="#_b1""##).count(), 1);
1210            let ssh = apply(SSH, of(&copied.edits, "SSH.xml"));
1211            assert!(ssh.contains(&format!(r##"<cim:Breaker rdf:about="#{b2}">"##)), "{ssh}");
1212            // Only the terminal: its reference to the breaker stays.
1213            let alone = copy(files, &["_t1"], None, None, &mut random).unwrap();
1214            assert_eq!(apply(EQ, of(&alone.edits, "EQ.xml")).matches(r##"rdf:resource="#_b1""##).count(), 2);
1215            // From one file, into another: the breaker's SSH part is not copied.
1216            let only = copy(files, &["_b1"], Some("EQ.xml"), None, &mut random).unwrap();
1217            assert_eq!(only.edits.len(), 1, "EQ only");
1218            let moved = copy(files, &["_t1"], None, Some("SSH.xml"), &mut random).unwrap();
1219            let ssh = apply(SSH, of(&moved.edits, "SSH.xml"));
1220            assert!(ssh.contains(&format!(r#"<cim:Terminal rdf:ID="{}">"#, moved.ids[0].1)) && ssh.ends_with("</rdf:RDF>"), "{ssh}");
1221            assert!(copy(files, &["_nothing"], None, None, &mut random).is_err());
1222            assert!(copy(files, &["_t1"], Some("SSH.xml"), None, &mut random).is_err());
1223        });
1224    }
1225
1226    #[test]
1227    fn creates_an_object_of_any_class_with_its_values() {
1228        with_files(|files| {
1229            let created = create(files, "EQ.xml", "Breaker", &[("IdentifiedObject.name", "B9"), ("Switch.normalOpen", "true")], &mut counting()).unwrap();
1230            let eq = apply(EQ, of(&created.edits, "EQ.xml"));
1231            let id = &created.id;
1232            assert!(eq.contains(&format!("  <cim:Breaker rdf:ID=\"{id}\">\n    <cim:IdentifiedObject.mRID>{}</cim:IdentifiedObject.mRID>\n    <cim:IdentifiedObject.name>B9</cim:IdentifiedObject.name>\n    <cim:Switch.normalOpen>true</cim:Switch.normalOpen>\n  </cim:Breaker>\n</rdf:RDF>", &id[1..])), "{eq}");
1233            assert!(create(files, "EQ.xml", "NoSuchClass", &[], &mut counting()).is_err());
1234            assert!(create(files, "EQ.xml", "Breaker", &[("ACLineSegment.r", "1")], &mut counting()).is_err());
1235        });
1236    }
1237
1238    #[test]
1239    fn lists_what_refers_to_an_object() {
1240        with_files(|files| {
1241            assert_eq!(referrers(files, "_b1"), [("_t1", "Terminal.ConductingEquipment")]);
1242            assert!(referrers(files, "_t1").is_empty());
1243        });
1244    }
1245
1246    #[test]
1247    fn deletes_an_object_from_every_file() {
1248        with_files(|files| {
1249            let d = delete(files, &HashSet::from(["_b1"]));
1250            assert_eq!((d.objects, d.references), (1, 1));
1251            let eq = apply(EQ, of(&d.edits, "EQ.xml"));
1252            assert!(!eq.contains("Breaker") && !eq.contains("ConductingEquipment") && eq.contains("<cim:Terminal rdf:ID=\"_t1\">\n    <cim:IdentifiedObject.name>T1"), "{eq}");
1253            assert!(!apply(SSH, of(&d.edits, "SSH.xml")).contains("Breaker"));
1254        });
1255    }
1256
1257    /// On MicroGrid, the object each reference names is among the
1258    /// candidates offered for it, mostly first.
1259    #[test]
1260    fn candidates_rank_what_the_data_names() {
1261        let read = crate::testing::collect(&micro_grid());
1262        let set = crate::testing::validate(&read);
1263        let built: Vec<Index> = read.iter().map(|(_, t)| Index::build(t)).collect();
1264        let indexes: Vec<&Index> = built.iter().collect();
1265        let mut stats: HashMap<&str, (usize, usize, usize)> = HashMap::new();
1266        for ix in &indexes {
1267            for el in &ix.elements {
1268                for f in &el.fields {
1269                    let key = f.key();
1270                    let Some((target, _)) = &f.resource else { continue };
1271                    // Not the containment's own fields: the object is where they put it.
1272                    if !["ConductingEquipment.BaseVoltage", "Terminal.ConnectivityNode", "Terminal.TopologicalNode", "RegulatingControl.Terminal"].contains(&key) {
1273                        continue;
1274                    }
1275                    let c = candidates(&indexes, &set.tree, &el.mrid, key, 5);
1276                    let s = stats.entry(key).or_default();
1277                    s.0 += 1;
1278                    if c.first().is_some_and(|c| c.id == *target) { s.1 += 1 }
1279                    if c.iter().any(|c| c.id == *target) { s.2 += 1 }
1280                }
1281            }
1282        }
1283        for (key, (n, first, top5)) in &stats {
1284            eprintln!("{key}: {n} references, first {first}, top 5 {top5}");
1285        }
1286        // Linked through the topological node: always first. A base voltage:
1287        // a line's, among its sub-region's, not always.
1288        assert_eq!(stats["Terminal.ConnectivityNode"], (73, 73, 73));
1289        assert_eq!(stats["Terminal.TopologicalNode"], (73, 73, 73));
1290        assert_eq!(stats["RegulatingControl.Terminal"], (7, 7, 7));
1291        assert_eq!(stats["ConductingEquipment.BaseVoltage"], (23, 20, 23));
1292    }
1293
1294    /// On MicroGrid: what a voltage level and a transformer can hold; a breaker
1295    /// added in a voltage level, in EQ with an SSH part, which validates
1296    /// with findings for what it lacks and sits in the voltage level.
1297    #[test]
1298    fn adds_an_object_in_a_container() {
1299        let read = crate::testing::collect(&micro_grid());
1300        let set = crate::testing::validate(&read);
1301        let names: Vec<String> = read.iter().map(|(p, _)| p.to_string_lossy().into_owned()).collect();
1302        let lines: Vec<LineIndex> = read.iter().map(|(_, t)| LineIndex::new(t)).collect();
1303        let indexes: Vec<Index> = read.iter().map(|(_, t)| Index::build(t)).collect();
1304        let files: Vec<File> = (0..read.len()).map(|i| File { name: &names[i], text: &read[i].1, lines: &lines[i], index: &indexes[i] }).collect();
1305        let find = |class: &str, name: &str| indexes.iter().flat_map(|ix| &ix.elements)
1306            .find(|e| local(&e.qname) == class && e.name.as_deref() == Some(name)).unwrap().mrid.clone();
1307        let vl = find("VoltageLevel", "110.0");
1308        let classes: Vec<&str> = addable(&files, &vl).iter().map(|a| a.class.local).collect();
1309        for c in ["Breaker", "Bay", "ConnectivityNode", "LinearShuntCompensator"] {
1310            assert!(classes.contains(&c), "{classes:?}");
1311        }
1312        assert!(!classes.contains(&"Terminal"), "{classes:?}");
1313        let transformer = find("PowerTransformer", "BE-TR2_1");
1314        let classes: Vec<&str> = addable(&files, &transformer).iter().map(|a| a.class.local).collect();
1315        assert!(classes.contains(&"Terminal") && classes.contains(&"PowerTransformerEnd"), "{classes:?}");
1316
1317        let mut draws = 0u8;
1318        let mut random = || {
1319            draws += 1;
1320            [draws; 16]
1321        };
1322        let added = add(&files, &set.tree, &vl, "Breaker", Some("B-new"), &mut random).unwrap();
1323        assert_eq!(added.edits.len(), 2, "EQ and SSH");
1324        assert_eq!(added.id, format!("_{}", uuid([1; 16])));
1325        let edited: Vec<(std::path::PathBuf, std::sync::Arc<str>)> = read.iter().enumerate().map(|(i, (p, t))| {
1326            let e = of(&added.edits, &names[i]);
1327            (p.clone(), std::sync::Arc::from(if e.is_empty() { t.to_string() } else { apply(t, e) }))
1328        }).collect();
1329        let main = names.iter().position(|n| *n == added.file).unwrap();
1330        assert!(edited[main].0.to_string_lossy().contains("_EQ_"));
1331        let text = &edited[main].1;
1332        let selected = apply(text, vec![TextEdit::new(added.select, "|".into())]);
1333        assert!(selected.contains("<cim:IdentifiedObject.name>|</cim:IdentifiedObject.name>"), "the name is selected");
1334
1335        let set2 = crate::testing::validate(&edited);
1336        assert_eq!(set2.tree.containers(&added.id), ["PP_Brussels", "110.0"]);
1337        let ssh = edited.iter().find(|(p, _)| p.to_string_lossy().contains("_BE_SSH_")).unwrap();
1338        assert!(ssh.1.contains(&format!("rdf:about=\"#{}\"", added.id)));
1339    }
1340
1341    /// A DL file beside MicroGrid's EQ: its namespaces, a header of its own
1342    /// dependent on EQ's, and room for a diagram, which validates.
1343    #[test]
1344    fn a_companion_file_takes_a_diagram() {
1345        let read = crate::testing::collect(&micro_grid());
1346        let names: Vec<String> = read.iter().map(|(p, _)| p.to_string_lossy().into_owned()).collect();
1347        let at = names.iter().position(|n| n.contains("_BE_EQ_")).unwrap();
1348        let (lines, index) = (LineIndex::new(&read[at].1), Index::build(&read[at].1));
1349        let eq = File { name: &names[at], text: &read[at].1, lines: &lines, index: &index };
1350        let text = companion(&eq, "DL", "0d1e2f30-0000-4000-8000-000000000000").unwrap();
1351        assert!(text.contains("<md:Model.profile>http://iec.ch/TC57/ns/CIM/DiagramLayout-EU/3.0</md:Model.profile>"), "{text}");
1352        assert!(text.contains(&format!("<md:Model.DependentOn rdf:resource=\"{}\" />", index.elements[0].mrid)), "{text}");
1353        assert!(!text.contains("CoreEquipment"), "{text}");
1354        let (dl_lines, dl_index) = (LineIndex::new(&text), Index::build(&text));
1355        let dl = File { name: "new_DL.xml", text: &text, lines: &dl_lines, index: &dl_index };
1356        let mut counter = 0u8;
1357        let mut random = || {
1358            counter += 1;
1359            [counter; 16]
1360        };
1361        let breaker = index.elements.iter().find(|e| local(&e.qname) == "Breaker").map(|e| e.mrid.clone());
1362        let shown = breaker.as_deref().unwrap_or("_x");
1363        let added = diagram(&[dl], "new_DL.xml", None, "One", &[(shown, "B", vec![(1.0, 2.5)])], &mut random).unwrap();
1364        let written = crate::text::apply(&text, &added.edits[0].1);
1365        assert!(written.contains("<cim:DiagramObjectPoint.xPosition>1</cim:DiagramObjectPoint.xPosition>"), "{written}");
1366        assert!(written.contains("<cim:DiagramObjectPoint.yPosition>2.5</cim:DiagramObjectPoint.yPosition>"), "{written}");
1367        assert!(written.contains("OrientationKind.negative"), "{written}");
1368        cimmodel::CimDataset::decode_str(&written).unwrap();
1369    }
1370}
1371