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