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(
38            self.lines.position(self.text, end.saturating_sub(len)),
39            r.end,
40        )
41    }
42
43    /// `r` widened to whole lines when nothing else is written on them.
44    pub(crate) fn lines_of(&self, r: Range) -> Range {
45        let (text, start, end) = (
46            self.text,
47            self.lines.offset(self.text, r.start),
48            self.lines.offset(self.text, r.end),
49        );
50        let line_start = text[..start].rfind('\n').map_or(0, |i| i + 1);
51        let line_end = text[end..].find('\n').map_or(text.len(), |i| end + i + 1);
52        if text[line_start..start].trim().is_empty() && text[end..line_end].trim().is_empty() {
53            self.lines.range(text, line_start, line_end)
54        } else {
55            r
56        }
57    }
58
59    /// The text of a field written `<q>text</q>`, and its range.
60    fn field_text(&self, head: Range, full: Range, qname: &str) -> Option<(&str, Range)> {
61        let start = self.lines.offset(self.text, head.end);
62        let end = self
63            .lines
64            .offset(self.text, full.end)
65            .checked_sub(qname.len() + 3)?;
66        let value = self.text.get(start..end)?;
67        (!value.contains('<')).then(|| (value, self.lines.range(self.text, start, end)))
68    }
69}
70
71/// The mRID at `pos` in the file `name` — an element's `rdf:ID`/`rdf:about`,
72/// or an `rdf:resource` — and the range of it as written; anywhere else in an
73/// element's start tag, that element's.
74pub fn prepare_rename(files: &[File], name: &str, pos: Position) -> Option<(Range, String)> {
75    let file = files.iter().find(|f| f.name == name)?;
76    let el = file.index.element_at(pos)?;
77    if let Some((mrid, r)) = el
78        .fields
79        .iter()
80        .filter_map(|f| f.resource.as_ref())
81        .find(|(_, r)| contains(*r, pos))
82    {
83        return Some((file.suffix(*r, mrid.len()), mrid.clone()));
84    }
85    let id = el.id_range?;
86    (contains(el.head, pos) && !el.mrid.is_empty())
87        .then(|| (file.suffix(id, el.mrid.len()), el.mrid.clone()))
88}
89
90/// Rename mRID `old` to `new` in every file: each element's `rdf:ID` or
91/// `rdf:about`, each `rdf:resource` to it, and an `IdentifiedObject.mRID`
92/// (or a class's own `….mRID`) that writes it (without its leading `_`, as
93/// CGMES 3 does, if so).
94pub fn rename<'a>(files: &[File<'a>], old: &str, new: &str) -> Result<Edits<'a>, String> {
95    let new = new.trim();
96    if new.is_empty() || new.contains(|c: char| c.is_whitespace() || "\"'<>&#".contains(c)) {
97        return Err(format!(
98            "`{new}` cannot be an mRID: no spaces, quotes, `<`, `>`, `&` or `#`"
99        ));
100    }
101    let defined = files
102        .iter()
103        .flat_map(|f| &f.index.elements)
104        .any(|e| e.mrid == old && e.id_kind == Some(IdKind::Id));
105    let ncname = new.starts_with(|c: char| c.is_alphabetic() || c == '_') && !new.contains(':');
106    if defined && !ncname {
107        return Err(format!(
108            "`{new}` cannot be an `rdf:ID`: it must start with a letter or `_` and hold no `:`"
109        ));
110    }
111    if files
112        .iter()
113        .flat_map(|f| &f.index.elements)
114        .any(|e| e.mrid == new)
115    {
116        return Err(format!("the model set already has an object `{new}`"));
117    }
118    let mut changes = Vec::new();
119    for file in files {
120        let mut edits = Vec::new();
121        for el in &file.index.elements {
122            if el.mrid == old
123                && let Some(id) = el.id_range
124            {
125                edits.push(TextEdit::new(file.suffix(id, old.len()), new.into()));
126                for f in el.fields.iter().filter(|f| f.key().ends_with(".mRID")) {
127                    let Some((text, r)) = file.field_text(f.head, f.full, &f.qname) else {
128                        continue;
129                    };
130                    let bare = |s: &str| s.strip_prefix('_').unwrap_or(s).to_string();
131                    if text.trim() == old {
132                        edits.push(TextEdit::new(r, new.into()));
133                    } else if text.trim() == bare(old) {
134                        edits.push(TextEdit::new(r, bare(new)));
135                    }
136                }
137            }
138            for (mrid, r) in el.fields.iter().filter_map(|f| f.resource.as_ref()) {
139                if mrid == old {
140                    edits.push(TextEdit::new(file.suffix(*r, old.len()), new.into()));
141                }
142            }
143        }
144        if !edits.is_empty() {
145            changes.push((file.name, edits));
146        }
147    }
148    Ok(changes)
149}
150
151/// What deleting objects changes: the elements writing them, in every file,
152/// and the fields referring to them from what stays. Whole lines go, so a
153/// client should show it before applying it.
154pub struct Deletion<'a> {
155    pub edits: Edits<'a>,
156    pub objects: usize,
157    pub references: usize,
158}
159
160/// Delete objects `ids`.
161pub fn delete<'a>(files: &[File<'a>], ids: &HashSet<&str>) -> Deletion<'a> {
162    let mut changes = Vec::new();
163    let (mut objects, mut references) = (HashSet::new(), 0);
164    for file in files {
165        let mut edits: Vec<TextEdit> = Vec::new();
166        let mut edit = |r: Range| edits.push(TextEdit::new(file.lines_of(r), String::new()));
167        for el in &file.index.elements {
168            if ids.contains(el.mrid.as_str()) {
169                objects.insert(el.mrid.as_str());
170                edit(el.full);
171                continue;
172            }
173            for f in &el.fields {
174                if f.resource
175                    .as_ref()
176                    .is_some_and(|(m, _)| ids.contains(m.as_str()))
177                {
178                    references += 1;
179                    edit(f.full);
180                }
181            }
182        }
183        if !edits.is_empty() {
184            changes.push((file.name, edits));
185        }
186    }
187    Deletion {
188        edits: changes,
189        objects: objects.len(),
190        references,
191    }
192}
193
194/// A field to add: where, and where its value is once added.
195pub struct Addition {
196    /// The file it goes in, by its name.
197    pub file: String,
198    pub edit: TextEdit,
199    /// The inserted value (or where it goes), to select after the edit.
200    pub value: Range,
201    /// A reference, inserted empty: `rdf:resource="#"`.
202    pub reference: bool,
203}
204
205impl Addition {
206    /// The edit with the reference to `c` filled in.
207    pub fn naming(&self, c: &Candidate) -> TextEdit {
208        TextEdit::new(
209            self.edit.range,
210            self.edit.new_text.replacen(
211                "rdf:resource=\"#\"",
212                &format!("rdf:resource=\"{}\"", c.reference()),
213                1,
214            ),
215        )
216    }
217}
218
219/// The profile codes `file`'s header declares (`md:Model.profile`,
220/// `dcterms:conformsTo`), by the schemas' profile tables.
221pub(crate) fn profiles(file: &File) -> Vec<&'static str> {
222    let reg = type_registry();
223    let tables: Vec<&[(&str, &str)]> = ["cgmes", "nc"]
224        .iter()
225        .filter_map(|f| reg.schema(f))
226        .map(|s| s.profiles)
227        .collect();
228    let Some(header) = file
229        .index
230        .elements
231        .iter()
232        .find(|e| matches!(local(&e.qname), "FullModel" | "Dataset" | "DifferenceModel"))
233    else {
234        return Vec::new();
235    };
236    header
237        .fields
238        .iter()
239        .filter(|f| matches!(f.key(), "Model.profile" | "conformsTo"))
240        .filter_map(|f| match &f.resource {
241            Some((uri, _)) => Some(uri.as_str()),
242            None => file
243                .field_text(f.head, f.full, &f.qname)
244                .map(|(t, _)| t.trim()),
245        })
246        .filter_map(|uri| {
247            tables
248                .iter()
249                .flat_map(|t| t.iter())
250                .find(|(_, u)| *u == uri)
251                .map(|(code, _)| *code)
252        })
253        .collect()
254}
255
256/// Add field `key` to object `id`, which writes it nowhere: in the file
257/// (`prefer` first) whose profile carries it and that writes the object,
258/// after its last field, with a value to type over — the object's mRID for
259/// `IdentifiedObject.mRID`, `false`, `0`, an enumeration's first value, or
260/// none. `None` if a file writes it already, its class does not declare
261/// it, or no file fits.
262pub fn add_missing(files: &[File], prefer: &str, id: &str, key: &str) -> Option<Addition> {
263    addition(files, prefer, id, key, None)
264}
265
266/// [`add_missing`], with `given` as the value written (as [`set_field`] takes it) rather than
267/// one to type over.
268fn addition(
269    files: &[File],
270    prefer: &str,
271    id: &str,
272    key: &str,
273    given: Option<&str>,
274) -> Option<Addition> {
275    let reg = type_registry();
276    let sites: Vec<(&File, &crate::index::Element)> = files
277        .iter()
278        .flat_map(|f| {
279            f.index
280                .elements
281                .iter()
282                .filter(|e| e.mrid == id)
283                .map(move |e| (f, e))
284        })
285        .collect();
286    if sites
287        .iter()
288        .any(|(_, e)| e.fields.iter().any(|f| f.key() == key))
289    {
290        return None;
291    }
292    let (def_file, def) = sites
293        .iter()
294        .max_by_key(|(_, e)| e.id_kind == Some(IdKind::Id))?;
295    let class = def_file.index.class_of(&def.qname)?;
296    let attr = reg.attr(class, key).filter(|a| a.used)?;
297    let fits = |f: &File| {
298        let declared = profiles(f);
299        declared.is_empty()
300            || attr.origins.is_empty()
301            || declared.iter().any(|p| attr.origins.contains(p))
302    };
303    let (file, el) = sites
304        .iter()
305        .filter(|(f, _)| fits(f))
306        .min_by_key(|(f, e)| (f.name != prefer, e.id_kind != Some(IdKind::Id)))?;
307    let tag = format!("{}:{}", file.index.prefix_of(attr.ns)?, attr.id);
308    let (open, value, close) = match attr.kind {
309        AttrKind::Literal => {
310            let value = match (attr.id, attr.xsd) {
311                _ if given.is_some() => escape(given.unwrap_or_default()),
312                ("IdentifiedObject.mRID", _) => id.strip_prefix('_').unwrap_or(id).to_string(),
313                (_, "boolean") => "false".into(),
314                (_, "double" | "float" | "decimal" | "integer" | "int" | "long" | "short") => {
315                    "0".into()
316                }
317                _ => String::new(),
318            };
319            (format!("<{tag}>"), value, format!("</{tag}>"))
320        }
321        AttrKind::Association => match given {
322            Some(target) => (
323                format!("<{tag} rdf:resource=\""),
324                reference(target),
325                "\" />".into(),
326            ),
327            None => (
328                format!("<{tag} rdf:resource=\"#"),
329                String::new(),
330                "\" />".into(),
331            ),
332        },
333        AttrKind::Enum => {
334            let first = reg
335                .family_of(class.qualified)
336                .and_then(|f| reg.schema(f))
337                .and_then(|s| s.enumeration(attr.range))
338                .and_then(|e| e.values.first());
339            let value = given.map_or_else(
340                || first.map_or(String::new(), |v| v.id.to_string()),
341                |v| enum_value(attr.range, v).to_string(),
342            );
343            (
344                format!("<{tag} rdf:resource=\"{}", attr.value_ns),
345                value,
346                "\" />".into(),
347            )
348        }
349    };
350    // On a line of its own after the last field, indented as it is; else
351    // inside the element, a step in from it.
352    let (text, lines) = (file.text, file.lines);
353    let indent_of = |r: Range| {
354        let start = lines.offset(text, Position::new(r.start.line, 0));
355        let at = lines.offset(text, r.start);
356        text[start..at]
357            .chars()
358            .take_while(|c| c.is_whitespace())
359            .collect::<String>()
360    };
361    let (at, indent) = match el.fields.last() {
362        Some(f) => (f.full.end, indent_of(f.head)),
363        None => {
364            let end = lines.offset(text, el.full.end);
365            let closing = end
366                .checked_sub(el.qname.len() + 3)
367                .filter(|&c| text.get(c..end) == Some(&format!("</{}>", el.qname)))?;
368            (
369                lines.position(text, closing),
370                format!("{}  ", indent_of(el.head)),
371            )
372        }
373    };
374    // Lines end as the file's do.
375    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
376    let new_text = if el.fields.is_empty() {
377        format!("  {open}{value}{close}{eol}{}", indent_of(el.head))
378    } else {
379        format!("{eol}{indent}{open}{value}{close}")
380    };
381    let utf16 = |s: &str| s.encode_utf16().count() as u32;
382    let start = if el.fields.is_empty() {
383        Position::new(at.line, at.character + 2 + utf16(&open))
384    } else {
385        Position::new(at.line + 1, utf16(&indent) + utf16(&open))
386    };
387    let value_range = Range::new(
388        start,
389        Position::new(start.line, start.character + utf16(&value)),
390    );
391    let reference = attr.kind == AttrKind::Association && given.is_none();
392    Some(Addition {
393        file: file.name.to_string(),
394        edit: TextEdit::new(Range::new(at, at), new_text),
395        value: value_range,
396        reference,
397    })
398}
399
400/// `text` as XML character data.
401fn escape(text: &str) -> String {
402    text.replace('&', "&amp;")
403        .replace('<', "&lt;")
404        .replace('>', "&gt;")
405}
406
407/// A reference to object `target` as written: `#_id`, or an IRI as it is.
408fn reference(target: &str) -> String {
409    if target.contains(':') {
410        target.to_string()
411    } else {
412        format!("#{target}")
413    }
414}
415
416/// An enumeration's value as its IRI ends: `WindingConnection.D`, from `D` or the whole name.
417fn enum_value<'v>(range: &str, value: &'v str) -> std::borrow::Cow<'v, str> {
418    let value = value.rsplit_once('#').map_or(value, |(_, v)| v);
419    if value.contains('.') {
420        value.into()
421    } else {
422        format!("{range}.{value}").into()
423    }
424}
425
426/// Set field `key` of object `id` to `value`: a literal's text (escaped here), a reference's
427/// object (its mRID, or an IRI), or an enumeration's value (`D`, or `WindingConnection.D`).
428/// Wherever a file writes the field, its value is replaced; where none does, it is added as
429/// [`add_missing`] adds it, `prefer` first. An error if the object's class does not declare it.
430pub fn set_field<'a>(
431    files: &[File<'a>],
432    prefer: &str,
433    id: &str,
434    key: &str,
435    value: &str,
436) -> Result<Edits<'a>, String> {
437    let reg = type_registry();
438    let (def_file, def) = files
439        .iter()
440        .flat_map(|f| {
441            f.index
442                .elements
443                .iter()
444                .filter(|e| e.mrid == id)
445                .map(move |e| (f, e))
446        })
447        .max_by_key(|(_, e)| e.id_kind == Some(IdKind::Id))
448        .ok_or_else(|| format!("no file writes `{id}`"))?;
449    let class = def_file
450        .index
451        .class_of(&def.qname)
452        .ok_or_else(|| format!("`{}` is no class of the tables", def.qname))?;
453    let attr = reg
454        .attr(class, key)
455        .ok_or_else(|| format!("{} has no field {key}", class.local))?;
456    let mut changes: Edits<'a> = Vec::new();
457    for file in files {
458        let mut edits = Vec::new();
459        for el in file.index.elements.iter().filter(|e| e.mrid == id) {
460            for f in el.fields.iter().filter(|f| f.key() == key) {
461                let edit = match (attr.kind, &f.resource) {
462                    (AttrKind::Literal, None) => match file.field_text(f.head, f.full, &f.qname) {
463                        Some((_, r)) => TextEdit::new(r, escape(value)),
464                        // `<x/>`: written anew.
465                        None => TextEdit::new(
466                            f.full,
467                            format!("<{q}>{}</{q}>", escape(value), q = f.qname),
468                        ),
469                    },
470                    (AttrKind::Association, Some((_, r))) => TextEdit::new(*r, reference(value)),
471                    (AttrKind::Enum, Some((_, r))) => {
472                        let start = file.lines.offset(file.text, r.start);
473                        let end = file.lines.offset(file.text, r.end);
474                        let written = &file.text[start..end];
475                        // Its namespace as written, else the attribute's.
476                        let ns = written
477                            .rsplit_once('#')
478                            .map_or(attr.value_ns.to_string(), |(ns, _)| format!("{ns}#"));
479                        TextEdit::new(*r, format!("{ns}{}", enum_value(attr.range, value)))
480                    }
481                    _ => {
482                        return Err(format!(
483                            "{key} is written in {} as it cannot be set",
484                            file.name
485                        ));
486                    }
487                };
488                edits.push(edit);
489            }
490        }
491        if !edits.is_empty() {
492            changes.push((file.name, edits));
493        }
494    }
495    if changes.is_empty() {
496        let added = addition(files, prefer, id, key, Some(value))
497            .ok_or_else(|| format!("no file of the set takes {key} for `{id}`"))?;
498        let name = files
499            .iter()
500            .find(|f| f.name == added.file)
501            .map(|f| f.name)
502            .expect("one of the files");
503        changes.push((name, vec![added.edit]));
504    }
505    Ok(changes)
506}
507
508/// Remove field `key` from object `id` in every file writing it, its lines with it.
509pub fn remove_field<'a>(files: &[File<'a>], id: &str, key: &str) -> Edits<'a> {
510    let mut changes = Vec::new();
511    for file in files {
512        let edits: Vec<TextEdit> = file
513            .index
514            .elements
515            .iter()
516            .filter(|e| e.mrid == id)
517            .flat_map(|e| e.fields.iter().filter(|f| f.key() == key))
518            .map(|f| TextEdit::new(file.lines_of(f.full), String::new()))
519            .collect();
520        if !edits.is_empty() {
521            changes.push((file.name, edits));
522        }
523    }
524    changes
525}
526
527/// A field of `class` written as an element of `file`, its value as [`set_field`] takes it.
528pub(crate) fn field_element(
529    file: &File,
530    class: &'static cimmodel::base::ClassDef,
531    key: &str,
532    value: &str,
533) -> Result<String, String> {
534    let attr = type_registry()
535        .attr(class, key)
536        .ok_or_else(|| format!("{} has no field {key}", class.local))?;
537    let prefix = file
538        .index
539        .prefix_of(attr.ns)
540        .ok_or_else(|| format!("{} binds no prefix to {}", file.name, attr.ns))?;
541    let tag = format!("{prefix}:{}", attr.id);
542    Ok(match attr.kind {
543        AttrKind::Literal => format!("<{tag}>{}</{tag}>", escape(value)),
544        AttrKind::Association => format!("<{tag} rdf:resource=\"{}\" />", reference(value)),
545        AttrKind::Enum => format!(
546            "<{tag} rdf:resource=\"{}{}\" />",
547            attr.value_ns,
548            enum_value(attr.range, value)
549        ),
550    })
551}
552
553/// `lines` (an element, unindented) inserted before the end tag of `file`'s root, indented as its
554/// elements are, in its line endings.
555pub(crate) fn at_end(file: &File, lines: &[String]) -> Result<TextEdit, String> {
556    let text = file.text;
557    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
558    let root_end = text.rfind("</").ok_or("the file has no root end tag")?;
559    let line_start = text[..root_end].rfind('\n').map_or(0, |i| i + 1);
560    let indent = file.index.elements.last().map_or("  ".to_string(), |el| {
561        let head = file.lines.offset(text, el.head.start);
562        text[text[..head].rfind('\n').map_or(0, |i| i + 1)..head].to_string()
563    });
564    let at = file.lines.position(text, line_start);
565    let body: String = lines.iter().map(|l| format!("{indent}{l}{eol}")).collect();
566    Ok(TextEdit::new(Range::new(at, at), body))
567}
568
569/// A fresh mRID, `_` and a UUID from `random`, that the set does not have yet nor `taken`.
570pub(crate) fn fresh(
571    files: &[File],
572    taken: &HashSet<String>,
573    random: &mut dyn FnMut() -> [u8; 16],
574) -> String {
575    loop {
576        let id = format!("_{}", uuid(random()));
577        if !taken.contains(&id)
578            && !files
579                .iter()
580                .any(|f| f.index.elements.iter().any(|e| e.mrid == id))
581        {
582            return id;
583        }
584    }
585}
586
587/// A new object of `class`, with `values` (field, value as [`set_field`] takes it) and its
588/// 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
589/// `rdf:ID` whose UUID is drawn from `random`. For objects in no container, which [`add`] cannot
590/// place: a response, a dependency.
591pub fn create<'a>(
592    files: &[File<'a>],
593    into: &str,
594    class: &str,
595    values: &[(&str, &str)],
596    random: &mut dyn FnMut() -> [u8; 16],
597) -> Result<Added<'a>, String> {
598    let reg = type_registry();
599    let file = files
600        .iter()
601        .find(|f| f.name == into)
602        .ok_or_else(|| format!("no file {into}"))?;
603    // The class by the namespaces the file binds: CGMES's or NC's, whichever has it.
604    let found = file
605        .index
606        .namespaces
607        .iter()
608        .filter_map(|(_, ns)| reg.ns_table(ns)?.get(class).copied())
609        .next()
610        .ok_or_else(|| format!("{into} binds no namespace with a class {class}"))?;
611    let prefix = file.index.prefix_of(found.ns).ok_or("no prefix")?;
612    let id = fresh(files, &HashSet::new(), random);
613    let mut lines = vec![format!("<{prefix}:{} rdf:ID=\"{id}\">", found.local)];
614    // Its mRID as text: `IdentifiedObject.mRID`, or a class's own (`…Response.mRID`).
615    let mrid_key = reg
616        .attrs(found)
617        .map(|a| a.id)
618        .find(|k| k.ends_with(".mRID"));
619    if let Some(key) = mrid_key.filter(|k| !values.iter().any(|(v, _)| v == k)) {
620        lines.push(format!("  {}", field_element(file, found, key, &id[1..])?));
621    }
622    for (key, value) in values {
623        lines.push(format!("  {}", field_element(file, found, key, value)?));
624    }
625    lines.push(format!("</{prefix}:{}>", found.local));
626    let edit = at_end(file, &lines)?;
627    let first = edit.range.start.line;
628    let select = Range::new(Position::new(first, 0), Position::new(first, 0));
629    Ok(Added {
630        edits: vec![(file.name, vec![edit])],
631        file: file.name.to_string(),
632        select,
633        id,
634    })
635}
636
637/// The text of a new file of profile `code` (`DL`) beside `like`: its
638/// prolog and root, with their namespaces, and a FullModel header under the
639/// model id `urn:uuid:{id}` dependent on `like`'s model, with its times,
640/// version and modelling authority set.
641pub fn companion(like: &File, code: &str, id: &str) -> Result<String, String> {
642    let profile = type_registry()
643        .schema("cgmes")
644        .and_then(|s| s.profiles.iter().find(|(c, _)| *c == code))
645        .map(|(_, uri)| *uri)
646        .ok_or_else(|| format!("no profile {code}"))?;
647    let text = like.text;
648    let root_end = text
649        .find("<rdf:RDF")
650        .and_then(|s| text[s..].find('>').map(|e| s + e + 1))
651        .ok_or_else(|| format!("{} has no rdf:RDF root", like.name))?;
652    let header = like
653        .index
654        .elements
655        .iter()
656        .find(|e| local(&e.qname) == "FullModel")
657        .ok_or_else(|| format!("{} has no FullModel header", like.name))?;
658    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
659    let start = like.lines.offset(text, header.full.start);
660    let indent = text[..start].rsplit_once('\n').map_or("", |(_, i)| i);
661    let prefix = header.qname.split_once(':').map_or("md", |(p, _)| p);
662    let model = if header.mrid.contains(':') {
663        header.mrid.clone()
664    } else {
665        format!("#{}", header.mrid)
666    };
667    let mut lines = vec![format!("<{prefix}:FullModel rdf:about=\"urn:uuid:{id}\">")];
668    for f in &header.fields {
669        if matches!(
670            f.key(),
671            "Model.created" | "Model.scenarioTime" | "Model.version" | "Model.modelingAuthoritySet"
672        ) {
673            lines.push(format!(
674                "  {}",
675                &text[like.lines.offset(text, f.full.start)..like.lines.offset(text, f.full.end)]
676            ));
677        }
678    }
679    lines.push(format!(
680        "  <{prefix}:Model.profile>{profile}</{prefix}:Model.profile>"
681    ));
682    lines.push(format!(
683        "  <{prefix}:Model.DependentOn rdf:resource=\"{model}\" />"
684    ));
685    lines.push(format!("</{prefix}:FullModel>"));
686    let body: String = lines.iter().map(|l| format!("{indent}{l}{eol}")).collect();
687    Ok(format!("{}{eol}{body}</rdf:RDF>{eol}", &text[..root_end]))
688}
689
690/// An object a diagram draws: the mRID it shows, its name, and its points.
691pub type Drawn<'a> = (&'a str, &'a str, Vec<(f64, f64)>);
692
693/// A DL diagram written into `into`: a new `Diagram` named `name` (y
694/// downwards), or in `existing` (in the file defining it, whatever `into`
695/// says), its drawing of what `objects` show replaced and the rest kept. Each of `objects` (the mRID it shows, its name,
696/// its points) a `DiagramObject` with its `DiagramObjectPoint`s, numbered
697/// from 1. UUIDs from `random`. The diagram's mRID is the result's `id`.
698pub fn diagram<'a>(
699    files: &[File<'a>],
700    into: &str,
701    existing: Option<&str>,
702    name: &str,
703    objects: &[Drawn],
704    random: &mut dyn FnMut() -> [u8; 16],
705) -> Result<Added<'a>, String> {
706    let defines = |f: &&File, id: &str| {
707        f.index
708            .elements
709            .iter()
710            .any(|e| e.mrid == id && e.id_kind == Some(IdKind::Id))
711    };
712    let file = match existing {
713        Some(d) => files
714            .iter()
715            .find(|f| defines(f, d))
716            .ok_or_else(|| format!("no file defines the diagram {d}"))?,
717        None => files
718            .iter()
719            .find(|f| f.name == into)
720            .ok_or_else(|| format!("no file {into}"))?,
721    };
722    let reg = type_registry();
723    let class = |local: &str| {
724        file.index
725            .namespaces
726            .iter()
727            .filter_map(|(_, ns)| reg.ns_table(ns)?.get(local).copied())
728            .next()
729            .ok_or_else(|| format!("{} binds no namespace with a class {local}", file.name))
730    };
731    let (diagram_class, object_class, point_class) = (
732        class("Diagram")?,
733        class("DiagramObject")?,
734        class("DiagramObjectPoint")?,
735    );
736    let mut taken = HashSet::new();
737    let mut fresh_id = |random: &mut dyn FnMut() -> [u8; 16]| {
738        let id = fresh(files, &taken, random);
739        taken.insert(id.clone());
740        id
741    };
742    let mut edits: Edits<'a> = Vec::new();
743    let mut lines = Vec::new();
744    let diagram = match existing {
745        Some(d) => {
746            // Its objects of what is drawn anew go, with their points; the
747            // diagram stays, with its name and the rest.
748            let anew: HashSet<&str> = objects.iter().map(|(m, _, _)| *m).collect();
749            let shows = |e: &crate::index::Element| {
750                e.fields.iter().any(|f| {
751                    f.key() == "DiagramObject.IdentifiedObject"
752                        && f.resource
753                            .as_ref()
754                            .is_some_and(|(m, _)| anew.contains(m.as_str()))
755                })
756            };
757            let shown: HashSet<&str> = file
758                .index
759                .elements
760                .iter()
761                .filter(|e| local(&e.qname) == "DiagramObject")
762                .filter(|e| {
763                    e.fields.iter().any(|f| {
764                        f.key() == "DiagramObject.Diagram"
765                            && f.resource.as_ref().is_some_and(|(m, _)| m == d)
766                    })
767                })
768                .filter(|e| shows(e))
769                .map(|e| e.mrid.as_str())
770                .collect();
771            let mut gone: HashSet<&str> = shown.clone();
772            for e in files.iter().flat_map(|f| &f.index.elements) {
773                if local(&e.qname) == "DiagramObjectPoint"
774                    && e.fields.iter().any(|f| {
775                        f.resource
776                            .as_ref()
777                            .is_some_and(|(m, _)| shown.contains(m.as_str()))
778                    })
779                {
780                    gone.insert(e.mrid.as_str());
781                }
782            }
783            edits = delete(files, &gone).edits;
784            d.to_string()
785        }
786        None => {
787            let id = fresh_id(random);
788            lines.extend(element(
789                file,
790                diagram_class,
791                &id,
792                &[
793                    ("IdentifiedObject.name", name),
794                    ("Diagram.orientation", "negative"),
795                ],
796            )?);
797            id
798        }
799    };
800    for (shown, label, points) in objects {
801        let id = fresh_id(random);
802        let mut values = vec![
803            ("DiagramObject.Diagram", diagram.as_str()),
804            ("DiagramObject.IdentifiedObject", *shown),
805            ("DiagramObject.rotation", "0"),
806        ];
807        if !label.is_empty() {
808            values.insert(0, ("IdentifiedObject.name", *label));
809        }
810        lines.extend(element(file, object_class, &id, &values)?);
811        for (k, (x, y)) in points.iter().enumerate() {
812            let point = fresh_id(random);
813            let (k, x, y) = ((k + 1).to_string(), number(*x), number(*y));
814            lines.extend(element(
815                file,
816                point_class,
817                &point,
818                &[
819                    ("DiagramObjectPoint.sequenceNumber", &k),
820                    ("DiagramObjectPoint.xPosition", &x),
821                    ("DiagramObjectPoint.yPosition", &y),
822                    ("DiagramObjectPoint.DiagramObject", &id),
823                ],
824            )?);
825        }
826    }
827    let edit = at_end(file, &lines)?;
828    let first = edit.range.start.line;
829    match edits.iter_mut().find(|(n, _)| *n == file.name) {
830        Some((_, es)) => es.push(edit),
831        None => edits.push((file.name, vec![edit])),
832    }
833    let select = Range::new(Position::new(first, 0), Position::new(first, 0));
834    Ok(Added {
835        edits,
836        file: file.name.to_string(),
837        select,
838        id: diagram,
839    })
840}
841
842/// A coordinate as DL writes it: to a hundredth, without trailing zeros.
843fn number(x: f64) -> String {
844    let s = format!("{:.2}", (x * 100.0).round() / 100.0);
845    let s = s.trim_end_matches('0').trim_end_matches('.');
846    if s == "-0" { "0".into() } else { s.into() }
847}
848
849/// An object's element, unindented: its `rdf:ID`, its mRID as text where the class has a field for
850/// it, and `values` as [`set_field`] takes them.
851pub(crate) fn element(
852    file: &File,
853    class: &'static cimmodel::base::ClassDef,
854    id: &str,
855    values: &[(&str, &str)],
856) -> Result<Vec<String>, String> {
857    let prefix = file.index.prefix_of(class.ns).ok_or("no prefix")?;
858    let mut lines = vec![format!("<{prefix}:{} rdf:ID=\"{id}\">", class.local)];
859    let mrid_key = type_registry()
860        .attrs(class)
861        .map(|a| a.id)
862        .find(|k| k.ends_with(".mRID"));
863    if let Some(key) = mrid_key.filter(|k| !values.iter().any(|(v, _)| v == k)) {
864        lines.push(format!("  {}", field_element(file, class, key, &id[1..])?));
865    }
866    for (key, value) in values {
867        lines.push(format!("  {}", field_element(file, class, key, value)?));
868    }
869    lines.push(format!("</{prefix}:{}>", class.local));
870    Ok(lines)
871}
872
873/// Objects copied: the edits, and each object's new mRID.
874pub struct Copied<'a> {
875    pub edits: Edits<'a>,
876    /// (original, copy), in the order given.
877    pub ids: Vec<(String, String)>,
878}
879
880/// Copy objects `ids` with new mRIDs (`_` and a UUID from `random`): every element writing each
881/// of them, in every file or only in `from`, its `rdf:ID` or `rdf:about`, its mRID field, and its
882/// references to the objects copied, rewritten to the copies; references to anything else stay.
883/// Each copy goes after its original, or with `into`, at the end of that file, which must bind
884/// the prefixes the copies use as their files do. `from` matters where two files define the same
885/// objects (a proposal and what was agreed of it): their copies would be one object written twice.
886pub fn copy<'a>(
887    files: &[File<'a>],
888    ids: &[&str],
889    from: Option<&str>,
890    into: Option<&str>,
891    random: &mut dyn FnMut() -> [u8; 16],
892) -> Result<Copied<'a>, String> {
893    let sources = |f: &&File| from.is_none_or(|n| f.name == n);
894    let target = match into {
895        Some(name) => Some(
896            files
897                .iter()
898                .find(|f| f.name == name)
899                .ok_or_else(|| format!("no file {name}"))?,
900        ),
901        None => None,
902    };
903    let mut taken = HashSet::new();
904    let mut renamed: Vec<(String, String)> = Vec::new();
905    for id in ids {
906        if !files
907            .iter()
908            .filter(sources)
909            .any(|f| f.index.elements.iter().any(|e| e.mrid == *id))
910        {
911            return Err(format!(
912                "no file {}writes `{id}`",
913                from.map_or(String::new(), |n| format!("but {n} "))
914            ));
915        }
916        let new = fresh(files, &taken, random);
917        taken.insert(new.clone());
918        renamed.push((id.to_string(), new));
919    }
920    let to: HashMap<&str, &str> = renamed
921        .iter()
922        .map(|(o, n)| (o.as_str(), n.as_str()))
923        .collect();
924    let mut changes: Edits<'a> = Vec::new();
925    let mut moved: Vec<String> = Vec::new();
926    for file in files.iter().filter(sources) {
927        let text = file.text;
928        let mut edits = Vec::new();
929        for el in file
930            .index
931            .elements
932            .iter()
933            .filter(|e| to.contains_key(e.mrid.as_str()))
934        {
935            if let Some(t) = target.filter(|t| t.name != file.name) {
936                // The copy's prefixes, bound as they are here.
937                let qnames = std::iter::once(&el.qname).chain(el.fields.iter().map(|f| &f.qname));
938                for q in qnames {
939                    let p = crate::index::prefix(q);
940                    if t.index.namespace(p) != file.index.namespace(p) {
941                        return Err(format!(
942                            "{} binds `{p}` otherwise than {}",
943                            t.name, file.name
944                        ));
945                    }
946                }
947            }
948            let block = file.lines_of(el.full);
949            let (start, end) = (
950                file.lines.offset(text, block.start),
951                file.lines.offset(text, block.end),
952            );
953            // Replacements within the block, by offset.
954            let mut swaps: Vec<(usize, usize, String)> = Vec::new();
955            // An mRID at the end of the value written at `r`.
956            let suffix = |r: Range, old: &str, new: &str| {
957                let at = file.lines.offset(text, r.end);
958                (at - old.len(), at, new.to_string())
959            };
960            let old = el.mrid.as_str();
961            let new = to[old];
962            if let Some(r) = el.id_range {
963                swaps.push(suffix(r, old, new));
964            }
965            for f in &el.fields {
966                if let Some((target_id, r)) = &f.resource
967                    && let Some(n) = to.get(target_id.as_str())
968                {
969                    swaps.push(suffix(*r, target_id, n));
970                }
971                if f.key().ends_with(".mRID")
972                    && let Some((value, r)) = file.field_text(f.head, f.full, &f.qname)
973                {
974                    let bare = |s: &str| s.strip_prefix('_').unwrap_or(s).to_string();
975                    let (vs, ve) = (
976                        file.lines.offset(text, r.start),
977                        file.lines.offset(text, r.end),
978                    );
979                    if value.trim() == old {
980                        swaps.push((vs, ve, new.to_string()));
981                    } else if value.trim() == bare(old) {
982                        swaps.push((vs, ve, bare(new)));
983                    }
984                }
985            }
986            swaps.sort_by_key(|s| std::cmp::Reverse(s.0));
987            let mut copied = text[start..end].to_string();
988            for (s, e, with) in swaps {
989                copied.replace_range(s - start..e - start, &with);
990            }
991            if !copied.ends_with('\n') {
992                copied.push_str(if text.contains("\r\n") { "\r\n" } else { "\n" });
993            }
994            match target {
995                Some(_) => moved.push(copied),
996                None => edits.push(TextEdit::new(Range::new(block.end, block.end), copied)),
997            }
998        }
999        if !edits.is_empty() {
1000            changes.push((file.name, edits));
1001        }
1002    }
1003    if let Some(t) = target {
1004        let root_end = t.text.rfind("</").ok_or("the file has no root end tag")?;
1005        let line_start = t.text[..root_end].rfind('\n').map_or(0, |i| i + 1);
1006        let at = t.lines.position(t.text, line_start);
1007        let edit = TextEdit::new(Range::new(at, at), moved.concat());
1008        match changes.iter_mut().find(|(n, _)| *n == t.name) {
1009            Some((_, e)) => e.push(edit),
1010            None => changes.push((t.name, vec![edit])),
1011        }
1012    }
1013    Ok(Copied {
1014        edits: changes,
1015        ids: renamed,
1016    })
1017}
1018
1019/// An object a reference can name.
1020pub struct Candidate {
1021    pub id: String,
1022    pub label: String,
1023    pub class: &'static str,
1024    /// Its containers' labels, as the outline shows them.
1025    pub place: String,
1026}
1027
1028impl Candidate {
1029    /// The reference to it as written: `#_id`, or an IRI as it is.
1030    pub fn reference(&self) -> String {
1031        if self.id.contains(':') {
1032            self.id.clone()
1033        } else {
1034            format!("#{}", self.id)
1035        }
1036    }
1037}
1038
1039/// The objects field `key` of object `id` can name — of the class it ranges
1040/// over, or below — at most `limit`, the likeliest first: those linked to
1041/// the object, naming what it names with its other fields or named by it
1042/// (a terminal's connectivity node, of its topological node; equipment's
1043/// base voltage, its voltage level's); then those that share the most
1044/// containers with it, by where they are or by where the objects are that
1045/// name them with the same field (a line's base voltage is the one the
1046/// equipment of its voltage level names); then the most named.
1047/// Empty if `key` is not a reference of the object's class.
1048pub fn candidates(
1049    indexes: &[&Index],
1050    tree: &Tree,
1051    id: &str,
1052    key: &str,
1053    limit: usize,
1054) -> Vec<Candidate> {
1055    let reg = type_registry();
1056    let class = indexes
1057        .iter()
1058        .flat_map(|ix| {
1059            ix.elements
1060                .iter()
1061                .filter(|e| e.mrid == id)
1062                .map(move |e| (ix, e))
1063        })
1064        .max_by_key(|(_, e)| e.id_kind == Some(IdKind::Id))
1065        .and_then(|(ix, e)| ix.class_of(&e.qname));
1066    let Some(attr) = class
1067        .and_then(|c| reg.attr(c, key))
1068        .filter(|a| a.kind == AttrKind::Association)
1069    else {
1070        return Vec::new();
1071    };
1072    // What the object names with its other fields.
1073    let own: HashSet<&str> = indexes
1074        .iter()
1075        .flat_map(|ix| ix.elements.iter().filter(|e| e.mrid == id))
1076        .flat_map(|e| {
1077            e.fields
1078                .iter()
1079                .filter(|f| f.key() != key)
1080                .filter_map(|f| f.resource.as_ref().map(|(t, _)| t.as_str()))
1081        })
1082        .filter(|t| !t.is_empty())
1083        .collect();
1084    let mut linked: HashSet<&str> = HashSet::new();
1085    let mut found: HashMap<&str, (Option<&str>, &'static str)> = HashMap::new();
1086    let mut named: HashMap<&str, Vec<&str>> = HashMap::new();
1087    for ix in indexes {
1088        for el in &ix.elements {
1089            let targets = || {
1090                el.fields
1091                    .iter()
1092                    .filter_map(|f| f.resource.as_ref().map(|(t, _)| t.as_str()))
1093            };
1094            if own.contains(el.mrid.as_str()) {
1095                linked.extend(targets());
1096            } else if targets().any(|t| own.contains(t)) {
1097                linked.insert(el.mrid.as_str());
1098            }
1099            for f in el.fields.iter().filter(|f| f.key() == key && el.mrid != id) {
1100                if let Some((target, _)) = &f.resource {
1101                    named
1102                        .entry(target.as_str())
1103                        .or_default()
1104                        .push(el.mrid.as_str());
1105                }
1106            }
1107            if el.mrid.is_empty() || el.mrid == id {
1108                continue;
1109            }
1110            let Some(c) = ix
1111                .class_of(&el.qname)
1112                .filter(|c| reg.chain(c).iter().any(|a| a.local == attr.range))
1113            else {
1114                continue;
1115            };
1116            let entry = found.entry(el.mrid.as_str()).or_insert((None, c.local));
1117            if entry.0.is_none() {
1118                entry.0 = el.name.as_deref().filter(|n| !n.is_empty());
1119            }
1120        }
1121    }
1122    let here = {
1123        let mut chain = tree.chain(id);
1124        chain.pop();
1125        chain
1126    };
1127    let shared = |chain: &[u32]| here.iter().zip(chain).take_while(|(a, b)| a == b).count();
1128    let mut ranked: Vec<(bool, usize, usize, String, &str, &'static str)> = found
1129        .into_iter()
1130        .map(|(c, (name, class))| {
1131            let by = named.get(c).map_or(&[][..], Vec::as_slice);
1132            let near = by.iter().map(|r| {
1133                let mut chain = tree.chain(r);
1134                chain.pop();
1135                shared(&chain)
1136            });
1137            let score = near
1138                .chain(std::iter::once(shared(&tree.chain(c))))
1139                .max()
1140                .unwrap_or(0);
1141            (
1142                linked.contains(c),
1143                score,
1144                by.len(),
1145                name.unwrap_or(c).to_string(),
1146                c,
1147                class,
1148            )
1149        })
1150        .collect();
1151    ranked.sort_by(|a, b| {
1152        b.0.cmp(&a.0)
1153            .then(b.1.cmp(&a.1))
1154            .then(b.2.cmp(&a.2))
1155            .then_with(|| a.3.to_lowercase().cmp(&b.3.to_lowercase()))
1156    });
1157    ranked
1158        .into_iter()
1159        .take(limit)
1160        .map(|(_, _, _, label, c, class)| Candidate {
1161            id: c.to_string(),
1162            label,
1163            class,
1164            place: tree.containers(c).join(" › "),
1165        })
1166        .collect()
1167}
1168
1169/// A class that can be added in an object, and the field naming it there.
1170pub struct Addable {
1171    pub class: &'static cimmodel::base::ClassDef,
1172    pub key: &'static str,
1173}
1174
1175/// The class of object `id` as the file defining it writes it.
1176fn class_in(files: &[File], id: &str) -> Option<&'static cimmodel::base::ClassDef> {
1177    let (file, el) = files
1178        .iter()
1179        .flat_map(|f| {
1180            f.index
1181                .elements
1182                .iter()
1183                .filter(|e| e.mrid == id)
1184                .map(move |e| (f, e))
1185        })
1186        .max_by_key(|(_, e)| e.id_kind == Some(IdKind::Id))?;
1187    file.index.class_of(&el.qname)
1188}
1189
1190/// The concrete classes of `parent`'s family whose objects the containment
1191/// puts in it: the first of [`CONTAINED`] they declare that
1192/// ranges over its class. Only classes of the profiles the set's files
1193/// declare (all, if none declares one).
1194pub fn addable(files: &[File], parent: &str) -> Vec<Addable> {
1195    let reg = type_registry();
1196    let Some(class) = class_in(files, parent) else {
1197        return Vec::new();
1198    };
1199    let Some(schema) = reg.family_of(class.qualified).and_then(|f| reg.schema(f)) else {
1200        return Vec::new();
1201    };
1202    let is = |range: &str| reg.chain(class).iter().any(|c| c.local == range);
1203    let declared: HashSet<&str> = files.iter().flat_map(profiles).collect();
1204    let mut out: Vec<Addable> = schema
1205        .classes
1206        .iter()
1207        .filter(|c| {
1208            c.concrete && (declared.is_empty() || c.origins.iter().any(|o| declared.contains(o)))
1209        })
1210        .filter_map(|c| {
1211            let key = CONTAINED.iter().find_map(|k| {
1212                reg.attr(c, k)
1213                    .filter(|a| a.used && a.kind == AttrKind::Association)
1214            })?;
1215            is(key.range).then_some(Addable {
1216                class: c,
1217                key: key.id,
1218            })
1219        })
1220        .collect();
1221    out.sort_by_key(|a| a.class.local);
1222    out
1223}
1224
1225/// A version 4 UUID from 16 random bytes, which the caller draws: the standard
1226/// library has no randomness on every target this runs on.
1227pub fn uuid(mut b: [u8; 16]) -> String {
1228    b[6] = (b[6] & 0x0f) | 0x40;
1229    b[8] = (b[8] & 0x3f) | 0x80;
1230    let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
1231    format!(
1232        "{}-{}-{}-{}-{}",
1233        &hex[..8],
1234        &hex[8..12],
1235        &hex[12..16],
1236        &hex[16..20],
1237        &hex[20..]
1238    )
1239}
1240
1241/// An object added: the edits, and where its name (else its start tag) is.
1242pub struct Added<'a> {
1243    pub edits: Edits<'a>,
1244    /// The file its element is in, by its name.
1245    pub file: String,
1246    pub select: Range,
1247    pub id: String,
1248}
1249
1250/// Add an object of `class` in `parent`, named `name` if given: an
1251/// `rdf:ID`, its mRID, name and the field naming `parent`, in the file
1252/// whose profile carries the class (the parent's own first), after the last
1253/// of the parent's objects there, else after the parent, else at the end;
1254/// and where the set has an SSH file and the class SSH attributes, an empty
1255/// `rdf:about` there for them. What else it needs, validation asks for. Its
1256/// mRID is `_` and a UUID from `random` ([`uuid`]), drawn again while the set
1257/// has it.
1258pub fn add<'a>(
1259    files: &[File<'a>],
1260    tree: &Tree,
1261    parent: &str,
1262    class: &str,
1263    name: Option<&str>,
1264    random: &mut dyn FnMut() -> [u8; 16],
1265) -> Result<Added<'a>, String> {
1266    let reg = type_registry();
1267    let found = addable(files, parent);
1268    let Addable { class, key } = found
1269        .into_iter()
1270        .find(|a| a.class.local == class)
1271        .ok_or_else(|| format!("a {class} cannot be added there"))?;
1272    let fits = |f: &File| {
1273        let declared = profiles(f);
1274        declared.is_empty() || declared.iter().any(|p| class.origins.contains(p))
1275    };
1276    let defines = |f: &File, id: &str| {
1277        f.index
1278            .elements
1279            .iter()
1280            .any(|e| e.mrid == id && e.id_kind == Some(IdKind::Id))
1281    };
1282    let main = files
1283        .iter()
1284        .filter(|f| fits(f) && !profiles(f).contains(&"SSH"))
1285        .max_by_key(|f| defines(f, parent))
1286        .ok_or_else(|| format!("no file of the model set has a profile for {}", class.local))?;
1287    let mut id = format!("_{}", uuid(random()));
1288    while files
1289        .iter()
1290        .any(|f| f.index.elements.iter().any(|e| e.mrid == id))
1291    {
1292        id = format!("_{}", uuid(random()));
1293    }
1294
1295    let prefix = |f: &File, ns: &str| f.index.prefix_of(ns).map(str::to_string);
1296    let tag = format!(
1297        "{}:{}",
1298        prefix(main, class.ns).ok_or("the file binds no prefix to the class's namespace")?,
1299        class.local
1300    );
1301    let field = |f: &File, key: &str| {
1302        reg.attr(class, key)
1303            .and_then(|a| Some((a, format!("{}:{}", prefix(f, a.ns)?, a.id))))
1304    };
1305    let carries = |f: &File, key: &str| {
1306        let declared = profiles(f);
1307        reg.attr(class, key)
1308            .is_some_and(|a| declared.is_empty() || a.origins.iter().any(|o| declared.contains(o)))
1309    };
1310    let mut lines = vec![format!("<{tag} rdf:ID=\"{id}\">")];
1311    let mut select_line = None;
1312    if carries(main, "IdentifiedObject.mRID")
1313        && let Some((_, t)) = field(main, "IdentifiedObject.mRID")
1314    {
1315        lines.push(format!("  <{t}>{}</{t}>", &id[1..]));
1316    }
1317    if let Some(name) = name.map(str::trim).filter(|n| !n.is_empty())
1318        && let Some((_, t)) = field(main, "IdentifiedObject.name")
1319    {
1320        select_line = Some((lines.len(), t.len() + 4, name.encode_utf16().count()));
1321        let escaped = name.replace('&', "&amp;").replace('<', "&lt;");
1322        lines.push(format!("  <{t}>{escaped}</{t}>"));
1323    }
1324    let (_, container) =
1325        field(main, key).ok_or("the file binds no prefix to the field's namespace")?;
1326    let target = if parent.contains(':') {
1327        parent.to_string()
1328    } else {
1329        format!("#{parent}")
1330    };
1331    lines.push(format!("  <{container} rdf:resource=\"{target}\" />"));
1332    lines.push(format!("</{tag}>"));
1333
1334    let mut changes: Edits<'a> = Vec::new();
1335    let (at, line_no) = insertion(main, tree, parent, &lines)?;
1336    let select = match select_line {
1337        Some((l, col, len)) => {
1338            let start = Position::new(line_no + l as u32, at.1 + col as u32);
1339            Range::new(
1340                start,
1341                Position::new(start.line, start.character + len as u32),
1342            )
1343        }
1344        None => Range::new(Position::new(line_no, at.1), Position::new(line_no, at.1)),
1345    };
1346    changes.push((main.name, vec![at.0]));
1347    // Its steady-state part.
1348    if class.origins.contains(&"SSH")
1349        && let Some(ssh) = files.iter().find(|f| profiles(f).contains(&"SSH"))
1350        && let Some(p) = prefix(ssh, class.ns)
1351    {
1352        let tag = format!("{p}:{}", class.local);
1353        let ssh_lines = vec![format!("<{tag} rdf:about=\"#{id}\">"), format!("</{tag}>")];
1354        let (edit, _) = insertion(ssh, tree, parent, &ssh_lines)?;
1355        changes.push((ssh.name, vec![edit.0]));
1356    }
1357    Ok(Added {
1358        edits: changes,
1359        file: main.name.to_string(),
1360        select,
1361        id,
1362    })
1363}
1364
1365/// Where to insert `lines` (an element, unindented) in `file`: after the
1366/// last element there of an object `parent` holds, else after `parent`'s,
1367/// else before the root's end tag; indented as the elements are, in the
1368/// file's line endings. The edit with the indent's width, and the line the
1369/// element starts on.
1370pub(crate) fn insertion(
1371    file: &File,
1372    tree: &Tree,
1373    parent: &str,
1374    lines: &[String],
1375) -> Result<((TextEdit, u32), u32), String> {
1376    let (text, li) = (file.text, file.lines);
1377    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
1378    let siblings: HashSet<&str> = tree.children(parent).into_iter().collect();
1379    let anchor = file
1380        .index
1381        .elements
1382        .iter()
1383        .rev()
1384        .find(|e| siblings.contains(e.mrid.as_str()))
1385        .or_else(|| file.index.elements.iter().rev().find(|e| e.mrid == parent));
1386    let (offset, indent) = match anchor {
1387        Some(el) => {
1388            let end = li.offset(text, el.full.end);
1389            let line_end = text[end..].find('\n').map_or(text.len(), |i| end + i + 1);
1390            let head = li.offset(text, el.head.start);
1391            let line_start = text[..head].rfind('\n').map_or(0, |i| i + 1);
1392            (line_end, text[line_start..head].to_string())
1393        }
1394        None => {
1395            let root_end = text.rfind("</").ok_or("the file has no root end tag")?;
1396            let line_start = text[..root_end].rfind('\n').map_or(0, |i| i + 1);
1397            let indent = file.index.elements.last().map_or("  ".to_string(), |el| {
1398                let head = li.offset(text, el.head.start);
1399                text[text[..head].rfind('\n').map_or(0, |i| i + 1)..head].to_string()
1400            });
1401            (line_start, indent)
1402        }
1403    };
1404    // An anchor ending the file without a newline: start a line first.
1405    let lead = if offset == text.len() && !text.ends_with('\n') {
1406        eol
1407    } else {
1408        ""
1409    };
1410    let body: String = lines.iter().map(|l| format!("{indent}{l}{eol}")).collect();
1411    let at = li.position(text, offset);
1412    let first = if lead.is_empty() {
1413        at.line
1414    } else {
1415        at.line + 1
1416    };
1417    Ok((
1418        (
1419            TextEdit::new(Range::new(at, at), format!("{lead}{body}")),
1420            indent.encode_utf16().count() as u32,
1421        ),
1422        first,
1423    ))
1424}
1425
1426/// A fix for a reference to nothing (`rdf:resource="#"`) or to an object the
1427/// set lacks: name one of the likeliest objects instead.
1428pub struct ReferenceFix {
1429    pub key: String,
1430    /// The file it is in, by its name.
1431    pub file: String,
1432    pub edit: TextEdit,
1433    pub title: String,
1434    /// It names nothing; else something the set does not have.
1435    pub empty: bool,
1436}
1437
1438/// The fixes for object `id`'s references to nothing or to objects the set
1439/// lacks, in every file that writes it, or only the field at `at`: each the
1440/// five likeliest objects ([`candidates`]); `at` names a file and a place in
1441/// it. An enumeration value is not a reference to an object, so it has none.
1442pub fn reference_fixes(
1443    files: &[File],
1444    tree: &Tree,
1445    id: &str,
1446    at: Option<(&str, Position)>,
1447) -> Vec<ReferenceFix> {
1448    let sites: Vec<(&File, &crate::index::Field, &str, Range)> = files
1449        .iter()
1450        .filter(|f| at.is_none_or(|(n, _)| f.name == n))
1451        .flat_map(|f| {
1452            f.index
1453                .elements
1454                .iter()
1455                .filter(|e| e.mrid == id)
1456                .map(move |e| (f, e))
1457        })
1458        .flat_map(|(f, e)| e.fields.iter().map(move |x| (f, x)))
1459        .filter(|(_, x)| at.is_none_or(|(_, pos)| contains(x.full, pos)))
1460        .filter_map(|(f, x)| x.resource.as_ref().map(|(t, r)| (f, x, t.as_str(), *r)))
1461        .collect();
1462    if sites.is_empty() {
1463        return Vec::new();
1464    }
1465    let known: HashSet<&str> = files
1466        .iter()
1467        .flat_map(|f| f.index.elements.iter().map(|e| e.mrid.as_str()))
1468        .collect();
1469    let indexes: Vec<&Index> = files.iter().map(|f| f.index).collect();
1470    let mut out = Vec::new();
1471    for (file, field, target, value) in sites {
1472        if !target.is_empty() && known.contains(target) {
1473            continue;
1474        }
1475        for c in candidates(&indexes, tree, id, field.key(), 5) {
1476            let place = if c.place.is_empty() {
1477                String::new()
1478            } else {
1479                format!(" in {}", c.place)
1480            };
1481            out.push(ReferenceFix {
1482                key: field.key().to_string(),
1483                file: file.name.to_string(),
1484                edit: TextEdit::new(value, c.reference()),
1485                title: format!("Set {} to {} {}{place}", field.key(), c.class, c.label),
1486                empty: target.is_empty(),
1487            });
1488        }
1489    }
1490    out
1491}
1492
1493/// The objects that refer to object `id`, and by which field, as the files
1494/// write them: (referrer, field), each once.
1495pub fn referrers<'a>(files: &[File<'a>], id: &str) -> Vec<(&'a str, &'a str)> {
1496    let mut out: Vec<(&str, &str)> = files
1497        .iter()
1498        .flat_map(|f| f.index.elements.iter())
1499        .flat_map(|e| {
1500            e.fields
1501                .iter()
1502                .filter(|x| x.resource.as_ref().is_some_and(|(t, _)| t == id))
1503                .map(move |x| (e.mrid.as_str(), x.key()))
1504        })
1505        .filter(|(r, _)| !r.is_empty() && *r != id)
1506        .collect();
1507    out.sort_unstable();
1508    out.dedup();
1509    out
1510}
1511
1512/// How an object is named in a title: its class and name, else mRID.
1513pub fn describe(files: &[File], id: &str) -> String {
1514    let el = files
1515        .iter()
1516        .flat_map(|f| &f.index.elements)
1517        .filter(|e| e.mrid == id)
1518        .max_by_key(|e| e.id_kind == Some(IdKind::Id));
1519    match el {
1520        Some(el) => format!(
1521            "{} {}",
1522            local(&el.qname),
1523            el.name.as_deref().filter(|n| !n.is_empty()).unwrap_or(id)
1524        ),
1525        None => id.to_string(),
1526    }
1527}
1528
1529#[cfg(test)]
1530mod tests {
1531    use super::*;
1532
1533    fn micro_grid() -> std::path::PathBuf {
1534        std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1535            .join("../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged")
1536    }
1537
1538    #[test]
1539    fn a_uuid_is_version_4() {
1540        let id = uuid([0xff; 16]);
1541        assert_eq!(id.len(), 36);
1542        assert_eq!(&id[14..15], "4");
1543        assert!(matches!(&id[19..20], "8" | "9" | "a" | "b"), "{id}");
1544    }
1545
1546    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#">
1547  <cim:Breaker rdf:ID="_b1">
1548    <cim:IdentifiedObject.mRID>b1</cim:IdentifiedObject.mRID>
1549    <cim:IdentifiedObject.name>B1</cim:IdentifiedObject.name>
1550  </cim:Breaker>
1551  <cim:Terminal rdf:ID="_t1">
1552    <cim:Terminal.ConductingEquipment rdf:resource="#_b1" />
1553    <cim:IdentifiedObject.name>T1</cim:IdentifiedObject.name>
1554  </cim:Terminal>
1555</rdf:RDF>"##;
1556    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#">
1557  <cim:Breaker rdf:about="#_b1">
1558    <cim:Switch.open>false</cim:Switch.open>
1559  </cim:Breaker>
1560</rdf:RDF>"##;
1561
1562    fn apply(text: &str, edits: Vec<TextEdit>) -> String {
1563        crate::text::apply(text, &edits)
1564    }
1565
1566    /// The edits of the file `name`.
1567    fn of<'a>(edits: &Edits<'a>, name: &str) -> Vec<TextEdit> {
1568        edits
1569            .iter()
1570            .find(|(n, _)| *n == name)
1571            .map(|(_, e)| e.clone())
1572            .unwrap_or_default()
1573    }
1574
1575    fn with_files<R>(f: impl FnOnce(&[File]) -> R) -> R {
1576        let names = ["EQ.xml", "SSH.xml"];
1577        let texts = [EQ, SSH];
1578        let lines: Vec<LineIndex> = texts.iter().map(|t| LineIndex::new(t)).collect();
1579        let indexes: Vec<Index> = texts.iter().map(|t| Index::build(t)).collect();
1580        let files: Vec<File> = (0..2)
1581            .map(|i| File {
1582                name: names[i],
1583                text: texts[i],
1584                lines: &lines[i],
1585                index: &indexes[i],
1586            })
1587            .collect();
1588        f(&files)
1589    }
1590
1591    #[test]
1592    fn renames_an_mrid_everywhere() {
1593        with_files(|files| {
1594            // On the reference, and on the start tag.
1595            let (r, old) = prepare_rename(files, "EQ.xml", Position::new(6, 55)).unwrap();
1596            assert_eq!(
1597                (old.as_str(), r),
1598                (
1599                    "_b1",
1600                    Range::new(Position::new(6, 53), Position::new(6, 56))
1601                )
1602            );
1603            assert_eq!(
1604                prepare_rename(files, "SSH.xml", Position::new(1, 4))
1605                    .unwrap()
1606                    .1,
1607                "_b1"
1608            );
1609            assert!(prepare_rename(files, "EQ.xml", Position::new(2, 10)).is_none());
1610
1611            let changes = rename(files, "_b1", "_b2").unwrap();
1612            let eq = apply(EQ, of(&changes, "EQ.xml"));
1613            assert!(
1614                eq.contains(r#"rdf:ID="_b2""#)
1615                    && eq.contains(">b2</")
1616                    && eq.contains(r##"rdf:resource="#_b2""##),
1617                "{eq}"
1618            );
1619            assert!(!eq.contains("b1"), "{eq}");
1620            assert_eq!(
1621                apply(SSH, of(&changes, "SSH.xml")),
1622                SSH.replace("#_b1", "#_b2")
1623            );
1624
1625            assert!(rename(files, "_b1", "_t1").is_err());
1626            assert!(rename(files, "_b1", "a b").is_err());
1627            assert!(rename(files, "_b1", "1b").is_err());
1628        });
1629    }
1630
1631    #[test]
1632    fn adds_a_missing_field_where_its_profile_is() {
1633        let header = |p: &str| {
1634            format!(
1635                r#"  <md:FullModel rdf:about="urn:uuid:{p}">
1636    <md:Model.profile>http://iec.ch/TC57/ns/CIM/{p}/3.0</md:Model.profile>
1637  </md:FullModel>
1638"#
1639            )
1640        };
1641        let with_header = |text: &str, p: &str| {
1642            text.replacen(
1643                r#"xmlns:rdf"#,
1644                r#"xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#" xmlns:rdf"#,
1645                1,
1646            )
1647            .replacen(">\n", &format!(">\n{}", header(p)), 1)
1648        };
1649        let texts = [
1650            with_header(EQ, "CoreEquipment-EU"),
1651            with_header(SSH, "SteadyStateHypothesis-EU"),
1652        ];
1653        let names = ["EQ.xml", "SSH.xml"];
1654        let lines: Vec<LineIndex> = texts.iter().map(|t| LineIndex::new(t)).collect();
1655        let indexes: Vec<Index> = texts.iter().map(|t| Index::build(t)).collect();
1656        let files: Vec<File> = (0..2)
1657            .map(|i| File {
1658                name: names[i],
1659                text: &texts[i],
1660                lines: &lines[i],
1661                index: &indexes[i],
1662            })
1663            .collect();
1664        let added = |id: &str, key: &str| {
1665            let a = add_missing(&files, names[0], id, key)?;
1666            let i = names.iter().position(|n| *n == a.file).unwrap();
1667            let out = apply(&texts[i], vec![a.edit.clone()]);
1668            let selected = apply(&out, vec![TextEdit::new(a.value, "|".into())]);
1669            Some((i, out, selected))
1670        };
1671
1672        // An SSH attribute goes to the SSH file, though asked from the EQ one.
1673        let (i, out, selected) = added("_b1", "Equipment.inService").unwrap();
1674        assert_eq!(i, 1);
1675        assert!(out.contains("<cim:Switch.open>false</cim:Switch.open>\n    <cim:Equipment.inService>false</cim:Equipment.inService>\n  </cim:Breaker>"), "{out}");
1676        assert!(
1677            selected.contains("<cim:Equipment.inService>|</cim:Equipment.inService>"),
1678            "{selected}"
1679        );
1680        // An EQ one to the EQ file; a reference left to fill in, an enumeration its first value.
1681        let (i, _, selected) = added("_t1", "Terminal.ConnectivityNode").unwrap();
1682        assert_eq!(i, 0);
1683        assert!(
1684            selected.contains(r##"<cim:Terminal.ConnectivityNode rdf:resource="#|" />"##),
1685            "{selected}"
1686        );
1687        let (_, out, _) = added("_t1", "Terminal.phases").unwrap();
1688        assert!(
1689            out.contains(
1690                r#"<cim:Terminal.phases rdf:resource="http://iec.ch/TC57/CIM100#PhaseCode."#
1691            ),
1692            "{out}"
1693        );
1694        // Written already, or not the class's.
1695        assert!(added("_b1", "Switch.open").is_none());
1696        assert!(added("_b1", "ACLineSegment.r").is_none());
1697    }
1698
1699    #[test]
1700    fn sets_and_removes_a_field_wherever_it_is_written() {
1701        with_files(|files| {
1702            // A literal, escaped; written in the SSH file.
1703            let set = set_field(files, "EQ.xml", "_b1", "Switch.open", "true").unwrap();
1704            assert_eq!(
1705                apply(SSH, of(&set, "SSH.xml")),
1706                SSH.replace(">false<", ">true<")
1707            );
1708            let named =
1709                set_field(files, "EQ.xml", "_b1", "IdentifiedObject.name", "B & 1").unwrap();
1710            assert!(
1711                apply(EQ, of(&named, "EQ.xml"))
1712                    .contains("<cim:IdentifiedObject.name>B &amp; 1</cim:IdentifiedObject.name>")
1713            );
1714            // A reference, to an mRID.
1715            let to = set_field(
1716                files,
1717                "EQ.xml",
1718                "_t1",
1719                "Terminal.ConductingEquipment",
1720                "_b2",
1721            )
1722            .unwrap();
1723            assert!(
1724                apply(EQ, of(&to, "EQ.xml"))
1725                    .contains(r##"<cim:Terminal.ConductingEquipment rdf:resource="#_b2" />"##)
1726            );
1727            // Written nowhere: added, with the value given.
1728            let added = set_field(files, "EQ.xml", "_t1", "Terminal.phases", "ABC").unwrap();
1729            assert!(apply(EQ, of(&added, "EQ.xml")).contains(
1730                r#"<cim:Terminal.phases rdf:resource="http://iec.ch/TC57/CIM100#PhaseCode.ABC" />"#
1731            ));
1732            assert!(set_field(files, "EQ.xml", "_b1", "ACLineSegment.r", "1").is_err());
1733
1734            let removed = remove_field(files, "_t1", "Terminal.ConductingEquipment");
1735            let eq = apply(EQ, of(&removed, "EQ.xml"));
1736            assert!(
1737                !eq.contains("ConductingEquipment")
1738                    && eq.contains(
1739                        "<cim:Terminal rdf:ID=\"_t1\">\n    <cim:IdentifiedObject.name>T1"
1740                    ),
1741                "{eq}"
1742            );
1743        });
1744    }
1745
1746    fn counting() -> impl FnMut() -> [u8; 16] {
1747        let mut n = 0u8;
1748        move || {
1749            n += 1;
1750            [n; 16]
1751        }
1752    }
1753
1754    #[test]
1755    fn copies_objects_with_new_mrids_and_their_references_among_them() {
1756        with_files(|files| {
1757            let mut random = counting();
1758            let copied = copy(files, &["_b1", "_t1"], None, None, &mut random).unwrap();
1759            let (b2, t2) = (format!("_{}", uuid([1; 16])), format!("_{}", uuid([2; 16])));
1760            assert_eq!(
1761                copied.ids,
1762                [
1763                    ("_b1".to_string(), b2.clone()),
1764                    ("_t1".to_string(), t2.clone())
1765                ]
1766            );
1767            let eq = apply(EQ, of(&copied.edits, "EQ.xml"));
1768            // The originals stay; the copies follow them, naming each other.
1769            assert!(
1770                eq.contains(r#"<cim:Breaker rdf:ID="_b1">"#)
1771                    && eq.contains(&format!(r#"<cim:Breaker rdf:ID="{b2}">"#)),
1772                "{eq}"
1773            );
1774            assert!(
1775                eq.contains(&format!(
1776                    "<cim:IdentifiedObject.mRID>{}</cim:IdentifiedObject.mRID>",
1777                    &b2[1..]
1778                )),
1779                "{eq}"
1780            );
1781            assert!(
1782                eq.contains(&format!(
1783                    r##"<cim:Terminal.ConductingEquipment rdf:resource="#{b2}" />"##
1784                )),
1785                "{eq}"
1786            );
1787            assert_eq!(eq.matches(r##"rdf:resource="#_b1""##).count(), 1);
1788            let ssh = apply(SSH, of(&copied.edits, "SSH.xml"));
1789            assert!(
1790                ssh.contains(&format!(r##"<cim:Breaker rdf:about="#{b2}">"##)),
1791                "{ssh}"
1792            );
1793            // Only the terminal: its reference to the breaker stays.
1794            let alone = copy(files, &["_t1"], None, None, &mut random).unwrap();
1795            assert_eq!(
1796                apply(EQ, of(&alone.edits, "EQ.xml"))
1797                    .matches(r##"rdf:resource="#_b1""##)
1798                    .count(),
1799                2
1800            );
1801            // From one file, into another: the breaker's SSH part is not copied.
1802            let only = copy(files, &["_b1"], Some("EQ.xml"), None, &mut random).unwrap();
1803            assert_eq!(only.edits.len(), 1, "EQ only");
1804            let moved = copy(files, &["_t1"], None, Some("SSH.xml"), &mut random).unwrap();
1805            let ssh = apply(SSH, of(&moved.edits, "SSH.xml"));
1806            assert!(
1807                ssh.contains(&format!(r#"<cim:Terminal rdf:ID="{}">"#, moved.ids[0].1))
1808                    && ssh.ends_with("</rdf:RDF>"),
1809                "{ssh}"
1810            );
1811            assert!(copy(files, &["_nothing"], None, None, &mut random).is_err());
1812            assert!(copy(files, &["_t1"], Some("SSH.xml"), None, &mut random).is_err());
1813        });
1814    }
1815
1816    #[test]
1817    fn creates_an_object_of_any_class_with_its_values() {
1818        with_files(|files| {
1819            let created = create(
1820                files,
1821                "EQ.xml",
1822                "Breaker",
1823                &[
1824                    ("IdentifiedObject.name", "B9"),
1825                    ("Switch.normalOpen", "true"),
1826                ],
1827                &mut counting(),
1828            )
1829            .unwrap();
1830            let eq = apply(EQ, of(&created.edits, "EQ.xml"));
1831            let id = &created.id;
1832            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}");
1833            assert!(create(files, "EQ.xml", "NoSuchClass", &[], &mut counting()).is_err());
1834            assert!(
1835                create(
1836                    files,
1837                    "EQ.xml",
1838                    "Breaker",
1839                    &[("ACLineSegment.r", "1")],
1840                    &mut counting()
1841                )
1842                .is_err()
1843            );
1844        });
1845    }
1846
1847    #[test]
1848    fn lists_what_refers_to_an_object() {
1849        with_files(|files| {
1850            assert_eq!(
1851                referrers(files, "_b1"),
1852                [("_t1", "Terminal.ConductingEquipment")]
1853            );
1854            assert!(referrers(files, "_t1").is_empty());
1855        });
1856    }
1857
1858    #[test]
1859    fn deletes_an_object_from_every_file() {
1860        with_files(|files| {
1861            let d = delete(files, &HashSet::from(["_b1"]));
1862            assert_eq!((d.objects, d.references), (1, 1));
1863            let eq = apply(EQ, of(&d.edits, "EQ.xml"));
1864            assert!(
1865                !eq.contains("Breaker")
1866                    && !eq.contains("ConductingEquipment")
1867                    && eq.contains(
1868                        "<cim:Terminal rdf:ID=\"_t1\">\n    <cim:IdentifiedObject.name>T1"
1869                    ),
1870                "{eq}"
1871            );
1872            assert!(!apply(SSH, of(&d.edits, "SSH.xml")).contains("Breaker"));
1873        });
1874    }
1875
1876    /// On MicroGrid, the object each reference names is among the
1877    /// candidates offered for it, mostly first.
1878    #[test]
1879    fn candidates_rank_what_the_data_names() {
1880        let read = crate::testing::collect(&micro_grid());
1881        let set = crate::testing::validate(&read);
1882        let built: Vec<Index> = read.iter().map(|(_, t)| Index::build(t)).collect();
1883        let indexes: Vec<&Index> = built.iter().collect();
1884        let mut stats: HashMap<&str, (usize, usize, usize)> = HashMap::new();
1885        for ix in &indexes {
1886            for el in &ix.elements {
1887                for f in &el.fields {
1888                    let key = f.key();
1889                    let Some((target, _)) = &f.resource else {
1890                        continue;
1891                    };
1892                    // Not the containment's own fields: the object is where they put it.
1893                    if ![
1894                        "ConductingEquipment.BaseVoltage",
1895                        "Terminal.ConnectivityNode",
1896                        "Terminal.TopologicalNode",
1897                        "RegulatingControl.Terminal",
1898                    ]
1899                    .contains(&key)
1900                    {
1901                        continue;
1902                    }
1903                    let c = candidates(&indexes, &set.tree, &el.mrid, key, 5);
1904                    let s = stats.entry(key).or_default();
1905                    s.0 += 1;
1906                    if c.first().is_some_and(|c| c.id == *target) {
1907                        s.1 += 1
1908                    }
1909                    if c.iter().any(|c| c.id == *target) {
1910                        s.2 += 1
1911                    }
1912                }
1913            }
1914        }
1915        for (key, (n, first, top5)) in &stats {
1916            eprintln!("{key}: {n} references, first {first}, top 5 {top5}");
1917        }
1918        // Linked through the topological node: always first. A base voltage:
1919        // a line's, among its sub-region's, not always.
1920        assert_eq!(stats["Terminal.ConnectivityNode"], (73, 73, 73));
1921        assert_eq!(stats["Terminal.TopologicalNode"], (73, 73, 73));
1922        assert_eq!(stats["RegulatingControl.Terminal"], (7, 7, 7));
1923        assert_eq!(stats["ConductingEquipment.BaseVoltage"], (23, 20, 23));
1924    }
1925
1926    /// On MicroGrid: what a voltage level and a transformer can hold; a breaker
1927    /// added in a voltage level, in EQ with an SSH part, which validates
1928    /// with findings for what it lacks and sits in the voltage level.
1929    #[test]
1930    fn adds_an_object_in_a_container() {
1931        let read = crate::testing::collect(&micro_grid());
1932        let set = crate::testing::validate(&read);
1933        let names: Vec<String> = read
1934            .iter()
1935            .map(|(p, _)| p.to_string_lossy().into_owned())
1936            .collect();
1937        let lines: Vec<LineIndex> = read.iter().map(|(_, t)| LineIndex::new(t)).collect();
1938        let indexes: Vec<Index> = read.iter().map(|(_, t)| Index::build(t)).collect();
1939        let files: Vec<File> = (0..read.len())
1940            .map(|i| File {
1941                name: &names[i],
1942                text: &read[i].1,
1943                lines: &lines[i],
1944                index: &indexes[i],
1945            })
1946            .collect();
1947        let find = |class: &str, name: &str| {
1948            indexes
1949                .iter()
1950                .flat_map(|ix| &ix.elements)
1951                .find(|e| local(&e.qname) == class && e.name.as_deref() == Some(name))
1952                .unwrap()
1953                .mrid
1954                .clone()
1955        };
1956        let vl = find("VoltageLevel", "110.0");
1957        let classes: Vec<&str> = addable(&files, &vl).iter().map(|a| a.class.local).collect();
1958        for c in [
1959            "Breaker",
1960            "Bay",
1961            "ConnectivityNode",
1962            "LinearShuntCompensator",
1963        ] {
1964            assert!(classes.contains(&c), "{classes:?}");
1965        }
1966        assert!(!classes.contains(&"Terminal"), "{classes:?}");
1967        let transformer = find("PowerTransformer", "BE-TR2_1");
1968        let classes: Vec<&str> = addable(&files, &transformer)
1969            .iter()
1970            .map(|a| a.class.local)
1971            .collect();
1972        assert!(
1973            classes.contains(&"Terminal") && classes.contains(&"PowerTransformerEnd"),
1974            "{classes:?}"
1975        );
1976
1977        let mut draws = 0u8;
1978        let mut random = || {
1979            draws += 1;
1980            [draws; 16]
1981        };
1982        let added = add(
1983            &files,
1984            &set.tree,
1985            &vl,
1986            "Breaker",
1987            Some("B-new"),
1988            &mut random,
1989        )
1990        .unwrap();
1991        assert_eq!(added.edits.len(), 2, "EQ and SSH");
1992        assert_eq!(added.id, format!("_{}", uuid([1; 16])));
1993        let edited: Vec<(std::path::PathBuf, std::sync::Arc<str>)> = read
1994            .iter()
1995            .enumerate()
1996            .map(|(i, (p, t))| {
1997                let e = of(&added.edits, &names[i]);
1998                (
1999                    p.clone(),
2000                    std::sync::Arc::from(if e.is_empty() {
2001                        t.to_string()
2002                    } else {
2003                        apply(t, e)
2004                    }),
2005                )
2006            })
2007            .collect();
2008        let main = names.iter().position(|n| *n == added.file).unwrap();
2009        assert!(edited[main].0.to_string_lossy().contains("_EQ_"));
2010        let text = &edited[main].1;
2011        let selected = apply(text, vec![TextEdit::new(added.select, "|".into())]);
2012        assert!(
2013            selected.contains("<cim:IdentifiedObject.name>|</cim:IdentifiedObject.name>"),
2014            "the name is selected"
2015        );
2016
2017        let set2 = crate::testing::validate(&edited);
2018        assert_eq!(set2.tree.containers(&added.id), ["PP_Brussels", "110.0"]);
2019        let ssh = edited
2020            .iter()
2021            .find(|(p, _)| p.to_string_lossy().contains("_BE_SSH_"))
2022            .unwrap();
2023        assert!(ssh.1.contains(&format!("rdf:about=\"#{}\"", added.id)));
2024    }
2025
2026    /// A DL file beside MicroGrid's EQ: its namespaces, a header of its own
2027    /// dependent on EQ's, and room for a diagram, which validates.
2028    #[test]
2029    fn a_companion_file_takes_a_diagram() {
2030        let read = crate::testing::collect(&micro_grid());
2031        let names: Vec<String> = read
2032            .iter()
2033            .map(|(p, _)| p.to_string_lossy().into_owned())
2034            .collect();
2035        let at = names.iter().position(|n| n.contains("_BE_EQ_")).unwrap();
2036        let (lines, index) = (LineIndex::new(&read[at].1), Index::build(&read[at].1));
2037        let eq = File {
2038            name: &names[at],
2039            text: &read[at].1,
2040            lines: &lines,
2041            index: &index,
2042        };
2043        let text = companion(&eq, "DL", "0d1e2f30-0000-4000-8000-000000000000").unwrap();
2044        assert!(text.contains("<md:Model.profile>http://iec.ch/TC57/ns/CIM/DiagramLayout-EU/3.0</md:Model.profile>"), "{text}");
2045        assert!(
2046            text.contains(&format!(
2047                "<md:Model.DependentOn rdf:resource=\"{}\" />",
2048                index.elements[0].mrid
2049            )),
2050            "{text}"
2051        );
2052        assert!(!text.contains("CoreEquipment"), "{text}");
2053        let (dl_lines, dl_index) = (LineIndex::new(&text), Index::build(&text));
2054        let dl = File {
2055            name: "new_DL.xml",
2056            text: &text,
2057            lines: &dl_lines,
2058            index: &dl_index,
2059        };
2060        let mut counter = 0u8;
2061        let mut random = || {
2062            counter += 1;
2063            [counter; 16]
2064        };
2065        let breaker = index
2066            .elements
2067            .iter()
2068            .find(|e| local(&e.qname) == "Breaker")
2069            .map(|e| e.mrid.clone());
2070        let shown = breaker.as_deref().unwrap_or("_x");
2071        let added = diagram(
2072            &[dl],
2073            "new_DL.xml",
2074            None,
2075            "One",
2076            &[(shown, "B", vec![(1.0, 2.5)])],
2077            &mut random,
2078        )
2079        .unwrap();
2080        let written = crate::text::apply(&text, &added.edits[0].1);
2081        assert!(
2082            written
2083                .contains("<cim:DiagramObjectPoint.xPosition>1</cim:DiagramObjectPoint.xPosition>"),
2084            "{written}"
2085        );
2086        assert!(
2087            written.contains(
2088                "<cim:DiagramObjectPoint.yPosition>2.5</cim:DiagramObjectPoint.yPosition>"
2089            ),
2090            "{written}"
2091        );
2092        assert!(written.contains("OrientationKind.negative"), "{written}");
2093        cimmodel::CimDataset::decode_str(&written).unwrap();
2094    }
2095}