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

kicad_monkey_core/
symbol_text.rs

1//! Library-symbol body text and pin name/number Plotter-IR emission.
2
3use crate::plotter_types::{PlotterOperation, PlotterText, PlotterTextHAlign, PlotterTextVAlign};
4use crate::sexpr::{Error, ErrorKind, ErrorPhase, Position, Sexp};
5use crate::text_metadata::parse_text_effects;
6use crate::{KiCadColor, KiCadTextEffects};
7use std::collections::BTreeMap;
8
9const DEFAULT_PIN_NAME_OFFSET_MM: f64 = 0.508;
10const DEFAULT_TEXT_PEN_WIDTH_NM: i64 = 152_400;
11const PIN_TEXT_MARGIN_NM: i64 = 101_600;
12const DEVICE_COLOR: &str = "#840000FF";
13const PIN_NAME_COLOR: &str = "#006464FF";
14const PIN_NUMBER_COLOR: &str = "#A90000FF";
15const DEFAULT_FONT_FACE: &str = "Arial";
16const JS_SAFE_MAX: f64 = 9_007_199_254_740_991.0;
17const JS_SAFE_MAX_I64: i64 = 9_007_199_254_740_991;
18
19/// Exact-name `${NAME}` values supplied by the caller for symbol body text.
20#[derive(Clone, Debug, Default, Eq, PartialEq)]
21pub struct SymbolTextVariables {
22    by_name: BTreeMap<String, String>,
23}
24
25impl SymbolTextVariables {
26    pub fn from_entries<N, V>(entries: impl IntoIterator<Item = (N, V)>) -> Self
27    where
28        N: Into<String>,
29        V: Into<String>,
30    {
31        Self {
32            by_name: entries
33                .into_iter()
34                .map(|(name, value)| (name.into(), value.into()))
35                .collect(),
36        }
37    }
38
39    fn substitute_bounded(&self, text: &str, max_bytes: usize) -> Result<String, Error> {
40        let mut output = String::with_capacity(text.len().min(max_bytes));
41        let mut rest = text;
42        while let Some(start) = rest.find("${") {
43            push_bounded(&mut output, &rest[..start], max_bytes)?;
44            let after = &rest[start + 2..];
45            let Some(end) = after.find('}') else {
46                push_bounded(&mut output, &rest[start..], max_bytes)?;
47                rest = "";
48                break;
49            };
50            let placeholder = &rest[start..start + end + 3];
51            let name = &after[..end];
52            let replacement = if name.is_empty() {
53                placeholder
54            } else {
55                self.by_name.get(name).map_or(placeholder, String::as_str)
56            };
57            push_bounded(&mut output, replacement, max_bytes)?;
58            rest = &after[end + 1..];
59        }
60        push_bounded(&mut output, rest, max_bytes)?;
61        Ok(output)
62    }
63}
64
65#[derive(Clone, Copy, Debug)]
66pub(crate) struct SymbolTextSettings {
67    pin_names_offset: f64,
68    pin_names_hide: bool,
69    pin_numbers_hide: bool,
70    /// Extra distance from the pin for pin numbers and for pin names drawn
71    /// beside the pin: `SCH_PIN::PlotPinTexts`'s `pinTextOffset`. Zero for
72    /// library-symbol plots; see [`Self::with_pin_text_offset_nm`].
73    pin_text_offset_nm: i64,
74}
75
76impl SymbolTextSettings {
77    pub(crate) fn from_header(form: &Sexp, position: Position) -> Result<Self, Error> {
78        let pin_names = child(form, "pin_names");
79        Ok(Self {
80            pin_names_offset: pin_names
81                .and_then(|value| child(value, "offset"))
82                .map(|value| {
83                    numeric_or_missing(Some(value), 1, DEFAULT_PIN_NAME_OFFSET_MM, position)
84                })
85                .transpose()?
86                .unwrap_or(DEFAULT_PIN_NAME_OFFSET_MM),
87            pin_names_hide: pin_names.is_some_and(hidden),
88            pin_numbers_hide: child(form, "pin_numbers").is_some_and(hidden),
89            pin_text_offset_nm: 0,
90        })
91    }
92
93    /// KiCad 10.0.8 plots pin numbers, and pin names drawn beside the pin,
94    /// `pinTextOffset` further from the pin than the 10.99 builds did
95    /// (eeschema/sch_pin.cpp:910-914, KiCad 9773c27e0f, issue 24796).
96    /// Schematic pages pass it; library-symbol plots keep zero.
97    pub(crate) const fn with_pin_text_offset_nm(mut self, offset_nm: i64) -> Self {
98        self.pin_text_offset_nm = offset_nm;
99        self
100    }
101}
102
103pub(crate) struct SymbolTextBudget {
104    carriers: usize,
105    bytes: usize,
106}
107
108impl SymbolTextBudget {
109    pub(crate) fn new() -> Self {
110        Self {
111            carriers: 0,
112            bytes: 0,
113        }
114    }
115
116    fn remaining_bytes(&self) -> Result<usize, Error> {
117        Ok(usize::MAX)
118    }
119
120    fn charge_carrier(&mut self) -> Result<(), Error> {
121        self.carriers = self.carriers.checked_add(1).ok_or_else(text_limit)?;
122        Ok(())
123    }
124
125    fn retain_bytes(&mut self, text: &str) -> Result<(), Error> {
126        self.bytes = self.bytes.checked_add(text.len()).ok_or_else(text_limit)?;
127        Ok(())
128    }
129}
130
131pub(crate) fn body_text_operation(
132    form: &Sexp,
133    variables: &SymbolTextVariables,
134    budget: &mut SymbolTextBudget,
135    position: Position,
136) -> Result<Option<PlotterOperation>, Error> {
137    budget.charge_carrier()?;
138    let effects = parse_text_effects(form)?.unwrap_or_default();
139    if hidden(form) || effects.hidden {
140        return Ok(None);
141    }
142    let raw = value_at(form, 1).unwrap_or_default();
143    let substitution_limit = budget.remaining_bytes()?.saturating_add(1);
144    let mut resolved = variables.substitute_bounded(raw, substitution_limit)?;
145    if resolved.ends_with('\n') {
146        resolved.pop();
147    }
148    budget.retain_bytes(&resolved)?;
149    let at = child(form, "at");
150    let multiline = resolved.contains('\n');
151    Ok(Some(PlotterOperation::Text(styled_text(
152        resolved,
153        TextStyleInput {
154            x: numeric_or_missing(at, 1, 0.0, position)?,
155            y: -numeric_or_missing(at, 2, 0.0, position)?,
156            orient_deg: angle_or_default(at, 3, position)? / 10.0,
157            effects: &effects,
158            color: DEVICE_COLOR,
159            default_h: PlotterTextHAlign::Center,
160            default_v: PlotterTextVAlign::Center,
161            multiline,
162            clamp_pen_width: true,
163            pin_number_width: false,
164        },
165        position,
166    )?)))
167}
168
169pub(crate) fn pin_text_operations(
170    form: &Sexp,
171    settings: SymbolTextSettings,
172    default_line_width_nm: Option<i64>,
173    budget: &mut SymbolTextBudget,
174    position: Position,
175) -> Result<Vec<PlotterOperation>, Error> {
176    placed_pin_text_operations(form, settings, default_line_width_nm, budget, position, Ok)
177}
178
179/// Pin name and number text for a pin whose library coordinates `place` maps
180/// onto the page. Like `SCH_PIN::Plot` (eeschema/sch_pin.cpp:1400-1425), the
181/// pin is placed first and `PlotPinTexts` lays its text out on the page from
182/// the placed pin's draw orientation, so the text is always upright or reads
183/// upwards and sits on KiCad's side of the pin whatever the rotation or mirror.
184pub(crate) fn placed_pin_text_operations(
185    form: &Sexp,
186    settings: SymbolTextSettings,
187    default_line_width_nm: Option<i64>,
188    budget: &mut SymbolTextBudget,
189    position: Position,
190    place: impl Fn([i64; 2]) -> Result<[i64; 2], Error>,
191) -> Result<Vec<PlotterOperation>, Error> {
192    let name_form = child(form, "name");
193    for _ in 0..child_count(form, "name") {
194        budget.charge_carrier()?;
195    }
196    for _ in 0..child_count(form, "number") {
197        budget.charge_carrier()?;
198    }
199    if hidden(form) {
200        return Ok(Vec::new());
201    }
202    let geometry = pin_geometry(form, position, place)?;
203    let name = name_form
204        .and_then(|value| value_at(value, 1))
205        .unwrap_or_default();
206    let name_effects = name_form.map(parse_text_effects).transpose()?.flatten();
207    let draws_name = !name.is_empty()
208        && name != "~"
209        && !settings.pin_names_hide
210        && positive_text_size(name_effects.as_ref());
211    let mut operations = Vec::with_capacity(2);
212    append_pin_number(
213        &mut operations,
214        PinNumberInput {
215            form,
216            geometry,
217            draws_name,
218            settings,
219            default_line_width_nm,
220            position,
221        },
222        budget,
223    )?;
224    if draws_name {
225        append_pin_name(
226            &mut operations,
227            name,
228            name_effects.unwrap_or_default(),
229            geometry,
230            settings,
231            budget,
232            position,
233        )?;
234    }
235    Ok(operations)
236}
237
238#[derive(Clone, Copy)]
239struct PinGeometry {
240    root_x: i64,
241    root_y: i64,
242    pos_x: i64,
243    pos_y: i64,
244    horizontal: bool,
245    pin_right: bool,
246    pin_down: bool,
247    orient_deg: f64,
248}
249
250struct PinNumberInput<'a> {
251    form: &'a Sexp,
252    geometry: PinGeometry,
253    draws_name: bool,
254    settings: SymbolTextSettings,
255    default_line_width_nm: Option<i64>,
256    position: Position,
257}
258
259fn pin_geometry(
260    form: &Sexp,
261    position: Position,
262    place: impl Fn([i64; 2]) -> Result<[i64; 2], Error>,
263) -> Result<PinGeometry, Error> {
264    let at = child(form, "at");
265    let x = numeric_or_missing(at, 1, 0.0, position)?;
266    let y = numeric_or_missing(at, 2, 0.0, position)?;
267    let angle = angle_or_default(at, 3, position)?;
268    let length = numeric_or_missing(child(form, "length"), 1, 2.54, position)?;
269    let local_x = mm_to_nm(x, position)?;
270    let local_y = mm_to_nm(-y, position)?;
271    let length_nm = mm_to_nm(length, position)?;
272    let (local_root_x, local_root_y) = pin_root(
273        PinRootInput {
274            x,
275            y,
276            angle,
277            length,
278            pos_x: local_x,
279            pos_y: local_y,
280            length_nm,
281        },
282        position,
283    )?;
284    let (local_direction_x, local_direction_y) = pin_direction(angle);
285    let [pos_x, pos_y] = place([local_x, local_y])?;
286    let [root_x, root_y] = place([local_root_x, local_root_y])?;
287    let [tip_x, tip_y] = place([
288        coordinate_add(local_x, local_direction_x, position)?,
289        coordinate_add(local_y, local_direction_y, position)?,
290    ])?;
291    let direction_x = coordinate_add(tip_x, -pos_x, position)?;
292    let direction_y = coordinate_add(tip_y, -pos_y, position)?;
293    let horizontal = direction_x.abs() >= direction_y.abs();
294    Ok(PinGeometry {
295        root_x,
296        root_y,
297        pos_x,
298        pos_y,
299        horizontal,
300        pin_right: horizontal && direction_x > 0,
301        pin_down: !horizontal && direction_y > 0,
302        orient_deg: if horizontal { 0.0 } else { 90.0 },
303    })
304}
305
306fn append_pin_number(
307    operations: &mut Vec<PlotterOperation>,
308    input: PinNumberInput<'_>,
309    budget: &mut SymbolTextBudget,
310) -> Result<(), Error> {
311    let PinNumberInput {
312        form,
313        geometry,
314        draws_name,
315        settings,
316        default_line_width_nm,
317        position,
318    } = input;
319    let number_form = child(form, "number");
320    let number = number_form
321        .and_then(|value| value_at(value, 1))
322        .unwrap_or_default();
323    let effects = number_form.map(parse_text_effects).transpose()?.flatten();
324    if number.is_empty() || settings.pin_numbers_hide || !positive_text_size(effects.as_ref()) {
325        return Ok(());
326    }
327    let effects = effects.unwrap_or_default();
328    let mut style = resolved_style(&effects, false, true, PIN_NUMBER_COLOR, position)?;
329    if effects.font.thickness.unwrap_or(0.0) <= 0.0
330        && let Some(default_line_width_nm) = default_line_width_nm
331    {
332        style.pen_width_nm = default_line_width_nm;
333    }
334    let clearance = pin_text_clearance(style.pen_width_nm, settings, position)?;
335    let midpoint_x = midpoint(geometry.root_x, geometry.pos_x, position)?;
336    let midpoint_y = midpoint(geometry.root_y, geometry.pos_y, position)?;
337    let (x, y, v_align) = if settings.pin_names_offset > 0.0 || !draws_name {
338        if geometry.horizontal {
339            (
340                midpoint_x,
341                coordinate_add(geometry.root_y, -clearance, position)?,
342                PlotterTextVAlign::Bottom,
343            )
344        } else {
345            (
346                coordinate_add(geometry.root_x, -clearance, position)?,
347                midpoint_y,
348                PlotterTextVAlign::Bottom,
349            )
350        }
351    } else if geometry.horizontal {
352        (
353            midpoint_x,
354            coordinate_add(geometry.root_y, clearance, position)?,
355            PlotterTextVAlign::Top,
356        )
357    } else {
358        (
359            coordinate_add(geometry.root_x, clearance, position)?,
360            midpoint_y,
361            PlotterTextVAlign::Top,
362        )
363    };
364    budget.retain_bytes(number)?;
365    operations.push(PlotterOperation::Text(PlotterText {
366        x,
367        y,
368        text: number.to_owned(),
369        color: style.color,
370        orient_deg: geometry.orient_deg,
371        size_x_nm: style.size_x_nm,
372        size_y_nm: style.size_y_nm,
373        h_align: PlotterTextHAlign::Center,
374        v_align,
375        pen_width_nm: style.pen_width_nm,
376        italic: effects.font.italic,
377        bold: effects.font.bold,
378        mirror: effects.justify.iter().any(|token| token == "mirror"),
379        multiline: false,
380        font_face: style.font_face,
381        layer: None,
382    }));
383    Ok(())
384}
385
386fn append_pin_name(
387    operations: &mut Vec<PlotterOperation>,
388    name: &str,
389    effects: KiCadTextEffects,
390    geometry: PinGeometry,
391    settings: SymbolTextSettings,
392    budget: &mut SymbolTextBudget,
393    position: Position,
394) -> Result<(), Error> {
395    let style = resolved_style(&effects, false, false, PIN_NAME_COLOR, position)?;
396    // Only a name drawn beside the pin uses the clearance; a name inside the
397    // body sits at the library's pin-name offset.
398    let clearance = pin_text_clearance(style.pen_width_nm, settings, position)?;
399    let midpoint_x = midpoint(geometry.root_x, geometry.pos_x, position)?;
400    let midpoint_y = midpoint(geometry.root_y, geometry.pos_y, position)?;
401    let offset_mm = settings.pin_names_offset;
402    let (x, y, h_align, v_align) = if offset_mm > 0.0 {
403        let offset = mm_to_nm(offset_mm, position)?;
404        if geometry.horizontal {
405            (
406                if geometry.pin_right {
407                    coordinate_add(geometry.root_x, offset, position)?
408                } else {
409                    coordinate_add(geometry.root_x, -offset, position)?
410                },
411                geometry.root_y,
412                if geometry.pin_right {
413                    PlotterTextHAlign::Left
414                } else {
415                    PlotterTextHAlign::Right
416                },
417                PlotterTextVAlign::Center,
418            )
419        } else {
420            (
421                geometry.root_x,
422                if geometry.pin_down {
423                    coordinate_add(geometry.root_y, offset, position)?
424                } else {
425                    coordinate_add(geometry.root_y, -offset, position)?
426                },
427                if geometry.pin_down {
428                    PlotterTextHAlign::Right
429                } else {
430                    PlotterTextHAlign::Left
431                },
432                PlotterTextVAlign::Center,
433            )
434        }
435    } else if geometry.horizontal {
436        (
437            midpoint_x,
438            coordinate_add(geometry.root_y, -clearance, position)?,
439            PlotterTextHAlign::Center,
440            PlotterTextVAlign::Bottom,
441        )
442    } else {
443        (
444            coordinate_add(geometry.root_x, -clearance, position)?,
445            midpoint_y,
446            PlotterTextHAlign::Center,
447            PlotterTextVAlign::Bottom,
448        )
449    };
450    budget.retain_bytes(name)?;
451    operations.push(PlotterOperation::Text(PlotterText {
452        x,
453        y,
454        text: name.to_owned(),
455        color: style.color,
456        orient_deg: geometry.orient_deg,
457        size_x_nm: style.size_x_nm,
458        size_y_nm: style.size_y_nm,
459        h_align,
460        v_align,
461        pen_width_nm: style.pen_width_nm,
462        italic: effects.font.italic,
463        bold: effects.font.bold,
464        mirror: effects.justify.iter().any(|token| token == "mirror"),
465        multiline: false,
466        font_face: style.font_face,
467        layer: None,
468    }));
469    Ok(())
470}
471
472struct TextStyleInput<'a> {
473    x: f64,
474    y: f64,
475    orient_deg: f64,
476    effects: &'a KiCadTextEffects,
477    color: &'a str,
478    default_h: PlotterTextHAlign,
479    default_v: PlotterTextVAlign,
480    multiline: bool,
481    clamp_pen_width: bool,
482    pin_number_width: bool,
483}
484
485fn styled_text(
486    text: String,
487    input: TextStyleInput<'_>,
488    position: Position,
489) -> Result<PlotterText, Error> {
490    let style = resolved_style(
491        input.effects,
492        input.clamp_pen_width,
493        input.pin_number_width,
494        input.color,
495        position,
496    )?;
497    let (h_align, v_align) = alignments(input.effects);
498    Ok(PlotterText {
499        x: mm_to_nm(input.x, position)?,
500        y: mm_to_nm(input.y, position)?,
501        text,
502        color: style.color,
503        orient_deg: input.orient_deg,
504        size_x_nm: style.size_x_nm,
505        size_y_nm: style.size_y_nm,
506        h_align: h_align.unwrap_or(input.default_h),
507        v_align: v_align.unwrap_or(input.default_v),
508        pen_width_nm: style.pen_width_nm,
509        italic: input.effects.font.italic,
510        bold: input.effects.font.bold,
511        mirror: input.effects.justify.iter().any(|token| token == "mirror"),
512        multiline: input.multiline,
513        font_face: style.font_face,
514        layer: None,
515    })
516}
517
518struct ResolvedStyle {
519    color: String,
520    font_face: String,
521    size_x_nm: i64,
522    size_y_nm: i64,
523    pen_width_nm: i64,
524}
525
526fn resolved_style(
527    effects: &KiCadTextEffects,
528    clamp_pen_width: bool,
529    pin_number_width: bool,
530    default_color: &str,
531    position: Position,
532) -> Result<ResolvedStyle, Error> {
533    let size_x_nm = mm_to_nm(effects.font.size_x, position)?;
534    let size_y_nm = mm_to_nm(effects.font.size_y, position)?;
535    let text_size = size_x_nm.abs().min(size_y_nm.abs());
536    let explicit = effects
537        .font
538        .thickness
539        .map(|value| mm_to_nm(value, position))
540        .transpose()?;
541    let mut pen_width_nm = explicit.filter(|width| *width > 0).unwrap_or_else(|| {
542        if pin_number_width {
543            if text_size > 0 {
544                (text_size as f64 / 5.0 + 0.5) as i64
545            } else {
546                DEFAULT_TEXT_PEN_WIDTH_NM
547            }
548        } else if effects.font.bold {
549            if text_size > 0 {
550                round_pen_width(text_size as f64 / 5.0)
551            } else {
552                DEFAULT_TEXT_PEN_WIDTH_NM
553            }
554        } else {
555            DEFAULT_TEXT_PEN_WIDTH_NM
556        }
557    });
558    if clamp_pen_width && text_size > 0 {
559        pen_width_nm = pen_width_nm.min((text_size as f64 * 0.25 + 0.5) as i64);
560    }
561    Ok(ResolvedStyle {
562        color: effects
563            .font
564            .color
565            .and_then(rgba_to_hex)
566            .unwrap_or_else(|| default_color.to_owned()),
567        font_face: effects
568            .font
569            .face
570            .clone()
571            .filter(|face| !face.is_empty())
572            .unwrap_or_else(|| DEFAULT_FONT_FACE.to_owned()),
573        size_x_nm,
574        size_y_nm,
575        pen_width_nm,
576    })
577}
578
579fn alignments(
580    effects: &KiCadTextEffects,
581) -> (Option<PlotterTextHAlign>, Option<PlotterTextVAlign>) {
582    let mut horizontal = None;
583    let mut vertical = None;
584    for token in &effects.justify {
585        match token.as_str() {
586            "left" => horizontal = Some(PlotterTextHAlign::Left),
587            "right" => horizontal = Some(PlotterTextHAlign::Right),
588            "center" => horizontal = Some(PlotterTextHAlign::Center),
589            "top" => vertical = Some(PlotterTextVAlign::Top),
590            "bottom" => vertical = Some(PlotterTextVAlign::Bottom),
591            _ => {}
592        }
593    }
594    (horizontal, vertical)
595}
596
597fn positive_text_size(effects: Option<&KiCadTextEffects>) -> bool {
598    effects.is_none_or(|value| value.font.size_x.abs() > 0.0 && value.font.size_y.abs() > 0.0)
599}
600
601#[derive(Clone, Copy)]
602struct PinRootInput {
603    x: f64,
604    y: f64,
605    angle: f64,
606    length: f64,
607    pos_x: i64,
608    pos_y: i64,
609    length_nm: i64,
610}
611
612fn pin_root(input: PinRootInput, position: Position) -> Result<(i64, i64), Error> {
613    let PinRootInput {
614        x,
615        y,
616        angle,
617        length,
618        pos_x,
619        pos_y,
620        length_nm,
621    } = input;
622    match (angle.round_ties_even() as i64).rem_euclid(360) {
623        0 => Ok((coordinate_add(pos_x, length_nm, position)?, pos_y)),
624        90 => Ok((pos_x, coordinate_add(pos_y, -length_nm, position)?)),
625        180 => Ok((coordinate_add(pos_x, -length_nm, position)?, pos_y)),
626        270 => Ok((pos_x, coordinate_add(pos_y, length_nm, position)?)),
627        _ => {
628            let radians = angle.to_radians();
629            Ok((
630                mm_to_nm(x + length * radians.cos(), position)?,
631                mm_to_nm(-(y + length * radians.sin()), position)?,
632            ))
633        }
634    }
635}
636
637fn pin_direction(angle: f64) -> (i64, i64) {
638    match (angle.round_ties_even() as i64).rem_euclid(360) {
639        0 => (1_000_000, 0),
640        180 => (-1_000_000, 0),
641        90 => (0, -1_000_000),
642        270 => (0, 1_000_000),
643        _ => {
644            let radians = angle.to_radians();
645            (
646                (radians.cos() * 1_000_000.0).round_ties_even() as i64,
647                (-radians.sin() * 1_000_000.0).round_ties_even() as i64,
648            )
649        }
650    }
651}
652
653fn mm_to_nm(value: f64, position: Position) -> Result<i64, Error> {
654    let scaled = value * 1_000_000.0;
655    if !scaled.is_finite() || !(-JS_SAFE_MAX..=JS_SAFE_MAX).contains(&scaled) {
656        return Err(model(
657            "Symbol text exceeds JavaScript safe-integer range",
658            position,
659        ));
660    }
661    Ok(scaled.round_ties_even() as i64)
662}
663
664fn coordinate_add(left: i64, right: i64, position: Position) -> Result<i64, Error> {
665    derived_coordinate(left as i128 + right as i128, position)
666}
667
668/// `SCH_PIN::PlotPinTexts`'s `name_offset`/`num_offset`: the pin-text offset,
669/// `PIN_TEXT_MARGIN` and the text pen width.
670fn pin_text_clearance(
671    pen_width_nm: i64,
672    settings: SymbolTextSettings,
673    position: Position,
674) -> Result<i64, Error> {
675    let margin = coordinate_add(PIN_TEXT_MARGIN_NM, settings.pin_text_offset_nm, position)?;
676    coordinate_add(margin, pen_width_nm, position)
677}
678
679fn midpoint(left: i64, right: i64, position: Position) -> Result<i64, Error> {
680    derived_coordinate((left as i128 + right as i128).div_euclid(2), position)
681}
682
683fn derived_coordinate(value: i128, position: Position) -> Result<i64, Error> {
684    if !(-(JS_SAFE_MAX_I64 as i128)..=JS_SAFE_MAX_I64 as i128).contains(&value) {
685        return Err(model(
686            "Derived symbol text coordinate exceeds JavaScript safe-integer range",
687            position,
688        ));
689    }
690    Ok(value as i64)
691}
692
693fn rgba_to_hex(color: KiCadColor) -> Option<String> {
694    if color.alpha <= 0.0 {
695        return None;
696    }
697    let alpha = if color.alpha <= 1.0 {
698        (color.alpha * 255.0).round_ties_even()
699    } else {
700        color.alpha.round_ties_even()
701    };
702    Some(format!(
703        "#{:02X}{:02X}{:02X}{:02X}",
704        color.red.clamp(0, 255),
705        color.green.clamp(0, 255),
706        color.blue.clamp(0, 255),
707        (alpha as i64).clamp(0, 255)
708    ))
709}
710
711fn round_pen_width(value: f64) -> i64 {
712    (value / 100.0 + 0.5) as i64 * 100
713}
714
715fn hidden(form: &Sexp) -> bool {
716    has_atom(form, "hide")
717        || child(form, "hide").and_then(|value| value_at(value, 1)) == Some("yes")
718}
719
720fn push_bounded(output: &mut String, value: &str, _max_bytes: usize) -> Result<(), Error> {
721    output
722        .len()
723        .checked_add(value.len())
724        .ok_or_else(text_limit)?;
725    output.push_str(value);
726    Ok(())
727}
728
729fn child<'a>(form: &'a Sexp, head: &str) -> Option<&'a Sexp> {
730    list(form)?
731        .iter()
732        .find(|candidate| value_at(candidate, 0) == Some(head))
733}
734
735fn child_count(form: &Sexp, head: &str) -> usize {
736    list(form)
737        .into_iter()
738        .flatten()
739        .filter(|candidate| value_at(candidate, 0) == Some(head))
740        .count()
741}
742
743fn list(form: &Sexp) -> Option<&[Sexp]> {
744    match form {
745        Sexp::List(values) => Some(values),
746        _ => None,
747    }
748}
749
750fn text(value: &Sexp) -> Option<&str> {
751    match value {
752        Sexp::Atom(value) | Sexp::Quoted(value) => Some(value),
753        _ => None,
754    }
755}
756
757fn value_at(form: &Sexp, index: usize) -> Option<&str> {
758    list(form)?.get(index).and_then(text)
759}
760
761fn has_atom(form: &Sexp, expected: &str) -> bool {
762    list(form).is_some_and(|values| values.iter().any(|value| text(value) == Some(expected)))
763}
764
765fn numeric_or_missing(
766    form: Option<&Sexp>,
767    index: usize,
768    default: f64,
769    position: Position,
770) -> Result<f64, Error> {
771    let Some(value) = form.and_then(list).and_then(|values| values.get(index)) else {
772        return Ok(default);
773    };
774    finite_numeric(value, position)
775}
776
777fn angle_or_default(form: Option<&Sexp>, index: usize, position: Position) -> Result<f64, Error> {
778    let Some(value) = form.and_then(list).and_then(|values| values.get(index)) else {
779        return Ok(0.0);
780    };
781    match parse_numeric(value) {
782        Ok(number) if number.is_finite() => Ok(number),
783        Ok(_) => Err(model("Symbol text numeric value must be finite", position)),
784        Err(()) => Ok(0.0),
785    }
786}
787
788fn finite_numeric(value: &Sexp, position: Position) -> Result<f64, Error> {
789    let number =
790        parse_numeric(value).map_err(|()| model("Expected numeric symbol text value", position))?;
791    if number.is_finite() {
792        Ok(number)
793    } else {
794        Err(model("Symbol text numeric value must be finite", position))
795    }
796}
797
798fn parse_numeric(value: &Sexp) -> Result<f64, ()> {
799    let number = match value {
800        Sexp::Integer(value) => *value as f64,
801        Sexp::Float(value) => *value,
802        Sexp::Atom(value) | Sexp::Quoted(value) => value.parse().map_err(|_| ())?,
803        _ => return Err(()),
804    };
805    Ok(number)
806}
807
808fn model(message: &'static str, position: Position) -> Error {
809    Error::at(
810        ErrorPhase::Tree,
811        ErrorKind::UnexpectedToken,
812        message,
813        position,
814    )
815}
816
817fn text_limit() -> Error {
818    Error::at(
819        ErrorPhase::Tree,
820        ErrorKind::ResourceLimit,
821        "Symbol text resource limit exceeded",
822        Position::START,
823    )
824}