1pub mod autoroute;
7pub mod board;
8pub mod erc;
9pub mod fabrication;
10pub mod footprint;
11pub mod kicad;
12pub mod netlist;
13use serde::{Deserialize, Serialize};
14use std::collections::{BTreeMap, BTreeSet};
15pub use uuid::Uuid;
16
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
19pub struct Point {
20 pub x: i32,
21 pub y: i32,
22}
23impl Point {
24 pub const fn new(x: i32, y: i32) -> Self {
25 Self { x, y }
26 }
27 pub fn offset(self, other: Self) -> Self {
28 Self::new(self.x + other.x, self.y + other.y)
29 }
30 pub fn rotate(self, turns: u8) -> Self {
31 match turns % 4 {
32 1 => Self::new(-self.y, self.x),
33 2 => Self::new(-self.x, -self.y),
34 3 => Self::new(self.y, -self.x),
35 _ => self,
36 }
37 }
38 pub fn snapped(self) -> Self {
39 Self::new(
40 (self.x as f64 / 1270.).round() as i32 * 1270,
41 (self.y as f64 / 1270.).round() as i32 * 1270,
42 )
43 }
44}
45#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
46pub enum Graphic {
47 Path(Vec<Point>),
48 Circle { center: Point, radius: i32 },
49 Text { at: Point, text: String, size: i32 },
50}
51fn unit_is_unset(unit: &u32) -> bool {
52 *unit == 0
53}
54
55#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
56pub struct Pin {
57 #[serde(default)]
58 pub hidden: bool,
59 #[serde(default, skip_serializing_if = "unit_is_unset")]
70 pub unit: u32,
71 #[serde(default, skip_serializing_if = "unit_is_unset")]
82 pub gate: u32,
83 pub number: String,
84 pub name: String,
85 pub electrical_type: String,
86 pub at: Point,
87 pub end: Point,
88}
89#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
90pub struct Symbol {
91 #[serde(default)]
92 pub unit_count: u32,
93 #[serde(default)]
94 pub properties: BTreeMap<String, String>,
95 #[serde(default)]
96 pub power_net: Option<String>,
97 pub library_id: String,
98 pub reference_prefix: String,
99 pub description: String,
100 pub graphics: Vec<Graphic>,
101 pub pins: Vec<Pin>,
102 #[serde(default, skip_serializing_if = "Vec::is_empty")]
107 pub graphic_gates: Vec<u32>,
108 #[serde(default, skip_serializing_if = "is_false")]
112 pub hide_pin_names: bool,
113 #[serde(default, skip_serializing_if = "is_false")]
116 pub hide_pin_numbers: bool,
117}
118fn is_false(value: &bool) -> bool {
119 !*value
120}
121impl Symbol {
122 pub fn default_value(&self) -> String {
128 match self.properties.get("Value").map(|v| v.trim()).filter(|v| !v.is_empty()) {
129 Some(value) => value.to_owned(),
130 None => self.library_id.split(':').next_back().unwrap_or("").to_owned(),
131 }
132 }
133 pub fn gate_count(&self) -> u32 {
136 self.pins
137 .iter()
138 .map(|p| p.gate)
139 .chain(self.graphic_gates.iter().copied())
140 .max()
141 .unwrap_or(0)
142 }
143 pub fn migrate_legacy_units(&mut self) -> bool {
162 let Some(captions) = self.legacy_unit_captions() else {
163 return false;
164 };
165 let mut gates = Vec::with_capacity(self.graphics.len());
166 let mut gate = 1;
167 for (index, _) in self.graphics.iter().enumerate() {
168 if captions.contains(&index) {
169 gate += 1;
170 } else {
171 gates.push(if gate <= self.unit_count { gate } else { 0 });
174 }
175 }
176 let mut index = 0;
177 self.graphics.retain(|_| {
178 index += 1;
179 !captions.contains(&(index - 1))
180 });
181 self.graphic_gates = gates;
182 for pin in &mut self.pins {
183 pin.gate = pin.unit;
184 pin.unit = 0;
185 }
186 self.unit_count = 1;
187 true
188 }
189 fn legacy_unit_captions(&self) -> Option<Vec<usize>> {
193 let count = self.unit_count;
194 if count < 2 || self.gate_count() > 0 {
195 return None;
196 }
197 if !self.pins.iter().all(|p| (1..=count).contains(&p.unit)) {
198 return None;
199 }
200 let captions: Vec<(usize, u32)> = self
201 .graphics
202 .iter()
203 .enumerate()
204 .filter_map(|(i, g)| match g {
205 Graphic::Text { at, text, size } if *size == 1270 && at.y == -15000 => text
206 .strip_prefix("Unit ")
207 .and_then(|n| n.parse::<u32>().ok())
208 .map(|n| (i, n)),
209 _ => None,
210 })
211 .collect();
212 let in_order = captions.iter().map(|&(_, n)| n).eq(1..=count);
213 in_order.then(|| captions.into_iter().map(|(i, _)| i).collect())
214 }
215 pub fn graphic_gate(&self, index: usize) -> u32 {
217 self.graphic_gates.get(index).copied().unwrap_or(0)
218 }
219 pub fn gate_extent(&self, gate: u32) -> Option<(Point, Point)> {
222 let mut points = vec![];
223 for pin in self.pins.iter().filter(|p| p.gate == gate) {
224 points.extend([pin.at, pin.end]);
225 }
226 for (i, g) in self.graphics.iter().enumerate() {
227 if self.graphic_gate(i) == gate {
228 points.extend(graphic_points(g));
229 }
230 }
231 extent(&points)
232 }
233}
234pub fn gate_letter(gate: u32) -> String {
237 let mut n = gate.max(1);
238 let mut letters = vec![];
239 while n > 0 {
240 n -= 1;
241 letters.push(char::from(b'A' + (n % 26) as u8));
242 n /= 26;
243 }
244 letters.iter().rev().collect()
245}
246fn graphic_points(g: &Graphic) -> Vec<Point> {
247 match g {
248 Graphic::Path(path) => path.clone(),
249 Graphic::Circle { center, radius } => vec![
250 Point::new(center.x - radius, center.y - radius),
251 Point::new(center.x + radius, center.y + radius),
252 ],
253 Graphic::Text { at, .. } => vec![*at],
254 }
255}
256fn extent(points: &[Point]) -> Option<(Point, Point)> {
257 let lo = Point::new(points.iter().map(|p| p.x).min()?, points.iter().map(|p| p.y).min()?);
258 let hi = Point::new(points.iter().map(|p| p.x).max()?, points.iter().map(|p| p.y).max()?);
259 Some((lo, hi))
260}
261#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
265pub struct PartSource {
266 #[serde(default, skip_serializing_if = "Option::is_none")]
268 pub instance: Option<String>,
269 pub key: String,
270 pub signature: String,
271}
272#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
273pub struct Component {
274 pub id: Uuid,
275 pub reference: String,
278 pub value: String,
279 pub symbol: Symbol,
280 pub at: Point,
281 pub rotation: u8,
282 #[serde(default, skip_serializing_if = "Option::is_none")]
284 pub part: Option<PartSource>,
285 #[serde(default, skip_serializing_if = "Option::is_none")]
287 pub pads: Option<board::Footprint>,
288 #[serde(default, skip_serializing_if = "Vec::is_empty")]
294 pub gates: Vec<GatePlacement>,
295}
296#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
300pub struct GatePlacement {
301 pub gate: u32,
302 pub pivot: Point,
303 pub at: Point,
304 #[serde(default)]
305 pub rotation: u8,
306}
307impl Component {
308 pub fn is_valued_part(&self) -> bool {
312 self.symbol.power_net.is_none() && !self.reference.starts_with('#') && !self.symbol.pins.is_empty()
313 }
314 pub fn transform(&self, p: Point) -> Point {
315 p.rotate(self.rotation).offset(self.at)
316 }
317 pub fn gate_transform(&self, gate: u32, p: Point) -> Point {
321 match self.gate(gate) {
322 Some(g) => Point::new(p.x - g.pivot.x, p.y - g.pivot.y)
323 .rotate(g.rotation)
324 .offset(g.at),
325 None => self.transform(p),
326 }
327 }
328 pub fn gate(&self, gate: u32) -> Option<&GatePlacement> {
330 (gate > 0).then(|| self.gates.iter().find(|g| g.gate == gate)).flatten()
331 }
332 pub fn pin_at(&self, pin: &Pin) -> Point {
334 self.gate_transform(pin.gate, pin.at)
335 }
336 pub fn pin_end(&self, pin: &Pin) -> Point {
338 self.gate_transform(pin.gate, pin.end)
339 }
340 pub fn graphic_transform(&self, index: usize, p: Point) -> Point {
342 self.gate_transform(self.symbol.graphic_gate(index), p)
343 }
344 pub fn gate_reference(&self, gate: u32) -> String {
347 if self.gates.is_empty() || gate == 0 {
348 self.reference.clone()
349 } else {
350 format!("{}{}", self.reference, gate_letter(gate))
351 }
352 }
353 pub fn sheet_boxes(&self) -> Vec<(u32, Point, Point)> {
356 let gates: Vec<u32> = if self.gates.is_empty() {
357 vec![0]
358 } else {
359 self.gates.iter().map(|g| g.gate).collect()
360 };
361 gates
362 .into_iter()
363 .map(|gate| {
364 let mut points = vec![];
365 for pin in &self.symbol.pins {
366 if self.gates.is_empty() || pin.gate == gate {
367 points.extend([self.pin_at(pin), self.pin_end(pin)]);
368 }
369 }
370 for (i, g) in self.symbol.graphics.iter().enumerate() {
371 if self.gates.is_empty() || self.symbol.graphic_gate(i) == gate {
372 points.extend(graphic_points(g).into_iter().map(|p| self.graphic_transform(i, p)));
373 }
374 }
375 let at = self.gate(gate).map_or(self.at, |g| g.at);
376 points.push(at);
377 let (lo, hi) = extent(&points).unwrap_or((at, at));
378 (gate, lo, hi)
379 })
380 .collect()
381 }
382 pub fn sync_gates(&mut self) {
386 let count = self.symbol.gate_count();
387 if count <= 1 {
388 self.gates.clear();
389 return;
390 }
391 self.gates.retain(|g| (1..=count).contains(&g.gate));
392 for gate in 1..=count {
393 if self.gates.iter().any(|g| g.gate == gate) {
394 continue;
395 }
396 let Some((lo, hi)) = self.symbol.gate_extent(gate) else {
397 continue;
398 };
399 let pivot = Point::new((lo.x + hi.x) / 2, (lo.y + hi.y) / 2).snapped();
400 self.gates.push(GatePlacement {
401 gate,
402 pivot,
403 at: self.transform(pivot),
404 rotation: self.rotation,
405 });
406 }
407 self.gates.sort_by_key(|g| g.gate);
408 }
409}
410#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
412pub struct Terminal {
413 pub component: Uuid,
414 pub pin: String,
415}
416#[derive(Clone, Debug, PartialEq, Eq)]
418pub enum ConnectionTarget {
419 Terminal(Terminal),
420 Junction(Point),
421}
422
423#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
424pub struct Wire {
425 pub id: Uuid,
426 pub a: Point,
427 pub b: Point,
428 #[serde(default)]
429 pub bends: Vec<Point>,
430 #[serde(default)]
431 pub start: Option<Terminal>,
432 #[serde(default)]
433 pub end: Option<Terminal>,
434 #[serde(default, skip_serializing_if = "String::is_empty")]
436 pub connection_id: String,
437 #[serde(default, skip_serializing_if = "String::is_empty")]
439 pub stock_part_number: String,
440}
441impl Wire {
442 pub fn new(a: Point, b: Point) -> Self {
443 Self {
444 id: Uuid::new_v4(),
445 a,
446 b,
447 bends: vec![],
448 start: None,
449 end: None,
450 connection_id: String::new(),
451 stock_part_number: String::new(),
452 }
453 }
454 pub fn points(&self) -> Vec<Point> {
455 std::iter::once(self.a)
456 .chain(self.bends.iter().copied())
457 .chain(std::iter::once(self.b))
458 .collect()
459 }
460 pub fn set_points(&mut self, points: Vec<Point>) {
461 let mut clean: Vec<Point> = vec![];
462 for p in points {
463 if clean.last() == Some(&p) {
464 continue;
465 }
466 while clean.len() >= 2 {
467 let a = clean[clean.len() - 2];
468 let b = clean[clean.len() - 1];
469 if (a.x == b.x && b.x == p.x) || (a.y == b.y && b.y == p.y) {
470 clean.pop();
471 } else {
472 break;
473 }
474 }
475 clean.push(p);
476 }
477 if clean.len() >= 2 {
478 self.a = clean[0];
479 self.b = *clean.last().unwrap();
480 self.bends = clean[1..clean.len() - 1].to_vec();
481 }
482 }
483 pub fn slide_segment(&mut self, index: usize, delta: Point) {
485 let mut points = self.points();
486 if index + 1 >= points.len() {
487 return;
488 }
489 let a = points[index];
490 let b = points[index + 1];
491 let shift = if a.y == b.y {
492 Point::new(0, delta.y)
493 } else {
494 Point::new(delta.x, 0)
495 };
496 if shift == Point::default() {
497 return;
498 }
499 let moved_a = a.offset(shift);
500 let moved_b = b.offset(shift);
501 if index == 0 {
502 points.insert(1, moved_a);
503 points[2] = moved_b;
504 if points.len() == 3 {
505 points.push(b);
506 }
507 } else if index + 1 == points.len() - 1 {
508 points[index] = moved_a;
509 points.insert(index + 1, moved_b);
510 } else {
511 points[index] = moved_a;
512 points[index + 1] = moved_b;
513 }
514 self.set_points(points);
515 }
516 pub fn add_jog(&mut self, index: usize) {
518 let mut points = self.points();
519 if index + 1 >= points.len() {
520 return;
521 }
522 let a = points[index];
523 let b = points[index + 1];
524 let p = Point::new(a.x + (b.x - a.x) / 3, a.y + (b.y - a.y) / 3);
525 let q = Point::new(a.x + 2 * (b.x - a.x) / 3, a.y + 2 * (b.y - a.y) / 3);
526 if a == p || p == q || q == b {
527 return;
528 }
529 let offset = if a.y == b.y {
530 Point::new(0, 2540)
531 } else {
532 Point::new(2540, 0)
533 };
534 points.splice(
535 index + 1..index + 1,
536 [p, p.offset(offset), q.offset(offset), q],
537 );
538 self.set_points(points);
539 }
540 pub fn removable_jog(&self, near: usize) -> Option<usize> {
541 self.points()
542 .windows(4)
543 .enumerate()
544 .filter(|(_, p)| p[0] != p[3] && (p[0].x == p[3].x || p[0].y == p[3].y))
545 .min_by_key(|(i, _)| (i + 1).abs_diff(near))
546 .map(|(i, _)| i)
547 }
548 pub fn remove_jog(&mut self, near: usize) {
549 if let Some(i) = self.removable_jog(near) {
550 let mut p = self.points();
551 p.drain(i + 1..i + 3);
552 self.set_points(p);
553 }
554 }
555 fn follow_start(&mut self, at: Point) {
556 if at == self.a {
557 return;
558 }
559 let mut points = self.points();
560 let horizontal = points[0].y == points[1].y;
561 points[0] = at;
562 if points.len() == 2 {
563 let b = points[1];
564 let bend = if horizontal {
565 Point::new(b.x, at.y)
566 } else {
567 Point::new(at.x, b.y)
568 };
569 points.insert(1, bend);
570 } else if horizontal {
571 points[1].y = at.y;
572 } else {
573 points[1].x = at.x;
574 }
575 self.set_points(points);
576 }
577 pub fn follow(&mut self, a: Point, b: Point) {
578 if a == b {
579 self.set_points(vec![
580 a,
581 a.offset(Point::new(2540, 0)),
582 a.offset(Point::new(2540, 2540)),
583 a.offset(Point::new(0, 2540)),
584 b,
585 ]);
586 return;
587 }
588 self.follow_start(a);
589 let mut points = self.points();
590 points.reverse();
591 self.set_points(points);
592 self.follow_start(b);
593 let mut points = self.points();
594 points.reverse();
595 self.set_points(points);
596 }
597}
598#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
599pub struct Label {
600 #[serde(default)]
601 pub flag: bool,
602 #[serde(default)]
603 pub rotation: u8,
604 #[serde(default)]
605 pub terminal: Option<Terminal>,
606 pub id: Uuid,
607 pub name: String,
608 pub at: Point,
609}
610#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
612pub enum DocumentKind {
613 #[default]
615 Schematic,
616 Wiring,
619}
620impl DocumentKind {
621 fn is_schematic(&self) -> bool {
622 *self == Self::Schematic
623 }
624}
625#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
626pub struct Document {
627 pub version: u32,
628 #[serde(default, skip_serializing_if = "DocumentKind::is_schematic")]
629 pub kind: DocumentKind,
630 pub title: String,
631 pub components: Vec<Component>,
632 pub wires: Vec<Wire>,
633 pub junctions: BTreeSet<Point>,
634 pub labels: Vec<Label>,
635 #[serde(default)]
637 pub board: board::Board,
638 #[serde(default, skip_serializing_if = "Vec::is_empty")]
642 pub no_connects: Vec<Terminal>,
643 #[serde(default, skip_serializing_if = "Vec::is_empty")]
646 pub power_flags: Vec<Terminal>,
647}
648pub const DOCUMENT_VERSION: u32 = 4;
650pub const WIRING_DOCUMENT_VERSION: u32 = 5;
653impl Default for Document {
654 fn default() -> Self {
655 Self {
656 version: DOCUMENT_VERSION,
657 kind: DocumentKind::Schematic,
658 title: "Untitled schematic".into(),
659 components: vec![],
660 wires: vec![],
661 junctions: BTreeSet::new(),
662 labels: vec![],
663 board: board::Board::default(),
664 no_connects: vec![],
665 power_flags: vec![],
666 }
667 }
668}
669#[derive(Clone, Debug, PartialEq, Eq)]
671pub struct Connection {
672 pub connection_id: String,
673 pub from_ref_des: String,
674 pub from_port: String,
675 pub to_ref_des: String,
676 pub to_port: String,
677 pub stock_part_number: String,
678}
679impl Document {
680 pub fn new(kind: DocumentKind) -> Self {
682 match kind {
683 DocumentKind::Schematic => Self::default(),
684 DocumentKind::Wiring => Self {
685 version: WIRING_DOCUMENT_VERSION,
686 kind,
687 title: "Untitled wiring diagram".into(),
688 ..Self::default()
689 },
690 }
691 }
692 pub fn place(&mut self, mut symbol: Symbol, at: Point, rotation: u8) -> Uuid {
693 symbol.migrate_legacy_units();
695 let mut n = 1;
696 while self
697 .components
698 .iter()
699 .any(|c| c.reference == format!("{}{n}", symbol.reference_prefix))
700 {
701 n += 1;
702 }
703 let id = Uuid::new_v4();
704 self.components.push(Component {
705 id,
706 reference: format!("{}{n}", symbol.reference_prefix),
707 value: symbol.default_value(),
708 symbol,
709 at,
710 rotation: rotation % 4,
711 part: None,
712 pads: None,
713 gates: vec![],
714 });
715 self.components.last_mut().unwrap().sync_gates();
716 let flags: Vec<_> = self
717 .components
718 .last()
719 .unwrap()
720 .symbol
721 .pins
722 .iter()
723 .filter_map(|p| {
724 let symbol = &self.components.last().unwrap().symbol;
725 symbol
726 .power_net
727 .clone()
728 .or_else(|| {
729 (p.hidden && p.electrical_type == "power_in" && p.name != "~")
730 .then(|| p.name.clone())
731 })
732 .map(|name| (p.number.clone(), name))
733 })
734 .collect();
735 for (pin, name) in flags {
736 let _ = self.set_net_flag(Terminal { component: id, pin }, &name);
737 }
738 id
739 }
740 pub fn place_part(
745 &mut self,
746 part: PartSource,
747 symbol: Symbol,
748 pads: Option<board::Footprint>,
749 reference: Option<String>,
750 at: Point,
751 rotation: u8,
752 ) -> Result<Uuid, String> {
753 if let Some(instance) = &part.instance {
754 if self.components.iter().any(|c| c.part.as_ref().and_then(|p| p.instance.as_ref()) == Some(instance)) {
755 return Err("This native assembly instance is already placed".into());
756 }
757 }
758 let id = self.place(symbol, at, rotation);
759 if let Some(reference) = reference {
760 self.set_reference(id, &reference).inspect_err(|_| {
761 self.delete_component(id);
762 })?;
763 }
764 let c = self.components.iter_mut().find(|c| c.id == id).unwrap();
765 c.part = Some(part);
766 c.pads = pads;
767 Ok(id)
768 }
769 pub fn set_reference(&mut self, id: Uuid, reference: &str) -> Result<(), String> {
772 let reference = reference.trim();
773 if reference.is_empty() {
774 return Err("A label cannot be empty".into());
775 }
776 if self
777 .components
778 .iter()
779 .any(|c| c.id != id && c.reference == reference)
780 {
781 return Err(format!("{reference} is already used by another part"));
782 }
783 let c = self
784 .components
785 .iter_mut()
786 .find(|c| c.id == id)
787 .ok_or("Component no longer exists")?;
788 c.reference = reference.into();
789 Ok(())
790 }
791 pub fn set_value(&mut self, ids: &[Uuid], value: &str) -> usize {
797 let mut changed = 0;
798 for c in self.components.iter_mut().filter(|c| ids.contains(&c.id)) {
799 if c.value != value {
800 c.value = value.into();
801 changed += 1;
802 }
803 }
804 changed
805 }
806 pub fn unvalued_siblings(&self, id: Uuid) -> Vec<Uuid> {
811 let Some(c) = self.components.iter().find(|c| c.id == id) else {
812 return vec![];
813 };
814 let mut siblings: Vec<&Component> = self
815 .components
816 .iter()
817 .filter(|o| {
818 o.id != id
819 && o.is_valued_part()
820 && o.symbol.library_id == c.symbol.library_id
821 && o.value == o.symbol.default_value()
822 })
823 .collect();
824 siblings.sort_by(|a, b| footprint::natural_cmp(&a.reference, &b.reference));
825 siblings.into_iter().map(|o| o.id).collect()
826 }
827 pub fn parts(&self) -> Vec<PartSource> {
830 let mut parts: Vec<_> = self
831 .components
832 .iter()
833 .filter_map(|c| c.part.clone())
834 .collect();
835 parts.sort();
836 parts.dedup();
837 parts
838 }
839 pub fn refresh_part(
846 &mut self,
847 key: &str,
848 symbol: &Symbol,
849 pads: Option<&board::Footprint>,
850 signature: &str,
851 renames: &BTreeMap<String, String>,
852 ) -> Result<usize, String> {
853 if signature.trim().is_empty() {
854 return Err("A part needs a key and a signature".into());
855 }
856 let stale: Vec<Uuid> = self
857 .components
858 .iter()
859 .filter(|c| {
860 c.part
861 .as_ref()
862 .is_some_and(|p| p.key == key && p.signature != signature)
863 })
864 .map(|c| c.id)
865 .collect();
866 let mut draft = self.clone();
867 for id in &stale {
868 draft.rebind(*id, symbol, pads, renames, |part| part.signature = signature.into())?;
869 }
870 *self = draft;
871 Ok(stale.len())
872 }
873 pub fn refresh_component(
885 &mut self,
886 component: Uuid,
887 symbol: &Symbol,
888 pads: Option<&board::Footprint>,
889 signature: &str,
890 renames: &BTreeMap<String, String>,
891 ) -> Result<(), String> {
892 if signature.trim().is_empty() {
893 return Err("A part needs a key and a signature".into());
894 }
895 let mut draft = self.clone();
896 draft.rebind(component, symbol, pads, renames, |part| part.signature = signature.into())?;
897 *self = draft;
898 Ok(())
899 }
900 fn rebind(
908 &mut self,
909 id: Uuid,
910 symbol: &Symbol,
911 pads: Option<&board::Footprint>,
912 renames: &BTreeMap<String, String>,
913 bind: impl FnOnce(&mut PartSource),
914 ) -> Result<(), String> {
915 self.rename_terminals(id, renames);
916 self.replace_component_symbol(id, symbol.clone())?;
917 let c = self
918 .components
919 .iter_mut()
920 .find(|c| c.id == id)
921 .ok_or("Component no longer exists")?;
922 c.pads = pads.cloned();
923 if let Some(part) = &mut c.part {
924 bind(part);
925 }
926 if let Some(pads) = pads
927 && let Some(placement) = self.board.placements.iter_mut().find(|p| p.component == id)
928 {
929 placement.footprint = pads.clone();
930 }
931 if pads.is_none() {
932 self.board.placements.retain(|placement| placement.component != id);
933 }
934 Ok(())
935 }
936 pub fn relink(
951 &mut self,
952 component: Uuid,
953 part: PartSource,
954 symbol: &Symbol,
955 pads: Option<&board::Footprint>,
956 renames: &BTreeMap<String, String>,
957 ) -> Result<(), String> {
958 if part.signature.trim().is_empty() {
959 return Err("A part needs a key and a signature".into());
960 }
961 if !self.components.iter().any(|c| c.id == component) {
962 return Err("Component no longer exists".into());
963 }
964 if let Some(instance) = &part.instance
965 && self.components.iter().any(|c| {
966 c.id != component
967 && c.part.as_ref().and_then(|p| p.instance.as_ref()) == Some(instance)
968 })
969 {
970 return Err("This native assembly instance is already placed".into());
971 }
972 let mut draft = self.clone();
973 if let Some(c) = draft.components.iter_mut().find(|c| c.id == component)
976 && c.part.is_none()
977 {
978 c.part = Some(part.clone());
979 }
980 draft.rebind(component, symbol, pads, renames, |bound| *bound = part)?;
981 *self = draft;
982 Ok(())
983 }
984 fn rename_terminals(&mut self, id: Uuid, renames: &BTreeMap<String, String>) {
987 let rename = |terminal: &mut Terminal| {
988 if terminal.component == id
989 && let Some(label) = renames.get(&terminal.pin)
990 {
991 terminal.pin = label.clone();
992 }
993 };
994 let terminals = self
995 .wires
996 .iter_mut()
997 .flat_map(|w| [w.start.as_mut(), w.end.as_mut()])
998 .chain(self.labels.iter_mut().map(|l| l.terminal.as_mut()));
999 for terminal in terminals.flatten() {
1000 rename(terminal);
1001 }
1002 for terminal in self.no_connects.iter_mut().chain(self.power_flags.iter_mut()) {
1004 rename(terminal);
1005 }
1006 }
1007 pub fn add_wire(&mut self, a: Point, b: Point) {
1008 if self.kind == DocumentKind::Schematic
1009 && a != b
1010 && (a.x == b.x || a.y == b.y)
1011 && !self
1012 .wires
1013 .iter()
1014 .any(|w| (w.a == a && w.b == b) || (w.a == b && w.b == a))
1015 {
1016 let mut wire = Wire::new(a, b);
1017 wire.start = self.terminal_at(a);
1018 wire.end = self.terminal_at(b);
1019 self.wires.push(wire);
1020 }
1021 }
1022 pub fn set_net_flag(&mut self, terminal: Terminal, name: &str) -> Result<Uuid, String> {
1024 if self.kind == DocumentKind::Wiring {
1025 return Err("A wiring diagram has no nets".into());
1026 }
1027 let name = name.trim();
1028 if name.is_empty() {
1029 return Err("Enter a net name".into());
1030 }
1031 let at = self
1032 .terminal_position(&terminal)
1033 .ok_or("Terminal no longer exists")?;
1034 if let Some(label) = self
1035 .labels
1036 .iter_mut()
1037 .find(|l| l.terminal.as_ref() == Some(&terminal))
1038 {
1039 label.name = name.into();
1040 label.at = at;
1041 return Ok(label.id);
1042 }
1043 let id = Uuid::new_v4();
1044 self.labels.push(Label {
1045 flag: true,
1046 rotation: 0,
1047 id,
1048 name: name.into(),
1049 at,
1050 terminal: Some(terminal),
1051 });
1052 Ok(id)
1053 }
1054 pub fn transform_label(&mut self, id: Uuid, at: Point, rotation: u8) {
1057 let terminal = self.terminal_at(at);
1058 let Some(label) = self.labels.iter_mut().find(|l| l.id == id) else {
1059 return;
1060 };
1061 let old = label.at;
1062 label.flag |= label.terminal.is_some();
1063 label.at = at;
1064 label.rotation = rotation % 4;
1065 label.terminal = terminal;
1066 for wire in &mut self.wires {
1067 let a = if wire.a == old && wire.start.is_none() {
1068 at
1069 } else {
1070 wire.a
1071 };
1072 let b = if wire.b == old && wire.end.is_none() {
1073 at
1074 } else {
1075 wire.b
1076 };
1077 wire.follow(a, b);
1078 }
1079 }
1080 pub fn terminal_position(&self, terminal: &Terminal) -> Option<Point> {
1081 let c = self
1082 .components
1083 .iter()
1084 .find(|c| c.id == terminal.component)?;
1085 c.symbol
1086 .pins
1087 .iter()
1088 .find(|p| p.number == terminal.pin)
1089 .map(|p| c.pin_at(p))
1090 }
1091 pub fn terminal_at(&self, at: Point) -> Option<Terminal> {
1092 self.components.iter().find_map(|c| {
1093 c.symbol
1094 .pins
1095 .iter()
1096 .find(|p| c.pin_at(p) == at)
1097 .map(|p| Terminal {
1098 component: c.id,
1099 pin: p.number.clone(),
1100 })
1101 })
1102 }
1103 pub fn connection_path(&self, start: &Terminal, end: &Terminal) -> Option<Vec<Point>> {
1106 let a = self.terminal_position(start)?;
1107 let b = self.terminal_position(end)?;
1108 let outward = |t: &Terminal, at: Point| -> Option<Point> {
1109 let c = self.components.iter().find(|c| c.id == t.component)?;
1110 let p = c.symbol.pins.iter().find(|p| p.number == t.pin)?;
1111 let inside = c.pin_end(p);
1112 Some(Point::new(
1113 (at.x - inside.x).signum() * 2540,
1114 (at.y - inside.y).signum() * 2540,
1115 ))
1116 };
1117 let da = outward(start, a)?;
1118 let db = outward(end, b)?;
1119 let sa = a.offset(da);
1120 let sb = b.offset(db);
1121 let pins: Vec<_> = self
1122 .components
1123 .iter()
1124 .flat_map(|c| c.symbol.pins.iter().map(|p| c.pin_at(p)))
1125 .collect();
1126 let min_x = pins
1127 .iter()
1128 .map(|p| p.x)
1129 .min()
1130 .unwrap_or(0)
1131 .min(sa.x)
1132 .min(sb.x)
1133 - 5080;
1134 let max_x = pins
1135 .iter()
1136 .map(|p| p.x)
1137 .max()
1138 .unwrap_or(0)
1139 .max(sa.x)
1140 .max(sb.x)
1141 + 5080;
1142 let min_y = pins
1143 .iter()
1144 .map(|p| p.y)
1145 .min()
1146 .unwrap_or(0)
1147 .min(sa.y)
1148 .min(sb.y)
1149 - 5080;
1150 let max_y = pins
1151 .iter()
1152 .map(|p| p.y)
1153 .max()
1154 .unwrap_or(0)
1155 .max(sa.y)
1156 .max(sb.y)
1157 + 5080;
1158 let mut candidates = vec![
1159 vec![a, sa, Point::new(sb.x, sa.y), sb, b],
1160 vec![a, sa, Point::new(sa.x, sb.y), sb, b],
1161 ];
1162 for x in [min_x, max_x] {
1163 candidates.push(vec![a, sa, Point::new(x, sa.y), Point::new(x, sb.y), sb, b]);
1164 }
1165 for y in [min_y, max_y] {
1166 candidates.push(vec![a, sa, Point::new(sa.x, y), Point::new(sb.x, y), sb, b]);
1167 }
1168 candidates
1169 .into_iter()
1170 .filter_map(|p| {
1171 let mut w = Wire::new(a, b);
1172 w.set_points(p);
1173 let p = w.points();
1174 let first = Point::new(p[1].x - a.x, p[1].y - a.y);
1175 let n = p.len();
1176 let last = Point::new(p[n - 2].x - b.x, p[n - 2].y - b.y);
1177 let dot = |x: Point, y: Point| {
1178 i64::from(x.x) * i64::from(y.x) + i64::from(x.y) * i64::from(y.y)
1179 };
1180 if dot(first, da) <= 0 || dot(last, db) <= 0 {
1181 return None;
1182 }
1183 if pins
1184 .iter()
1185 .filter(|p| **p != a && **p != b)
1186 .any(|pin| p.windows(2).any(|s| on_segment(*pin, s[0], s[1])))
1187 {
1188 return None;
1189 }
1190 let length: u64 = p
1191 .windows(2)
1192 .map(|s| {
1193 u64::from(s[0].x.abs_diff(s[1].x)) + u64::from(s[0].y.abs_diff(s[1].y))
1194 })
1195 .sum();
1196 Some((length, p))
1197 })
1198 .min_by_key(|(length, _)| *length)
1199 .map(|(_, p)| p)
1200 }
1201 pub fn target_position(&self, target: &ConnectionTarget) -> Option<Point> {
1202 match target {
1203 ConnectionTarget::Terminal(t) => self.terminal_position(t),
1204 ConnectionTarget::Junction(p) => {
1205 (self.junctions.contains(p) || self.labels.iter().any(|l| l.at == *p)).then_some(*p)
1206 }
1207 }
1208 }
1209 pub fn target_path(
1210 &self,
1211 start: &ConnectionTarget,
1212 end: &ConnectionTarget,
1213 ) -> Option<Vec<Point>> {
1214 let a = self.target_position(start)?;
1215 let b = self.target_position(end)?;
1216 if let (ConnectionTarget::Terminal(start), ConnectionTarget::Terminal(end)) = (start, end) {
1217 return Some(
1218 self.connection_path(start, end)
1219 .unwrap_or_else(|| vec![a, Point::new(b.x, a.y), b]),
1220 );
1221 }
1222 Some(vec![a, Point::new(b.x, a.y), b])
1223 }
1224 pub fn connect_targets(
1225 &mut self,
1226 start: ConnectionTarget,
1227 end: ConnectionTarget,
1228 ) -> Option<Uuid> {
1229 if let (ConnectionTarget::Terminal(a), ConnectionTarget::Terminal(b)) = (&start, &end) {
1230 return self.connect(a.clone(), b.clone());
1231 }
1232 if self.kind == DocumentKind::Wiring {
1233 return None; }
1235 let a = self.target_position(&start)?;
1236 let b = self.target_position(&end)?;
1237 if a == b
1238 || self
1239 .wires
1240 .iter()
1241 .any(|w| (w.a == a && w.b == b) || (w.a == b && w.b == a))
1242 {
1243 return None;
1244 }
1245 let mut w = Wire::new(a, b);
1246 w.set_points(self.target_path(&start, &end)?);
1247 if let ConnectionTarget::Terminal(t) = start {
1248 w.start = Some(t);
1249 }
1250 if let ConnectionTarget::Terminal(t) = end {
1251 w.end = Some(t);
1252 }
1253 let id = w.id;
1254 self.wires.push(w);
1255 Some(id)
1256 }
1257 pub fn connect(&mut self, start: Terminal, end: Terminal) -> Option<Uuid> {
1258 if start == end {
1259 return None;
1260 }
1261 let a = self.terminal_position(&start)?;
1262 let b = self.terminal_position(&end)?;
1263 if a == b {
1264 return None;
1265 }
1266 if self.wires.iter().any(|w| {
1267 (w.start.as_ref() == Some(&start) && w.end.as_ref() == Some(&end))
1268 || (w.start.as_ref() == Some(&end) && w.end.as_ref() == Some(&start))
1269 }) {
1270 return None;
1271 }
1272 let wiring = self.kind == DocumentKind::Wiring;
1273 if wiring && (self.attached_wire(&start).is_some() || self.attached_wire(&end).is_some()) {
1274 return None;
1275 }
1276 let mut wire = Wire::new(a, b);
1277 wire.set_points(
1278 self.connection_path(&start, &end)
1279 .unwrap_or_else(|| vec![a, Point::new(b.x, a.y), b]),
1280 );
1281 wire.start = Some(start);
1282 wire.end = Some(end);
1283 if wiring {
1284 let mut n = 1;
1285 while self
1286 .wires
1287 .iter()
1288 .any(|w| w.connection_id == format!("W{n}"))
1289 {
1290 n += 1;
1291 }
1292 wire.connection_id = format!("W{n}");
1293 }
1294 let id = wire.id;
1295 self.wires.push(wire);
1296 Some(id)
1297 }
1298 pub fn attached_wire(&self, terminal: &Terminal) -> Option<&Wire> {
1300 self.wires
1301 .iter()
1302 .find(|w| w.start.as_ref() == Some(terminal) || w.end.as_ref() == Some(terminal))
1303 }
1304 pub fn terminal_name(&self, terminal: &Terminal) -> String {
1306 let reference = self
1307 .components
1308 .iter()
1309 .find(|c| c.id == terminal.component)
1310 .map_or("?", |c| c.reference.as_str());
1311 format!("{reference}.{}", terminal.pin)
1312 }
1313 pub fn connections(&self) -> Vec<Connection> {
1316 let reference = |t: &Terminal| {
1317 self.components
1318 .iter()
1319 .find(|c| c.id == t.component)
1320 .map(|c| c.reference.clone())
1321 };
1322 let mut rows: Vec<_> = self
1323 .wires
1324 .iter()
1325 .filter_map(|w| {
1326 let (start, end) = (w.start.as_ref()?, w.end.as_ref()?);
1327 Some(Connection {
1328 connection_id: w.connection_id.clone(),
1329 from_ref_des: reference(start)?,
1330 from_port: start.pin.clone(),
1331 to_ref_des: reference(end)?,
1332 to_port: end.pin.clone(),
1333 stock_part_number: w.stock_part_number.clone(),
1334 })
1335 })
1336 .collect();
1337 rows.sort_by(|a, b| id_order(&a.connection_id).cmp(&id_order(&b.connection_id)));
1338 rows
1339 }
1340 pub fn connections_csv(&self) -> Result<String, String> {
1342 if self.kind != DocumentKind::Wiring {
1343 return Err("Only a wiring diagram has a connection list".into());
1344 }
1345 self.validate()?;
1346 let mut csv =
1347 String::from("connectionID,fromRefDes,fromPort,toRefDes,toPort,stockPartNumber\n");
1348 for c in self.connections() {
1349 let fields = [
1350 &c.connection_id,
1351 &c.from_ref_des,
1352 &c.from_port,
1353 &c.to_ref_des,
1354 &c.to_port,
1355 &c.stock_part_number,
1356 ];
1357 csv.push_str(&fields.map(|f| csv_field(f)).join(","));
1358 csv.push('\n');
1359 }
1360 Ok(csv)
1361 }
1362 pub fn migrate_legacy_units(&mut self) -> Vec<String> {
1372 let mut migrated = vec![];
1373 for c in &mut self.components {
1374 if c.symbol.migrate_legacy_units() {
1375 c.gates.clear();
1376 c.sync_gates();
1377 migrated.push(c.reference.clone());
1378 }
1379 }
1380 migrated
1381 }
1382 pub fn replace_component_symbol(&mut self, id: Uuid, mut symbol: Symbol) -> Result<(), String> {
1384 symbol.migrate_legacy_units();
1385 let mut draft = self.clone();
1386 let c = draft
1387 .components
1388 .iter()
1389 .find(|c| c.id == id)
1390 .ok_or("Component no longer exists")?;
1391 let (at, rotation) = (c.at, c.rotation);
1392 draft.transform_component(id, at, rotation); let valid_terminal =
1394 |t: &Terminal| t.component != id || symbol.pins.iter().any(|p| p.number == t.pin);
1395 if draft.kind == DocumentKind::Wiring {
1396 draft.wires.retain(|w| {
1398 w.start.as_ref().is_none_or(valid_terminal)
1399 && w.end.as_ref().is_none_or(valid_terminal)
1400 });
1401 }
1402 for wire in &mut draft.wires {
1403 if wire.start.as_ref().is_some_and(|t| !valid_terminal(t)) {
1404 wire.start = None;
1405 }
1406 if wire.end.as_ref().is_some_and(|t| !valid_terminal(t)) {
1407 wire.end = None;
1408 }
1409 }
1410 for label in &mut draft.labels {
1411 if label.terminal.as_ref().is_some_and(|t| !valid_terminal(t)) {
1412 label.flag = true;
1413 label.terminal = None;
1414 }
1415 }
1416 draft.no_connects.retain(valid_terminal);
1417 draft.power_flags.retain(valid_terminal);
1418 let c = draft.components.iter_mut().find(|c| c.id == id).unwrap();
1419 c.symbol = symbol;
1420 c.sync_gates();
1421 draft.transform_component(id, at, rotation);
1422 draft.validate()?;
1423 *self = draft;
1424 Ok(())
1425 }
1426 pub fn transform_component(&mut self, id: Uuid, at: Point, rotation: u8) {
1430 self.reposition(id, |c| {
1431 let turn = (rotation % 4 + 4 - c.rotation) % 4;
1432 for g in &mut c.gates {
1433 g.at = Point::new(g.at.x - c.at.x, g.at.y - c.at.y).rotate(turn).offset(at);
1434 g.rotation = (g.rotation + turn) % 4;
1435 }
1436 let rotated = c.rotation != rotation % 4;
1437 c.at = at;
1438 c.rotation = rotation % 4;
1439 rotated
1440 });
1441 }
1442 pub fn transform_gate(&mut self, id: Uuid, gate: u32, at: Point, rotation: u8) {
1446 self.reposition(id, |c| {
1447 let Some(g) = c.gates.iter_mut().find(|g| g.gate == gate) else {
1448 return false;
1449 };
1450 let rotated = g.rotation != rotation % 4;
1451 g.at = at;
1452 g.rotation = rotation % 4;
1453 rotated
1454 });
1455 }
1456 fn reposition(&mut self, id: Uuid, change: impl FnOnce(&mut Component) -> bool) {
1460 let bindings: Vec<_> = self
1461 .wires
1462 .iter()
1463 .map(|w| {
1464 (
1465 w.start.clone().or_else(|| self.terminal_at(w.a)),
1466 w.end.clone().or_else(|| self.terminal_at(w.b)),
1467 )
1468 })
1469 .collect();
1470 let leads_before: Vec<_> = self
1472 .labels
1473 .iter()
1474 .map(|l| l.terminal.as_ref().filter(|t| t.component == id).and_then(|t| self.lead(t)))
1475 .collect();
1476 let Some(c) = self.components.iter_mut().find(|c| c.id == id) else {
1477 return;
1478 };
1479 let rotated = change(c);
1480 let routes: Vec<_> = bindings
1481 .iter()
1482 .map(|(a, b)| {
1483 if rotated && a.as_ref().is_some_and(|t| t.component == id)
1484 || rotated && b.as_ref().is_some_and(|t| t.component == id)
1485 {
1486 a.as_ref()
1487 .zip(b.as_ref())
1488 .and_then(|(a, b)| self.connection_path(a, b))
1489 } else {
1490 None
1491 }
1492 })
1493 .collect();
1494 let positions: Vec<_> = bindings
1495 .iter()
1496 .map(|(a, b)| {
1497 (
1498 a.as_ref().and_then(|t| self.terminal_position(t)),
1499 b.as_ref().and_then(|t| self.terminal_position(t)),
1500 )
1501 })
1502 .collect();
1503 for (((w, (start, end)), (a, b)), route) in self
1504 .wires
1505 .iter_mut()
1506 .zip(bindings)
1507 .zip(positions)
1508 .zip(routes)
1509 {
1510 w.start = start;
1511 w.end = end;
1512 w.follow(a.unwrap_or(w.a), b.unwrap_or(w.b));
1513 if let Some(route) = route {
1514 w.set_points(route);
1515 }
1516 }
1517 let flag_positions: Vec<_> = self
1518 .labels
1519 .iter()
1520 .map(|l| l.terminal.as_ref().and_then(|t| self.terminal_position(t)))
1521 .collect();
1522 let leads_after: Vec<_> = self
1523 .labels
1524 .iter()
1525 .map(|l| l.terminal.as_ref().filter(|t| t.component == id).and_then(|t| self.lead(t)))
1526 .collect();
1527 for (((label, at), before), after) in self
1528 .labels
1529 .iter_mut()
1530 .zip(flag_positions)
1531 .zip(leads_before)
1532 .zip(leads_after)
1533 {
1534 if let Some(at) = at {
1535 label.at = at;
1536 }
1537 if let (Some(before), Some(after)) = (before, after)
1541 && let Some(turn) = (0..4u8).find(|&k| before.rotate(k) == after)
1542 {
1543 label.rotation = (label.rotation + turn) % 4;
1544 }
1545 }
1546 }
1547 fn lead(&self, terminal: &Terminal) -> Option<Point> {
1551 let c = self.components.iter().find(|c| c.id == terminal.component)?;
1552 let pin = c.symbol.pins.iter().find(|p| p.number == terminal.pin)?;
1553 let (at, end) = (c.pin_at(pin), c.pin_end(pin));
1554 let step = Point::new((end.x - at.x).signum(), (end.y - at.y).signum());
1555 (step != Point::default()).then_some(step)
1556 }
1557 pub fn open_spot(&self, symbol: &Symbol) -> Point {
1570 const ACROSS: i32 = 10160;
1571 const DOWN: i32 = 5080;
1572 let (lo, hi) = symbol_extent(symbol, 0);
1573 let cell = |span: i32, gap: i32| (span.max(0) + gap + 1269) / 1270 * 1270;
1574 let (w, h) = (cell(hi.x - lo.x, ACROSS), cell(hi.y - lo.y, DOWN));
1575 let taken: Vec<(Point, Point)> = self
1576 .components
1577 .iter()
1578 .flat_map(Component::sheet_boxes)
1579 .map(|(_, a, b)| (a, b))
1580 .collect();
1581 let (x, y) = (ACROSS / 2, DOWN / 2);
1582 for row in 0..256 {
1583 for col in 0..8 {
1584 let at = Point::new(col * w, row * h);
1585 let (a, b) = (lo.offset(at), hi.offset(at));
1586 let clear = taken.iter().all(|(c, d)| {
1587 a.x - x > d.x || b.x + x < c.x || a.y - y > d.y || b.y + y < c.y
1588 });
1589 if clear {
1590 return at;
1591 }
1592 }
1593 }
1594 Point::default()
1595 }
1596 pub fn covers_another(&self, id: Uuid) -> bool {
1601 let spans = |c: &Component| -> Vec<(Point, Point)> {
1602 c.sheet_boxes()
1603 .into_iter()
1604 .map(|(_, a, b)| (a.offset(Point::new(-635, -635)), b.offset(Point::new(635, 635))))
1605 .collect()
1606 };
1607 let Some(mine) = self.components.iter().find(|c| c.id == id).map(spans) else {
1608 return false;
1609 };
1610 self.components
1611 .iter()
1612 .filter(|c| c.id != id)
1613 .flat_map(spans)
1614 .any(|(c, d)| mine.iter().any(|(a, b)| a.x < d.x && c.x < b.x && a.y < d.y && c.y < b.y))
1615 }
1616 pub fn delete_component(&mut self, id: Uuid) {
1617 self.components.retain(|c| c.id != id);
1618 self.board.placements.retain(|p| p.component != id);
1619 self.labels
1620 .retain(|l| !l.terminal.as_ref().is_some_and(|t| t.component == id));
1621 self.no_connects.retain(|t| t.component != id);
1622 self.power_flags.retain(|t| t.component != id);
1623 if self.kind == DocumentKind::Wiring {
1624 let attached = |t: &Option<Terminal>| t.as_ref().is_some_and(|t| t.component == id);
1626 self.wires
1627 .retain(|w| !attached(&w.start) && !attached(&w.end));
1628 }
1629 for w in &mut self.wires {
1630 if w.start.as_ref().is_some_and(|t| t.component == id) {
1631 w.start = None;
1632 }
1633 if w.end.as_ref().is_some_and(|t| t.component == id) {
1634 w.end = None;
1635 }
1636 }
1637 }
1638 pub fn from_json(text: &str) -> Result<Self, String> {
1639 Self::migrated(serde_json::from_str(text).map_err(|e| e.to_string())?)
1640 }
1641 pub fn to_json(&self) -> Result<String, String> {
1642 self.validate()?;
1643 serde_json::to_string_pretty(self).map_err(|e| e.to_string())
1644 }
1645 pub fn from_value(value: serde_json::Value) -> Result<Self, String> {
1648 Self::migrated(serde_json::from_value(value).map_err(|e| e.to_string())?)
1649 }
1650 pub fn to_value(&self) -> Result<serde_json::Value, String> {
1653 self.validate()?;
1654 serde_json::to_value(self).map_err(|e| e.to_string())
1655 }
1656 fn migrated(mut doc: Self) -> Result<Self, String> {
1657 if (1..DOCUMENT_VERSION).contains(&doc.version) {
1658 doc.version = DOCUMENT_VERSION;
1659 }
1660 doc.validate()?;
1661 Ok(doc)
1662 }
1663 pub fn validate(&self) -> Result<(), String> {
1664 let version = match self.kind {
1665 DocumentKind::Schematic => DOCUMENT_VERSION,
1666 DocumentKind::Wiring => WIRING_DOCUMENT_VERSION,
1667 };
1668 if self.version != version {
1669 return Err(format!("Unsupported document version {}", self.version));
1670 }
1671 let mut ids = BTreeSet::new();
1672 let mut refs = BTreeSet::new();
1673 for id in self
1674 .components
1675 .iter()
1676 .map(|c| c.id)
1677 .chain(self.wires.iter().map(|w| w.id))
1678 .chain(self.labels.iter().map(|l| l.id))
1679 .chain(self.board.tracks.iter().map(|t| t.id))
1680 .chain(self.board.vias.iter().map(|v| v.id))
1681 {
1682 if !ids.insert(id) {
1683 return Err("Duplicate object ID".into());
1684 }
1685 }
1686 let valid = |p: Point| p.x.abs_diff(0) <= 100_000_000 && p.y.abs_diff(0) <= 100_000_000;
1687 for c in &self.components {
1688 if c.reference.trim().is_empty() || !refs.insert(&c.reference) {
1689 return Err("Component references must be nonempty and unique".into());
1690 }
1691 if !valid(c.at) || c.rotation > 3 {
1692 return Err("Invalid component placement".into());
1693 }
1694 let mut gates = BTreeSet::new();
1695 for g in &c.gates {
1696 if g.gate == 0 || !gates.insert(g.gate) || !valid(g.at) || !valid(g.pivot) || g.rotation > 3 {
1697 return Err("Invalid gate placement".into());
1698 }
1699 }
1700 let mut pins = BTreeSet::new();
1701 for pin in &c.symbol.pins {
1702 if pin.number.is_empty()
1703 || !pins.insert(&pin.number)
1704 || !valid(pin.at)
1705 || !valid(pin.end)
1706 {
1707 return Err("Invalid or duplicate symbol pin".into());
1708 }
1709 }
1710 if let Some(part) = &c.part
1711 && (part.key.trim().is_empty() || part.signature.trim().is_empty())
1712 {
1713 return Err("A part needs a key and a signature".into());
1714 }
1715 if let Some(pads) = &c.pads {
1716 pads.validate_placeable()?;
1717 }
1718 for g in &c.symbol.graphics {
1719 match g {
1720 Graphic::Path(p) if p.iter().any(|p| !valid(*p)) => {
1721 return Err("Invalid graphic coordinates".into());
1722 }
1723 Graphic::Circle { center, radius }
1724 if !valid(*center) || !(0..=100_000_000).contains(radius) =>
1725 {
1726 return Err("Invalid circle".into());
1727 }
1728 Graphic::Text { at, size, .. }
1729 if !valid(*at) || !(1..=100_000_000).contains(size) =>
1730 {
1731 return Err("Invalid symbol text".into());
1732 }
1733 _ => {}
1734 }
1735 }
1736 }
1737 for w in &self.wires {
1738 let points = w.points();
1739 if points.iter().any(|p| !valid(*p))
1740 || points
1741 .windows(2)
1742 .any(|p| p[0] == p[1] || (p[0].x != p[1].x && p[0].y != p[1].y))
1743 {
1744 return Err("Wire paths must contain nonzero orthogonal segments".into());
1745 }
1746 for (t, p) in [(&w.start, w.a), (&w.end, w.b)] {
1747 if let Some(t) = t
1748 && self.terminal_position(t) != Some(p)
1749 {
1750 return Err("Wire terminal attachment is missing or out of date".into());
1751 }
1752 }
1753 }
1754 for label in &self.labels {
1755 if let Some(t) = &label.terminal
1756 && self.terminal_position(t) != Some(label.at)
1757 {
1758 return Err("Net flag terminal attachment is missing or out of date".into());
1759 }
1760 }
1761 if self.junctions.iter().any(|p| !valid(*p))
1762 || self
1763 .labels
1764 .iter()
1765 .any(|l| l.name.trim().is_empty() || l.rotation > 3 || !valid(l.at))
1766 {
1767 return Err("Invalid junction or label".into());
1768 }
1769 if self.kind == DocumentKind::Wiring {
1770 self.validate_wiring()?;
1771 }
1772 self.board
1773 .validate(&self.components.iter().map(|c| c.id).collect())?;
1774 Ok(())
1775 }
1776 fn validate_wiring(&self) -> Result<(), String> {
1779 if !self.junctions.is_empty() || !self.labels.is_empty() {
1780 return Err("A wiring diagram has no junctions or net labels".into());
1781 }
1782 let mut ids = BTreeSet::new();
1783 let mut pins = BTreeSet::new();
1784 for w in &self.wires {
1785 if w.connection_id.trim().is_empty() || !ids.insert(&w.connection_id) {
1786 return Err("Connection IDs must be nonempty and unique".into());
1787 }
1788 let (Some(start), Some(end)) = (&w.start, &w.end) else {
1789 return Err(format!("Connection {} must join two pins", w.connection_id));
1790 };
1791 for t in [start, end] {
1792 if !pins.insert((t.component, &t.pin)) {
1793 return Err(format!(
1794 "{} has more than one connection; a wiring diagram pin takes one",
1795 self.terminal_name(t)
1796 ));
1797 }
1798 }
1799 }
1800 Ok(())
1801 }
1802 pub fn netlist(&self) -> Netlist {
1805 let mut points = BTreeSet::new();
1806 for w in &self.wires {
1807 points.extend([w.a, w.b]);
1808 }
1809 points.extend(self.junctions.iter().copied());
1810 points.extend(self.labels.iter().map(|l| l.at));
1811 for c in &self.components {
1812 points.extend(c.symbol.pins.iter().map(|p| c.pin_at(p)));
1813 }
1814 let points: Vec<_> = points.into_iter().collect();
1815 let index: BTreeMap<_, _> = points.iter().enumerate().map(|(i, p)| (*p, i)).collect();
1816 let mut groups: Vec<usize> = (0..points.len()).collect();
1817 fn root(g: &[usize], mut i: usize) -> usize {
1818 while g[i] != i {
1819 i = g[i];
1820 }
1821 i
1822 }
1823 fn join(g: &mut [usize], a: usize, b: usize) {
1824 let a = root(g, a);
1825 let b = root(g, b);
1826 g[b] = a;
1827 }
1828 for w in &self.wires {
1829 let a = index[&w.a];
1830 let path = w.points();
1831 for (i, p) in points.iter().enumerate() {
1832 if path.windows(2).any(|s| on_segment(*p, s[0], s[1])) {
1833 join(&mut groups, a, i);
1834 }
1835 }
1836 }
1837 let mut names = BTreeMap::new();
1838 for l in &self.labels {
1839 let i = index[&l.at];
1840 if let Some(&other) = names.get(&l.name) {
1841 join(&mut groups, i, other);
1842 } else {
1843 names.insert(l.name.clone(), i);
1844 }
1845 }
1846 let mut nets: BTreeMap<usize, Net> = BTreeMap::new();
1847 for (i, p) in points.iter().enumerate() {
1848 nets.entry(root(&groups, i)).or_default().points.push(*p);
1849 }
1850 for l in &self.labels {
1851 nets.get_mut(&root(&groups, index[&l.at]))
1852 .unwrap()
1853 .labels
1854 .insert(l.name.clone());
1855 }
1856 for c in &self.components {
1857 for p in &c.symbol.pins {
1858 nets.get_mut(&root(&groups, index[&c.pin_at(p)]))
1859 .unwrap()
1860 .pins
1861 .push(NetPin {
1862 component_id: c.id,
1863 reference: c.reference.clone(),
1864 number: p.number.clone(),
1865 electrical_type: p.electrical_type.clone(),
1866 });
1867 }
1868 }
1869 let mut nets: Vec<_> = nets.into_values().collect();
1870 nets.sort_by_key(|n| n.points[0]);
1871 let mut diagnostics = vec![];
1872 for (i, n) in nets.iter_mut().enumerate() {
1873 n.name = n
1874 .labels
1875 .iter()
1876 .next()
1877 .cloned()
1878 .unwrap_or_else(|| format!("N${}", i + 1));
1879 if n.labels.len() > 1 {
1880 diagnostics.push(format!(
1881 "{}: conflicting labels {}",
1882 n.name,
1883 n.labels.iter().cloned().collect::<Vec<_>>().join(", ")
1884 ));
1885 }
1886 if n.pins.len() == 1 {
1887 diagnostics.push(format!(
1888 "{}.{} has no other connected pin",
1889 n.pins[0].reference, n.pins[0].number
1890 ));
1891 }
1892 if n.pins
1893 .iter()
1894 .filter(|p| p.electrical_type == "output")
1895 .count()
1896 > 1
1897 {
1898 diagnostics.push(format!("{}: multiple output pins", n.name));
1899 }
1900 }
1901 Netlist {
1902 version: 1,
1903 nets,
1904 diagnostics,
1905 }
1906 }
1907}
1908fn id_order(id: &str) -> (&str, u64, &str) {
1910 let prefix = id.trim_end_matches(|c: char| c.is_ascii_digit());
1911 (prefix, id[prefix.len()..].parse().unwrap_or(0), id)
1912}
1913fn symbol_extent(symbol: &Symbol, rotation: u8) -> (Point, Point) {
1917 let mut points = vec![Point::default()];
1918 for pin in &symbol.pins {
1919 points.extend([pin.at, pin.end]);
1920 }
1921 for g in &symbol.graphics {
1922 match g {
1923 Graphic::Path(path) => points.extend(path.iter().copied()),
1924 Graphic::Circle { center, radius } => points.extend([
1925 Point::new(center.x - radius, center.y - radius),
1926 Point::new(center.x + radius, center.y + radius),
1927 ]),
1928 Graphic::Text { at, .. } => points.push(*at),
1929 }
1930 }
1931 let turned: Vec<Point> = points.into_iter().map(|p| p.rotate(rotation)).collect();
1932 let lo = Point::new(
1933 turned.iter().map(|p| p.x).min().unwrap_or(0),
1934 turned.iter().map(|p| p.y).min().unwrap_or(0),
1935 );
1936 let hi = Point::new(
1937 turned.iter().map(|p| p.x).max().unwrap_or(0),
1938 turned.iter().map(|p| p.y).max().unwrap_or(0),
1939 );
1940 (lo, hi)
1941}
1942fn csv_field(text: &str) -> String {
1943 if text.contains([',', '"', '\n', '\r']) {
1944 format!("\"{}\"", text.replace('"', "\"\""))
1945 } else {
1946 text.into()
1947 }
1948}
1949pub fn on_segment(p: Point, a: Point, b: Point) -> bool {
1950 (a.x == b.x && p.x == a.x && p.y >= a.y.min(b.y) && p.y <= a.y.max(b.y))
1951 || (a.y == b.y && p.y == a.y && p.x >= a.x.min(b.x) && p.x <= a.x.max(b.x))
1952}
1953#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1954pub struct Net {
1955 pub name: String,
1956 pub labels: BTreeSet<String>,
1957 pub pins: Vec<NetPin>,
1958 pub points: Vec<Point>,
1959}
1960#[derive(Clone, Debug, Serialize, Deserialize)]
1961pub struct NetPin {
1962 pub component_id: Uuid,
1963 pub reference: String,
1964 pub number: String,
1965 pub electrical_type: String,
1966}
1967#[derive(Clone, Debug, Serialize, Deserialize)]
1968pub struct Netlist {
1969 pub version: u32,
1970 pub nets: Vec<Net>,
1971 pub diagnostics: Vec<String>,
1972}
1973
1974pub struct History<T = Document> {
1977 undo: Vec<T>,
1978 redo: Vec<T>,
1979}
1980impl<T> Default for History<T> {
1981 fn default() -> Self {
1982 Self { undo: Vec::new(), redo: Vec::new() }
1983 }
1984}
1985impl<T: PartialEq> History<T> {
1986 pub fn record(&mut self, before: T, after: &T) {
1987 if &before != after {
1988 self.undo.push(before);
1989 if self.undo.len() > 100 {
1990 self.undo.remove(0);
1991 }
1992 self.redo.clear();
1993 }
1994 }
1995 pub fn undo(&mut self, doc: &mut T) {
1996 if let Some(previous) = self.undo.pop() {
1997 self.redo.push(std::mem::replace(doc, previous));
1998 }
1999 }
2000 pub fn redo(&mut self, doc: &mut T) {
2001 if let Some(next) = self.redo.pop() {
2002 self.undo.push(std::mem::replace(doc, next));
2003 }
2004 }
2005 pub fn can_undo(&self) -> bool {
2006 !self.undo.is_empty()
2007 }
2008 pub fn can_redo(&self) -> bool {
2009 !self.redo.is_empty()
2010 }
2011}