Skip to main content

viva_genapi/
persistence.rs

1//! Saving a camera's configuration and restoring it: GenICam's `<Streamable>`
2//! features (ADR-0028).
3//!
4//! GenICam Standard v2.1.1 §2.8.1 marks a feature `<Streamable>` when it "is
5//! prepared to be stored to and loaded from a file via the GenApi node tree.
6//! The idea is to persist the state of a camera by storing the features marked
7//! as Streamable and restore the state by writing those features back to the
8//! node tree." This module is that idea, in three parts:
9//!
10//! - [`NodeMap::persistence_plan`] decides from the XML alone which features a
11//!   configuration holds, which selectors each is saved under, and the order a
12//!   restore writes them in;
13//! - [`NodeMap::save_configuration`] reads them from the device into a
14//!   [`Configuration`], and [`NodeMap::load_configuration`] writes one back,
15//!   reporting every value it could not write;
16//! - [`Configuration::to_text`] and [`Configuration::parse`] are the file
17//!   format: the text format of GenApi's reference implementation
18//!   (`CFeatureBag`), chosen in ADR-0028.
19//!
20//! Nothing here touches a file or a socket, so it builds for wasm.
21
22use std::cmp::Reverse;
23use std::collections::{BTreeSet, BinaryHeap, HashMap, HashSet};
24use std::fmt;
25
26use tracing::{debug, warn};
27use viva_genapi_xml::{AccessMode, DocumentIdentity};
28
29use crate::nodemap::Limit;
30use crate::nodes::Node;
31use crate::text::{bytes_to_hex, hex_to_bytes};
32use crate::{GenApiError, NodeMap, RegisterIo};
33
34/// The first line of every file: the magic GUID that GenApi's reference
35/// implementation (`Persistence.h`, `GENAPI_PERSISTENCE_MAGIC`) writes and
36/// requires.
37pub const FILE_MAGIC: &str = "{05D8C294-F295-4dfb-9D01-096BD04049F4}";
38
39/// The magic of the reference implementation's *other* format,
40/// `CFeatureBagger`, which this module does not read.
41const BAGGER_MAGIC: &str = "{4709CB3C-7322-4460-84C3-DA11DDA09939}";
42
43/// How many values one feature may be saved under, counting every
44/// combination of its selectors' entries. A bound, so that a save always ends:
45/// an integer selector may declare no useful maximum.
46pub const MAX_SELECTOR_COMBINATIONS: usize = 65_536;
47
48/// One feature as a configuration holds it.
49#[derive(Debug, Clone, PartialEq, Eq)]
50#[non_exhaustive]
51pub struct PlannedFeature {
52    /// The feature.
53    pub name: String,
54    /// The selectors whose entries the feature is saved under, outermost
55    /// first: a selector that selects another comes before it. Empty for a
56    /// feature no selector selects.
57    pub selectors: Vec<String>,
58    /// The features in the plan that a restore writes before this one,
59    /// because writing them can change this one: its selector, the provider
60    /// of its `pIsAvailable`/`pIsLocked`, a feature its bounds or address are
61    /// computed from. Features that depend on each other in a cycle — `Width`
62    /// and `OffsetX` bound each other — keep document order between them.
63    pub after: Vec<String>,
64}
65
66/// What a configuration holds and the order a restore writes it in, decided
67/// from the XML alone. See [`NodeMap::persistence_plan`].
68#[derive(Debug, Clone, Default, PartialEq, Eq)]
69pub struct PersistencePlan {
70    features: Vec<PlannedFeature>,
71}
72
73impl PersistencePlan {
74    /// The streamable features, in restore order.
75    pub fn features(&self) -> &[PlannedFeature] {
76        &self.features
77    }
78
79    /// Where `name` comes in the restore order, if the plan holds it.
80    pub fn position(&self, name: &str) -> Option<usize> {
81        self.features.iter().position(|f| f.name == name)
82    }
83}
84
85/// One value of a configuration.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct SavedValue {
88    /// The feature.
89    pub feature: String,
90    /// The selector entries the value belongs to, outermost first, as
91    /// `(selector, entry)`; empty for a feature no selector selects.
92    pub selectors: Vec<(String, String)>,
93    /// The value as text: an integer in decimal, a float in the shortest form
94    /// that reads back to the same value, an enumeration entry by name, a
95    /// boolean as `1`/`0`, a register as `0x` and hexadecimal bytes.
96    pub value: String,
97}
98
99/// A feature a save left out, and why.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct Omission {
102    /// The feature.
103    pub feature: String,
104    /// The selector entries, when only some of the feature's values were
105    /// left out.
106    pub selectors: Vec<(String, String)>,
107    /// Why: "not available", "locked by ExposureAuto", ...
108    pub reason: String,
109}
110
111/// A camera configuration: the streamable features' values, and the camera
112/// they were read from.
113#[derive(Debug, Clone, Default, PartialEq, Eq)]
114pub struct Configuration {
115    /// The camera the configuration was saved from, as its XML names it.
116    /// Empty fields when a file does not say.
117    pub identity: DocumentIdentity,
118    /// The values, in the order a restore writes them.
119    pub values: Vec<SavedValue>,
120    /// What a save left out. Written to a file as comments, so a reader sees
121    /// why a feature is missing; not read back.
122    pub omitted: Vec<Omission>,
123}
124
125/// A configuration file that could not be read.
126#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
127#[error("line {line}: {message}")]
128#[non_exhaustive]
129pub struct ParseConfigurationError {
130    /// 1-based line number.
131    pub line: usize,
132    /// What was wrong with it.
133    pub message: &'static str,
134}
135
136/// A value [`NodeMap::load_configuration`] could not write.
137#[derive(Debug)]
138#[non_exhaustive]
139pub struct LoadFailure {
140    /// The value, as the configuration holds it.
141    pub value: SavedValue,
142    /// Why the write failed, after the second pass.
143    pub error: GenApiError,
144}
145
146/// What [`NodeMap::load_configuration`] did.
147#[derive(Debug, Default)]
148#[non_exhaustive]
149pub struct LoadReport {
150    /// Values written.
151    pub written: usize,
152    /// Of [`LoadReport::written`], those written only on the second pass,
153    /// once the values they depend on were in place.
154    pub written_on_retry: usize,
155    /// Values that could not be written, each with its reason.
156    pub failures: Vec<LoadFailure>,
157    /// Doubts about the configuration as a whole: saved from another camera
158    /// model, or from another version of its XML.
159    pub warnings: Vec<String>,
160}
161
162impl LoadReport {
163    /// Whether every value was written.
164    pub fn is_complete(&self) -> bool {
165        self.failures.is_empty()
166    }
167}
168
169impl fmt::Display for SavedValue {
170    /// `Gain[GainSelector=DigitalAll] = 9`.
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        f.write_str(&self.feature)?;
173        write_selectors(f, &self.selectors)?;
174        write!(f, " = {}", self.value)
175    }
176}
177
178impl fmt::Display for LoadFailure {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        write!(f, "{}: {}", self.value, self.error)
181    }
182}
183
184/// `[Selector=Entry, ...]`, or nothing for no selectors.
185fn write_selectors(f: &mut impl fmt::Write, selectors: &[(String, String)]) -> fmt::Result {
186    if selectors.is_empty() {
187        return Ok(());
188    }
189    f.write_char('[')?;
190    for (i, (selector, entry)) in selectors.iter().enumerate() {
191        if i > 0 {
192            f.write_str(", ")?;
193        }
194        write!(f, "{selector}={entry}")?;
195    }
196    f.write_char(']')
197}
198
199/// The comment keys that carry [`Configuration::identity`].
200const KEY_VENDOR: &str = "VendorName";
201const KEY_MODEL: &str = "ModelName";
202const KEY_VERSION: &str = "DeviceXmlVersion";
203
204impl Configuration {
205    /// The configuration as a file, in the layout GenApi's reference
206    /// implementation writes (`CFeatureBag`, ADR-0028):
207    ///
208    /// ```text
209    /// # {05D8C294-F295-4dfb-9D01-096BD04049F4}
210    /// # viva-genicam configuration
211    /// # VendorName = Basler
212    /// # ModelName = acA1600-20gm
213    /// # DeviceXmlVersion = 3.2.1
214    /// # not saved: ExposureTime: locked by ExposureAuto
215    /// GainSelector<TAB>AnalogAll
216    /// Gain<TAB>{GainSelector=DigitalAll}<TAB>9
217    /// ```
218    ///
219    /// One value per line, the feature name and the value separated by a tab
220    /// (`<TAB>` above);
221    /// a value read under selectors puts them between the two, in braces.
222    /// Lines starting with `#` are comments: the camera's identity, and what
223    /// the save left out and why.
224    pub fn to_text(&self) -> String {
225        use fmt::Write as _;
226        let mut out = String::new();
227        let _ = writeln!(out, "# {FILE_MAGIC}");
228        let _ = writeln!(out, "# viva-genicam configuration");
229        let _ = writeln!(out, "# {KEY_VENDOR} = {}", self.identity.vendor_name);
230        let _ = writeln!(out, "# {KEY_MODEL} = {}", self.identity.model_name);
231        let _ = writeln!(out, "# {KEY_VERSION} = {}", self.identity.version);
232        for omission in &self.omitted {
233            let _ = write!(out, "# not saved: {}", omission.feature);
234            let _ = write_selectors(&mut out, &omission.selectors);
235            let _ = writeln!(out, ": {}", omission.reason);
236        }
237        for value in &self.values {
238            out.push_str(&value.feature);
239            out.push('\t');
240            if !value.selectors.is_empty() {
241                out.push('{');
242                for (i, (selector, entry)) in value.selectors.iter().enumerate() {
243                    if i > 0 {
244                        out.push('\t');
245                    }
246                    let _ = write!(out, "{selector}={entry}");
247                }
248                out.push_str("}\t");
249            }
250            out.push_str(&value.value);
251            out.push('\n');
252        }
253        out
254    }
255
256    /// Read a configuration file: ours, or one in the same layout from
257    /// another GenApi-based tool.
258    ///
259    /// Blank lines and `#` comments are skipped, and line endings may be
260    /// `\n` or `\r\n`. The camera's identity is read from the comments this
261    /// crate writes; a file without them has an empty
262    /// [`Configuration::identity`]. A file of GenApi's other format
263    /// (`CFeatureBagger`) is refused, as is a line with no value.
264    pub fn parse(text: &str) -> Result<Self, ParseConfigurationError> {
265        let mut configuration = Configuration::default();
266        for (index, line) in text.lines().enumerate() {
267            let error = |message: &'static str| ParseConfigurationError {
268                line: index + 1,
269                message,
270            };
271            if line.trim().is_empty() {
272                continue;
273            }
274            if let Some(comment) = line.strip_prefix('#') {
275                let comment = comment.trim();
276                if comment.contains(BAGGER_MAGIC) {
277                    return Err(error(
278                        "written by GenApi's CFeatureBagger, a format this reader does not read",
279                    ));
280                }
281                if let Some((key, value)) = comment.split_once('=') {
282                    let value = value.trim().to_string();
283                    match key.trim() {
284                        KEY_VENDOR => configuration.identity.vendor_name = value,
285                        KEY_MODEL => configuration.identity.model_name = value,
286                        KEY_VERSION => configuration.identity.version = value,
287                        _ => {}
288                    }
289                }
290                continue;
291            }
292            let (name, rest) = line
293                .split_once('\t')
294                .ok_or_else(|| error("expected a feature name, a tab and a value"))?;
295            let name = name.trim();
296            if name.is_empty() {
297                return Err(error("no feature name before the tab"));
298            }
299            let (selectors, value) = match rest.strip_prefix('{') {
300                Some(group) => {
301                    let (inner, after) = group
302                        .split_once('}')
303                        .ok_or_else(|| error("a selector group without its closing brace"))?;
304                    let value = after
305                        .strip_prefix('\t')
306                        .ok_or_else(|| error("expected a tab after the selector group"))?;
307                    let selectors = inner
308                        .split('\t')
309                        .map(|pair| {
310                            pair.split_once('=')
311                                .map(|(s, e)| (s.trim().to_string(), e.trim().to_string()))
312                                .filter(|(s, e)| !s.is_empty() && !e.is_empty())
313                                .ok_or_else(|| error("expected Selector=Entry in the group"))
314                        })
315                        .collect::<Result<Vec<_>, _>>()?;
316                    (selectors, value)
317                }
318                None => (Vec::new(), rest),
319            };
320            if value.is_empty() {
321                return Err(error("no value after the tab"));
322            }
323            configuration.values.push(SavedValue {
324                feature: name.to_string(),
325                selectors,
326                value: value.to_string(),
327            });
328        }
329        Ok(configuration)
330    }
331}
332
333impl NodeMap {
334    /// Which features a configuration holds, under which selectors, and the
335    /// order a restore writes them in — decided from the XML alone.
336    ///
337    /// The features are those the XML marks `<Streamable>Yes</Streamable>`,
338    /// except categories and commands, which have no value. A feature is
339    /// written after every feature in the plan whose write can change it —
340    /// whatever the dependency graph links from the nodes the first is
341    /// written through to the second: a `<pSelected>`, a `pIsAvailable` or
342    /// `pIsLocked` provider, a `<pMin>`/`<pMax>`, an address, a
343    /// `<pInvalidator>`. Features that depend on one another in a cycle keep
344    /// document order between them, and otherwise the plan follows document
345    /// order too.
346    pub fn persistence_plan(&self) -> PersistencePlan {
347        let names: Vec<&str> = self
348            .node_names()
349            .filter(|name| {
350                self.node(name).is_some_and(|node| {
351                    node.meta().streamable && !matches!(node, Node::Category(_) | Node::Command(_))
352                })
353            })
354            .collect();
355        let index: HashMap<&str, usize> = names.iter().enumerate().map(|(i, n)| (*n, i)).collect();
356
357        // successors[p] holds every f that p's write can change.
358        let mut successors: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); names.len()];
359        for (p, name) in names.iter().enumerate() {
360            let mut seen: HashSet<&str> = HashSet::new();
361            let mut pending: Vec<&str> = self.value_reach(name);
362            while let Some(current) = pending.pop() {
363                if !seen.insert(current) {
364                    continue;
365                }
366                for dependent in self.dependents(current) {
367                    match index.get(dependent.as_str()) {
368                        // Stop at a planned feature: its own edges carry on.
369                        Some(&f) => {
370                            if f != p {
371                                successors[p].insert(f);
372                            }
373                        }
374                        None => pending.push(dependent),
375                    }
376                }
377            }
378        }
379
380        let order = restore_order(&successors);
381        let mut predecessors: Vec<Vec<String>> = vec![Vec::new(); names.len()];
382        for (p, targets) in successors.iter().enumerate() {
383            for &f in targets {
384                predecessors[f].push(names[p].to_string());
385            }
386        }
387        let features = order
388            .into_iter()
389            .map(|i| PlannedFeature {
390                name: names[i].to_string(),
391                selectors: self.selectors_outermost_first(names[i]),
392                after: std::mem::take(&mut predecessors[i]),
393            })
394            .collect();
395        PersistencePlan { features }
396    }
397
398    /// The selectors of `name` — those that select it, and the selectors of
399    /// those in turn — a selector that selects another (directly or through
400    /// others) before it, document order otherwise.
401    ///
402    /// A selector of a selector matters as much as a direct one: when
403    /// `LUTSelector` selects `LUTIndex` and `LUTIndex` selects `LUTValue`,
404    /// `LUTValue` read under each `LUTIndex` differs for each `LUTSelector`
405    /// entry too, though `LUTSelector` does not name it (Codex review of
406    /// #200).
407    fn selectors_outermost_first(&self, name: &str) -> Vec<String> {
408        let mut selectors: Vec<&str> = Vec::new();
409        let mut pending: Vec<&str> = self.selectors_of(name);
410        while let Some(selector) = pending.pop() {
411            if selector == name || selectors.contains(&selector) {
412                continue;
413            }
414            selectors.push(selector);
415            pending.extend(self.selectors_of(selector));
416        }
417        let position: HashMap<&str, usize> = self
418            .node_names()
419            .enumerate()
420            .map(|(i, node)| (node, i))
421            .collect();
422        selectors.sort_by_key(|selector| position.get(selector).copied());
423        let selects = |outer: &str, inner: &str| -> bool {
424            let mut seen: HashSet<&str> = HashSet::new();
425            let mut pending: Vec<&str> = vec![outer];
426            while let Some(current) = pending.pop() {
427                if !seen.insert(current) {
428                    continue;
429                }
430                for selected in self.node(current).map(Node::selected).unwrap_or(&[]) {
431                    if selected == inner {
432                        return true;
433                    }
434                    pending.push(selected);
435                }
436            }
437            false
438        };
439        let mut ranked: Vec<(usize, &str)> = selectors
440            .iter()
441            .map(|s| {
442                let depth = selectors
443                    .iter()
444                    .filter(|t| *t != s && selects(t, s))
445                    .count();
446                (depth, *s)
447            })
448            .collect();
449        ranked.sort_by_key(|(depth, _)| *depth);
450        ranked.into_iter().map(|(_, s)| s.to_string()).collect()
451    }
452
453    /// Read every streamable feature from the device: each selected one
454    /// under every entry of its selectors, which are put back afterwards.
455    ///
456    /// A selector selects only while it can be set: one that is not
457    /// implemented, not available, locked or read-only now leaves the
458    /// feature a single value, which is saved once, without that selector.
459    /// The mvBlueFOX3-2004G does not implement `ExposureTimeSelector`, and
460    /// `ExposureTime` used to be left out of every save for it (ADR-0028,
461    /// amendment of 2026-10-13).
462    ///
463    /// A feature is left out, with the reason in [`Configuration::omitted`],
464    /// when it cannot be both read and written — declared read-only or
465    /// write-only — or when, now, it is not implemented, not available,
466    /// locked, or its read fails. A locked feature would not be written on
467    /// restore either: what locks it (`ExposureAuto` for `ExposureTime`) is
468    /// saved and restored first. One that `TLParamsLocked` locks is left out
469    /// while the camera acquires, so save while it does not.
470    pub fn save_configuration(&mut self, io: &dyn RegisterIo) -> Configuration {
471        let plan = self.persistence_plan();
472        let mut saved = Configuration {
473            identity: self.identity().clone(),
474            ..Configuration::default()
475        };
476        for feature in plan.features() {
477            if let Some(reason) = self.not_persistable(&feature.name) {
478                saved.omitted.push(Omission {
479                    feature: feature.name.clone(),
480                    selectors: Vec::new(),
481                    reason: reason.to_string(),
482                });
483                continue;
484            }
485            let mut walk = SelectorWalk {
486                feature: &feature.name,
487                selectors: &feature.selectors,
488                context: Vec::new(),
489                values: Vec::new(),
490                omitted: Vec::new(),
491                reads: 0,
492                abandoned: None,
493            };
494            self.walk_selectors(&mut walk, io, 0);
495            match walk.abandoned {
496                Some(reason) => saved.omitted.push(Omission {
497                    feature: feature.name.clone(),
498                    selectors: Vec::new(),
499                    reason,
500                }),
501                None => {
502                    saved.values.append(&mut walk.values);
503                    saved.omitted.append(&mut walk.omitted);
504                }
505            }
506        }
507        saved
508    }
509
510    /// Why `name` cannot be saved whatever the device's state: a value that
511    /// cannot be written back, or not read.
512    fn not_persistable(&self, name: &str) -> Option<&'static str> {
513        match self.declared_access_mode(name) {
514            Some(AccessMode::RW) => None,
515            Some(AccessMode::RO) => Some("read-only"),
516            Some(AccessMode::WO) => Some("write-only"),
517            None => Some("neither readable nor writable"),
518        }
519    }
520
521    /// Set each of `walk.selectors` from `index` on to each of its entries
522    /// in turn, read the feature under every combination, and put each
523    /// selector that moved back as it was. A selector that cannot be set now
524    /// selects nothing, and is passed over.
525    fn walk_selectors(&mut self, walk: &mut SelectorWalk<'_>, io: &dyn RegisterIo, index: usize) {
526        let Some(selector) = walk.selectors.get(index) else {
527            walk.reads += 1;
528            if walk.reads > MAX_SELECTOR_COMBINATIONS {
529                walk.abandoned = Some(format!(
530                    "more than {MAX_SELECTOR_COMBINATIONS} combinations of selector entries"
531                ));
532                return;
533            }
534            match self.read_for_saving(walk.feature, io) {
535                Ok(value) => walk.values.push(SavedValue {
536                    feature: walk.feature.to_string(),
537                    selectors: walk.context.clone(),
538                    value,
539                }),
540                Err(reason) => walk.omitted.push(Omission {
541                    feature: walk.feature.to_string(),
542                    selectors: walk.context.clone(),
543                    reason,
544                }),
545            }
546            return;
547        };
548        match self.selects_now(selector, io) {
549            Ok(true) => {}
550            Ok(false) => {
551                debug!(feature = walk.feature, %selector, "the selector cannot be set now; saving the feature without it");
552                self.walk_selectors(walk, io, index + 1);
553                return;
554            }
555            Err(err) => {
556                walk.omitted.push(Omission {
557                    feature: walk.feature.to_string(),
558                    selectors: walk.context.clone(),
559                    reason: format!("the state of its selector {selector}: {err}"),
560                });
561                return;
562            }
563        }
564        let original = match self.get_text(selector, io) {
565            Ok(value) => value,
566            Err(err) => {
567                walk.omitted.push(Omission {
568                    feature: walk.feature.to_string(),
569                    selectors: walk.context.clone(),
570                    reason: format!("its selector {selector} cannot be read: {err}"),
571                });
572                return;
573            }
574        };
575        let entries = match self.selector_entries(selector, io) {
576            Ok(entries) => entries,
577            Err(reason) => {
578                walk.abandoned = Some(reason);
579                return;
580            }
581        };
582        // The entry the selector holds after our writes; `None` while none
583        // succeeded, and it has not moved.
584        let mut holds: Option<String> = None;
585        for entry in entries {
586            if walk.abandoned.is_some() {
587                break;
588            }
589            if let Err(err) = self.set_text(selector, &entry, io) {
590                let mut selectors = walk.context.clone();
591                selectors.push((selector.clone(), entry.clone()));
592                walk.omitted.push(Omission {
593                    feature: walk.feature.to_string(),
594                    selectors,
595                    reason: format!("its selector cannot be set to {entry}: {err}"),
596                });
597                continue;
598            }
599            holds = Some(entry.clone());
600            walk.context.push((selector.clone(), entry));
601            self.walk_selectors(walk, io, index + 1);
602            walk.context.pop();
603        }
604        // Put it back only if the walk moved it.
605        if holds.is_some_and(|entry| entry != original)
606            && let Err(err) = self.set_text(selector, &original, io)
607        {
608            warn!(%selector, %original, error = %err, "could not put the selector back");
609        }
610    }
611
612    /// Whether `selector` selects now: it can be set — implemented,
613    /// available, not locked, and declared writable. One that cannot be set
614    /// leaves the features it selects one value each.
615    fn selects_now(&self, selector: &str, io: &dyn RegisterIo) -> Result<bool, GenApiError> {
616        if !matches!(
617            self.declared_access_mode(selector),
618            Some(AccessMode::RW | AccessMode::WO)
619        ) {
620            return Ok(false);
621        }
622        if !self.is_available(selector, io)? {
623            return Ok(false);
624        }
625        Ok(self.locked_by(selector, io)?.is_none())
626    }
627
628    /// The entries a save iterates a selector over: an enumeration's
629    /// available entries, an integer's values from its minimum to its maximum
630    /// by its increment.
631    fn selector_entries(&self, selector: &str, io: &dyn RegisterIo) -> Result<Vec<String>, String> {
632        match self.node(selector) {
633            Some(Node::Enum(_)) => self
634                .available_enum_entries(selector, io)
635                .map_err(|err| format!("the entries of its selector {selector}: {err}")),
636            Some(Node::Integer(_)) => {
637                let bound = |which: Limit| {
638                    self.limit(selector, which, io, &mut HashSet::new())
639                        .map(|value| value.map(|v| v.as_i64()))
640                        .map_err(|err| format!("the bounds of its selector {selector}: {err}"))
641                };
642                let (Some(min), Some(max)) = (bound(Limit::Min)?, bound(Limit::Max)?) else {
643                    return Err(format!("its selector {selector} declares no bounds"));
644                };
645                let inc = bound(Limit::Inc)?.filter(|inc| *inc > 0).unwrap_or(1);
646                let count = if max < min {
647                    0
648                } else {
649                    (max as i128 - min as i128) / inc as i128 + 1
650                };
651                if count > MAX_SELECTOR_COMBINATIONS as i128 {
652                    return Err(format!(
653                        "its selector {selector} has {count} values, more than the \
654                         {MAX_SELECTOR_COMBINATIONS} a configuration saves"
655                    ));
656                }
657                Ok((0..count as i64)
658                    .map(|k| (min + k * inc).to_string())
659                    .collect())
660            }
661            _ => Err(format!(
662                "its selector {selector} is neither an enumeration nor an integer"
663            )),
664        }
665    }
666
667    /// Read `name` as a configuration holds it, or say why not.
668    fn read_for_saving(&self, name: &str, io: &dyn RegisterIo) -> Result<String, String> {
669        match self.is_implemented(name, io) {
670            Ok(true) => {}
671            Ok(false) => return Err("not implemented".into()),
672            Err(err) => return Err(format!("pIsImplemented: {err}")),
673        }
674        match self.is_available(name, io) {
675            Ok(true) => {}
676            Ok(false) => return Err("not available".into()),
677            Err(err) => return Err(format!("pIsAvailable: {err}")),
678        }
679        match self.locked_by(name, io) {
680            Ok(None) => {}
681            Ok(Some(provider)) => return Err(format!("locked by {provider}")),
682            Err(err) => return Err(format!("pIsLocked: {err}")),
683        }
684        let value = match self.node(name) {
685            Some(Node::Register(_)) => self.get_register(name, io).map(|b| bytes_to_hex(&b)),
686            Some(Node::Boolean(_)) => self
687                .get_bool(name, io)
688                .map(|on| if on { "1" } else { "0" }.to_string()),
689            _ => self.get_text(name, io),
690        }
691        .map_err(|err| format!("read failed: {err}"))?;
692        if value.contains(['\n', '\r']) {
693            return Err("its value has a line break, which the file cannot hold".into());
694        }
695        // GenApi's reader refuses a line with no value, so a file holding one
696        // could not be loaded there.
697        if value.is_empty() {
698            return Err("empty, and the file has no way to hold an empty value".into());
699        }
700        Ok(value)
701    }
702
703    /// Write a configuration back to the device.
704    ///
705    /// Values are written in the plan's order, whatever their order in
706    /// `configuration`: a feature after the selectors, availability and lock
707    /// providers and bounds it depends on. A value saved under selectors is
708    /// written with each selector set to its entry, and the selectors are put
709    /// back afterwards. A file of plain lines that sets a selector on one line
710    /// and a selected feature on the next — a replay of writes, as some tools
711    /// save — binds each such value to the selector line before it.
712    ///
713    /// A write that fails is tried once more after all the others, for the
714    /// failures that are only a matter of order: `Width` and `OffsetX` bound
715    /// each other, so one of the two may have to wait. Whatever still fails
716    /// is in [`LoadReport::failures`] with its reason, in the configuration's
717    /// order; nothing stops the load early. A configuration saved from
718    /// another camera model, or another major version of its XML, is loaded
719    /// all the same, with a warning in [`LoadReport::warnings`].
720    ///
721    /// `TLParamsLocked` is not touched: the standard does not ask for it, and
722    /// a camera that acquires reports the features it locks as failures.
723    pub fn load_configuration(
724        &mut self,
725        configuration: &Configuration,
726        io: &dyn RegisterIo,
727    ) -> LoadReport {
728        let mut report = LoadReport {
729            warnings: identity_warnings(&configuration.identity, self.identity()),
730            ..LoadReport::default()
731        };
732        let plan = self.persistence_plan();
733        let values = self.bind_replayed_selectors(&configuration.values, &plan);
734        let mut ordered: Vec<(usize, SavedValue)> = values.into_iter().enumerate().collect();
735        ordered.sort_by_key(|(index, value)| {
736            (plan.position(&value.feature).unwrap_or(usize::MAX), *index)
737        });
738
739        let mut retry = Vec::new();
740        let mut failed = Vec::new();
741        for (index, value) in ordered {
742            match self.write_saved(&value, io) {
743                Ok(()) => report.written += 1,
744                Err(err) if is_permanent(&err) => failed.push((index, value, err)),
745                Err(_) => retry.push((index, value)),
746            }
747        }
748        for (index, value) in retry {
749            match self.write_saved(&value, io) {
750                Ok(()) => {
751                    report.written += 1;
752                    report.written_on_retry += 1;
753                }
754                Err(err) => failed.push((index, value, err)),
755            }
756        }
757        failed.sort_by_key(|(index, _, _)| *index);
758        report.failures = failed
759            .into_iter()
760            .map(|(_, value, error)| LoadFailure { value, error })
761            .collect();
762        report
763    }
764
765    /// Give each plain value of a selected feature the selector entries the
766    /// lines before it set, for files that replay writes in order.
767    fn bind_replayed_selectors(
768        &self,
769        values: &[SavedValue],
770        plan: &PersistencePlan,
771    ) -> Vec<SavedValue> {
772        let mut current: HashMap<&str, &str> = HashMap::new();
773        let mut bound = Vec::with_capacity(values.len());
774        for value in values {
775            let mut out = value.clone();
776            if value.selectors.is_empty() {
777                let selectors = match plan.position(&value.feature) {
778                    Some(i) => plan.features()[i].selectors.clone(),
779                    None => self.selectors_outermost_first(&value.feature),
780                };
781                out.selectors = selectors
782                    .into_iter()
783                    .filter_map(|s| {
784                        let entry = current.get(s.as_str())?.to_string();
785                        Some((s, entry))
786                    })
787                    .collect();
788                if self
789                    .node(&value.feature)
790                    .is_some_and(|node| !node.selected().is_empty())
791                {
792                    current.insert(&value.feature, &value.value);
793                }
794            }
795            bound.push(out);
796        }
797        bound
798    }
799
800    /// Write one value, under its selector entries, and put the selectors
801    /// back.
802    fn write_saved(&mut self, value: &SavedValue, io: &dyn RegisterIo) -> Result<(), GenApiError> {
803        let mut moved: Vec<(&str, String)> = Vec::new();
804        let result = self.write_under_selectors(value, io, &mut moved);
805        for (selector, original) in moved.into_iter().rev() {
806            if let Err(err) = self.set_text(selector, &original, io) {
807                warn!(%selector, %original, error = %err, "could not put the selector back");
808            }
809        }
810        result
811    }
812
813    fn write_under_selectors<'v>(
814        &mut self,
815        value: &'v SavedValue,
816        io: &dyn RegisterIo,
817        moved: &mut Vec<(&'v str, String)>,
818    ) -> Result<(), GenApiError> {
819        for (selector, entry) in &value.selectors {
820            let original = self.get_text(selector, io)?;
821            // A selector that already holds the entry is not moved, and so
822            // has nothing to be put back to.
823            if original == *entry {
824                continue;
825            }
826            self.set_text(selector, entry, io)?;
827            moved.push((selector, original));
828        }
829        match self.node(&value.feature) {
830            Some(Node::Register(_)) => {
831                let bytes = hex_to_bytes(&value.value).ok_or_else(|| GenApiError::InvalidText {
832                    name: value.feature.clone(),
833                    expected: "hexadecimal bytes",
834                    text: value.value.clone(),
835                })?;
836                self.set_register(&value.feature, &bytes, io)
837            }
838            _ => self.set_text(&value.feature, &value.value, io),
839        }
840    }
841}
842
843/// The state of one feature's walk over its selectors' entries.
844struct SelectorWalk<'a> {
845    feature: &'a str,
846    selectors: &'a [String],
847    /// The selector entries set so far, outermost first.
848    context: Vec<(String, String)>,
849    values: Vec<SavedValue>,
850    omitted: Vec<Omission>,
851    reads: usize,
852    /// Set when the feature cannot be saved at all.
853    abandoned: Option<String>,
854}
855
856/// Errors no second attempt can change: the feature, its type or its access,
857/// or the text itself.
858fn is_permanent(err: &GenApiError) -> bool {
859    matches!(
860        err,
861        GenApiError::NodeNotFound(_)
862            | GenApiError::Type { .. }
863            | GenApiError::Access { .. }
864            | GenApiError::InvalidText { .. }
865            | GenApiError::Unsupported { .. }
866    )
867}
868
869/// Warn when a configuration was saved from another camera model, or from
870/// another major version of its XML — "files with a higher Major version
871/// number are not backward compatible" (GenICam Standard v2.1.1 §2.7).
872fn identity_warnings(saved: &DocumentIdentity, camera: &DocumentIdentity) -> Vec<String> {
873    let differs = |a: &str, b: &str| !a.is_empty() && a != b;
874    if differs(&saved.vendor_name, &camera.vendor_name)
875        || differs(&saved.model_name, &camera.model_name)
876    {
877        return vec![format!(
878            "saved from a {} {}, loaded onto a {} {}",
879            saved.vendor_name, saved.model_name, camera.vendor_name, camera.model_name
880        )];
881    }
882    let major = |version: &str| version.split('.').next().unwrap_or("").to_string();
883    if !camera.version.is_empty() && differs(&major(&saved.version), &major(&camera.version)) {
884        return vec![format!(
885            "saved with version {} of the camera's XML, loaded with version {}: \
886             a different major version is not compatible",
887            saved.version, camera.version
888        )];
889    }
890    Vec::new()
891}
892
893/// The order a restore writes the plan's features in, given `successors[p]`,
894/// every feature whose value `p`'s write can change.
895///
896/// Strongly connected components (features in a cycle) are written as a
897/// unit, their members in document order; the components follow the
898/// dependencies between them, and document order where none applies.
899fn restore_order(successors: &[BTreeSet<usize>]) -> Vec<usize> {
900    let components = strongly_connected(successors);
901    let mut component_of = vec![0usize; successors.len()];
902    for (c, members) in components.iter().enumerate() {
903        for &v in members {
904            component_of[v] = c;
905        }
906    }
907    let mut indegree = vec![0usize; components.len()];
908    let mut component_successors: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); components.len()];
909    for (p, targets) in successors.iter().enumerate() {
910        for &f in targets {
911            let (from, to) = (component_of[p], component_of[f]);
912            if from != to && component_successors[from].insert(to) {
913                indegree[to] += 1;
914            }
915        }
916    }
917    // Members are sorted, so a component's first member is its earliest.
918    let mut ready: BinaryHeap<Reverse<(usize, usize)>> = components
919        .iter()
920        .enumerate()
921        .filter(|(c, _)| indegree[*c] == 0)
922        .map(|(c, members)| Reverse((members[0], c)))
923        .collect();
924    let mut order = Vec::with_capacity(successors.len());
925    while let Some(Reverse((_, c))) = ready.pop() {
926        order.extend(components[c].iter().copied());
927        for &next in &component_successors[c] {
928            indegree[next] -= 1;
929            if indegree[next] == 0 {
930                ready.push(Reverse((components[next][0], next)));
931            }
932        }
933    }
934    order
935}
936
937/// Tarjan's strongly connected components, iteratively; each component's
938/// members sorted ascending.
939fn strongly_connected(successors: &[BTreeSet<usize>]) -> Vec<Vec<usize>> {
940    const UNSEEN: usize = usize::MAX;
941    let n = successors.len();
942    let adjacency: Vec<Vec<usize>> = successors
943        .iter()
944        .map(|s| s.iter().copied().collect())
945        .collect();
946    let mut index = vec![UNSEEN; n];
947    let mut low = vec![0usize; n];
948    let mut on_stack = vec![false; n];
949    let mut stack = Vec::new();
950    let mut next_index = 0;
951    let mut components = Vec::new();
952    for root in 0..n {
953        if index[root] != UNSEEN {
954            continue;
955        }
956        // (vertex, position in its adjacency list)
957        let mut call: Vec<(usize, usize)> = vec![(root, 0)];
958        index[root] = next_index;
959        low[root] = next_index;
960        next_index += 1;
961        stack.push(root);
962        on_stack[root] = true;
963        while let Some(&mut (v, ref mut edge)) = call.last_mut() {
964            if let Some(&w) = adjacency[v].get(*edge) {
965                *edge += 1;
966                if index[w] == UNSEEN {
967                    index[w] = next_index;
968                    low[w] = next_index;
969                    next_index += 1;
970                    stack.push(w);
971                    on_stack[w] = true;
972                    call.push((w, 0));
973                } else if on_stack[w] {
974                    low[v] = low[v].min(index[w]);
975                }
976                continue;
977            }
978            call.pop();
979            if let Some(&(parent, _)) = call.last() {
980                low[parent] = low[parent].min(low[v]);
981            }
982            if low[v] == index[v] {
983                let mut members = Vec::new();
984                while let Some(w) = stack.pop() {
985                    on_stack[w] = false;
986                    members.push(w);
987                    if w == v {
988                        break;
989                    }
990                }
991                members.sort_unstable();
992                components.push(members);
993            }
994        }
995    }
996    components
997}
998
999#[cfg(test)]
1000mod tests {
1001    use super::*;
1002
1003    fn graph(n: usize, edges: &[(usize, usize)]) -> Vec<BTreeSet<usize>> {
1004        let mut successors = vec![BTreeSet::new(); n];
1005        for &(p, f) in edges {
1006            successors[p].insert(f);
1007        }
1008        successors
1009    }
1010
1011    #[test]
1012    fn a_dependency_moves_a_feature_ahead_of_document_order() {
1013        assert_eq!(restore_order(&graph(3, &[(2, 0)])), [1, 2, 0]);
1014    }
1015
1016    #[test]
1017    fn a_cycle_keeps_document_order_and_its_dependencies() {
1018        // 1 <-> 2 is a cycle that 3 must precede; 0 is free.
1019        assert_eq!(
1020            restore_order(&graph(4, &[(1, 2), (2, 1), (3, 1)])),
1021            [0, 3, 1, 2]
1022        );
1023    }
1024
1025    #[test]
1026    fn components_are_found_in_a_chain_of_cycles() {
1027        let mut found = strongly_connected(&graph(5, &[(0, 1), (1, 0), (1, 2), (2, 3), (3, 2)]));
1028        found.sort();
1029        assert_eq!(found, [vec![0, 1], vec![2, 3], vec![4]]);
1030    }
1031}