Skip to main content

sheetkit_core/
doc_props.rs

1//! User-facing document properties types and conversion helpers.
2//!
3//! These types provide an ergonomic API for working with the three kinds of
4//! OOXML document properties (core, extended/application, and custom).
5
6use sheetkit_xml::doc_props::{
7    CoreProperties, CustomProperty, CustomPropertyValue as XmlCustomPropertyValue,
8    ExtendedProperties, CUSTOM_PROPERTY_FMTID,
9};
10use sheetkit_xml::namespaces;
11use sheetkit_xml::workbook::{CalcPr, WorkbookPr};
12
13use crate::error::{Error, Result};
14
15/// User-facing document core properties.
16#[derive(Debug, Clone, Default)]
17pub struct DocProperties {
18    pub title: Option<String>,
19    pub subject: Option<String>,
20    pub creator: Option<String>,
21    pub keywords: Option<String>,
22    pub description: Option<String>,
23    pub last_modified_by: Option<String>,
24    pub revision: Option<String>,
25    pub created: Option<String>,
26    pub modified: Option<String>,
27    pub category: Option<String>,
28    pub content_status: Option<String>,
29}
30
31impl From<&CoreProperties> for DocProperties {
32    fn from(props: &CoreProperties) -> Self {
33        Self {
34            title: props.title.clone(),
35            subject: props.subject.clone(),
36            creator: props.creator.clone(),
37            keywords: props.keywords.clone(),
38            description: props.description.clone(),
39            last_modified_by: props.last_modified_by.clone(),
40            revision: props.revision.clone(),
41            created: props.created.clone(),
42            modified: props.modified.clone(),
43            category: props.category.clone(),
44            content_status: props.content_status.clone(),
45        }
46    }
47}
48
49impl DocProperties {
50    /// Convert to the XML-level `CoreProperties` struct.
51    pub fn to_core_properties(&self) -> CoreProperties {
52        CoreProperties {
53            title: self.title.clone(),
54            subject: self.subject.clone(),
55            creator: self.creator.clone(),
56            keywords: self.keywords.clone(),
57            description: self.description.clone(),
58            last_modified_by: self.last_modified_by.clone(),
59            revision: self.revision.clone(),
60            created: self.created.clone(),
61            modified: self.modified.clone(),
62            category: self.category.clone(),
63            content_status: self.content_status.clone(),
64        }
65    }
66}
67
68/// User-facing application properties.
69#[derive(Debug, Clone, Default)]
70pub struct AppProperties {
71    pub application: Option<String>,
72    pub doc_security: Option<u32>,
73    pub company: Option<String>,
74    pub app_version: Option<String>,
75    pub manager: Option<String>,
76    pub template: Option<String>,
77}
78
79impl From<&ExtendedProperties> for AppProperties {
80    fn from(props: &ExtendedProperties) -> Self {
81        Self {
82            application: props.application.clone(),
83            doc_security: props.doc_security,
84            company: props.company.clone(),
85            app_version: props.app_version.clone(),
86            manager: props.manager.clone(),
87            template: props.template.clone(),
88        }
89    }
90}
91
92impl AppProperties {
93    /// Convert to the XML-level `ExtendedProperties` struct.
94    pub fn to_extended_properties(&self) -> ExtendedProperties {
95        ExtendedProperties {
96            xmlns: namespaces::EXTENDED_PROPERTIES.to_string(),
97            xmlns_vt: Some(namespaces::VT.to_string()),
98            application: self.application.clone(),
99            doc_security: self.doc_security,
100            scale_crop: None,
101            company: self.company.clone(),
102            links_up_to_date: None,
103            shared_doc: None,
104            hyperlinks_changed: None,
105            app_version: self.app_version.clone(),
106            template: self.template.clone(),
107            manager: self.manager.clone(),
108        }
109    }
110}
111
112/// Value type for custom properties.
113#[derive(Debug, Clone, PartialEq)]
114pub enum CustomPropertyValue {
115    String(String),
116    Int(i32),
117    Float(f64),
118    Bool(bool),
119    DateTime(String),
120}
121
122impl CustomPropertyValue {
123    /// Convert to the XML-level `CustomPropertyValue`.
124    pub(crate) fn to_xml(&self) -> XmlCustomPropertyValue {
125        match self {
126            Self::String(s) => XmlCustomPropertyValue::String(s.clone()),
127            Self::Int(n) => XmlCustomPropertyValue::Int(*n),
128            Self::Float(f) => XmlCustomPropertyValue::Float(*f),
129            Self::Bool(b) => XmlCustomPropertyValue::Bool(*b),
130            Self::DateTime(dt) => XmlCustomPropertyValue::DateTime(dt.clone()),
131        }
132    }
133
134    /// Convert from the XML-level `CustomPropertyValue`.
135    pub(crate) fn from_xml(val: &XmlCustomPropertyValue) -> Self {
136        match val {
137            XmlCustomPropertyValue::String(s) => Self::String(s.clone()),
138            XmlCustomPropertyValue::Int(n) => Self::Int(*n),
139            XmlCustomPropertyValue::Float(f) => Self::Float(*f),
140            XmlCustomPropertyValue::Bool(b) => Self::Bool(*b),
141            XmlCustomPropertyValue::DateTime(dt) => Self::DateTime(dt.clone()),
142        }
143    }
144}
145
146/// Find a custom property by name and return its value, or None.
147pub(crate) fn find_custom_property(
148    props: &sheetkit_xml::doc_props::CustomProperties,
149    name: &str,
150) -> Option<CustomPropertyValue> {
151    props
152        .properties
153        .iter()
154        .find(|p| p.name == name)
155        .map(|p| CustomPropertyValue::from_xml(&p.value))
156}
157
158/// Set a custom property by name (insert or update).
159///
160/// A new property gets the lowest unused pid in `2..=u32::MAX` (pids 0 and 1
161/// are reserved by OOXML), so gaps left by deleted properties are reused.
162/// Returns `Error::InvalidArgument` without modifying `props` when every
163/// valid pid is taken.
164pub(crate) fn set_custom_property(
165    props: &mut sheetkit_xml::doc_props::CustomProperties,
166    name: &str,
167    value: CustomPropertyValue,
168) -> Result<()> {
169    if let Some(existing) = props.properties.iter_mut().find(|p| p.name == name) {
170        existing.value = value.to_xml();
171        return Ok(());
172    }
173
174    let used: std::collections::HashSet<u32> = props.properties.iter().map(|p| p.pid).collect();
175    let next_pid = (2..=u32::MAX)
176        .find(|pid| !used.contains(pid))
177        .ok_or_else(|| Error::InvalidArgument("no unused custom property pid available".into()))?;
178
179    props.properties.push(CustomProperty {
180        fmtid: CUSTOM_PROPERTY_FMTID.to_string(),
181        pid: next_pid,
182        name: name.to_string(),
183        value: value.to_xml(),
184    });
185    Ok(())
186}
187
188/// Remove a custom property by name. Returns true if found and removed.
189pub(crate) fn delete_custom_property(
190    props: &mut sheetkit_xml::doc_props::CustomProperties,
191    name: &str,
192) -> bool {
193    let before = props.properties.len();
194    props.properties.retain(|p| p.name != name);
195    props.properties.len() < before
196}
197
198/// High-level workbook properties (maps to the `WorkbookPr` XML element).
199///
200/// All fields are optional; `None` means the attribute is omitted from the XML.
201#[derive(Debug, Clone, Default)]
202pub struct WorkbookSettings {
203    /// Use 1904 date system instead of 1900.
204    pub date1904: Option<bool>,
205    /// Preserve date compatibility behavior.
206    pub date_compatibility: Option<bool>,
207    /// Filter privacy setting.
208    pub filter_privacy: Option<bool>,
209    /// Default theme version.
210    pub default_theme_version: Option<u32>,
211    /// Show objects mode (e.g. "all", "placeholders", "none").
212    pub show_objects: Option<String>,
213    /// Code name for VBA.
214    pub code_name: Option<String>,
215    /// Check compatibility on save.
216    pub check_compatibility: Option<bool>,
217    /// Auto compress pictures.
218    pub auto_compress_pictures: Option<bool>,
219    /// Refresh all external data connections on open.
220    pub refresh_all_connections: Option<bool>,
221    /// Backup file setting.
222    pub backup_file: Option<bool>,
223    /// Save external link values.
224    pub save_external_link_values: Option<bool>,
225    /// Update links mode.
226    pub update_links: Option<String>,
227    /// Hide pivot field list.
228    pub hide_pivot_field_list: Option<bool>,
229    /// Show pivot chart filter.
230    pub show_pivot_chart_filter: Option<bool>,
231    /// Allow refresh query.
232    pub allow_refresh_query: Option<bool>,
233    /// Publish items.
234    pub publish_items: Option<bool>,
235    /// Show border on unselected tables.
236    pub show_border_unselected_tables: Option<bool>,
237    /// Prompted solutions.
238    pub prompted_solutions: Option<bool>,
239    /// Show ink annotation.
240    pub show_ink_annotation: Option<bool>,
241}
242
243impl From<&WorkbookPr> for WorkbookSettings {
244    fn from(pr: &WorkbookPr) -> Self {
245        Self {
246            date1904: pr.date1904,
247            date_compatibility: pr.date_compatibility,
248            filter_privacy: pr.filter_privacy,
249            default_theme_version: pr.default_theme_version,
250            show_objects: pr.show_objects.clone(),
251            code_name: pr.code_name.clone(),
252            check_compatibility: pr.check_compatibility,
253            auto_compress_pictures: pr.auto_compress_pictures,
254            refresh_all_connections: pr.refresh_all_connections,
255            backup_file: pr.backup_file,
256            save_external_link_values: pr.save_external_link_values,
257            update_links: pr.update_links.clone(),
258            hide_pivot_field_list: pr.hide_pivot_field_list,
259            show_pivot_chart_filter: pr.show_pivot_chart_filter,
260            allow_refresh_query: pr.allow_refresh_query,
261            publish_items: pr.publish_items,
262            show_border_unselected_tables: pr.show_border_unselected_tables,
263            prompted_solutions: pr.prompted_solutions,
264            show_ink_annotation: pr.show_ink_annotation,
265        }
266    }
267}
268
269impl WorkbookSettings {
270    /// Convert to the XML-level `WorkbookPr` struct.
271    pub fn to_workbook_pr(&self) -> WorkbookPr {
272        WorkbookPr {
273            date1904: self.date1904,
274            date_compatibility: self.date_compatibility,
275            filter_privacy: self.filter_privacy,
276            default_theme_version: self.default_theme_version,
277            show_objects: self.show_objects.clone(),
278            code_name: self.code_name.clone(),
279            check_compatibility: self.check_compatibility,
280            auto_compress_pictures: self.auto_compress_pictures,
281            refresh_all_connections: self.refresh_all_connections,
282            backup_file: self.backup_file,
283            save_external_link_values: self.save_external_link_values,
284            update_links: self.update_links.clone(),
285            hide_pivot_field_list: self.hide_pivot_field_list,
286            show_pivot_chart_filter: self.show_pivot_chart_filter,
287            allow_refresh_query: self.allow_refresh_query,
288            publish_items: self.publish_items,
289            show_border_unselected_tables: self.show_border_unselected_tables,
290            prompted_solutions: self.prompted_solutions,
291            show_ink_annotation: self.show_ink_annotation,
292        }
293    }
294}
295
296/// High-level calculation properties (maps to the `CalcPr` XML element).
297///
298/// All fields are optional; `None` means the attribute is omitted from the XML.
299#[derive(Debug, Clone, Default)]
300pub struct CalcSettings {
301    /// Calculation engine ID.
302    pub calc_id: Option<u32>,
303    /// Calculation mode: "auto", "manual", or "autoNoTable".
304    pub calc_mode: Option<String>,
305    /// Full calculation on load.
306    pub full_calc_on_load: Option<bool>,
307    /// Reference mode: "A1" or "R1C1".
308    pub ref_mode: Option<String>,
309    /// Enable iterative calculation.
310    pub iterate: Option<bool>,
311    /// Maximum iterations for iterative calculation.
312    pub iterate_count: Option<u32>,
313    /// Delta threshold for iterative calculation convergence.
314    pub iterate_delta: Option<f64>,
315    /// Full precision for calculations.
316    pub full_precision: Option<bool>,
317    /// Whether calculation was completed before save.
318    pub calc_completed: Option<bool>,
319    /// Calculate on save.
320    pub calc_on_save: Option<bool>,
321    /// Enable concurrent calculation.
322    pub concurrent_calc: Option<bool>,
323    /// Manual concurrent calculation thread count.
324    pub concurrent_manual_count: Option<u32>,
325    /// Force full calculation.
326    pub force_full_calc: Option<bool>,
327}
328
329impl From<&CalcPr> for CalcSettings {
330    fn from(pr: &CalcPr) -> Self {
331        Self {
332            calc_id: pr.calc_id,
333            calc_mode: pr.calc_mode.clone(),
334            full_calc_on_load: pr.full_calc_on_load,
335            ref_mode: pr.ref_mode.clone(),
336            iterate: pr.iterate,
337            iterate_count: pr.iterate_count,
338            iterate_delta: pr.iterate_delta,
339            full_precision: pr.full_precision,
340            calc_completed: pr.calc_completed,
341            calc_on_save: pr.calc_on_save,
342            concurrent_calc: pr.concurrent_calc,
343            concurrent_manual_count: pr.concurrent_manual_count,
344            force_full_calc: pr.force_full_calc,
345        }
346    }
347}
348
349impl CalcSettings {
350    /// Convert to the XML-level `CalcPr` struct.
351    pub fn to_calc_pr(&self) -> CalcPr {
352        CalcPr {
353            calc_id: self.calc_id,
354            calc_mode: self.calc_mode.clone(),
355            full_calc_on_load: self.full_calc_on_load,
356            ref_mode: self.ref_mode.clone(),
357            iterate: self.iterate,
358            iterate_count: self.iterate_count,
359            iterate_delta: self.iterate_delta,
360            full_precision: self.full_precision,
361            calc_completed: self.calc_completed,
362            calc_on_save: self.calc_on_save,
363            concurrent_calc: self.concurrent_calc,
364            concurrent_manual_count: self.concurrent_manual_count,
365            force_full_calc: self.force_full_calc,
366        }
367    }
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373
374    #[test]
375    fn test_doc_properties_from_core_properties() {
376        let core = CoreProperties {
377            title: Some("T".to_string()),
378            creator: Some("C".to_string()),
379            ..Default::default()
380        };
381        let doc = DocProperties::from(&core);
382        assert_eq!(doc.title.as_deref(), Some("T"));
383        assert_eq!(doc.creator.as_deref(), Some("C"));
384        assert!(doc.subject.is_none());
385    }
386
387    #[test]
388    fn test_doc_properties_to_core_properties() {
389        let doc = DocProperties {
390            title: Some("T".to_string()),
391            subject: Some("S".to_string()),
392            ..Default::default()
393        };
394        let core = doc.to_core_properties();
395        assert_eq!(core.title.as_deref(), Some("T"));
396        assert_eq!(core.subject.as_deref(), Some("S"));
397        assert!(core.creator.is_none());
398    }
399
400    #[test]
401    fn test_app_properties_from_extended_properties() {
402        let ext = ExtendedProperties {
403            xmlns: namespaces::EXTENDED_PROPERTIES.to_string(),
404            xmlns_vt: None,
405            application: Some("TestApp".to_string()),
406            doc_security: Some(0),
407            company: Some("Corp".to_string()),
408            ..Default::default()
409        };
410        let app = AppProperties::from(&ext);
411        assert_eq!(app.application.as_deref(), Some("TestApp"));
412        assert_eq!(app.doc_security, Some(0));
413        assert_eq!(app.company.as_deref(), Some("Corp"));
414    }
415
416    #[test]
417    fn test_app_properties_to_extended_properties() {
418        let app = AppProperties {
419            application: Some("SheetKit".to_string()),
420            company: Some("Acme".to_string()),
421            ..Default::default()
422        };
423        let ext = app.to_extended_properties();
424        assert_eq!(ext.xmlns, namespaces::EXTENDED_PROPERTIES);
425        assert_eq!(ext.application.as_deref(), Some("SheetKit"));
426        assert_eq!(ext.company.as_deref(), Some("Acme"));
427    }
428
429    #[test]
430    fn test_custom_property_value_roundtrip() {
431        let vals = vec![
432            CustomPropertyValue::String("hello".to_string()),
433            CustomPropertyValue::Int(42),
434            CustomPropertyValue::Float(3.15),
435            CustomPropertyValue::Bool(true),
436            CustomPropertyValue::DateTime("2024-01-01T00:00:00Z".to_string()),
437        ];
438        for v in &vals {
439            let xml = v.to_xml();
440            let back = CustomPropertyValue::from_xml(&xml);
441            assert_eq!(*v, back);
442        }
443    }
444
445    #[test]
446    fn test_set_and_find_custom_property() {
447        let mut props = sheetkit_xml::doc_props::CustomProperties::default();
448        set_custom_property(
449            &mut props,
450            "Project",
451            CustomPropertyValue::String("SK".to_string()),
452        )
453        .unwrap();
454        let found = find_custom_property(&props, "Project");
455        assert_eq!(found, Some(CustomPropertyValue::String("SK".to_string())));
456        assert_eq!(props.properties[0].pid, 2);
457    }
458
459    #[test]
460    fn test_set_custom_property_update_existing() {
461        let mut props = sheetkit_xml::doc_props::CustomProperties::default();
462        set_custom_property(
463            &mut props,
464            "Key",
465            CustomPropertyValue::String("old".to_string()),
466        )
467        .unwrap();
468        set_custom_property(
469            &mut props,
470            "Key",
471            CustomPropertyValue::String("new".to_string()),
472        )
473        .unwrap();
474        assert_eq!(props.properties.len(), 1);
475        assert_eq!(
476            find_custom_property(&props, "Key"),
477            Some(CustomPropertyValue::String("new".to_string()))
478        );
479    }
480
481    #[test]
482    fn test_delete_custom_property() {
483        let mut props = sheetkit_xml::doc_props::CustomProperties::default();
484        set_custom_property(&mut props, "Key", CustomPropertyValue::Int(1)).unwrap();
485        assert!(delete_custom_property(&mut props, "Key"));
486        assert!(!delete_custom_property(&mut props, "Key")); // already gone
487        assert!(find_custom_property(&props, "Key").is_none());
488    }
489
490    #[test]
491    fn test_custom_property_pid_auto_increment() {
492        let mut props = sheetkit_xml::doc_props::CustomProperties::default();
493        set_custom_property(&mut props, "A", CustomPropertyValue::Int(1)).unwrap();
494        set_custom_property(&mut props, "B", CustomPropertyValue::Int(2)).unwrap();
495        set_custom_property(&mut props, "C", CustomPropertyValue::Int(3)).unwrap();
496        assert_eq!(props.properties[0].pid, 2);
497        assert_eq!(props.properties[1].pid, 3);
498        assert_eq!(props.properties[2].pid, 4);
499    }
500
501    #[test]
502    fn test_custom_property_pid_after_parsed_u32_max_reuses_free_pid() {
503        let mut props = sheetkit_xml::doc_props::CustomProperties::default();
504        set_custom_property(&mut props, "A", CustomPropertyValue::Int(1)).unwrap();
505        props.properties[0].pid = u32::MAX;
506        set_custom_property(&mut props, "B", CustomPropertyValue::Int(2)).unwrap();
507        set_custom_property(&mut props, "C", CustomPropertyValue::Int(3)).unwrap();
508        let pids: Vec<u32> = props.properties.iter().map(|p| p.pid).collect();
509        assert_eq!(pids, vec![u32::MAX, 2, 3]);
510    }
511
512    #[test]
513    fn test_custom_property_pid_never_uses_reserved_values() {
514        let mut props = sheetkit_xml::doc_props::CustomProperties::default();
515        set_custom_property(&mut props, "A", CustomPropertyValue::Int(1)).unwrap();
516        props.properties[0].pid = 0;
517        set_custom_property(&mut props, "B", CustomPropertyValue::Int(2)).unwrap();
518        assert_eq!(props.properties[1].pid, 2);
519    }
520
521    // WorkbookSettings tests
522
523    #[test]
524    fn test_workbook_settings_default() {
525        let settings = WorkbookSettings::default();
526        assert!(settings.date1904.is_none());
527        assert!(settings.date_compatibility.is_none());
528        assert!(settings.filter_privacy.is_none());
529        assert!(settings.default_theme_version.is_none());
530        assert!(settings.show_objects.is_none());
531        assert!(settings.code_name.is_none());
532        assert!(settings.check_compatibility.is_none());
533        assert!(settings.auto_compress_pictures.is_none());
534        assert!(settings.refresh_all_connections.is_none());
535        assert!(settings.backup_file.is_none());
536        assert!(settings.save_external_link_values.is_none());
537        assert!(settings.update_links.is_none());
538        assert!(settings.hide_pivot_field_list.is_none());
539        assert!(settings.show_pivot_chart_filter.is_none());
540        assert!(settings.allow_refresh_query.is_none());
541        assert!(settings.publish_items.is_none());
542        assert!(settings.show_border_unselected_tables.is_none());
543        assert!(settings.prompted_solutions.is_none());
544        assert!(settings.show_ink_annotation.is_none());
545    }
546
547    #[test]
548    fn test_workbook_settings_to_xml_roundtrip() {
549        let settings = WorkbookSettings {
550            date1904: Some(false),
551            date_compatibility: Some(true),
552            filter_privacy: Some(true),
553            default_theme_version: Some(166925),
554            show_objects: Some("all".to_string()),
555            code_name: Some("ThisWorkbook".to_string()),
556            check_compatibility: Some(true),
557            auto_compress_pictures: Some(false),
558            refresh_all_connections: Some(true),
559            backup_file: Some(true),
560            save_external_link_values: Some(true),
561            update_links: Some("always".to_string()),
562            hide_pivot_field_list: Some(false),
563            show_pivot_chart_filter: Some(true),
564            allow_refresh_query: Some(true),
565            publish_items: Some(false),
566            show_border_unselected_tables: Some(true),
567            prompted_solutions: Some(false),
568            show_ink_annotation: Some(true),
569        };
570        let pr = settings.to_workbook_pr();
571        let back = WorkbookSettings::from(&pr);
572
573        assert_eq!(back.date1904, Some(false));
574        assert_eq!(back.date_compatibility, Some(true));
575        assert_eq!(back.filter_privacy, Some(true));
576        assert_eq!(back.default_theme_version, Some(166925));
577        assert_eq!(back.show_objects.as_deref(), Some("all"));
578        assert_eq!(back.code_name.as_deref(), Some("ThisWorkbook"));
579        assert_eq!(back.check_compatibility, Some(true));
580        assert_eq!(back.auto_compress_pictures, Some(false));
581        assert_eq!(back.refresh_all_connections, Some(true));
582        assert_eq!(back.backup_file, Some(true));
583        assert_eq!(back.save_external_link_values, Some(true));
584        assert_eq!(back.update_links.as_deref(), Some("always"));
585        assert_eq!(back.hide_pivot_field_list, Some(false));
586        assert_eq!(back.show_pivot_chart_filter, Some(true));
587        assert_eq!(back.allow_refresh_query, Some(true));
588        assert_eq!(back.publish_items, Some(false));
589        assert_eq!(back.show_border_unselected_tables, Some(true));
590        assert_eq!(back.prompted_solutions, Some(false));
591        assert_eq!(back.show_ink_annotation, Some(true));
592    }
593
594    #[test]
595    fn test_workbook_settings_date1904() {
596        let settings = WorkbookSettings {
597            date1904: Some(true),
598            ..Default::default()
599        };
600        let pr = settings.to_workbook_pr();
601        assert_eq!(pr.date1904, Some(true));
602        // All other fields should be None
603        assert!(pr.filter_privacy.is_none());
604        assert!(pr.default_theme_version.is_none());
605        assert!(pr.code_name.is_none());
606
607        let back = WorkbookSettings::from(&pr);
608        assert_eq!(back.date1904, Some(true));
609        assert!(back.filter_privacy.is_none());
610    }
611
612    // CalcSettings tests
613
614    #[test]
615    fn test_calc_settings_default() {
616        let settings = CalcSettings::default();
617        assert!(settings.calc_id.is_none());
618        assert!(settings.calc_mode.is_none());
619        assert!(settings.full_calc_on_load.is_none());
620        assert!(settings.ref_mode.is_none());
621        assert!(settings.iterate.is_none());
622        assert!(settings.iterate_count.is_none());
623        assert!(settings.iterate_delta.is_none());
624        assert!(settings.full_precision.is_none());
625        assert!(settings.calc_completed.is_none());
626        assert!(settings.calc_on_save.is_none());
627        assert!(settings.concurrent_calc.is_none());
628        assert!(settings.concurrent_manual_count.is_none());
629        assert!(settings.force_full_calc.is_none());
630    }
631
632    #[test]
633    fn test_calc_settings_to_xml_roundtrip() {
634        let settings = CalcSettings {
635            calc_id: Some(191029),
636            calc_mode: Some("auto".to_string()),
637            full_calc_on_load: Some(true),
638            ref_mode: Some("A1".to_string()),
639            iterate: Some(true),
640            iterate_count: Some(100),
641            iterate_delta: Some(0.001),
642            full_precision: Some(true),
643            calc_completed: Some(true),
644            calc_on_save: Some(true),
645            concurrent_calc: Some(true),
646            concurrent_manual_count: Some(4),
647            force_full_calc: Some(false),
648        };
649        let pr = settings.to_calc_pr();
650        let back = CalcSettings::from(&pr);
651
652        assert_eq!(back.calc_id, Some(191029));
653        assert_eq!(back.calc_mode.as_deref(), Some("auto"));
654        assert_eq!(back.full_calc_on_load, Some(true));
655        assert_eq!(back.ref_mode.as_deref(), Some("A1"));
656        assert_eq!(back.iterate, Some(true));
657        assert_eq!(back.iterate_count, Some(100));
658        assert_eq!(back.iterate_delta, Some(0.001));
659        assert_eq!(back.full_precision, Some(true));
660        assert_eq!(back.calc_completed, Some(true));
661        assert_eq!(back.calc_on_save, Some(true));
662        assert_eq!(back.concurrent_calc, Some(true));
663        assert_eq!(back.concurrent_manual_count, Some(4));
664        assert_eq!(back.force_full_calc, Some(false));
665    }
666
667    #[test]
668    fn test_calc_settings_manual_mode() {
669        let settings = CalcSettings {
670            calc_mode: Some("manual".to_string()),
671            calc_on_save: Some(false),
672            ..Default::default()
673        };
674        let pr = settings.to_calc_pr();
675        assert_eq!(pr.calc_mode.as_deref(), Some("manual"));
676        assert_eq!(pr.calc_on_save, Some(false));
677        // All other fields should be None
678        assert!(pr.calc_id.is_none());
679        assert!(pr.iterate.is_none());
680
681        let back = CalcSettings::from(&pr);
682        assert_eq!(back.calc_mode.as_deref(), Some("manual"));
683        assert_eq!(back.calc_on_save, Some(false));
684        assert!(back.calc_id.is_none());
685    }
686
687    #[test]
688    fn test_calc_settings_iterative() {
689        let settings = CalcSettings {
690            iterate: Some(true),
691            iterate_count: Some(200),
692            iterate_delta: Some(0.0001),
693            ..Default::default()
694        };
695        let pr = settings.to_calc_pr();
696        assert_eq!(pr.iterate, Some(true));
697        assert_eq!(pr.iterate_count, Some(200));
698        assert_eq!(pr.iterate_delta, Some(0.0001));
699        // Other fields None
700        assert!(pr.calc_mode.is_none());
701        assert!(pr.ref_mode.is_none());
702
703        let back = CalcSettings::from(&pr);
704        assert_eq!(back.iterate, Some(true));
705        assert_eq!(back.iterate_count, Some(200));
706        assert_eq!(back.iterate_delta, Some(0.0001));
707    }
708}