1use std::fmt;
4
5use kicad_monkey_contracts::generated::schematic_plot_document::SchematicPlotDocumentA0;
6
7use crate::{
8 PlotProjectionError, PlotterTextCacheResources, SchematicBundleIndex, SchematicDrawingSettings,
9 SchematicOccurrence, SchematicPlotContext, SchematicPlotDocument, SchematicPlotVariables,
10 SourceBundle, schematic_plot_document_with_sheets,
11};
12
13#[derive(Clone, Debug, Eq, PartialEq)]
14pub enum SchematicOccurrenceSelector {
15 Address(String),
16}
17
18#[derive(Clone, Debug, Default, Eq, PartialEq)]
19pub struct SchematicPageContextOverrides {
20 pub source_path: Option<String>,
21 pub document_id: Option<String>,
22 pub sheet_name: Option<String>,
23}
24
25pub struct SchematicPagePlotRequest<'resources, 'font> {
26 pub selector: SchematicOccurrenceSelector,
27 pub context_overrides: SchematicPageContextOverrides,
28 pub drawing_settings: SchematicDrawingSettings,
29 pub worksheet_source: Option<Vec<u8>>,
30 pub variables: SchematicPlotVariables,
31 pub text_resources: Option<&'resources PlotterTextCacheResources<'font>>,
32}
33
34impl<'resources, 'font> SchematicPagePlotRequest<'resources, 'font> {
35 pub fn new(address: impl Into<String>) -> Self {
36 Self {
37 selector: SchematicOccurrenceSelector::Address(address.into()),
38 context_overrides: SchematicPageContextOverrides::default(),
39 drawing_settings: SchematicDrawingSettings::default(),
40 worksheet_source: None,
41 variables: SchematicPlotVariables::default(),
42 text_resources: None,
43 }
44 }
45}
46
47#[derive(Clone, Copy, Debug, Eq, PartialEq)]
48pub enum SchematicPagePlotErrorKind {
49 BundleMismatch,
50 MalformedSelector,
51 MissingOccurrence,
52 DuplicateOccurrence,
53 MissingSource,
54 Source,
55 Producer,
56}
57
58#[derive(Clone, Debug, Eq, PartialEq)]
59pub struct SchematicPagePlotError {
60 pub kind: SchematicPagePlotErrorKind,
61 message: String,
62}
63
64impl SchematicPagePlotError {
65 fn new(kind: SchematicPagePlotErrorKind, message: impl Into<String>) -> Self {
66 Self {
67 kind,
68 message: message.into(),
69 }
70 }
71
72 pub fn message(&self) -> &str {
73 &self.message
74 }
75}
76
77impl fmt::Display for SchematicPagePlotError {
78 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
79 formatter.write_str(&self.message)
80 }
81}
82
83impl std::error::Error for SchematicPagePlotError {}
84
85#[derive(Clone, Debug)]
86pub struct SchematicPagePlotSourceArtifact {
87 document: SchematicPlotDocument,
88 occurrence_address: String,
89 source_path: String,
90}
91
92impl SchematicPagePlotSourceArtifact {
93 pub fn document(&self) -> &SchematicPlotDocument {
94 &self.document
95 }
96
97 pub fn occurrence_address(&self) -> &str {
98 &self.occurrence_address
99 }
100
101 pub fn source_path(&self) -> &str {
102 &self.source_path
103 }
104
105 pub(crate) fn into_parts(self) -> (SchematicPlotDocument, String, String) {
106 (self.document, self.occurrence_address, self.source_path)
107 }
108}
109
110#[derive(Clone, Debug)]
111pub struct ProjectedSchematicPagePlotArtifact {
112 document: SchematicPlotDocumentA0,
113 occurrence_address: String,
114 source_path: String,
115}
116
117impl ProjectedSchematicPagePlotArtifact {
118 pub fn document(&self) -> &SchematicPlotDocumentA0 {
119 &self.document
120 }
121
122 pub fn occurrence_address(&self) -> &str {
123 &self.occurrence_address
124 }
125
126 pub fn source_path(&self) -> &str {
127 &self.source_path
128 }
129}
130
131pub fn schematic_page_plot_document(
132 bundle: &SourceBundle,
133 index: &SchematicBundleIndex,
134 request: SchematicPagePlotRequest<'_, '_>,
135) -> Result<SchematicPagePlotSourceArtifact, SchematicPagePlotError> {
136 if !index.bundle_belongs_to(bundle) {
137 return Err(SchematicPagePlotError::new(
138 SchematicPagePlotErrorKind::BundleMismatch,
139 "schematic bundle index was built from a different source bundle",
140 ));
141 }
142 let address = match request.selector {
143 SchematicOccurrenceSelector::Address(ref value) => normalize_selector(value)?,
144 };
145 let mut matches = index
146 .occurrences()
147 .filter(|occurrence| occurrence.occurrence_address == address);
148 let occurrence = matches.next().ok_or_else(|| {
149 SchematicPagePlotError::new(
150 SchematicPagePlotErrorKind::MissingOccurrence,
151 format!("schematic occurrence address {address:?} is absent"),
152 )
153 })?;
154 if matches.next().is_some() {
155 return Err(SchematicPagePlotError::new(
156 SchematicPagePlotErrorKind::DuplicateOccurrence,
157 format!("schematic occurrence address {address:?} is ambiguous"),
158 ));
159 }
160 build_occurrence_document(bundle, index, occurrence, request, None)
161 .map(|(artifact, _, _)| artifact)
162}
163
164pub(crate) fn owned_page_plot(
165 bundle: &SourceBundle,
166 index: &SchematicBundleIndex,
167 occurrence: &SchematicOccurrence,
168 request: SchematicPagePlotRequest<'_, '_>,
169 input: crate::schematic_plotter_ir::owned::OwnedPlotInput,
170) -> Result<
171 (
172 SchematicPagePlotSourceArtifact,
173 Vec<crate::schematic_plotter_ir::owned::NativePlotBinding>,
174 Vec<crate::KiCadDiagnostic>,
175 ),
176 SchematicPagePlotError,
177> {
178 build_occurrence_document(bundle, index, occurrence, request, Some(input))
179}
180
181pub fn project_schematic_page_plot_artifact_a0(
182 source: SchematicPagePlotSourceArtifact,
183) -> Result<ProjectedSchematicPagePlotArtifact, PlotProjectionError> {
184 let (document, occurrence_address, source_path) = source.into_parts();
185 let document = crate::project_schematic_plot_document_a0(&document)?;
186 Ok(ProjectedSchematicPagePlotArtifact {
187 document,
188 occurrence_address,
189 source_path,
190 })
191}
192
193fn build_occurrence_document(
194 bundle: &SourceBundle,
195 index: &SchematicBundleIndex,
196 occurrence: &SchematicOccurrence,
197 request: SchematicPagePlotRequest<'_, '_>,
198 owned: Option<crate::schematic_plotter_ir::owned::OwnedPlotInput>,
199) -> Result<
200 (
201 SchematicPagePlotSourceArtifact,
202 Vec<crate::schematic_plotter_ir::owned::NativePlotBinding>,
203 Vec<crate::KiCadDiagnostic>,
204 ),
205 SchematicPagePlotError,
206> {
207 let source_text = index
208 .source_text(bundle, &occurrence.source_path)
209 .map_err(|error| {
210 SchematicPagePlotError::new(SchematicPagePlotErrorKind::Source, error.to_string())
211 })?
212 .ok_or_else(|| {
213 SchematicPagePlotError::new(
214 SchematicPagePlotErrorKind::MissingSource,
215 format!("schematic source {:?} is absent", occurrence.source_path),
216 )
217 })?;
218 let definition = index.definition(&occurrence.source_path).ok_or_else(|| {
219 SchematicPagePlotError::new(
220 SchematicPagePlotErrorKind::MissingSource,
221 format!(
222 "schematic definition {:?} is absent from the index",
223 occurrence.source_path
224 ),
225 )
226 })?;
227 let source_path = request
228 .context_overrides
229 .source_path
230 .unwrap_or_else(|| occurrence.source_path.clone());
231 let document_id = request.context_overrides.document_id.unwrap_or_else(|| {
232 definition
233 .uuid
234 .clone()
235 .filter(|value| !value.is_empty())
236 .unwrap_or_else(|| source_stem(&occurrence.source_path, occurrence.index))
237 });
238 let sheet_name = request.context_overrides.sheet_name.unwrap_or_else(|| {
239 if occurrence.parent_index.is_none() {
240 index.root_sheet_name().to_owned()
241 } else {
242 occurrence.sheet_name.clone()
243 }
244 });
245 let context = SchematicPlotContext {
246 source_path: Some(source_path.clone()),
247 document_id: Some(document_id),
248 sheet_index: sheet_number(index, occurrence),
249 sheet_count: index.occurrences().len(),
250 sheet_path: occurrence.human_address.clone(),
251 sheet_instance_path: occurrence.occurrence_address.clone(),
252 sheet_name,
253 project_variables: request.variables,
254 worksheet_source: request.worksheet_source,
255 };
256 let (document, bindings, diagnostics) = if let Some(input) = owned {
257 crate::schematic_plotter_ir::owned::render(
258 source_text,
259 &context,
260 request.drawing_settings,
261 request.text_resources,
262 input,
263 )
264 } else {
265 schematic_plot_document_with_sheets(
266 source_text,
267 &context,
268 request.drawing_settings,
269 request.text_resources,
270 )
271 .map(|document| (document, Vec::new(), Vec::new()))
272 }
273 .map_err(|error| {
274 SchematicPagePlotError::new(SchematicPagePlotErrorKind::Producer, error.to_string())
275 })?;
276 Ok((
277 SchematicPagePlotSourceArtifact {
278 document,
279 occurrence_address: occurrence.occurrence_address.clone(),
280 source_path,
281 },
282 bindings,
283 diagnostics,
284 ))
285}
286
287fn normalize_selector(value: &str) -> Result<String, SchematicPagePlotError> {
288 if value == "/" {
289 return Ok(value.to_owned());
290 }
291 if value.is_empty() || !value.starts_with('/') {
292 return Err(SchematicPagePlotError::new(
293 SchematicPagePlotErrorKind::MalformedSelector,
294 "schematic occurrence address must be an absolute non-empty path",
295 ));
296 }
297 Ok(value.strip_suffix('/').unwrap_or(value).to_owned())
298}
299
300fn sheet_number(index: &SchematicBundleIndex, occurrence: &SchematicOccurrence) -> usize {
301 if let (Some(parent_index), Some(sheet_index)) =
302 (occurrence.parent_index, occurrence.parent_sheet_index)
303 && let Some(parent) = index.occurrence(parent_index)
304 && let Some(definition) = index.definition(&parent.source_path)
305 && let Some(number) = definition
306 .sheets
307 .get(sheet_index)
308 .and_then(|sheet| page_number(&sheet.page_instances, &occurrence.occurrence_address))
309 {
310 return if number == 0 {
311 occurrence.index
312 } else {
313 number
314 };
315 }
316 index
317 .definition(&occurrence.source_path)
318 .and_then(|definition| {
319 page_number(
320 &definition.root_page_instances,
321 &occurrence.occurrence_address,
322 )
323 })
324 .filter(|number| *number != 0)
325 .unwrap_or(occurrence.index)
326}
327
328fn page_number(instances: &[crate::SchematicPageInstance], target_path: &str) -> Option<usize> {
329 instances
330 .iter()
331 .find(|instance| normalize_authored_path(&instance.path) == target_path)
332 .or_else(|| instances.first())
333 .map(|instance| instance.page_number)
334}
335
336fn normalize_authored_path(path: &str) -> &str {
337 let trimmed = path.trim_end_matches('/');
338 if trimmed.is_empty() { "/" } else { trimmed }
339}
340
341fn source_stem(path: &str, index: usize) -> String {
342 let filename = path.rsplit('/').next().unwrap_or(path);
343 filename
344 .strip_suffix(".kicad_sch")
345 .filter(|value| !value.is_empty())
346 .map_or_else(|| format!("sheet_{index}"), str::to_owned)
347}