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