1mod emit;
18mod validate;
19
20use crate::sexpr::Error;
21use std::borrow::Cow;
22use std::collections::BTreeMap;
23
24pub const KICAD_SYMBOL_LIBRARY_VERSION_2025_10_24: i64 = 20_251_024;
26
27pub const KICAD_DEFAULT_PIN_NAME_OFFSET_NM: i64 = 508_000;
29
30pub const KICAD_DEFAULT_TEXT_SIZE_NM: i64 = 1_270_000;
32
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub struct SymbolAuthoringLimits {
36 pub max_symbols: usize,
37 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#[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#[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#[derive(Clone, Debug, PartialEq)]
107pub struct AuthoredSymbolTextEffects {
108 pub face: Option<String>,
110 pub height_nm: i64,
111 pub width_nm: i64,
112 pub line_spacing: f64,
114 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#[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 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#[derive(Clone, Debug, Default, Eq, PartialEq)]
183pub enum AuthoredSymbolBodyStyles {
184 #[default]
186 Single,
187 DeMorgan,
189 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#[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#[derive(Clone, Copy, Debug, Default, PartialEq)]
225pub enum AuthoredSymbolFill {
226 #[default]
227 None,
228 Outline,
230 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 Rectangle {
251 start: AuthoredSymbolPoint,
252 end: AuthoredSymbolPoint,
253 corner_radius_nm: i64,
254 },
255 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#[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#[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 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#[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#[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 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#[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#[derive(Clone, Debug, PartialEq)]
405pub struct AuthoredSymbol {
406 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 pub properties: Vec<AuthoredSymbolProperty>,
422 pub units_locked: bool,
424 pub keywords: String,
426 pub footprint_filters: Vec<String>,
428 pub unit_names: BTreeMap<u32, String>,
430 pub units: Vec<AuthoredSymbolUnit>,
432 pub embedded_fonts: bool,
433}
434
435impl AuthoredSymbol {
436 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#[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 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 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
503pub 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
525pub 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
559pub 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}