Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/
schematic_page.rs

1//! Close-to-format schematic paper access, independent of plotting output.
2use crate::KiCadPaper;
3use crate::sexpr::{Error, ErrorKind, Sexp, parse};
4use crate::sexpr_projection::{Selector, scan_form_spans};
5use std::collections::BTreeSet;
6
7/// Native schematic PAGE_INFO bounds for custom dimensions (KiCad 9 and 10).
8pub const CUSTOM_PAPER_MIN_MM: f64 = 25.4;
9pub const CUSTOM_PAPER_MAX_MM: f64 = 3048.0;
10
11/// Read the first authored paper declaration. Missing paper uses KiCad's A4 default.
12pub fn schematic_paper(source: &str) -> Result<KiCadPaper, Error> {
13    let spans = scan_form_spans(
14        source,
15        &Selector {
16            paths: Some(BTreeSet::from([
17                vec!["kicad_sch".into()],
18                vec!["kicad_sch".into(), "paper".into()],
19            ])),
20            min_depth: Some(0),
21            max_depth: Some(1),
22            ..Selector::default()
23        },
24    )?;
25    if spans
26        .iter()
27        .filter(|span| span.depth == 0 && span.head.as_deref() == Some("kicad_sch"))
28        .count()
29        != 1
30    {
31        return Err(invalid("paper source must be one schematic document"));
32    }
33    let Some(span) = spans
34        .iter()
35        .find(|span| span.depth == 1 && span.head.as_deref() == Some("paper"))
36    else {
37        return Ok(KiCadPaper {
38            size: "A4".into(),
39            width: None,
40            height: None,
41            portrait: false,
42            source_range: None,
43        });
44    };
45    let form = parse(span.text(source)?)?;
46    let Sexp::List(values) = &form else {
47        return Err(invalid("paper is not a list"));
48    };
49    let dimension = |index| -> Result<Option<f64>, Error> {
50        match values.get(index) {
51            None => Ok(None),
52            Some(Sexp::Integer(value)) => Ok(Some(*value as f64)),
53            Some(Sexp::Float(value)) if value.is_finite() => Ok(Some(*value)),
54            Some(value) if scalar(value) == Some("portrait") => Ok(None),
55            _ => Err(invalid("paper dimension is not finite numeric data")),
56        }
57    };
58    Ok(KiCadPaper {
59        size: values
60            .get(1)
61            .and_then(scalar)
62            .filter(|name| !name.is_empty())
63            .ok_or_else(|| invalid("authored paper declaration has no size name"))?
64            .into(),
65        width: dimension(2)?,
66        height: dimension(3)?,
67        portrait: values
68            .iter()
69            .skip(2)
70            .any(|value| scalar(value) == Some("portrait")),
71        source_range: Some(span.range.clone()),
72    })
73}
74
75/// KiCad's effective schematic page extent, after orientation, in nanometres.
76/// ISO sizes follow KiCad's mil-rounded PAGE_INFO dimensions, rather than nominal mm.
77pub fn schematic_paper_extent_nm(paper: &KiCadPaper) -> Result<(i64, i64), Error> {
78    let iso = |width: f64, height: f64| {
79        (
80            ((width * 1000.0 / 25.4 + 0.5) as i64) * 25_400,
81            ((height * 1000.0 / 25.4 + 0.5) as i64) * 25_400,
82        )
83    };
84    let custom = |value: f64| -> Result<i64, Error> {
85        if !value.is_finite() {
86            return Err(invalid("custom paper dimension is not finite"));
87        }
88        // Native schematic parsing clamps PAGE_INFO in mm. Fractions survive;
89        // the SVG viewport's integer-mil size is not the physical page data.
90        Ok((value.clamp(CUSTOM_PAPER_MIN_MM, CUSTOM_PAPER_MAX_MM) * 1_000_000.0).round() as i64)
91    };
92    let dimensions = match paper.size.as_str() {
93        "User" => match (paper.width, paper.height) {
94            (Some(width), Some(height)) => (custom(width)?, custom(height)?),
95            _ => return Err(invalid("custom paper requires both width and height")),
96        },
97        "A0" => iso(1189.0, 841.0),
98        "A1" => iso(841.0, 594.0),
99        "A2" => iso(594.0, 420.0),
100        "A3" => iso(420.0, 297.0),
101        "A5" => iso(210.0, 148.0),
102        "A" | "USLetter" => (279_400_000, 215_900_000),
103        "B" => (431_800_000, 279_400_000),
104        "C" => (558_800_000, 431_800_000),
105        "D" => (863_600_000, 558_800_000),
106        "E" => (1_117_600_000, 863_600_000),
107        "USLegal" => (355_600_000, 215_900_000),
108        "USLedger" => (431_800_000, 279_400_000),
109        "A4" => iso(297.0, 210.0),
110        _ => return Err(invalid("authored paper name is unsupported")),
111    };
112    // PAGE_INFO::SetPortrait does not swap an already-portrait page.
113    Ok(if paper.portrait && dimensions.0 > dimensions.1 {
114        (dimensions.1, dimensions.0)
115    } else {
116        dimensions
117    })
118}
119
120fn invalid(message: &'static str) -> Error {
121    Error::build(ErrorKind::UnexpectedToken, message)
122}
123
124fn scalar(value: &Sexp) -> Option<&str> {
125    match value {
126        Sexp::Atom(value) | Sexp::Quoted(value) => Some(value),
127        _ => None,
128    }
129}