Skip to main content

section_properties/
io.rs

1//! Input/Output module for section data exchange.
2//!
3//! Supports DXF, JSON, CSV, and other formats for interoperability
4//! with CAD software and other engineering tools.
5
6pub mod csv;
7pub mod dxf;
8pub mod json;
9pub mod mesh_export;
10pub mod svg;
11
12pub use csv::{CsvExportOptions, from_csv, to_csv};
13pub use dxf::{DxfColor, DxfExportOptions, to_dxf};
14pub use json::{JsonMaterial, JsonSection, from_json, to_json};
15pub use mesh_export::{to_nastran, to_vtk};
16pub use svg::{SvgExportOptions, plot_centroids, plot_warping_svg, to_interactive_html, to_svg};
17
18use crate::material::Material;
19use crate::section::Section;
20use crate::section_library::{CompositeSection, ParametricSection};
21use crate::section_properties::SectionProperties;
22
23/// Export a section to multiple formats.
24pub struct SectionExporter {
25    pub section: Section,
26    pub properties: Option<SectionProperties>,
27    pub material: Option<Material>,
28    pub designation: Option<String>,
29}
30
31impl SectionExporter {
32    pub fn new(section: Section) -> Self {
33        Self {
34            section,
35            properties: None,
36            material: None,
37            designation: None,
38        }
39    }
40
41    pub fn with_properties(mut self, props: SectionProperties) -> Self {
42        self.properties = Some(props);
43        self
44    }
45
46    pub fn with_material(mut self, material: Material) -> Self {
47        self.material = Some(material);
48        self
49    }
50
51    pub fn with_designation(mut self, designation: String) -> Self {
52        self.designation = Some(designation);
53        self
54    }
55
56    /// Export to DXF string.
57    pub fn to_dxf(&self, options: DxfExportOptions) -> String {
58        dxf::to_dxf(&self.section, options)
59    }
60
61    /// Export to JSON string.
62    pub fn to_json(&self, pretty: bool) -> String {
63        json::to_json(
64            &self.section,
65            self.properties.as_ref(),
66            self.material.as_ref(),
67            self.designation.as_deref(),
68            pretty,
69        )
70    }
71
72    /// Export to CSV string.
73    pub fn to_csv(&self, options: CsvExportOptions) -> String {
74        csv::to_csv(&self.section, options)
75    }
76
77    /// Export to SVG string.
78    pub fn to_svg(&self, options: SvgExportOptions) -> String {
79        svg::to_svg(&self.section, options)
80    }
81
82    /// Save to file (auto-detect format from extension).
83    pub fn save<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), std::io::Error> {
84        let path = path.as_ref();
85        let ext = path
86            .extension()
87            .and_then(|s| s.to_str())
88            .unwrap_or("")
89            .to_lowercase();
90
91        let content = match ext.as_str() {
92            "dxf" => self.to_dxf(DxfExportOptions::default()),
93            "json" => self.to_json(true),
94            "csv" => self.to_csv(CsvExportOptions::default()),
95            "svg" => self.to_svg(SvgExportOptions::default()),
96            _ => {
97                return Err(std::io::Error::new(
98                    std::io::ErrorKind::InvalidInput,
99                    "Unsupported format",
100                ));
101            }
102        };
103
104        std::fs::write(path, content)
105    }
106}
107
108/// Import a section from various formats.
109pub struct SectionImporter;
110
111impl SectionImporter {
112    /// Import from JSON.
113    pub fn from_json(json_str: &str) -> Result<JsonSection, serde_json::Error> {
114        json::from_json(json_str)
115    }
116
117    /// Import from CSV.
118    pub fn from_csv(csv_str: &str) -> Result<Section, Box<dyn std::error::Error>> {
119        csv::from_csv(csv_str)
120    }
121
122    /// Import from DXF (simplified - reads POLYLINE/LWPOLYLINE).
123    pub fn from_dxf(dxf_str: &str) -> Result<Vec<Section>, DxfImportError> {
124        dxf::from_dxf(dxf_str)
125    }
126}
127
128/// DXF import errors.
129#[derive(Debug, Clone)]
130pub enum DxfImportError {
131    ParseError(String),
132    NoClosedPolylines,
133    InvalidGeometry(String),
134}
135
136impl std::fmt::Display for DxfImportError {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        match self {
139            DxfImportError::ParseError(e) => write!(f, "DXF parse error: {}", e),
140            DxfImportError::NoClosedPolylines => write!(f, "No closed polylines found"),
141            DxfImportError::InvalidGeometry(e) => write!(f, "Invalid geometry: {}", e),
142        }
143    }
144}
145
146impl std::error::Error for DxfImportError {}
147
148/// Batch export multiple sections.
149pub fn export_section_library<P: AsRef<std::path::Path>>(
150    sections: &[(String, Section)],
151    directory: P,
152    format: ExportFormat,
153) -> Result<(), std::io::Error> {
154    let dir = directory.as_ref();
155    std::fs::create_dir_all(dir)?;
156
157    for (name, section) in sections {
158        let safe_name = name.replace('/', "_").replace('\\', "_").replace(':', "_");
159        let filename = format!("{}.{}", safe_name, format.extension());
160        let path = dir.join(filename);
161
162        let exporter = SectionExporter::new(section.clone());
163        exporter.save(&path)?;
164    }
165
166    Ok(())
167}
168
169/// Export format options.
170#[derive(Debug, Clone, Copy)]
171pub enum ExportFormat {
172    Dxf,
173    Json,
174    Csv,
175    Svg,
176}
177
178impl ExportFormat {
179    pub fn extension(&self) -> &'static str {
180        match self {
181            ExportFormat::Dxf => "dxf",
182            ExportFormat::Json => "json",
183            ExportFormat::Csv => "csv",
184            ExportFormat::Svg => "svg",
185        }
186    }
187}
188
189/// Create a section from a parametric section for export.
190pub fn section_from_parametric<S: ParametricSection>(parametric: &S) -> SectionExporter {
191    SectionExporter::new(parametric.build()).with_designation(parametric.designation())
192}
193
194/// Create a section from composite section for export.
195pub fn section_from_composite(composite: &CompositeSection) -> SectionExporter {
196    let section = crate::section::Section::new(composite.outer.clone(), composite.holes.clone());
197    SectionExporter::new(section)
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    use crate::material::presets::STEEL_S355;
205
206    use crate::section_library::steel::ISection;
207
208    #[test]
209    fn exporter_basic() {
210        let i = ISection::from_designation("IPE300").unwrap();
211        let section = i.build();
212
213        let exporter = SectionExporter::new(section)
214            .with_material(STEEL_S355)
215            .with_designation("IPE300".to_string());
216
217        let dxf = exporter.to_dxf(DxfExportOptions::default());
218        assert!(dxf.contains("SECTION"));
219        assert!(dxf.contains("POLYLINE"));
220
221        let json = exporter.to_json(true);
222        assert!(json.contains("IPE300"));
223        assert!(json.contains("vertices"));
224
225        let svg = exporter.to_svg(SvgExportOptions::default());
226        assert!(svg.contains("<svg"));
227        assert!(svg.contains("<path"));
228    }
229
230    #[test]
231    fn json_roundtrip() {
232        let i = ISection::from_designation("IPE300").unwrap();
233        let section = i.build();
234
235        let exporter = SectionExporter::new(section.clone()).with_designation("IPE300".to_string());
236
237        let json = exporter.to_json(false);
238        let imported = SectionImporter::from_json(&json).unwrap();
239
240        assert_eq!(imported.designation, Some("IPE300".to_string()));
241        assert_eq!(imported.outer_vertices.len(), section.outer.vertices.len());
242    }
243}