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

kicad_monkey_core/
symbol_authoring.rs

1//! Typed fresh-source authoring for KiCad symbol libraries (`.kicad_sym`).
2//!
3//! Build an [`AuthoredSymbolLibrary`] and call
4//! [`canonical_text`](AuthoredSymbolLibrary::canonical_text) or
5//! [`write_into`](AuthoredSymbolLibrary::write_into). The output is what KiCad
6//! 10's own writer produces (`SCH_WRITER_V10::SaveSymbolLibrary`): the same
7//! tokens in the same order, the same number spelling and the same file layout
8//! (`KICAD_FORMAT::Prettify`). Lengths are integer nanometres and points are in
9//! the file's frame, +Y up, so callers never format numbers. Lines end in LF on
10//! every platform (KiCad itself saves CRLF on Windows). The whole library is
11//! checked before anything is written; an invalid library writes nothing.
12//!
13//! Items keep the order they are given in. KiCad keeps that order within each
14//! item kind when it loads a library and sorts them on its next save. Derived
15//! symbols (`extends`) and embedded files are not written.
16
17mod emit;
18mod validate;
19
20use crate::sexpr::Error;
21use std::borrow::Cow;
22use std::collections::BTreeMap;
23
24/// The symbol-library format revision KiCad 10.0 writes.
25pub const KICAD_SYMBOL_LIBRARY_VERSION_2025_10_24: i64 = 20_251_024;
26
27/// KiCad's default pin name offset (`DEFAULT_PIN_NAME_OFFSET`, 20 mil).
28pub const KICAD_DEFAULT_PIN_NAME_OFFSET_NM: i64 = 508_000;
29
30/// KiCad's default text size (`DEFAULT_TEXT_SIZE`, 50 mil).
31pub const KICAD_DEFAULT_TEXT_SIZE_NM: i64 = 1_270_000;
32
33/// Independent ceilings for one library write.
34#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub struct SymbolAuthoringLimits {
36    pub max_symbols: usize,
37    /// Units, items, properties, alternates and jumper names together.
38    pub max_objects: usize,
39    pub max_points: usize,
40    pub max_string_bytes: usize,
41    pub max_output_bytes: usize,
42}
43
44impl Default for SymbolAuthoringLimits {
45    fn default() -> Self {
46        Self {
47            max_symbols: 100_000,
48            max_objects: 16_000_000,
49            max_points: 16_000_000,
50            max_string_bytes: 256 * 1024 * 1024,
51            max_output_bytes: 512 * 1024 * 1024,
52        }
53    }
54}
55
56/// A point in the library file's frame: nanometres, +Y up.
57#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
58pub struct AuthoredSymbolPoint {
59    pub x_nm: i64,
60    pub y_nm: i64,
61}
62
63impl AuthoredSymbolPoint {
64    pub const fn new(x_nm: i64, y_nm: i64) -> Self {
65        Self { x_nm, y_nm }
66    }
67}
68
69/// `(color r g b a)`; alpha runs from 0 to 1 as KiCad stores it.
70#[derive(Clone, Copy, Debug, PartialEq)]
71pub struct AuthoredSymbolColor {
72    pub red: u8,
73    pub green: u8,
74    pub blue: u8,
75    pub alpha: f64,
76}
77
78impl AuthoredSymbolColor {
79    pub const fn opaque(red: u8, green: u8, blue: u8) -> Self {
80        Self {
81            red,
82            green,
83            blue,
84            alpha: 1.0,
85        }
86    }
87}
88
89#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
90pub enum AuthoredSymbolTextHorizontal {
91    Left,
92    #[default]
93    Center,
94    Right,
95}
96
97#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
98pub enum AuthoredSymbolTextVertical {
99    Top,
100    #[default]
101    Center,
102    Bottom,
103}
104
105/// `(effects (font ...) (justify ...) (href ...))` of a field, text or text box.
106#[derive(Clone, Debug, PartialEq)]
107pub struct AuthoredSymbolTextEffects {
108    /// A TrueType face; `None` is KiCad's built-in stroke font.
109    pub face: Option<String>,
110    pub height_nm: i64,
111    pub width_nm: i64,
112    /// Line pitch as a multiple of KiCad's default; 1 is not written.
113    pub line_spacing: f64,
114    /// Stroke pen width; `None` lets KiCad choose it from the size.
115    pub thickness_nm: Option<i64>,
116    pub bold: bool,
117    pub italic: bool,
118    pub color: Option<AuthoredSymbolColor>,
119    pub horizontal: AuthoredSymbolTextHorizontal,
120    pub vertical: AuthoredSymbolTextVertical,
121    pub mirrored: bool,
122    pub hyperlink: Option<String>,
123}
124
125impl Default for AuthoredSymbolTextEffects {
126    fn default() -> Self {
127        Self {
128            face: None,
129            height_nm: KICAD_DEFAULT_TEXT_SIZE_NM,
130            width_nm: KICAD_DEFAULT_TEXT_SIZE_NM,
131            line_spacing: 1.0,
132            thickness_nm: None,
133            bold: false,
134            italic: false,
135            color: None,
136            horizontal: AuthoredSymbolTextHorizontal::Center,
137            vertical: AuthoredSymbolTextVertical::Center,
138            mirrored: false,
139            hyperlink: None,
140        }
141    }
142}
143
144/// One `(property ...)` field.
145#[derive(Clone, Debug, PartialEq)]
146pub struct AuthoredSymbolProperty {
147    pub name: String,
148    pub value: String,
149    pub at: AuthoredSymbolPoint,
150    pub angle_deg: f64,
151    pub private: bool,
152    pub show_name: bool,
153    pub do_not_autoplace: bool,
154    pub hidden: bool,
155    pub effects: AuthoredSymbolTextEffects,
156}
157
158impl AuthoredSymbolProperty {
159    /// A visible field at the origin with KiCad's default text.
160    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
161        Self {
162            name: name.into(),
163            value: value.into(),
164            at: AuthoredSymbolPoint::default(),
165            angle_deg: 0.0,
166            private: false,
167            show_name: false,
168            do_not_autoplace: false,
169            hidden: false,
170            effects: AuthoredSymbolTextEffects::default(),
171        }
172    }
173}
174
175#[derive(Clone, Copy, Debug, Eq, PartialEq)]
176pub enum AuthoredSymbolPowerKind {
177    Global,
178    Local,
179}
180
181/// Body styles a symbol offers (`body_styles`).
182#[derive(Clone, Debug, Default, Eq, PartialEq)]
183pub enum AuthoredSymbolBodyStyles {
184    /// One body style; nothing is written.
185    #[default]
186    Single,
187    /// KiCad's two De Morgan styles.
188    DeMorgan,
189    /// Two or more named styles, in order (body style 1 first).
190    Named(Vec<String>),
191}
192
193impl AuthoredSymbolBodyStyles {
194    pub fn count(&self) -> usize {
195        match self {
196            Self::Single => 1,
197            Self::DeMorgan => 2,
198            Self::Named(names) => names.len(),
199        }
200    }
201}
202
203#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
204pub enum AuthoredSymbolLineStyle {
205    #[default]
206    Default,
207    Solid,
208    Dash,
209    Dot,
210    DashDot,
211    DashDotDot,
212}
213
214/// `(stroke ...)`. Width 0 is KiCad's default width and a negative width draws
215/// no outline.
216#[derive(Clone, Copy, Debug, Default, PartialEq)]
217pub struct AuthoredSymbolStroke {
218    pub width_nm: i64,
219    pub style: AuthoredSymbolLineStyle,
220    pub color: Option<AuthoredSymbolColor>,
221}
222
223/// `(fill ...)`.
224#[derive(Clone, Copy, Debug, Default, PartialEq)]
225pub enum AuthoredSymbolFill {
226    #[default]
227    None,
228    /// Filled with the outline colour.
229    Outline,
230    /// Filled with the body background colour.
231    Background,
232    Color(AuthoredSymbolColor),
233    Hatch(AuthoredSymbolColor),
234    ReverseHatch(AuthoredSymbolColor),
235    CrossHatch(AuthoredSymbolColor),
236}
237
238#[derive(Clone, Debug, PartialEq)]
239pub enum AuthoredSymbolShapeGeometry {
240    Arc {
241        start: AuthoredSymbolPoint,
242        mid: AuthoredSymbolPoint,
243        end: AuthoredSymbolPoint,
244    },
245    Circle {
246        center: AuthoredSymbolPoint,
247        radius_nm: i64,
248    },
249    /// Corner radius 0 draws square corners.
250    Rectangle {
251        start: AuthoredSymbolPoint,
252        end: AuthoredSymbolPoint,
253        corner_radius_nm: i64,
254    },
255    /// Start, control 1, control 2, end.
256    Bezier {
257        points: [AuthoredSymbolPoint; 4],
258    },
259    Polyline {
260        points: Vec<AuthoredSymbolPoint>,
261    },
262}
263
264#[derive(Clone, Debug, PartialEq)]
265pub struct AuthoredSymbolShape {
266    pub geometry: AuthoredSymbolShapeGeometry,
267    pub stroke: AuthoredSymbolStroke,
268    pub fill: AuthoredSymbolFill,
269    pub private: bool,
270}
271
272/// `(text ...)`. KiCad stores the angle in tenths of a degree.
273#[derive(Clone, Debug, PartialEq)]
274pub struct AuthoredSymbolText {
275    pub text: String,
276    pub at: AuthoredSymbolPoint,
277    pub angle_deg: f64,
278    pub private: bool,
279    pub effects: AuthoredSymbolTextEffects,
280}
281
282/// `(text_box ...)`: word-wrapped text in a fixed box from `start` to `end`.
283#[derive(Clone, Debug, PartialEq)]
284pub struct AuthoredSymbolTextBox {
285    pub text: String,
286    pub start: AuthoredSymbolPoint,
287    pub end: AuthoredSymbolPoint,
288    pub angle_deg: f64,
289    /// Left, top, right, bottom.
290    pub margins_nm: [i64; 4],
291    pub stroke: AuthoredSymbolStroke,
292    pub fill: AuthoredSymbolFill,
293    pub private: bool,
294    pub effects: AuthoredSymbolTextEffects,
295}
296
297#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
298pub enum AuthoredPinElectricalType {
299    Input,
300    Output,
301    Bidirectional,
302    TriState,
303    #[default]
304    Passive,
305    Free,
306    Unspecified,
307    PowerIn,
308    PowerOut,
309    OpenCollector,
310    OpenEmitter,
311    NoConnect,
312}
313
314#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
315pub enum AuthoredPinGraphicStyle {
316    #[default]
317    Line,
318    Inverted,
319    Clock,
320    InvertedClock,
321    InputLow,
322    ClockLow,
323    OutputLow,
324    EdgeClockHigh,
325    NonLogic,
326}
327
328/// Direction from a pin's connection point to its body end, as KiCad names it.
329#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
330pub enum AuthoredPinOrientation {
331    #[default]
332    Right,
333    Up,
334    Left,
335    Down,
336}
337
338#[derive(Clone, Debug, PartialEq)]
339pub struct AuthoredPinAlternate {
340    pub name: String,
341    pub electrical_type: AuthoredPinElectricalType,
342    pub graphic_style: AuthoredPinGraphicStyle,
343}
344
345/// `(pin ...)`. `at` is the connection point. Alternates are written in name
346/// order, as KiCad keeps them.
347#[derive(Clone, Debug, PartialEq)]
348pub struct AuthoredSymbolPin {
349    pub electrical_type: AuthoredPinElectricalType,
350    pub graphic_style: AuthoredPinGraphicStyle,
351    pub at: AuthoredSymbolPoint,
352    pub orientation: AuthoredPinOrientation,
353    pub length_nm: i64,
354    pub hidden: bool,
355    pub name: String,
356    pub name_size_nm: i64,
357    pub number: String,
358    pub number_size_nm: i64,
359    pub alternates: Vec<AuthoredPinAlternate>,
360}
361
362impl AuthoredSymbolPin {
363    /// A 100 mil passive pin with KiCad's default text size.
364    pub fn new(
365        number: impl Into<String>,
366        name: impl Into<String>,
367        at: AuthoredSymbolPoint,
368        orientation: AuthoredPinOrientation,
369    ) -> Self {
370        Self {
371            electrical_type: AuthoredPinElectricalType::Passive,
372            graphic_style: AuthoredPinGraphicStyle::Line,
373            at,
374            orientation,
375            length_nm: 2_540_000,
376            hidden: false,
377            name: name.into(),
378            name_size_nm: KICAD_DEFAULT_TEXT_SIZE_NM,
379            number: number.into(),
380            number_size_nm: KICAD_DEFAULT_TEXT_SIZE_NM,
381            alternates: Vec::new(),
382        }
383    }
384}
385
386#[derive(Clone, Debug, PartialEq)]
387pub enum AuthoredSymbolItem {
388    Shape(AuthoredSymbolShape),
389    Text(AuthoredSymbolText),
390    TextBox(AuthoredSymbolTextBox),
391    Pin(AuthoredSymbolPin),
392}
393
394/// The drawing of one unit in one body style. Unit 0 and body style 0 mean all
395/// units and all body styles.
396#[derive(Clone, Debug, Default, PartialEq)]
397pub struct AuthoredSymbolUnit {
398    pub unit: u32,
399    pub body_style: u32,
400    pub items: Vec<AuthoredSymbolItem>,
401}
402
403/// One root symbol.
404#[derive(Clone, Debug, PartialEq)]
405pub struct AuthoredSymbol {
406    /// The symbol's name as shown; stored as KiCad stores library item names.
407    pub name: String,
408    pub power: Option<AuthoredSymbolPowerKind>,
409    pub body_styles: AuthoredSymbolBodyStyles,
410    pub show_pin_numbers: bool,
411    pub show_pin_names: bool,
412    pub pin_name_offset_nm: i64,
413    pub exclude_from_sim: bool,
414    pub in_bom: bool,
415    pub on_board: bool,
416    pub in_pos_files: bool,
417    pub duplicate_pin_numbers_are_jumpers: bool,
418    pub jumper_pin_groups: Vec<Vec<String>>,
419    /// Fields in order; KiCad writes Reference, Value, Footprint, Datasheet and
420    /// Description first.
421    pub properties: Vec<AuthoredSymbolProperty>,
422    /// Units cannot be swapped for one another (`ki_locked`).
423    pub units_locked: bool,
424    /// Space-separated search keywords (`ki_keywords`); empty writes nothing.
425    pub keywords: String,
426    /// Footprint name patterns (`ki_fp_filters`).
427    pub footprint_filters: Vec<String>,
428    /// Display names by unit number (1 and up).
429    pub unit_names: BTreeMap<u32, String>,
430    /// Written in KiCad's order (unit, then body style) whatever their order here.
431    pub units: Vec<AuthoredSymbolUnit>,
432    pub embedded_fonts: bool,
433}
434
435impl AuthoredSymbol {
436    /// An empty symbol with KiCad's defaults: pin names and numbers shown, in
437    /// the BOM, on the board and in position files.
438    pub fn new(name: impl Into<String>) -> Self {
439        Self {
440            name: name.into(),
441            power: None,
442            body_styles: AuthoredSymbolBodyStyles::Single,
443            show_pin_numbers: true,
444            show_pin_names: true,
445            pin_name_offset_nm: KICAD_DEFAULT_PIN_NAME_OFFSET_NM,
446            exclude_from_sim: false,
447            in_bom: true,
448            on_board: true,
449            in_pos_files: true,
450            duplicate_pin_numbers_are_jumpers: false,
451            jumper_pin_groups: Vec::new(),
452            properties: Vec::new(),
453            units_locked: false,
454            keywords: String::new(),
455            footprint_filters: Vec::new(),
456            unit_names: BTreeMap::new(),
457            units: Vec::new(),
458            embedded_fonts: false,
459        }
460    }
461}
462
463/// A whole `.kicad_sym` file.
464#[derive(Clone, Debug, PartialEq)]
465pub struct AuthoredSymbolLibrary {
466    pub generator: String,
467    pub generator_version: String,
468    pub symbols: Vec<AuthoredSymbol>,
469}
470
471impl Default for AuthoredSymbolLibrary {
472    fn default() -> Self {
473        Self {
474            generator: "kicad_symbol_editor".to_owned(),
475            generator_version: "10.0".to_owned(),
476            symbols: Vec::new(),
477        }
478    }
479}
480
481impl AuthoredSymbolLibrary {
482    /// Check the library and return its file text.
483    pub fn canonical_text(&self, limits: SymbolAuthoringLimits) -> Result<String, Error> {
484        let mut out = String::new();
485        self.write_into(&mut out, limits)?;
486        Ok(out)
487    }
488
489    /// Check the library and append its file text to `out`. Nothing is
490    /// appended when the library is invalid.
491    pub fn write_into(&self, out: &mut String, limits: SymbolAuthoringLimits) -> Result<(), Error> {
492        let estimate = validate::library(self, limits)?;
493        let start = out.len();
494        out.reserve(estimate.min(limits.max_output_bytes));
495        let written = emit::library(self, out, limits.max_output_bytes);
496        if written.is_err() {
497            out.truncate(start);
498        }
499        written
500    }
501}
502
503/// A library item name as KiCad stores it (`EscapeString(..., CTX_LIBID)`):
504/// `\`, `<`, `>`, `:` and `"` become `{backslash}`, `{lt}`, `{gt}`, `{colon}`
505/// and `{dblquote}`; line breaks are dropped.
506pub fn escape_lib_item_name(name: &str) -> Cow<'_, str> {
507    if !name.contains(['\\', '<', '>', ':', '"', '\n', '\r']) {
508        return Cow::Borrowed(name);
509    }
510    let mut out = String::with_capacity(name.len() + 16);
511    for character in name.chars() {
512        match character {
513            '\\' => out.push_str("{backslash}"),
514            '<' => out.push_str("{lt}"),
515            '>' => out.push_str("{gt}"),
516            ':' => out.push_str("{colon}"),
517            '"' => out.push_str("{dblquote}"),
518            '\n' | '\r' => {}
519            other => out.push(other),
520        }
521    }
522    Cow::Owned(out)
523}
524
525/// The shown form of a stored library item name: the inverse of
526/// [`escape_lib_item_name`], plus the `{slash}` older KiCad wrote for `/`.
527pub fn unescape_lib_item_name(name: &str) -> Cow<'_, str> {
528    if !name.contains('{') {
529        return Cow::Borrowed(name);
530    }
531    const TOKENS: [(&str, char); 6] = [
532        ("{backslash}", '\\'),
533        ("{lt}", '<'),
534        ("{gt}", '>'),
535        ("{colon}", ':'),
536        ("{dblquote}", '"'),
537        ("{slash}", '/'),
538    ];
539    let mut out = String::with_capacity(name.len());
540    let mut rest = name;
541    while let Some(index) = rest.find('{') {
542        out.push_str(&rest[..index]);
543        rest = &rest[index..];
544        match TOKENS.iter().find(|(token, _)| rest.starts_with(token)) {
545            Some((token, character)) => {
546                out.push(*character);
547                rest = &rest[token.len()..];
548            }
549            None => {
550                out.push('{');
551                rest = &rest[1..];
552            }
553        }
554    }
555    out.push_str(rest);
556    Cow::Owned(out)
557}
558
559/// The text KiCad shows for a stored text (`UnescapeString`,
560/// common/string_utils.cpp, which `EDA_TEXT::cacheShownText` applies to every
561/// shown text): each escape token (`{slash}`, `{dblquote}`, ...) becomes its
562/// character. A brace group after `$`, `~`, `^` or `_` (a text variable or
563/// markup) and an unknown token keep their braces, their content read the
564/// same way; an unclosed `{` stays.
565pub fn unescape_string(text: &str) -> Cow<'_, str> {
566    if !text.contains('{') || text.chars().count() <= 2 {
567        return Cow::Borrowed(text);
568    }
569    let chars = text.chars().collect::<Vec<_>>();
570    let mut out = String::with_capacity(text.len());
571    let mut prev = None;
572    let mut i = 0;
573    while i < chars.len() {
574        let c = chars[i];
575        if c != '{' {
576            out.push(c);
577            prev = Some(c);
578            i += 1;
579            continue;
580        }
581        let mut depth = 1usize;
582        let close = chars.iter().enumerate().skip(i + 1).find_map(|(j, &d)| {
583            match d {
584                '{' => depth += 1,
585                '}' => depth -= 1,
586                _ => {}
587            }
588            (depth == 0).then_some(j)
589        });
590        let Some(close) = close else {
591            out.push('{');
592            out.push_str(&unescape_string(&chars[i + 1..].iter().collect::<String>()));
593            break;
594        };
595        let token = chars[i + 1..close].iter().collect::<String>();
596        let character = match token.as_str() {
597            _ if matches!(prev, Some('$' | '~' | '^' | '_')) => None,
598            "dblquote" => Some('"'),
599            "quote" => Some('\''),
600            "lt" => Some('<'),
601            "gt" => Some('>'),
602            "backslash" => Some('\\'),
603            "slash" => Some('/'),
604            "bar" => Some('|'),
605            "comma" => Some(','),
606            "colon" => Some(':'),
607            "space" => Some(' '),
608            "dollar" => Some('$'),
609            "tab" => Some('\t'),
610            "return" => Some('\n'),
611            "brace" => Some('{'),
612            _ => None,
613        };
614        match character {
615            Some(character) => out.push(character),
616            None => {
617                out.push('{');
618                out.push_str(&unescape_string(&token));
619                out.push('}');
620            }
621        }
622        prev = Some('}');
623        i = close + 1;
624    }
625    Cow::Owned(out)
626}