microcad_lang/model/attribute/
export_command.rs

1// Copyright © 2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Export attribute.
5
6use crate::{
7    builtin::{ExportError, Exporter},
8    model::Model,
9    render::RenderContext,
10    value::Value,
11};
12use microcad_core::RenderResolution;
13
14/// Export attribute, e.g. `#[export: "output.svg"]`.
15#[derive(Clone)]
16pub struct ExportCommand {
17    /// Filename.
18    pub filename: std::path::PathBuf,
19    /// Resolution
20    pub resolution: RenderResolution,
21    /// Exporter.
22    pub exporter: std::rc::Rc<dyn Exporter>,
23}
24
25impl ExportCommand {
26    /// Export the model. By the settings in the attribute.
27    pub fn export(&self, model: &Model) -> Result<Value, ExportError> {
28        let mut render_context = RenderContext::init(model, self.resolution.clone())?;
29
30        use crate::render::Render;
31        self.exporter
32            .export(&model.render(&mut render_context)?, &self.filename)
33    }
34}
35
36impl From<ExportCommand> for Value {
37    fn from(export_attribute: ExportCommand) -> Self {
38        crate::create_tuple_value!(
39            filename = Value::String(String::from(
40                export_attribute.filename.to_str().expect("PathBuf"),
41            )),
42            id = Value::String(export_attribute.exporter.id().to_string())
43        )
44    }
45}
46
47impl std::fmt::Debug for ExportCommand {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        write!(
50            f,
51            "Export: {id:?} => {filename}",
52            id = self.exporter.id(),
53            filename = self.filename.display()
54        )
55    }
56}
57
58impl std::fmt::Display for ExportCommand {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        write!(
61            f,
62            "\"{filename}\" with exporter `{id}`",
63            filename = self.filename.display(),
64            id = self.exporter.id(),
65        )
66    }
67}