1use super::*;
4use crate::{KiCadColor, KiCadFont};
5
6const MAX_PROPERTY_HEADER_SCALARS: usize = 256;
7const MAX_EFFECTS_FLAGS: usize = 64;
8
9pub(super) fn footprint_text_position(
13 source: &str,
14 children: &[FormSpan],
15 limits: PcbLimits,
16) -> Result<([f64; 3], bool), Error> {
17 let Some(at) = child(children, "at") else {
18 return Ok(([0.; 3], false));
19 };
20 if !direct_children(source, at, limits.max_object_children, limits)?.is_empty() {
21 return Err(source_error(
22 "primary placement has an invalid trailing token",
23 at.start,
24 ));
25 }
26 let values = bounded_scalar_values(source, at, limits.max_object_children)?;
27 let mut result = [0.; 3];
28 result[0] = required_f64(values.first(), "Expected footprint text X coordinate", at)?;
29 result[1] = required_f64(values.get(1), "Expected footprint text Y coordinate", at)?;
30 let mut tail = 2;
31 if values
32 .get(tail)
33 .is_some_and(|token| token_string(token) != "unlocked")
34 {
35 result[2] = required_f64(values.get(tail), "Expected footprint text angle", at)?;
36 tail += 1;
37 }
38 let unlocked = values
39 .get(tail)
40 .is_some_and(|token| token.kind == TokenKind::Atom && token.lexeme == "unlocked");
41 if values.len() != tail + usize::from(unlocked) {
42 return Err(source_error(
43 "primary placement has an invalid trailing token",
44 at.start,
45 ));
46 }
47 Ok((result, unlocked))
48}
49
50#[derive(Clone, Debug, PartialEq)]
52pub struct PcbFootprintProperty {
53 pub footprint_index: usize,
54 pub name: String,
55 pub value: String,
56 pub at: PcbPoint,
57 pub angle: f64,
58 pub layer: String,
59 pub knockout: bool,
60 pub hidden: bool,
61 pub unlocked: bool,
62 pub graphical: bool,
63 pub effects: KiCadTextEffects,
64 pub render_cache_range: Option<Range<usize>>,
65 pub uuid: Option<String>,
66 pub source_range: Range<usize>,
67}
68
69#[derive(Clone, Debug, PartialEq)]
71pub struct PcbFootprintGraphic {
72 pub footprint_index: usize,
73 pub graphic: PcbGraphic,
74}
75
76#[derive(Clone, Debug, PartialEq)]
78pub struct PcbFootprintText {
79 pub footprint_index: usize,
80 pub kind: String,
81 pub text: String,
82 pub at: PcbPoint,
83 pub angle: f64,
84 pub layer: String,
85 pub knockout: bool,
86 pub hidden: bool,
87 pub unlocked: bool,
88 pub uuid: Option<String>,
89 pub effects: KiCadTextEffects,
90 pub render_cache_range: Option<Range<usize>>,
91 pub source_range: Range<usize>,
92}
93
94#[derive(Clone, Debug, PartialEq)]
96pub struct PcbFootprintTextBox {
97 pub footprint_index: usize,
98 pub text: String,
99 pub start: PcbPoint,
100 pub end: PcbPoint,
101 pub margins: [f64; 4],
102 pub angle: f64,
103 pub polygon_points: Vec<PcbPoint>,
104 pub layer: String,
105 pub locked: bool,
106 pub effects: Option<KiCadTextEffects>,
107 pub stroke_width: Option<f64>,
108 pub stroke_kind: Option<String>,
109 pub border: Option<bool>,
110 pub knockout: Option<bool>,
111 pub render_cache_range: Option<Range<usize>>,
112 pub uuid: Option<String>,
113 pub source_range: Range<usize>,
114}
115
116impl<'a> PcbView<'a> {
117 pub fn footprint_properties(
119 &self,
120 ) -> impl Iterator<Item = Result<PcbFootprintProperty, Error>> + '_ {
121 self.footprint_properties
122 .iter()
123 .filter(move |_| self.selection.contains(PcbFamily::FootprintProperties))
124 .map(|indexed| footprint_property_from_span(self.source, indexed, self.limits))
125 }
126
127 pub fn footprint_graphics(
129 &self,
130 ) -> impl Iterator<Item = Result<PcbFootprintGraphic, Error>> + '_ {
131 self.footprint_graphics
132 .iter()
133 .filter(move |_| self.selection.contains(PcbFamily::FootprintGraphics))
134 .map(|indexed| {
135 Ok(PcbFootprintGraphic {
136 footprint_index: indexed.parent_index,
137 graphic: graphic_from_span(self.source, &indexed.span, self.limits)?,
138 })
139 })
140 }
141
142 pub fn footprint_texts(&self) -> impl Iterator<Item = Result<PcbFootprintText, Error>> + '_ {
144 self.footprint_texts
145 .iter()
146 .filter(move |_| self.selection.contains(PcbFamily::FootprintTexts))
147 .map(|indexed| footprint_text_from_span(self.source, indexed, self.limits))
148 }
149
150 pub fn footprint_text_boxes(
152 &self,
153 ) -> impl Iterator<Item = Result<PcbFootprintTextBox, Error>> + '_ {
154 self.footprint_text_boxes
155 .iter()
156 .filter(move |_| self.selection.contains(PcbFamily::FootprintTextBoxes))
157 .map(|indexed| footprint_text_box_from_span(self.source, indexed, self.limits))
158 }
159}
160
161pub(super) fn footprint_text_from_span(
162 source: &str,
163 indexed: &IndexedNestedForm,
164 limits: PcbLimits,
165) -> Result<PcbFootprintText, Error> {
166 let header = bounded_scalar_values(
167 source,
168 &indexed.span,
169 MAX_PROPERTY_HEADER_SCALARS.min(limits.max_object_children),
170 )?;
171 let children = direct_children(source, &indexed.span, limits.max_object_children, limits)?;
172 let at = footprint_text_position(source, &children, limits)?.0;
173 let effects = text_effects_from_children(source, &children, limits)?.unwrap_or_default();
174 let (layer, knockout) = text_layer(source, &children, limits.max_object_children)?;
175 Ok(PcbFootprintText {
176 footprint_index: indexed.parent_index,
177 kind: required_string(
178 header.first(),
179 "Expected footprint text kind",
180 &indexed.span,
181 )?,
182 text: required_string(header.get(1), "Expected footprint text", &indexed.span)?,
183 at: PcbPoint { x: at[0], y: at[1] },
184 angle: at[2],
185 layer,
186 knockout,
187 hidden: has_flag(&header, "hide")
188 || child_bool(source, &children, "hide")?
189 || effects.hidden,
190 unlocked: has_flag(&header, "unlocked") || child_bool(source, &children, "unlocked")?,
191 uuid: optional_uuid(source, &children)?,
192 effects,
193 render_cache_range: child(&children, "render_cache").map(|span| span.range.clone()),
194 source_range: indexed.span.range.clone(),
195 })
196}
197
198pub(super) fn footprint_text_box_from_span(
199 source: &str,
200 indexed: &IndexedNestedForm,
201 limits: PcbLimits,
202) -> Result<PcbFootprintTextBox, Error> {
203 let header = bounded_scalar_values(
204 source,
205 &indexed.span,
206 MAX_PROPERTY_HEADER_SCALARS.min(limits.max_object_children),
207 )?;
208 let children = direct_children(source, &indexed.span, limits.max_object_children, limits)?;
209 let polygon_points = child(&children, "pts")
210 .map(|span| text_box_points(source, span, limits))
211 .transpose()?
212 .unwrap_or_default();
213 let mut start =
214 optional_child_point(source, &children, "start")?.unwrap_or(PcbPoint { x: 0.0, y: 0.0 });
215 let mut end =
216 optional_child_point(source, &children, "end")?.unwrap_or(PcbPoint { x: 0.0, y: 0.0 });
217 if !polygon_points.is_empty()
218 && (child(&children, "start").is_none() || child(&children, "end").is_none())
219 {
220 let (min_x, max_x) = point_extents(&polygon_points, |point| point.x);
221 let (min_y, max_y) = point_extents(&polygon_points, |point| point.y);
222 start = PcbPoint { x: min_x, y: min_y };
223 end = PcbPoint { x: max_x, y: max_y };
224 }
225 let margins = text_box_margins(source, &children, limits.max_object_children)?;
226 let (stroke_width, stroke_kind) = text_box_stroke(source, &children, limits)?;
227 Ok(PcbFootprintTextBox {
228 footprint_index: indexed.parent_index,
229 text: header.first().map(token_string).unwrap_or_default(),
230 start,
231 end,
232 margins,
233 angle: optional_child_f64(source, &children, "angle")?.unwrap_or(0.0),
234 polygon_points,
235 layer: optional_child_string(source, &children, "layer")?
236 .unwrap_or_else(|| "F.SilkS".to_owned()),
237 locked: optional_named_bool(source, &header, &children, "locked")?.unwrap_or(false),
238 effects: text_effects_from_children(source, &children, limits)?,
239 stroke_width,
240 stroke_kind,
241 border: optional_named_bool(source, &header, &children, "border")?,
242 knockout: optional_named_bool(source, &header, &children, "knockout")?,
243 render_cache_range: child(&children, "render_cache").map(|span| span.range.clone()),
244 uuid: optional_uuid(source, &children)?,
245 source_range: indexed.span.range.clone(),
246 })
247}
248
249pub(super) fn text_effects_from_children(
250 source: &str,
251 children: &[FormSpan],
252 limits: PcbLimits,
253) -> Result<Option<KiCadTextEffects>, Error> {
254 let Some(effects) = child(children, "effects") else {
255 return Ok(None);
256 };
257 let header = bounded_scalar_values(
258 source,
259 effects,
260 MAX_EFFECTS_FLAGS.min(limits.max_text_effect_children),
261 )?;
262 let fields = direct_children(source, effects, limits.max_text_effect_children, limits)?;
263 let justify = child(&fields, "justify")
264 .map(|span| bounded_scalar_values(source, span, limits.max_text_justify_tokens))
265 .transpose()?
266 .unwrap_or_default()
267 .iter()
268 .map(token_string)
269 .collect();
270 Ok(Some(KiCadTextEffects {
271 font: text_font_from_children(source, &fields, limits)?,
272 justify,
273 hidden: has_flag(&header, "hide") || child_bool(source, &fields, "hide")?,
274 href: optional_child_string(source, &fields, "href")?,
275 source_range: Some(effects.range.clone()),
276 }))
277}
278
279fn text_font_from_children(
280 source: &str,
281 effects_children: &[FormSpan],
282 limits: PcbLimits,
283) -> Result<KiCadFont, Error> {
284 let Some(font) = child(effects_children, "font") else {
285 return Ok(KiCadFont::default());
286 };
287 let header = bounded_scalar_values(
288 source,
289 font,
290 MAX_EFFECTS_FLAGS.min(limits.max_text_font_children),
291 )?;
292 let fields = direct_children(source, font, limits.max_text_font_children, limits)?;
293 let size = child(&fields, "size")
294 .map(|span| bounded_scalar_values(source, span, 2.min(limits.max_text_font_children)))
295 .transpose()?
296 .unwrap_or_default();
297 Ok(KiCadFont {
298 face: optional_child_string(source, &fields, "face")?,
299 size_y: optional_f64(size.first(), font)?.unwrap_or(1.27),
300 size_x: optional_f64(size.get(1), font)?.unwrap_or(1.27),
301 thickness: optional_child_f64(source, &fields, "thickness")?,
302 bold: has_flag(&header, "bold") || child_bool(source, &fields, "bold")?,
303 italic: has_flag(&header, "italic") || child_bool(source, &fields, "italic")?,
304 line_spacing: optional_child_f64(source, &fields, "line_spacing")?,
305 color: optional_color(source, &fields, limits.max_text_font_children)?,
306 })
307}
308
309fn optional_color(
310 source: &str,
311 children: &[FormSpan],
312 maximum: usize,
313) -> Result<Option<KiCadColor>, Error> {
314 let Some(color) = child(children, "color") else {
315 return Ok(None);
316 };
317 let values = bounded_scalar_values(source, color, 4.min(maximum))?;
318 if values.len() < 4 {
319 return Ok(None);
320 }
321 Ok(Some(KiCadColor {
322 red: parse_i64(&values[0], color)?,
323 green: parse_i64(&values[1], color)?,
324 blue: parse_i64(&values[2], color)?,
325 alpha: parse_f64(&values[3], color)?,
326 }))
327}
328
329pub(super) fn text_layer(
330 source: &str,
331 children: &[FormSpan],
332 maximum: usize,
333) -> Result<(String, bool), Error> {
334 let Some(layer) = child(children, "layer") else {
335 return Ok(("F.SilkS".to_owned(), false));
336 };
337 let values = bounded_scalar_values(source, layer, 8.min(maximum))?;
338 Ok((
339 values
340 .first()
341 .map(token_string)
342 .unwrap_or_else(|| "F.SilkS".to_owned()),
343 has_flag(&values, "knockout"),
344 ))
345}
346
347fn text_box_points(
348 source: &str,
349 span: &FormSpan,
350 limits: PcbLimits,
351) -> Result<Vec<PcbPoint>, Error> {
352 let mut result = Vec::new();
353 for point in direct_children(source, span, limits.max_text_box_points, limits)?
354 .into_iter()
355 .filter(|point| point.head.as_deref() == Some("xy"))
356 {
357 let values = first_two_scalar_values(source, &point)?;
358 let [x, y] = values.as_slice() else {
359 continue;
360 };
361 result.push(PcbPoint {
362 x: parse_f64(x, &point)?,
363 y: parse_f64(y, &point)?,
364 });
365 }
366 Ok(result)
367}
368
369fn text_box_margins(
370 source: &str,
371 children: &[FormSpan],
372 maximum: usize,
373) -> Result<[f64; 4], Error> {
374 let Some(margins) = child(children, "margins") else {
375 return Ok([0.0; 4]);
376 };
377 let values = bounded_scalar_values(source, margins, 4.min(maximum))?;
378 let mut result = [0.0; 4];
379 for (index, value) in result.iter_mut().enumerate() {
380 *value = optional_f64(values.get(index), margins)?.unwrap_or(0.0);
381 }
382 Ok(result)
383}
384
385fn point_extents(points: &[PcbPoint], coordinate: impl Fn(&PcbPoint) -> f64) -> (f64, f64) {
386 points.iter().map(coordinate).fold(
387 (f64::INFINITY, f64::NEG_INFINITY),
388 |(minimum, maximum), value| (minimum.min(value), maximum.max(value)),
389 )
390}
391
392fn text_box_stroke(
393 source: &str,
394 children: &[FormSpan],
395 limits: PcbLimits,
396) -> Result<(Option<f64>, Option<String>), Error> {
397 let Some(stroke) = child(children, "stroke") else {
398 return Ok((None, None));
399 };
400 let fields = direct_children(source, stroke, limits.max_text_effect_children, limits)?;
401 Ok((
402 optional_child_f64(source, &fields, "width")?,
403 optional_child_string(source, &fields, "type")?,
404 ))
405}
406
407fn optional_named_bool(
408 source: &str,
409 header: &[Token<'_>],
410 children: &[FormSpan],
411 name: &str,
412) -> Result<Option<bool>, Error> {
413 if has_flag(header, name) {
414 return Ok(Some(true));
415 }
416 let Some(field) = child(children, name) else {
417 return Ok(None);
418 };
419 Ok(Some(
420 first_string(source, field)?.is_none_or(|value| value == "yes"),
421 ))
422}
423
424pub(super) fn footprint_property_from_span(
425 source: &str,
426 indexed: &IndexedNestedForm,
427 limits: PcbLimits,
428) -> Result<PcbFootprintProperty, Error> {
429 let header = bounded_scalar_values(
430 source,
431 &indexed.span,
432 MAX_PROPERTY_HEADER_SCALARS.min(limits.max_object_children),
433 )?;
434 let children = direct_children(source, &indexed.span, limits.max_object_children, limits)?;
435 let at = footprint_text_position(source, &children, limits)?.0;
436 let graphical = child(&children, "at").is_some() && child(&children, "layer").is_some();
437 let (layer, knockout) = text_layer(source, &children, limits.max_object_children)?;
438 let effects = text_effects_from_children(source, &children, limits)?.unwrap_or_default();
439 let hidden =
440 has_flag(&header, "hide") || child_bool(source, &children, "hide")? || effects.hidden;
441 Ok(PcbFootprintProperty {
442 footprint_index: indexed.parent_index,
443 name: required_string(
444 header.first(),
445 "Expected footprint property name",
446 &indexed.span,
447 )?,
448 value: required_string(
449 header.get(1),
450 "Expected footprint property value",
451 &indexed.span,
452 )?,
453 at: PcbPoint { x: at[0], y: at[1] },
454 angle: at[2],
455 layer,
456 knockout,
457 hidden,
458 unlocked: has_flag(&header, "unlocked") || child_bool(source, &children, "unlocked")?,
459 graphical,
460 effects,
461 render_cache_range: child(&children, "render_cache").map(|span| span.range.clone()),
462 uuid: optional_uuid(source, &children)?,
463 source_range: indexed.span.range.clone(),
464 })
465}