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 {
165 fn id(&self) -> i32;
166 fn x(&self) -> f32;
167 fn y(&self) -> f32;
168 fn selected(&self) -> bool;
169 fn set_x(&mut self, x: f32);
170 fn set_y(&mut self, y: f32);
171
172 fn draggable(&self) -> bool {
179 true
180 }
181}
182
183pub struct GraphLogic;
185
186impl GraphLogic {
187 pub fn find_links_connected_to_node<I, L, N>(
194 node_id: i32,
195 links: I,
196 cache: &GeometryCache<N>,
197 ) -> Vec<i32>
198 where
199 I: Iterator<Item = L>,
200 L: LinkModel,
201 N: NodeGeometry + Copy,
202 {
203 links
204 .filter(|link| {
205 let start_node = cache
206 .pin_positions
207 .get(&link.start_pin_id())
208 .map(|p| p.node_id);
209 let end_node = cache
210 .pin_positions
211 .get(&link.end_pin_id())
212 .map(|p| p.node_id);
213
214 start_node == Some(node_id) || end_node == Some(node_id)
215 })
216 .map(|l| l.id())
217 .collect()
218 }
219
220 pub fn normalize_link_direction<N>(
225 pin_a: i32,
226 pin_b: i32,
227 cache: &GeometryCache<N>,
228 output_type: i32,
229 ) -> Option<(i32, i32)>
230 where
231 N: NodeGeometry + Copy,
232 {
233 let pos_a = cache.pin_positions.get(&pin_a)?;
234 cache.pin_positions.get(&pin_b)?;
235 if pos_a.pin_type == output_type {
238 Some((pin_a, pin_b))
239 } else {
240 Some((pin_b, pin_a))
241 }
242 }
243
244 pub fn commit_drag<T>(model: &VecModel<T>, dragged_id: i32, delta_x: f32, delta_y: f32)
260 where
261 T: MovableNode,
262 {
263 for i in 0..model.row_count() {
264 if let Some(mut node) = model.row_data(i) {
265 if node.id() == dragged_id || Self::carried_by_selection(&node) {
266 node.set_x(node.x() + delta_x);
267 node.set_y(node.y() + delta_y);
268 model.set_row_data(i, node);
269 }
270 }
271 }
272 }
273
274 pub(crate) fn carried_by_selection<T: MovableNode>(node: &T) -> bool {
277 node.selected() && node.draggable()
278 }
279
280 pub fn duplicate_link_exists<I, L>(start_pin: i32, end_pin: i32, links: I) -> bool
289 where
290 I: IntoIterator<Item = L>,
291 L: LinkModel,
292 {
293 links
294 .into_iter()
295 .any(|link| link.start_pin_id() == start_pin && link.end_pin_id() == end_pin)
296 }
297
298 pub fn find_node_by_id<T, F>(
323 model: &impl Model<Data = T>,
324 id: i32,
325 predicate: F,
326 ) -> Option<(usize, T)>
327 where
328 T: Clone + 'static,
329 F: Fn(&T) -> i32,
330 {
331 for i in 0..model.row_count() {
332 if let Some(node) = model.row_data(i) {
333 if predicate(&node) == id {
334 return Some((i, node));
335 }
336 }
337 }
338 None
339 }
340}
341
342#[derive(Debug, Clone, PartialEq, Eq)]
348pub enum ValidationResult {
349 Valid,
351 Invalid(ValidationError),
353}
354
355impl ValidationResult {
356 pub fn is_valid(&self) -> bool {
358 matches!(self, ValidationResult::Valid)
359 }
360
361 pub fn and(self, other: ValidationResult) -> ValidationResult {
363 match self {
364 ValidationResult::Valid => other,
365 invalid => invalid,
366 }
367 }
368}
369
370#[derive(Debug, Clone, PartialEq, Eq)]
372pub enum ValidationError {
373 PinNotFound(i32),
375 SamePin,
377 SameNode,
379 IncompatibleDirection,
381 DuplicateLink,
383 MaxConnectionsReached { pin_id: i32, max: usize },
385 TypeMismatch { expected: i32, found: i32 },
387 Custom(String),
389}
390
391#[derive(Debug, Clone, Copy, PartialEq, Eq)]
398pub struct NormalizedLink {
399 pub output_pin_id: i32,
401 pub input_pin_id: i32,
403}
404
405impl fmt::Display for ValidationError {
406 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
407 match self {
408 Self::PinNotFound(id) => write!(f, "Pin {} not found", id),
409 Self::SamePin => write!(f, "Cannot link pin to itself"),
410 Self::SameNode => write!(f, "Cannot link pins on same node"),
411 Self::IncompatibleDirection => write!(f, "Must connect input to output"),
412 Self::DuplicateLink => write!(f, "Link already exists"),
413 Self::MaxConnectionsReached { pin_id, max } => {
414 write!(f, "Pin {} has reached max {} connections", pin_id, max)
415 }
416 Self::TypeMismatch { expected, found } => {
417 write!(f, "Type mismatch: expected {}, found {}", expected, found)
418 }
419 Self::Custom(msg) => write!(f, "{}", msg),
420 }
421 }
422}
423
424impl std::error::Error for ValidationError {}
425
426pub trait LinkValidator<N = SimpleNodeGeometry, L = ()> {
462 fn validate(
474 &self,
475 start_pin: i32,
476 end_pin: i32,
477 cache: &GeometryCache<N>,
478 links: &[L],
479 ) -> ValidationResult;
480}
481
482#[derive(Clone, Copy, Debug)]
509pub struct BasicLinkValidator {
510 output_type: i32,
511}
512
513impl BasicLinkValidator {
514 pub fn new(output_type: i32) -> Self {
520 Self { output_type }
521 }
522}
523
524impl<N, L> LinkValidator<N, L> for BasicLinkValidator
525where
526 N: NodeGeometry + Copy,
527{
528 fn validate(
529 &self,
530 start_pin: i32,
531 end_pin: i32,
532 cache: &GeometryCache<N>,
533 _links: &[L],
534 ) -> ValidationResult {
535 if start_pin == end_pin {
536 return ValidationResult::Invalid(ValidationError::SamePin);
537 }
538
539 let start_pos = match cache.pin_positions.get(&start_pin) {
540 Some(p) => p,
541 None => return ValidationResult::Invalid(ValidationError::PinNotFound(start_pin)),
542 };
543 let end_pos = match cache.pin_positions.get(&end_pin) {
544 Some(p) => p,
545 None => return ValidationResult::Invalid(ValidationError::PinNotFound(end_pin)),
546 };
547
548 if start_pos.node_id == end_pos.node_id {
549 return ValidationResult::Invalid(ValidationError::SameNode);
550 }
551
552 let start_is_output = start_pos.pin_type == self.output_type;
553 let end_is_output = end_pos.pin_type == self.output_type;
554
555 if start_is_output == end_is_output {
556 return ValidationResult::Invalid(ValidationError::IncompatibleDirection);
557 }
558
559 ValidationResult::Valid
560 }
561}
562
563pub fn validate_and_normalize_link<N, L, V>(
614 pin_a: i32,
615 pin_b: i32,
616 cache: &GeometryCache<N>,
617 links: &[L],
618 output_type: i32,
619 topology_validator: &V,
620) -> Result<NormalizedLink, ValidationError>
621where
622 N: NodeGeometry + Copy,
623 V: LinkValidator<N, L>,
624{
625 match BasicLinkValidator::new(output_type).validate(pin_a, pin_b, cache, links) {
626 ValidationResult::Valid => {}
627 ValidationResult::Invalid(error) => return Err(error),
628 }
629
630 let Some((output_pin_id, input_pin_id)) =
631 GraphLogic::normalize_link_direction(pin_a, pin_b, cache, output_type)
632 else {
633 return Err(ValidationError::PinNotFound(pin_a));
634 };
635
636 match topology_validator.validate(output_pin_id, input_pin_id, cache, links) {
637 ValidationResult::Valid => Ok(NormalizedLink {
638 output_pin_id,
639 input_pin_id,
640 }),
641 ValidationResult::Invalid(error) => Err(error),
642 }
643}
644
645#[derive(Clone, Debug, Default)]
666pub struct NoDuplicatesValidator;
667
668impl<N, L> LinkValidator<N, L> for NoDuplicatesValidator
669where
670 L: LinkModel + Clone,
671{
672 fn validate(
673 &self,
674 start_pin: i32,
675 end_pin: i32,
676 _cache: &GeometryCache<N>,
677 links: &[L],
678 ) -> ValidationResult {
679 if GraphLogic::duplicate_link_exists(start_pin, end_pin, links.iter().cloned()) {
681 ValidationResult::Invalid(ValidationError::DuplicateLink)
682 } else {
683 ValidationResult::Valid
684 }
685 }
686}
687
688pub struct CompositeValidator<N = SimpleNodeGeometry, L = ()> {
718 validators: Vec<Box<dyn LinkValidator<N, L>>>,
719}
720
721impl<N, L> Default for CompositeValidator<N, L> {
722 fn default() -> Self {
723 Self::new()
724 }
725}
726
727impl<N, L> CompositeValidator<N, L> {
728 pub fn new() -> Self {
730 Self {
731 validators: Vec::new(),
732 }
733 }
734
735 pub fn with<V: LinkValidator<N, L> + 'static>(mut self, validator: V) -> Self {
740 self.validators.push(Box::new(validator));
741 self
742 }
743}
744
745impl<N, L> LinkValidator<N, L> for CompositeValidator<N, L> {
746 fn validate(
747 &self,
748 start_pin: i32,
749 end_pin: i32,
750 cache: &GeometryCache<N>,
751 links: &[L],
752 ) -> ValidationResult {
753 for v in &self.validators {
754 let result = v.validate(start_pin, end_pin, cache, links);
755 if !result.is_valid() {
756 return result;
757 }
758 }
759 ValidationResult::Valid
760 }
761}
762
763#[cfg(test)]
768mod tests {
769 use super::*;
770 use crate::hit_test::SimpleNodeGeometry;
771 use crate::state::StoredPin;
772
773 fn setup_cache() -> GeometryCache<SimpleNodeGeometry> {
775 let mut cache = GeometryCache::new();
776
777 cache.node_rects.insert(
779 1,
780 SimpleNodeGeometry {
781 id: 1,
782 x: 0.0,
783 y: 0.0,
784 width: 100.0,
785 height: 50.0,
786 },
787 );
788 cache.node_rects.insert(
789 2,
790 SimpleNodeGeometry {
791 id: 2,
792 x: 200.0,
793 y: 0.0,
794 width: 100.0,
795 height: 50.0,
796 },
797 );
798
799 cache.pin_positions.insert(
801 1001,
802 StoredPin {
803 node_id: 1,
804 pin_type: 2,
805 rel_x: 100.0,
806 rel_y: 25.0,
807 },
808 );
809 cache.pin_positions.insert(
811 2001,
812 StoredPin {
813 node_id: 2,
814 pin_type: 1,
815 rel_x: 0.0,
816 rel_y: 25.0,
817 },
818 );
819 cache.pin_positions.insert(
821 2002,
822 StoredPin {
823 node_id: 2,
824 pin_type: 1,
825 rel_x: 0.0,
826 rel_y: 40.0,
827 },
828 );
829
830 cache
831 }
832
833 #[derive(Clone, Debug)]
835 struct TestLink {
836 id: i32,
837 start: i32,
838 end: i32,
839 }
840
841 impl LinkModel for TestLink {
842 fn id(&self) -> i32 {
843 self.id
844 }
845 fn start_pin_id(&self) -> i32 {
846 self.start
847 }
848 fn end_pin_id(&self) -> i32 {
849 self.end
850 }
851 }
852
853 #[test]
854 fn test_basic_validator_accepts_valid_link() {
855 let cache = setup_cache();
856 let validator = BasicLinkValidator::new(2); let links: Vec<TestLink> = vec![];
858
859 let result = validator.validate(1001, 2001, &cache, &links);
860 assert!(result.is_valid());
861 }
862
863 #[test]
864 fn removed_node_pins_are_no_longer_valid_endpoints() {
865 let mut cache = setup_cache();
866 let validator = BasicLinkValidator::new(2);
867 let links: Vec<TestLink> = vec![];
868
869 cache.remove_node(1);
870
871 assert_eq!(
872 validator.validate(1001, 2001, &cache, &links),
873 ValidationResult::Invalid(ValidationError::PinNotFound(1001))
874 );
875 }
876
877 #[test]
878 fn test_basic_validator_rejects_same_pin() {
879 let cache = setup_cache();
880 let validator = BasicLinkValidator::new(2);
881 let links: Vec<TestLink> = vec![];
882
883 let result = validator.validate(1001, 1001, &cache, &links);
884 assert_eq!(result, ValidationResult::Invalid(ValidationError::SamePin));
885 }
886
887 #[test]
888 fn test_basic_validator_rejects_same_node() {
889 let mut cache = setup_cache();
890 cache.pin_positions.insert(
892 1002,
893 StoredPin {
894 node_id: 1,
895 pin_type: 1,
896 rel_x: 0.0,
897 rel_y: 25.0,
898 },
899 );
900
901 let validator = BasicLinkValidator::new(2);
902 let links: Vec<TestLink> = vec![];
903
904 let result = validator.validate(1001, 1002, &cache, &links);
905 assert_eq!(result, ValidationResult::Invalid(ValidationError::SameNode));
906 }
907
908 #[test]
909 fn test_basic_validator_rejects_same_direction() {
910 let mut cache = setup_cache();
911 cache.pin_positions.insert(
913 2003,
914 StoredPin {
915 node_id: 2,
916 pin_type: 2,
917 rel_x: 100.0,
918 rel_y: 25.0,
919 },
920 );
921
922 let validator = BasicLinkValidator::new(2);
923 let links: Vec<TestLink> = vec![];
924
925 let result = validator.validate(1001, 2003, &cache, &links);
927 assert_eq!(
928 result,
929 ValidationResult::Invalid(ValidationError::IncompatibleDirection)
930 );
931 }
932
933 #[test]
934 fn test_basic_validator_rejects_missing_pin() {
935 let cache = setup_cache();
936 let validator = BasicLinkValidator::new(2);
937 let links: Vec<TestLink> = vec![];
938
939 let result = validator.validate(1001, 9999, &cache, &links);
940 assert_eq!(
941 result,
942 ValidationResult::Invalid(ValidationError::PinNotFound(9999))
943 );
944 }
945
946 #[test]
947 fn test_no_duplicates_validator_accepts_new_link() {
948 let cache = setup_cache();
949 let validator = NoDuplicatesValidator;
950 let links = vec![TestLink {
951 id: 1,
952 start: 1001,
953 end: 2002,
954 }];
955
956 let result = validator.validate(1001, 2001, &cache, &links);
958 assert!(result.is_valid());
959 }
960
961 #[test]
962 fn test_no_duplicates_validator_rejects_duplicate() {
963 let cache = setup_cache();
964 let validator = NoDuplicatesValidator;
965 let links = vec![TestLink {
966 id: 1,
967 start: 1001,
968 end: 2001,
969 }];
970
971 let result = validator.validate(1001, 2001, &cache, &links);
973 assert_eq!(
974 result,
975 ValidationResult::Invalid(ValidationError::DuplicateLink)
976 );
977 }
978
979 #[test]
980 fn validation_returns_the_same_normalized_endpoints_for_both_gesture_directions() {
981 let cache = setup_cache();
982 let links: Vec<TestLink> = vec![];
983
984 let output_first =
985 validate_and_normalize_link(1001, 2001, &cache, &links, 2, &NoDuplicatesValidator);
986 let input_first =
987 validate_and_normalize_link(2001, 1001, &cache, &links, 2, &NoDuplicatesValidator);
988
989 let expected = Ok(NormalizedLink {
990 output_pin_id: 1001,
991 input_pin_id: 2001,
992 });
993 assert_eq!(output_first, expected);
994 assert_eq!(input_first, expected);
995 }
996
997 #[test]
998 fn reverse_gesture_is_rejected_after_normalization_when_link_exists() {
999 let cache = setup_cache();
1000 let links = vec![TestLink {
1001 id: 1,
1002 start: 1001,
1003 end: 2001,
1004 }];
1005
1006 assert_eq!(
1007 validate_and_normalize_link(2001, 1001, &cache, &links, 2, &NoDuplicatesValidator,),
1008 Err(ValidationError::DuplicateLink),
1009 );
1010 }
1011
1012 #[test]
1013 fn topology_rules_receive_normalized_endpoints() {
1014 struct RequireExpectedOrder;
1015
1016 impl<N, L> LinkValidator<N, L> for RequireExpectedOrder {
1017 fn validate(
1018 &self,
1019 start_pin: i32,
1020 end_pin: i32,
1021 _cache: &GeometryCache<N>,
1022 _links: &[L],
1023 ) -> ValidationResult {
1024 if (start_pin, end_pin) == (1001, 2001) {
1025 ValidationResult::Valid
1026 } else {
1027 ValidationResult::Invalid(ValidationError::Custom(format!(
1028 "received ({start_pin}, {end_pin})"
1029 )))
1030 }
1031 }
1032 }
1033
1034 let cache = setup_cache();
1035 let links: Vec<TestLink> = vec![];
1036 assert!(
1037 validate_and_normalize_link(2001, 1001, &cache, &links, 2, &RequireExpectedOrder,)
1038 .is_ok()
1039 );
1040 }
1041
1042 #[test]
1043 fn test_composite_validator_passes_all() {
1044 let cache = setup_cache();
1045 let validator: CompositeValidator<_, TestLink> = CompositeValidator::new()
1046 .with(BasicLinkValidator::new(2))
1047 .with(NoDuplicatesValidator);
1048
1049 let links = vec![];
1050
1051 let result = validator.validate(1001, 2001, &cache, &links);
1052 assert!(result.is_valid());
1053 }
1054
1055 #[test]
1056 fn test_composite_validator_short_circuits_on_basic() {
1057 let cache = setup_cache();
1058 let validator: CompositeValidator<_, TestLink> = CompositeValidator::new()
1059 .with(BasicLinkValidator::new(2))
1060 .with(NoDuplicatesValidator);
1061
1062 let links = vec![];
1063
1064 let result = validator.validate(1001, 1001, &cache, &links);
1066 assert_eq!(result, ValidationResult::Invalid(ValidationError::SamePin));
1067 }
1068
1069 #[test]
1070 fn test_composite_validator_short_circuits_on_duplicates() {
1071 let cache = setup_cache();
1072 let validator: CompositeValidator<_, TestLink> = CompositeValidator::new()
1073 .with(BasicLinkValidator::new(2))
1074 .with(NoDuplicatesValidator);
1075
1076 let links = vec![TestLink {
1077 id: 1,
1078 start: 1001,
1079 end: 2001,
1080 }];
1081
1082 let result = validator.validate(1001, 2001, &cache, &links);
1084 assert_eq!(
1085 result,
1086 ValidationResult::Invalid(ValidationError::DuplicateLink)
1087 );
1088 }
1089
1090 #[test]
1091 fn test_validator_validate_directly() {
1092 let cache = setup_cache();
1093 let validator = BasicLinkValidator::new(2);
1094 let links: Vec<TestLink> = vec![];
1095
1096 let result = validator.validate(1001, 2001, &cache, &links);
1097 assert!(result.is_valid());
1098 }
1099
1100 #[test]
1101 fn test_validation_result_and_combinator() {
1102 let result1 = ValidationResult::Valid;
1103 let result2 = ValidationResult::Valid;
1104 assert!(result1.and(result2).is_valid());
1105
1106 let result1 = ValidationResult::Valid;
1107 let result2 = ValidationResult::Invalid(ValidationError::SamePin);
1108 assert_eq!(
1109 result1.and(result2),
1110 ValidationResult::Invalid(ValidationError::SamePin)
1111 );
1112
1113 let result1 = ValidationResult::Invalid(ValidationError::SameNode);
1114 let result2 = ValidationResult::Valid;
1115 assert_eq!(
1116 result1.and(result2),
1117 ValidationResult::Invalid(ValidationError::SameNode)
1118 );
1119
1120 let result1 = ValidationResult::Invalid(ValidationError::SameNode);
1122 let result2 = ValidationResult::Invalid(ValidationError::SamePin);
1123 assert_eq!(
1124 result1.and(result2),
1125 ValidationResult::Invalid(ValidationError::SameNode)
1126 );
1127 }
1128
1129 #[test]
1130 fn test_validation_error_display() {
1131 assert_eq!(
1132 format!("{}", ValidationError::PinNotFound(42)),
1133 "Pin 42 not found"
1134 );
1135 assert_eq!(
1136 format!("{}", ValidationError::SamePin),
1137 "Cannot link pin to itself"
1138 );
1139 assert_eq!(
1140 format!("{}", ValidationError::SameNode),
1141 "Cannot link pins on same node"
1142 );
1143 assert_eq!(
1144 format!("{}", ValidationError::IncompatibleDirection),
1145 "Must connect input to output"
1146 );
1147 assert_eq!(
1148 format!("{}", ValidationError::DuplicateLink),
1149 "Link already exists"
1150 );
1151 assert_eq!(
1152 format!(
1153 "{}",
1154 ValidationError::MaxConnectionsReached {
1155 pin_id: 123,
1156 max: 3
1157 }
1158 ),
1159 "Pin 123 has reached max 3 connections"
1160 );
1161 assert_eq!(
1162 format!(
1163 "{}",
1164 ValidationError::TypeMismatch {
1165 expected: 1,
1166 found: 2
1167 }
1168 ),
1169 "Type mismatch: expected 1, found 2"
1170 );
1171 assert_eq!(
1172 format!("{}", ValidationError::Custom("Test error".to_string())),
1173 "Test error"
1174 );
1175 }
1176
1177 #[test]
1179 fn test_custom_validator() {
1180 #[derive(Clone, Copy)]
1181 struct FanOutValidator {
1182 max_connections: usize,
1183 }
1184
1185 impl<N, L> LinkValidator<N, L> for FanOutValidator
1186 where
1187 L: LinkModel,
1188 {
1189 fn validate(
1190 &self,
1191 start_pin: i32,
1192 _end_pin: i32,
1193 _cache: &GeometryCache<N>,
1194 links: &[L],
1195 ) -> ValidationResult {
1196 let existing_count = links
1197 .iter()
1198 .filter(|link| link.start_pin_id() == start_pin)
1199 .count();
1200
1201 if existing_count >= self.max_connections {
1202 ValidationResult::Invalid(ValidationError::MaxConnectionsReached {
1203 pin_id: start_pin,
1204 max: self.max_connections,
1205 })
1206 } else {
1207 ValidationResult::Valid
1208 }
1209 }
1210 }
1211
1212 let cache = setup_cache();
1213 let validator = FanOutValidator { max_connections: 1 };
1214
1215 let existing_links = vec![TestLink {
1217 id: 1,
1218 start: 1001,
1219 end: 2001,
1220 }];
1221
1222 let result = validator.validate(1001, 2002, &cache, &existing_links);
1224 assert_eq!(
1225 result,
1226 ValidationResult::Invalid(ValidationError::MaxConnectionsReached {
1227 pin_id: 1001,
1228 max: 1,
1229 })
1230 );
1231
1232 let no_links: Vec<TestLink> = vec![];
1234 let result = validator.validate(1001, 2001, &cache, &no_links);
1235 assert!(result.is_valid());
1236 }
1237
1238 #[test]
1243 fn test_find_links_connected_to_node_by_start() {
1244 let cache = setup_cache();
1245 let links = vec![
1246 TestLink {
1247 id: 1,
1248 start: 1001,
1249 end: 2001,
1250 },
1251 TestLink {
1252 id: 2,
1253 start: 2001,
1254 end: 1001,
1255 },
1256 ];
1257
1258 let connected = GraphLogic::find_links_connected_to_node(1, links.into_iter(), &cache);
1260 assert!(connected.contains(&1));
1261 assert!(connected.contains(&2));
1262 }
1263
1264 #[test]
1265 fn test_find_links_connected_to_node_no_connections() {
1266 let cache = setup_cache();
1267 let links = vec![TestLink {
1268 id: 1,
1269 start: 1001,
1270 end: 2001,
1271 }];
1272
1273 let connected = GraphLogic::find_links_connected_to_node(999, links.into_iter(), &cache);
1275 assert!(connected.is_empty());
1276 }
1277
1278 #[test]
1279 fn test_find_links_connected_to_node_empty_links() {
1280 let cache = setup_cache();
1281 let links: Vec<TestLink> = vec![];
1282
1283 let connected = GraphLogic::find_links_connected_to_node(1, links.into_iter(), &cache);
1284 assert!(connected.is_empty());
1285 }
1286
1287 #[test]
1288 fn test_find_links_connected_to_node_multiple_pins() {
1289 let mut cache = setup_cache();
1290 cache.pin_positions.insert(
1292 1002,
1293 StoredPin {
1294 node_id: 1,
1295 pin_type: 1,
1296 rel_x: 0.0,
1297 rel_y: 40.0,
1298 },
1299 );
1300
1301 let links = vec![
1302 TestLink {
1303 id: 1,
1304 start: 1001,
1305 end: 2001,
1306 },
1307 TestLink {
1308 id: 2,
1309 start: 2001,
1310 end: 1002,
1311 },
1312 TestLink {
1313 id: 3,
1314 start: 2001,
1315 end: 2002,
1316 }, ];
1318
1319 let connected = GraphLogic::find_links_connected_to_node(1, links.into_iter(), &cache);
1320 assert!(connected.contains(&1));
1321 assert!(connected.contains(&2));
1322 assert!(!connected.contains(&3));
1323 }
1324
1325 #[test]
1330 fn test_normalize_link_direction_output_first() {
1331 let cache = setup_cache();
1332 let result = GraphLogic::normalize_link_direction(1001, 2001, &cache, 2);
1334 assert_eq!(result, Some((1001, 2001)));
1335 }
1336
1337 #[test]
1338 fn test_normalize_link_direction_input_first() {
1339 let cache = setup_cache();
1340 let result = GraphLogic::normalize_link_direction(2001, 1001, &cache, 2);
1342 assert_eq!(result, Some((1001, 2001)));
1343 }
1344
1345 #[test]
1346 fn test_normalize_link_direction_missing_pin() {
1347 let cache = setup_cache();
1348 let result = GraphLogic::normalize_link_direction(9999, 2001, &cache, 2);
1349 assert!(result.is_none());
1350 }
1351
1352 #[test]
1357 fn test_duplicate_link_exists_true() {
1358 let links = vec![TestLink {
1359 id: 1,
1360 start: 1001,
1361 end: 2001,
1362 }];
1363 assert!(GraphLogic::duplicate_link_exists(1001, 2001, links));
1364 }
1365
1366 #[test]
1367 fn test_duplicate_link_exists_false() {
1368 let links = vec![TestLink {
1369 id: 1,
1370 start: 1001,
1371 end: 2001,
1372 }];
1373 assert!(!GraphLogic::duplicate_link_exists(1001, 2002, links));
1374 }
1375
1376 #[test]
1377 fn test_duplicate_link_exists_empty() {
1378 let links: Vec<TestLink> = vec![];
1379 assert!(!GraphLogic::duplicate_link_exists(1001, 2001, links));
1380 }
1381
1382 #[test]
1383 fn test_duplicate_link_exists_direction_matters() {
1384 let links = vec![TestLink {
1385 id: 1,
1386 start: 1001,
1387 end: 2001,
1388 }];
1389 assert!(!GraphLogic::duplicate_link_exists(2001, 1001, links));
1391 }
1392
1393 #[test]
1398 fn test_find_node_by_id_found() {
1399 #[derive(Clone)]
1400 struct TestNode {
1401 id: i32,
1402 name: String,
1403 }
1404
1405 let model = std::rc::Rc::new(VecModel::from(vec![
1406 TestNode {
1407 id: 1,
1408 name: "Node 1".to_string(),
1409 },
1410 TestNode {
1411 id: 2,
1412 name: "Node 2".to_string(),
1413 },
1414 TestNode {
1415 id: 3,
1416 name: "Node 3".to_string(),
1417 },
1418 ]));
1419
1420 let result = GraphLogic::find_node_by_id(&model, 2, |n| n.id);
1421 assert!(result.is_some());
1422 let (index, node) = result.unwrap();
1423 assert_eq!(index, 1);
1424 assert_eq!(node.id, 2);
1425 assert_eq!(node.name, "Node 2");
1426 }
1427
1428 #[test]
1429 fn test_find_node_by_id_not_found() {
1430 #[derive(Clone)]
1431 struct TestNode {
1432 id: i32,
1433 }
1434
1435 let model = std::rc::Rc::new(VecModel::from(vec![TestNode { id: 1 }, TestNode { id: 2 }]));
1436
1437 let result = GraphLogic::find_node_by_id(&model, 999, |n| n.id);
1438 assert!(result.is_none());
1439 }
1440
1441 #[test]
1442 fn test_find_node_by_id_empty_model() {
1443 #[derive(Clone)]
1444 struct TestNode {
1445 id: i32,
1446 }
1447
1448 let model = std::rc::Rc::new(VecModel::<TestNode>::default());
1449
1450 let result = GraphLogic::find_node_by_id(&model, 1, |n| n.id);
1451 assert!(result.is_none());
1452 }
1453
1454 #[test]
1455 fn test_find_node_by_id_first_match() {
1456 #[derive(Clone)]
1457 struct TestNode {
1458 id: i32,
1459 value: i32,
1460 }
1461
1462 let model = std::rc::Rc::new(VecModel::from(vec![
1464 TestNode { id: 1, value: 100 },
1465 TestNode { id: 1, value: 200 },
1466 ]));
1467
1468 let result = GraphLogic::find_node_by_id(&model, 1, |n| n.id);
1469 assert!(result.is_some());
1470 let (index, node) = result.unwrap();
1471 assert_eq!(index, 0);
1472 assert_eq!(node.value, 100);
1473 }
1474
1475 #[derive(Clone)]
1480 struct TestMovableNode {
1481 id: i32,
1482 x: f32,
1483 y: f32,
1484 selected: bool,
1485 draggable: bool,
1486 }
1487
1488 impl MovableNode for TestMovableNode {
1489 fn id(&self) -> i32 {
1490 self.id
1491 }
1492 fn x(&self) -> f32 {
1493 self.x
1494 }
1495 fn y(&self) -> f32 {
1496 self.y
1497 }
1498 fn selected(&self) -> bool {
1499 self.selected
1500 }
1501 fn set_x(&mut self, x: f32) {
1502 self.x = x;
1503 }
1504 fn set_y(&mut self, y: f32) {
1505 self.y = y;
1506 }
1507 fn draggable(&self) -> bool {
1508 self.draggable
1509 }
1510 }
1511
1512 fn movable_model(rows: &[(i32, f32, f32, bool)]) -> std::rc::Rc<VecModel<TestMovableNode>> {
1514 std::rc::Rc::new(VecModel::from(
1515 rows.iter()
1516 .map(|&(id, x, y, selected)| TestMovableNode {
1517 id,
1518 x,
1519 y,
1520 selected,
1521 draggable: true,
1522 })
1523 .collect::<Vec<_>>(),
1524 ))
1525 }
1526
1527 fn positions(model: &VecModel<TestMovableNode>) -> Vec<(f32, f32)> {
1528 (0..model.row_count())
1529 .filter_map(|i| model.row_data(i))
1530 .map(|n| (n.x, n.y))
1531 .collect()
1532 }
1533
1534 #[test]
1535 fn commit_drag_moves_the_whole_selection() {
1536 let model = movable_model(&[
1537 (1, 0.0, 0.0, true),
1538 (2, 100.0, 100.0, false),
1539 (3, 200.0, 200.0, true),
1540 ]);
1541
1542 GraphLogic::commit_drag(&model, 1, 10.0, 20.0);
1543
1544 assert_eq!(
1546 positions(&model),
1547 vec![(10.0, 20.0), (100.0, 100.0), (210.0, 220.0)]
1548 );
1549 }
1550
1551 #[test]
1552 fn commit_drag_moves_the_dragged_node_even_when_nothing_is_selected() {
1553 let model = movable_model(&[(1, 50.0, 50.0, false), (2, 0.0, 0.0, false)]);
1555
1556 GraphLogic::commit_drag(&model, 1, 100.0, 100.0);
1557
1558 assert_eq!(positions(&model), vec![(150.0, 150.0), (0.0, 0.0)]);
1559 }
1560
1561 #[test]
1562 fn commit_drag_ignores_a_dragged_id_from_another_model() {
1563 let model = movable_model(&[(1, 0.0, 0.0, true), (2, 100.0, 100.0, false)]);
1566
1567 GraphLogic::commit_drag(&model, 99, 10.0, 10.0);
1568
1569 assert_eq!(positions(&model), vec![(10.0, 10.0), (100.0, 100.0)]);
1570 }
1571
1572 #[test]
1573 fn commit_drag_does_not_move_a_selected_node_twice() {
1574 let model = movable_model(&[(1, 0.0, 0.0, true)]);
1577
1578 GraphLogic::commit_drag(&model, 1, 10.0, 20.0);
1579
1580 assert_eq!(positions(&model), vec![(10.0, 20.0)]);
1581 }
1582
1583 #[test]
1584 fn commit_drag_accepts_a_negative_delta() {
1585 let model = movable_model(&[(1, 100.0, 100.0, true)]);
1586
1587 GraphLogic::commit_drag(&model, 1, -50.0, -30.0);
1588
1589 assert_eq!(positions(&model), vec![(50.0, 70.0)]);
1590 }
1591
1592 #[test]
1593 fn commit_drag_leaves_a_selected_undraggable_node_in_place() {
1594 let model = movable_model(&[(1, 0.0, 0.0, true), (2, 100.0, 100.0, true)]);
1595 let mut undraggable = model.row_data(1).unwrap();
1596 undraggable.draggable = false;
1597 model.set_row_data(1, undraggable);
1598
1599 GraphLogic::commit_drag(&model, 1, 10.0, 20.0);
1600
1601 assert_eq!(positions(&model), vec![(10.0, 20.0), (100.0, 100.0)]);
1602 }
1603}
1604
1605impl crate::nodeeditor::LinkData {
1606 pub fn new(id: i32, start_pin_id: i32, end_pin_id: i32, color: Color) -> Self {
1610 Self {
1611 id,
1612 start_pin_id,
1613 end_pin_id,
1614 color,
1615 line_width: 2.0,
1616 status: -1,
1617 selected: false,
1618 ..Default::default()
1619 }
1620 }
1621}
1622
1623#[cfg(test)]
1624mod contract_tests {
1625 use super::*;
1626 #[test]
1627 fn normalization_requires_both_endpoints() {
1628 let mut cache = GeometryCache::<SimpleNodeGeometry>::new();
1629 cache.handle_pin_report(1, 1, 2, 0.0, 0.0);
1630 assert_eq!(GraphLogic::normalize_link_direction(1, 2, &cache, 2), None);
1631 assert_eq!(GraphLogic::normalize_link_direction(2, 1, &cache, 2), None);
1632 }
1633 #[test]
1634 fn colored_link_has_no_status_override() {
1635 let color = Color::from_rgb_u8(1, 2, 3);
1636 let link = crate::LinkData::new(0, 1, 2, color);
1637 assert_eq!(link.color, color);
1638 assert_eq!(link.status, -1);
1639 assert_eq!(link.line_width, 2.0);
1640 assert!(!link.selected);
1641 }
1642}