1use crate::hit_test::{NodeGeometry, SimpleNodeGeometry};
2use crate::state::GeometryCache;
3use slint::{Color, Model, VecModel};
4use std::fmt;
5
6pub trait LinkModel {
35 fn id(&self) -> i32;
37 fn start_pin_id(&self) -> i32;
39 fn end_pin_id(&self) -> i32;
41 fn color(&self) -> Color {
44 Color::from_rgb_u8(255, 255, 255)
45 }
46 fn line_width(&self) -> f32 {
48 2.0
49 }
50 fn status(&self) -> i32 {
54 -1
55 }
56}
57
58impl LinkModel for crate::nodeeditor::LinkData {
66 fn id(&self) -> i32 {
67 self.id
68 }
69 fn start_pin_id(&self) -> i32 {
70 self.start_pin_id
71 }
72 fn end_pin_id(&self) -> i32 {
73 self.end_pin_id
74 }
75 fn color(&self) -> Color {
76 self.color
77 }
78 fn line_width(&self) -> f32 {
79 self.line_width
80 }
81 fn status(&self) -> i32 {
82 self.status
83 }
84}
85
86#[derive(Clone, Debug)]
91pub struct SimpleLink {
92 pub id: i32,
93 pub start_pin_id: i32,
94 pub end_pin_id: i32,
95 pub color: Color,
96 pub line_width: f32,
97 pub status: i32,
98}
99
100impl SimpleLink {
101 pub fn new(id: i32, start_pin_id: i32, end_pin_id: i32, color: Color) -> Self {
103 Self {
104 id,
105 start_pin_id,
106 end_pin_id,
107 color,
108 line_width: 2.0,
109 status: -1,
110 }
111 }
112
113 pub fn with_line_width(
115 id: i32,
116 start_pin_id: i32,
117 end_pin_id: i32,
118 color: Color,
119 line_width: f32,
120 ) -> Self {
121 Self {
122 id,
123 start_pin_id,
124 end_pin_id,
125 color,
126 line_width,
127 status: -1,
128 }
129 }
130}
131
132impl LinkModel for SimpleLink {
133 fn id(&self) -> i32 {
134 self.id
135 }
136 fn start_pin_id(&self) -> i32 {
137 self.start_pin_id
138 }
139 fn end_pin_id(&self) -> i32 {
140 self.end_pin_id
141 }
142 fn color(&self) -> Color {
143 self.color
144 }
145 fn line_width(&self) -> f32 {
146 self.line_width
147 }
148 fn status(&self) -> i32 {
149 self.status
150 }
151}
152
153pub trait MovableNode: Clone + 'static {
162 fn id(&self) -> i32;
163 fn x(&self) -> f32;
164 fn y(&self) -> f32;
165 fn selected(&self) -> bool;
166 fn set_x(&mut self, x: f32);
167 fn set_y(&mut self, y: f32);
168}
169
170pub struct GraphLogic;
172
173impl GraphLogic {
174 pub fn find_links_connected_to_node<I, L, N>(
181 node_id: i32,
182 links: I,
183 cache: &GeometryCache<N>,
184 ) -> Vec<i32>
185 where
186 I: Iterator<Item = L>,
187 L: LinkModel,
188 N: NodeGeometry + Copy,
189 {
190 links
191 .filter(|link| {
192 let start_node = cache
193 .pin_positions
194 .get(&link.start_pin_id())
195 .map(|p| p.node_id);
196 let end_node = cache
197 .pin_positions
198 .get(&link.end_pin_id())
199 .map(|p| p.node_id);
200
201 start_node == Some(node_id) || end_node == Some(node_id)
202 })
203 .map(|l| l.id())
204 .collect()
205 }
206
207 pub fn normalize_link_direction<N>(
212 pin_a: i32,
213 pin_b: i32,
214 cache: &GeometryCache<N>,
215 output_type: i32,
216 ) -> Option<(i32, i32)>
217 where
218 N: NodeGeometry + Copy,
219 {
220 let pos_a = cache.pin_positions.get(&pin_a)?;
221 cache.pin_positions.get(&pin_b)?;
222 if pos_a.pin_type == output_type {
225 Some((pin_a, pin_b))
226 } else {
227 Some((pin_b, pin_a))
228 }
229 }
230
231 pub fn commit_drag<T>(model: &VecModel<T>, dragged_id: i32, delta_x: f32, delta_y: f32)
245 where
246 T: MovableNode,
247 {
248 for i in 0..model.row_count() {
249 if let Some(mut node) = model.row_data(i) {
250 if node.selected() || node.id() == dragged_id {
251 node.set_x(node.x() + delta_x);
252 node.set_y(node.y() + delta_y);
253 model.set_row_data(i, node);
254 }
255 }
256 }
257 }
258
259 pub fn duplicate_link_exists<I, L>(start_pin: i32, end_pin: i32, links: I) -> bool
268 where
269 I: IntoIterator<Item = L>,
270 L: LinkModel,
271 {
272 links
273 .into_iter()
274 .any(|link| link.start_pin_id() == start_pin && link.end_pin_id() == end_pin)
275 }
276
277 pub fn find_node_by_id<T, F>(model: &VecModel<T>, id: i32, predicate: F) -> Option<(usize, T)>
302 where
303 T: Clone + 'static,
304 F: Fn(&T) -> i32,
305 {
306 for i in 0..model.row_count() {
307 if let Some(node) = model.row_data(i) {
308 if predicate(&node) == id {
309 return Some((i, node));
310 }
311 }
312 }
313 None
314 }
315}
316
317#[derive(Debug, Clone, PartialEq, Eq)]
323pub enum ValidationResult {
324 Valid,
326 Invalid(ValidationError),
328}
329
330impl ValidationResult {
331 pub fn is_valid(&self) -> bool {
333 matches!(self, ValidationResult::Valid)
334 }
335
336 pub fn and(self, other: ValidationResult) -> ValidationResult {
338 match self {
339 ValidationResult::Valid => other,
340 invalid => invalid,
341 }
342 }
343}
344
345#[derive(Debug, Clone, PartialEq, Eq)]
347pub enum ValidationError {
348 PinNotFound(i32),
350 SamePin,
352 SameNode,
354 IncompatibleDirection,
356 DuplicateLink,
358 MaxConnectionsReached { pin_id: i32, max: usize },
360 TypeMismatch { expected: i32, found: i32 },
362 Custom(String),
364}
365
366#[derive(Debug, Clone, Copy, PartialEq, Eq)]
373pub struct NormalizedLink {
374 pub output_pin_id: i32,
376 pub input_pin_id: i32,
378}
379
380impl fmt::Display for ValidationError {
381 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382 match self {
383 Self::PinNotFound(id) => write!(f, "Pin {} not found", id),
384 Self::SamePin => write!(f, "Cannot link pin to itself"),
385 Self::SameNode => write!(f, "Cannot link pins on same node"),
386 Self::IncompatibleDirection => write!(f, "Must connect input to output"),
387 Self::DuplicateLink => write!(f, "Link already exists"),
388 Self::MaxConnectionsReached { pin_id, max } => {
389 write!(f, "Pin {} has reached max {} connections", pin_id, max)
390 }
391 Self::TypeMismatch { expected, found } => {
392 write!(f, "Type mismatch: expected {}, found {}", expected, found)
393 }
394 Self::Custom(msg) => write!(f, "{}", msg),
395 }
396 }
397}
398
399impl std::error::Error for ValidationError {}
400
401pub trait LinkValidator<N = SimpleNodeGeometry, L = ()> {
437 fn validate(
449 &self,
450 start_pin: i32,
451 end_pin: i32,
452 cache: &GeometryCache<N>,
453 links: &[L],
454 ) -> ValidationResult;
455}
456
457#[derive(Clone, Copy, Debug)]
484pub struct BasicLinkValidator {
485 output_type: i32,
486}
487
488impl BasicLinkValidator {
489 pub fn new(output_type: i32) -> Self {
495 Self { output_type }
496 }
497}
498
499impl<N, L> LinkValidator<N, L> for BasicLinkValidator
500where
501 N: NodeGeometry + Copy,
502{
503 fn validate(
504 &self,
505 start_pin: i32,
506 end_pin: i32,
507 cache: &GeometryCache<N>,
508 _links: &[L],
509 ) -> ValidationResult {
510 if start_pin == end_pin {
511 return ValidationResult::Invalid(ValidationError::SamePin);
512 }
513
514 let start_pos = match cache.pin_positions.get(&start_pin) {
515 Some(p) => p,
516 None => return ValidationResult::Invalid(ValidationError::PinNotFound(start_pin)),
517 };
518 let end_pos = match cache.pin_positions.get(&end_pin) {
519 Some(p) => p,
520 None => return ValidationResult::Invalid(ValidationError::PinNotFound(end_pin)),
521 };
522
523 if start_pos.node_id == end_pos.node_id {
524 return ValidationResult::Invalid(ValidationError::SameNode);
525 }
526
527 let start_is_output = start_pos.pin_type == self.output_type;
528 let end_is_output = end_pos.pin_type == self.output_type;
529
530 if start_is_output == end_is_output {
531 return ValidationResult::Invalid(ValidationError::IncompatibleDirection);
532 }
533
534 ValidationResult::Valid
535 }
536}
537
538pub fn validate_and_normalize_link<N, L, V>(
589 pin_a: i32,
590 pin_b: i32,
591 cache: &GeometryCache<N>,
592 links: &[L],
593 output_type: i32,
594 topology_validator: &V,
595) -> Result<NormalizedLink, ValidationError>
596where
597 N: NodeGeometry + Copy,
598 V: LinkValidator<N, L>,
599{
600 match BasicLinkValidator::new(output_type).validate(pin_a, pin_b, cache, links) {
601 ValidationResult::Valid => {}
602 ValidationResult::Invalid(error) => return Err(error),
603 }
604
605 let Some((output_pin_id, input_pin_id)) =
606 GraphLogic::normalize_link_direction(pin_a, pin_b, cache, output_type)
607 else {
608 return Err(ValidationError::PinNotFound(pin_a));
609 };
610
611 match topology_validator.validate(output_pin_id, input_pin_id, cache, links) {
612 ValidationResult::Valid => Ok(NormalizedLink {
613 output_pin_id,
614 input_pin_id,
615 }),
616 ValidationResult::Invalid(error) => Err(error),
617 }
618}
619
620#[derive(Clone, Debug, Default)]
641pub struct NoDuplicatesValidator;
642
643impl<N, L> LinkValidator<N, L> for NoDuplicatesValidator
644where
645 L: LinkModel + Clone,
646{
647 fn validate(
648 &self,
649 start_pin: i32,
650 end_pin: i32,
651 _cache: &GeometryCache<N>,
652 links: &[L],
653 ) -> ValidationResult {
654 if GraphLogic::duplicate_link_exists(start_pin, end_pin, links.iter().cloned()) {
656 ValidationResult::Invalid(ValidationError::DuplicateLink)
657 } else {
658 ValidationResult::Valid
659 }
660 }
661}
662
663pub struct CompositeValidator<N = SimpleNodeGeometry, L = ()> {
693 validators: Vec<Box<dyn LinkValidator<N, L>>>,
694}
695
696impl<N, L> Default for CompositeValidator<N, L> {
697 fn default() -> Self {
698 Self::new()
699 }
700}
701
702impl<N, L> CompositeValidator<N, L> {
703 pub fn new() -> Self {
705 Self {
706 validators: Vec::new(),
707 }
708 }
709
710 pub fn with<V: LinkValidator<N, L> + 'static>(mut self, validator: V) -> Self {
715 self.validators.push(Box::new(validator));
716 self
717 }
718}
719
720impl<N, L> LinkValidator<N, L> for CompositeValidator<N, L> {
721 fn validate(
722 &self,
723 start_pin: i32,
724 end_pin: i32,
725 cache: &GeometryCache<N>,
726 links: &[L],
727 ) -> ValidationResult {
728 for v in &self.validators {
729 let result = v.validate(start_pin, end_pin, cache, links);
730 if !result.is_valid() {
731 return result;
732 }
733 }
734 ValidationResult::Valid
735 }
736}
737
738#[cfg(test)]
743mod tests {
744 use super::*;
745 use crate::hit_test::SimpleNodeGeometry;
746 use crate::state::StoredPin;
747
748 fn setup_cache() -> GeometryCache<SimpleNodeGeometry> {
750 let mut cache = GeometryCache::new();
751
752 cache.node_rects.insert(
754 1,
755 SimpleNodeGeometry {
756 id: 1,
757 x: 0.0,
758 y: 0.0,
759 width: 100.0,
760 height: 50.0,
761 },
762 );
763 cache.node_rects.insert(
764 2,
765 SimpleNodeGeometry {
766 id: 2,
767 x: 200.0,
768 y: 0.0,
769 width: 100.0,
770 height: 50.0,
771 },
772 );
773
774 cache.pin_positions.insert(
776 1001,
777 StoredPin {
778 node_id: 1,
779 pin_type: 2,
780 rel_x: 100.0,
781 rel_y: 25.0,
782 },
783 );
784 cache.pin_positions.insert(
786 2001,
787 StoredPin {
788 node_id: 2,
789 pin_type: 1,
790 rel_x: 0.0,
791 rel_y: 25.0,
792 },
793 );
794 cache.pin_positions.insert(
796 2002,
797 StoredPin {
798 node_id: 2,
799 pin_type: 1,
800 rel_x: 0.0,
801 rel_y: 40.0,
802 },
803 );
804
805 cache
806 }
807
808 #[derive(Clone, Debug)]
810 struct TestLink {
811 id: i32,
812 start: i32,
813 end: i32,
814 }
815
816 impl LinkModel for TestLink {
817 fn id(&self) -> i32 {
818 self.id
819 }
820 fn start_pin_id(&self) -> i32 {
821 self.start
822 }
823 fn end_pin_id(&self) -> i32 {
824 self.end
825 }
826 }
827
828 #[test]
829 fn test_basic_validator_accepts_valid_link() {
830 let cache = setup_cache();
831 let validator = BasicLinkValidator::new(2); let links: Vec<TestLink> = vec![];
833
834 let result = validator.validate(1001, 2001, &cache, &links);
835 assert!(result.is_valid());
836 }
837
838 #[test]
839 fn removed_node_pins_are_no_longer_valid_endpoints() {
840 let mut cache = setup_cache();
841 let validator = BasicLinkValidator::new(2);
842 let links: Vec<TestLink> = vec![];
843
844 cache.remove_node(1);
845
846 assert_eq!(
847 validator.validate(1001, 2001, &cache, &links),
848 ValidationResult::Invalid(ValidationError::PinNotFound(1001))
849 );
850 }
851
852 #[test]
853 fn test_basic_validator_rejects_same_pin() {
854 let cache = setup_cache();
855 let validator = BasicLinkValidator::new(2);
856 let links: Vec<TestLink> = vec![];
857
858 let result = validator.validate(1001, 1001, &cache, &links);
859 assert_eq!(result, ValidationResult::Invalid(ValidationError::SamePin));
860 }
861
862 #[test]
863 fn test_basic_validator_rejects_same_node() {
864 let mut cache = setup_cache();
865 cache.pin_positions.insert(
867 1002,
868 StoredPin {
869 node_id: 1,
870 pin_type: 1,
871 rel_x: 0.0,
872 rel_y: 25.0,
873 },
874 );
875
876 let validator = BasicLinkValidator::new(2);
877 let links: Vec<TestLink> = vec![];
878
879 let result = validator.validate(1001, 1002, &cache, &links);
880 assert_eq!(result, ValidationResult::Invalid(ValidationError::SameNode));
881 }
882
883 #[test]
884 fn test_basic_validator_rejects_same_direction() {
885 let mut cache = setup_cache();
886 cache.pin_positions.insert(
888 2003,
889 StoredPin {
890 node_id: 2,
891 pin_type: 2,
892 rel_x: 100.0,
893 rel_y: 25.0,
894 },
895 );
896
897 let validator = BasicLinkValidator::new(2);
898 let links: Vec<TestLink> = vec![];
899
900 let result = validator.validate(1001, 2003, &cache, &links);
902 assert_eq!(
903 result,
904 ValidationResult::Invalid(ValidationError::IncompatibleDirection)
905 );
906 }
907
908 #[test]
909 fn test_basic_validator_rejects_missing_pin() {
910 let cache = setup_cache();
911 let validator = BasicLinkValidator::new(2);
912 let links: Vec<TestLink> = vec![];
913
914 let result = validator.validate(1001, 9999, &cache, &links);
915 assert_eq!(
916 result,
917 ValidationResult::Invalid(ValidationError::PinNotFound(9999))
918 );
919 }
920
921 #[test]
922 fn test_no_duplicates_validator_accepts_new_link() {
923 let cache = setup_cache();
924 let validator = NoDuplicatesValidator;
925 let links = vec![TestLink {
926 id: 1,
927 start: 1001,
928 end: 2002,
929 }];
930
931 let result = validator.validate(1001, 2001, &cache, &links);
933 assert!(result.is_valid());
934 }
935
936 #[test]
937 fn test_no_duplicates_validator_rejects_duplicate() {
938 let cache = setup_cache();
939 let validator = NoDuplicatesValidator;
940 let links = vec![TestLink {
941 id: 1,
942 start: 1001,
943 end: 2001,
944 }];
945
946 let result = validator.validate(1001, 2001, &cache, &links);
948 assert_eq!(
949 result,
950 ValidationResult::Invalid(ValidationError::DuplicateLink)
951 );
952 }
953
954 #[test]
955 fn validation_returns_the_same_normalized_endpoints_for_both_gesture_directions() {
956 let cache = setup_cache();
957 let links: Vec<TestLink> = vec![];
958
959 let output_first =
960 validate_and_normalize_link(1001, 2001, &cache, &links, 2, &NoDuplicatesValidator);
961 let input_first =
962 validate_and_normalize_link(2001, 1001, &cache, &links, 2, &NoDuplicatesValidator);
963
964 let expected = Ok(NormalizedLink {
965 output_pin_id: 1001,
966 input_pin_id: 2001,
967 });
968 assert_eq!(output_first, expected);
969 assert_eq!(input_first, expected);
970 }
971
972 #[test]
973 fn reverse_gesture_is_rejected_after_normalization_when_link_exists() {
974 let cache = setup_cache();
975 let links = vec![TestLink {
976 id: 1,
977 start: 1001,
978 end: 2001,
979 }];
980
981 assert_eq!(
982 validate_and_normalize_link(2001, 1001, &cache, &links, 2, &NoDuplicatesValidator,),
983 Err(ValidationError::DuplicateLink),
984 );
985 }
986
987 #[test]
988 fn topology_rules_receive_normalized_endpoints() {
989 struct RequireExpectedOrder;
990
991 impl<N, L> LinkValidator<N, L> for RequireExpectedOrder {
992 fn validate(
993 &self,
994 start_pin: i32,
995 end_pin: i32,
996 _cache: &GeometryCache<N>,
997 _links: &[L],
998 ) -> ValidationResult {
999 if (start_pin, end_pin) == (1001, 2001) {
1000 ValidationResult::Valid
1001 } else {
1002 ValidationResult::Invalid(ValidationError::Custom(format!(
1003 "received ({start_pin}, {end_pin})"
1004 )))
1005 }
1006 }
1007 }
1008
1009 let cache = setup_cache();
1010 let links: Vec<TestLink> = vec![];
1011 assert!(
1012 validate_and_normalize_link(2001, 1001, &cache, &links, 2, &RequireExpectedOrder,)
1013 .is_ok()
1014 );
1015 }
1016
1017 #[test]
1018 fn test_composite_validator_passes_all() {
1019 let cache = setup_cache();
1020 let validator: CompositeValidator<_, TestLink> = CompositeValidator::new()
1021 .with(BasicLinkValidator::new(2))
1022 .with(NoDuplicatesValidator);
1023
1024 let links = vec![];
1025
1026 let result = validator.validate(1001, 2001, &cache, &links);
1027 assert!(result.is_valid());
1028 }
1029
1030 #[test]
1031 fn test_composite_validator_short_circuits_on_basic() {
1032 let cache = setup_cache();
1033 let validator: CompositeValidator<_, TestLink> = CompositeValidator::new()
1034 .with(BasicLinkValidator::new(2))
1035 .with(NoDuplicatesValidator);
1036
1037 let links = vec![];
1038
1039 let result = validator.validate(1001, 1001, &cache, &links);
1041 assert_eq!(result, ValidationResult::Invalid(ValidationError::SamePin));
1042 }
1043
1044 #[test]
1045 fn test_composite_validator_short_circuits_on_duplicates() {
1046 let cache = setup_cache();
1047 let validator: CompositeValidator<_, TestLink> = CompositeValidator::new()
1048 .with(BasicLinkValidator::new(2))
1049 .with(NoDuplicatesValidator);
1050
1051 let links = vec![TestLink {
1052 id: 1,
1053 start: 1001,
1054 end: 2001,
1055 }];
1056
1057 let result = validator.validate(1001, 2001, &cache, &links);
1059 assert_eq!(
1060 result,
1061 ValidationResult::Invalid(ValidationError::DuplicateLink)
1062 );
1063 }
1064
1065 #[test]
1066 fn test_validator_validate_directly() {
1067 let cache = setup_cache();
1068 let validator = BasicLinkValidator::new(2);
1069 let links: Vec<TestLink> = vec![];
1070
1071 let result = validator.validate(1001, 2001, &cache, &links);
1072 assert!(result.is_valid());
1073 }
1074
1075 #[test]
1076 fn test_validation_result_and_combinator() {
1077 let result1 = ValidationResult::Valid;
1078 let result2 = ValidationResult::Valid;
1079 assert!(result1.and(result2).is_valid());
1080
1081 let result1 = ValidationResult::Valid;
1082 let result2 = ValidationResult::Invalid(ValidationError::SamePin);
1083 assert_eq!(
1084 result1.and(result2),
1085 ValidationResult::Invalid(ValidationError::SamePin)
1086 );
1087
1088 let result1 = ValidationResult::Invalid(ValidationError::SameNode);
1089 let result2 = ValidationResult::Valid;
1090 assert_eq!(
1091 result1.and(result2),
1092 ValidationResult::Invalid(ValidationError::SameNode)
1093 );
1094
1095 let result1 = ValidationResult::Invalid(ValidationError::SameNode);
1097 let result2 = ValidationResult::Invalid(ValidationError::SamePin);
1098 assert_eq!(
1099 result1.and(result2),
1100 ValidationResult::Invalid(ValidationError::SameNode)
1101 );
1102 }
1103
1104 #[test]
1105 fn test_validation_error_display() {
1106 assert_eq!(
1107 format!("{}", ValidationError::PinNotFound(42)),
1108 "Pin 42 not found"
1109 );
1110 assert_eq!(
1111 format!("{}", ValidationError::SamePin),
1112 "Cannot link pin to itself"
1113 );
1114 assert_eq!(
1115 format!("{}", ValidationError::SameNode),
1116 "Cannot link pins on same node"
1117 );
1118 assert_eq!(
1119 format!("{}", ValidationError::IncompatibleDirection),
1120 "Must connect input to output"
1121 );
1122 assert_eq!(
1123 format!("{}", ValidationError::DuplicateLink),
1124 "Link already exists"
1125 );
1126 assert_eq!(
1127 format!(
1128 "{}",
1129 ValidationError::MaxConnectionsReached {
1130 pin_id: 123,
1131 max: 3
1132 }
1133 ),
1134 "Pin 123 has reached max 3 connections"
1135 );
1136 assert_eq!(
1137 format!(
1138 "{}",
1139 ValidationError::TypeMismatch {
1140 expected: 1,
1141 found: 2
1142 }
1143 ),
1144 "Type mismatch: expected 1, found 2"
1145 );
1146 assert_eq!(
1147 format!("{}", ValidationError::Custom("Test error".to_string())),
1148 "Test error"
1149 );
1150 }
1151
1152 #[test]
1154 fn test_custom_validator() {
1155 #[derive(Clone, Copy)]
1156 struct FanOutValidator {
1157 max_connections: usize,
1158 }
1159
1160 impl<N, L> LinkValidator<N, L> for FanOutValidator
1161 where
1162 L: LinkModel,
1163 {
1164 fn validate(
1165 &self,
1166 start_pin: i32,
1167 _end_pin: i32,
1168 _cache: &GeometryCache<N>,
1169 links: &[L],
1170 ) -> ValidationResult {
1171 let existing_count = links
1172 .iter()
1173 .filter(|link| link.start_pin_id() == start_pin)
1174 .count();
1175
1176 if existing_count >= self.max_connections {
1177 ValidationResult::Invalid(ValidationError::MaxConnectionsReached {
1178 pin_id: start_pin,
1179 max: self.max_connections,
1180 })
1181 } else {
1182 ValidationResult::Valid
1183 }
1184 }
1185 }
1186
1187 let cache = setup_cache();
1188 let validator = FanOutValidator { max_connections: 1 };
1189
1190 let existing_links = vec![TestLink {
1192 id: 1,
1193 start: 1001,
1194 end: 2001,
1195 }];
1196
1197 let result = validator.validate(1001, 2002, &cache, &existing_links);
1199 assert_eq!(
1200 result,
1201 ValidationResult::Invalid(ValidationError::MaxConnectionsReached {
1202 pin_id: 1001,
1203 max: 1,
1204 })
1205 );
1206
1207 let no_links: Vec<TestLink> = vec![];
1209 let result = validator.validate(1001, 2001, &cache, &no_links);
1210 assert!(result.is_valid());
1211 }
1212
1213 #[test]
1218 fn test_find_links_connected_to_node_by_start() {
1219 let cache = setup_cache();
1220 let links = vec![
1221 TestLink {
1222 id: 1,
1223 start: 1001,
1224 end: 2001,
1225 },
1226 TestLink {
1227 id: 2,
1228 start: 2001,
1229 end: 1001,
1230 },
1231 ];
1232
1233 let connected = GraphLogic::find_links_connected_to_node(1, links.into_iter(), &cache);
1235 assert!(connected.contains(&1));
1236 assert!(connected.contains(&2));
1237 }
1238
1239 #[test]
1240 fn test_find_links_connected_to_node_no_connections() {
1241 let cache = setup_cache();
1242 let links = vec![TestLink {
1243 id: 1,
1244 start: 1001,
1245 end: 2001,
1246 }];
1247
1248 let connected = GraphLogic::find_links_connected_to_node(999, links.into_iter(), &cache);
1250 assert!(connected.is_empty());
1251 }
1252
1253 #[test]
1254 fn test_find_links_connected_to_node_empty_links() {
1255 let cache = setup_cache();
1256 let links: Vec<TestLink> = vec![];
1257
1258 let connected = GraphLogic::find_links_connected_to_node(1, links.into_iter(), &cache);
1259 assert!(connected.is_empty());
1260 }
1261
1262 #[test]
1263 fn test_find_links_connected_to_node_multiple_pins() {
1264 let mut cache = setup_cache();
1265 cache.pin_positions.insert(
1267 1002,
1268 StoredPin {
1269 node_id: 1,
1270 pin_type: 1,
1271 rel_x: 0.0,
1272 rel_y: 40.0,
1273 },
1274 );
1275
1276 let links = vec![
1277 TestLink {
1278 id: 1,
1279 start: 1001,
1280 end: 2001,
1281 },
1282 TestLink {
1283 id: 2,
1284 start: 2001,
1285 end: 1002,
1286 },
1287 TestLink {
1288 id: 3,
1289 start: 2001,
1290 end: 2002,
1291 }, ];
1293
1294 let connected = GraphLogic::find_links_connected_to_node(1, links.into_iter(), &cache);
1295 assert!(connected.contains(&1));
1296 assert!(connected.contains(&2));
1297 assert!(!connected.contains(&3));
1298 }
1299
1300 #[test]
1305 fn test_normalize_link_direction_output_first() {
1306 let cache = setup_cache();
1307 let result = GraphLogic::normalize_link_direction(1001, 2001, &cache, 2);
1309 assert_eq!(result, Some((1001, 2001)));
1310 }
1311
1312 #[test]
1313 fn test_normalize_link_direction_input_first() {
1314 let cache = setup_cache();
1315 let result = GraphLogic::normalize_link_direction(2001, 1001, &cache, 2);
1317 assert_eq!(result, Some((1001, 2001)));
1318 }
1319
1320 #[test]
1321 fn test_normalize_link_direction_missing_pin() {
1322 let cache = setup_cache();
1323 let result = GraphLogic::normalize_link_direction(9999, 2001, &cache, 2);
1324 assert!(result.is_none());
1325 }
1326
1327 #[test]
1332 fn test_duplicate_link_exists_true() {
1333 let links = vec![TestLink {
1334 id: 1,
1335 start: 1001,
1336 end: 2001,
1337 }];
1338 assert!(GraphLogic::duplicate_link_exists(1001, 2001, links));
1339 }
1340
1341 #[test]
1342 fn test_duplicate_link_exists_false() {
1343 let links = vec![TestLink {
1344 id: 1,
1345 start: 1001,
1346 end: 2001,
1347 }];
1348 assert!(!GraphLogic::duplicate_link_exists(1001, 2002, links));
1349 }
1350
1351 #[test]
1352 fn test_duplicate_link_exists_empty() {
1353 let links: Vec<TestLink> = vec![];
1354 assert!(!GraphLogic::duplicate_link_exists(1001, 2001, links));
1355 }
1356
1357 #[test]
1358 fn test_duplicate_link_exists_direction_matters() {
1359 let links = vec![TestLink {
1360 id: 1,
1361 start: 1001,
1362 end: 2001,
1363 }];
1364 assert!(!GraphLogic::duplicate_link_exists(2001, 1001, links));
1366 }
1367
1368 #[test]
1373 fn test_find_node_by_id_found() {
1374 #[derive(Clone)]
1375 struct TestNode {
1376 id: i32,
1377 name: String,
1378 }
1379
1380 let model = std::rc::Rc::new(VecModel::from(vec![
1381 TestNode {
1382 id: 1,
1383 name: "Node 1".to_string(),
1384 },
1385 TestNode {
1386 id: 2,
1387 name: "Node 2".to_string(),
1388 },
1389 TestNode {
1390 id: 3,
1391 name: "Node 3".to_string(),
1392 },
1393 ]));
1394
1395 let result = GraphLogic::find_node_by_id(&model, 2, |n| n.id);
1396 assert!(result.is_some());
1397 let (index, node) = result.unwrap();
1398 assert_eq!(index, 1);
1399 assert_eq!(node.id, 2);
1400 assert_eq!(node.name, "Node 2");
1401 }
1402
1403 #[test]
1404 fn test_find_node_by_id_not_found() {
1405 #[derive(Clone)]
1406 struct TestNode {
1407 id: i32,
1408 }
1409
1410 let model = std::rc::Rc::new(VecModel::from(vec![TestNode { id: 1 }, TestNode { id: 2 }]));
1411
1412 let result = GraphLogic::find_node_by_id(&model, 999, |n| n.id);
1413 assert!(result.is_none());
1414 }
1415
1416 #[test]
1417 fn test_find_node_by_id_empty_model() {
1418 #[derive(Clone)]
1419 struct TestNode {
1420 id: i32,
1421 }
1422
1423 let model = std::rc::Rc::new(VecModel::<TestNode>::default());
1424
1425 let result = GraphLogic::find_node_by_id(&model, 1, |n| n.id);
1426 assert!(result.is_none());
1427 }
1428
1429 #[test]
1430 fn test_find_node_by_id_first_match() {
1431 #[derive(Clone)]
1432 struct TestNode {
1433 id: i32,
1434 value: i32,
1435 }
1436
1437 let model = std::rc::Rc::new(VecModel::from(vec![
1439 TestNode { id: 1, value: 100 },
1440 TestNode { id: 1, value: 200 },
1441 ]));
1442
1443 let result = GraphLogic::find_node_by_id(&model, 1, |n| n.id);
1444 assert!(result.is_some());
1445 let (index, node) = result.unwrap();
1446 assert_eq!(index, 0);
1447 assert_eq!(node.value, 100);
1448 }
1449
1450 #[derive(Clone)]
1455 struct TestMovableNode {
1456 id: i32,
1457 x: f32,
1458 y: f32,
1459 selected: bool,
1460 }
1461
1462 impl MovableNode for TestMovableNode {
1463 fn id(&self) -> i32 {
1464 self.id
1465 }
1466 fn x(&self) -> f32 {
1467 self.x
1468 }
1469 fn y(&self) -> f32 {
1470 self.y
1471 }
1472 fn selected(&self) -> bool {
1473 self.selected
1474 }
1475 fn set_x(&mut self, x: f32) {
1476 self.x = x;
1477 }
1478 fn set_y(&mut self, y: f32) {
1479 self.y = y;
1480 }
1481 }
1482
1483 fn movable_model(rows: &[(i32, f32, f32, bool)]) -> std::rc::Rc<VecModel<TestMovableNode>> {
1485 std::rc::Rc::new(VecModel::from(
1486 rows.iter()
1487 .map(|&(id, x, y, selected)| TestMovableNode { id, x, y, selected })
1488 .collect::<Vec<_>>(),
1489 ))
1490 }
1491
1492 fn positions(model: &VecModel<TestMovableNode>) -> Vec<(f32, f32)> {
1493 (0..model.row_count())
1494 .filter_map(|i| model.row_data(i))
1495 .map(|n| (n.x, n.y))
1496 .collect()
1497 }
1498
1499 #[test]
1500 fn commit_drag_moves_the_whole_selection() {
1501 let model = movable_model(&[
1502 (1, 0.0, 0.0, true),
1503 (2, 100.0, 100.0, false),
1504 (3, 200.0, 200.0, true),
1505 ]);
1506
1507 GraphLogic::commit_drag(&model, 1, 10.0, 20.0);
1508
1509 assert_eq!(
1511 positions(&model),
1512 vec![(10.0, 20.0), (100.0, 100.0), (210.0, 220.0)]
1513 );
1514 }
1515
1516 #[test]
1517 fn commit_drag_moves_the_dragged_node_even_when_nothing_is_selected() {
1518 let model = movable_model(&[(1, 50.0, 50.0, false), (2, 0.0, 0.0, false)]);
1520
1521 GraphLogic::commit_drag(&model, 1, 100.0, 100.0);
1522
1523 assert_eq!(positions(&model), vec![(150.0, 150.0), (0.0, 0.0)]);
1524 }
1525
1526 #[test]
1527 fn commit_drag_ignores_a_dragged_id_from_another_model() {
1528 let model = movable_model(&[(1, 0.0, 0.0, true), (2, 100.0, 100.0, false)]);
1531
1532 GraphLogic::commit_drag(&model, 99, 10.0, 10.0);
1533
1534 assert_eq!(positions(&model), vec![(10.0, 10.0), (100.0, 100.0)]);
1535 }
1536
1537 #[test]
1538 fn commit_drag_does_not_move_a_selected_node_twice() {
1539 let model = movable_model(&[(1, 0.0, 0.0, true)]);
1542
1543 GraphLogic::commit_drag(&model, 1, 10.0, 20.0);
1544
1545 assert_eq!(positions(&model), vec![(10.0, 20.0)]);
1546 }
1547
1548 #[test]
1549 fn commit_drag_accepts_a_negative_delta() {
1550 let model = movable_model(&[(1, 100.0, 100.0, true)]);
1551
1552 GraphLogic::commit_drag(&model, 1, -50.0, -30.0);
1553
1554 assert_eq!(positions(&model), vec![(50.0, 70.0)]);
1555 }
1556}
1557
1558impl crate::nodeeditor::LinkData {
1559 pub fn new(id: i32, start_pin_id: i32, end_pin_id: i32, color: Color) -> Self {
1562 Self {
1563 id,
1564 start_pin_id,
1565 end_pin_id,
1566 color,
1567 line_width: 2.0,
1568 status: -1,
1569 selected: false,
1570 }
1571 }
1572}
1573
1574#[cfg(test)]
1575mod contract_tests {
1576 use super::*;
1577 #[test]
1578 fn normalization_requires_both_endpoints() {
1579 let mut cache = GeometryCache::<SimpleNodeGeometry>::new();
1580 cache.handle_pin_report(1, 1, 2, 0.0, 0.0);
1581 assert_eq!(GraphLogic::normalize_link_direction(1, 2, &cache, 2), None);
1582 assert_eq!(GraphLogic::normalize_link_direction(2, 1, &cache, 2), None);
1583 }
1584 #[test]
1585 fn colored_link_has_no_status_override() {
1586 let color = Color::from_rgb_u8(1, 2, 3);
1587 let link = crate::LinkData::new(0, 1, 2, color);
1588 assert_eq!(link.color, color);
1589 assert_eq!(link.status, -1);
1590 assert_eq!(link.line_width, 2.0);
1591 assert!(!link.selected);
1592 }
1593}