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::RenderWithContext;
31        self.exporter.export(
32            &model.render_with_context(&mut render_context)?,
33            &self.filename,
34        )
35    }
36}
37
38impl From<ExportCommand> for Value {
39    fn from(export_attribute: ExportCommand) -> Self {
40        crate::create_tuple_value!(
41            filename = Value::String(String::from(
42                export_attribute.filename.to_str().expect("PathBuf"),
43            )),
44            id = Value::String(export_attribute.exporter.id().to_string())
45        )
46    }
47}
48
49impl std::fmt::Debug for ExportCommand {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        write!(
52            f,
53            "Export: {id:?} => {filename}",
54            id = self.exporter.id(),
55            filename = self.filename.display()
56        )
57    }
58}
59
60impl std::fmt::Display for ExportCommand {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        write!(
63            f,
64            "\"{filename}\" with exporter `{id}`",
65            filename = self.filename.display(),
66            id = self.exporter.id(),
67        )
68    }
69}