kicad_monkey_core/pcb/
document.rs1use super::*;
4use crate::sexpr::utf8_text;
5use std::io::{Read, Write};
6
7#[derive(Clone, Debug)]
13pub struct PcbDocument {
14 source: String,
15 limits: PcbLimits,
16}
17
18impl PcbDocument {
19 pub fn parse(source: String, limits: PcbLimits) -> Result<Self, Error> {
21 PcbView::parse(&source, limits)?;
22 Ok(Self { source, limits })
23 }
24
25 pub fn from_reader(mut reader: impl Read, limits: PcbLimits) -> Result<Self, Error> {
27 let read_limit = limits.max_source_bytes.saturating_add(1);
29 let mut bytes = Vec::new();
30 reader
31 .by_ref()
32 .take(read_limit as u64)
33 .read_to_end(&mut bytes)
34 .map_err(io_error)?;
35 if bytes.len() > limits.max_source_bytes {
36 return Err(limit_error());
37 }
38 let source = utf8_text(&bytes)?.to_owned();
39 Self::parse(source, limits)
40 }
41
42 pub fn source(&self) -> &str {
43 &self.source
44 }
45
46 pub fn into_source(self) -> String {
47 self.source
48 }
49
50 pub fn limits(&self) -> PcbLimits {
51 self.limits
52 }
53
54 pub fn view(&self) -> Result<PcbView<'_>, Error> {
56 PcbView::parse(&self.source, self.limits)
57 }
58
59 pub fn view_selected(&self, selection: PcbSelection) -> Result<PcbView<'_>, Error> {
61 PcbView::parse_selected(&self.source, self.limits, selection)
62 }
63
64 pub fn write_to(&self, mut writer: impl Write) -> Result<(), Error> {
66 if self.source.len() > self.limits.max_output_bytes {
67 return Err(output_limit_error());
68 }
69 writer.write_all(self.source.as_bytes()).map_err(io_error)
70 }
71
72 pub fn set_property(&mut self, name: &str, value: &str) -> Result<bool, Error> {
74 let edit = self.view()?.set_property(name, value)?;
75 self.commit(edit)
76 }
77
78 pub fn upsert_property(&mut self, name: &str, value: &str) -> Result<bool, Error> {
80 let edit = self.view()?.upsert_property(name, value)?;
81 self.commit(edit)
82 }
83
84 pub fn remove_property(&mut self, name: &str) -> Result<bool, Error> {
86 let edit = self.view()?.remove_property(name)?;
87 self.commit(edit)
88 }
89
90 pub fn remove_top_level_by_id(&mut self, identifier: &str) -> Result<bool, Error> {
92 let edit = self.view()?.remove_top_level_by_id(identifier)?;
93 self.commit(edit)
94 }
95
96 pub fn set_top_level_layer_by_id(
98 &mut self,
99 identifier: &str,
100 layer: &str,
101 ) -> Result<bool, Error> {
102 let edit = self.view()?.set_top_level_layer_by_id(identifier, layer)?;
103 self.commit(edit)
104 }
105
106 fn commit(&mut self, edit: PcbEdit) -> Result<bool, Error> {
107 if !edit.changed {
108 return Ok(false);
109 }
110 PcbView::parse(&edit.source, self.limits)?;
111 self.source = edit.source;
112 Ok(true)
113 }
114}
115
116fn io_error(error: std::io::Error) -> Error {
117 Error::build(ErrorKind::Io, format!("PCB source I/O failed: {error}"))
118}