Skip to main content

slint_node_editor/
state.rs

1use crate::hit_test::{
2    find_link_at, find_link_route_at, find_pin_at, links_in_selection_box, nodes_in_selection_box,
3    BezierLinkRoute, NodeGeometry, SimpleLinkGeometry, SimpleNodeGeometry, SimplePinGeometry,
4};
5use crate::path::{generate_bezier_path, CubicBezier};
6use std::collections::{HashMap, HashSet};
7
8#[derive(Clone, Copy, Debug)]
9pub struct StoredPin {
10    pub node_id: i32,
11    pub pin_type: i32,
12    pub rel_x: f32,
13    pub rel_y: f32,
14}
15
16/// Helper struct to manage spatial state of the editor (node rects and pin positions)
17///
18/// Generic over N to allow using specialized node types that implement NodeGeometry.
19pub struct GeometryCache<N = SimpleNodeGeometry> {
20    pub node_rects: HashMap<i32, N>,
21    pub pin_positions: HashMap<i32, StoredPin>,
22    non_hit_testable_pins: HashSet<i32>,
23}
24
25impl<N> Default for GeometryCache<N> {
26    fn default() -> Self {
27        Self {
28            node_rects: HashMap::new(),
29            pin_positions: HashMap::new(),
30            non_hit_testable_pins: HashSet::new(),
31        }
32    }
33}
34
35impl<N> GeometryCache<N> {
36    pub fn new() -> Self {
37        Self::default()
38    }
39
40    /// Remove one pin from the disposable geometry projection.
41    pub fn remove_pin(&mut self, pin_id: i32) -> bool {
42        self.non_hit_testable_pins.remove(&pin_id);
43        self.pin_positions.remove(&pin_id).is_some()
44    }
45
46    /// Remove a node and every pin currently owned by it.
47    ///
48    /// The returned pin IDs let higher layers retire topology that refers to
49    /// those pins without deriving ownership from an application-specific ID.
50    pub fn remove_node(&mut self, node_id: i32) -> Vec<i32> {
51        self.node_rects.remove(&node_id);
52        let mut removed_pins: Vec<_> = self
53            .pin_positions
54            .iter()
55            .filter_map(|(&pin_id, pin)| (pin.node_id == node_id).then_some(pin_id))
56            .collect();
57        removed_pins.sort_unstable();
58        for pin_id in &removed_pins {
59            self.remove_pin(*pin_id);
60        }
61        removed_pins
62    }
63
64    /// Clear all projected node and pin geometry.
65    pub fn clear(&mut self) {
66        self.node_rects.clear();
67        self.pin_positions.clear();
68        self.non_hit_testable_pins.clear();
69    }
70}
71
72impl<N> GeometryCache<N>
73where
74    N: NodeGeometry + Copy,
75{
76    /// Iterator over absolute pin positions for hit testing
77    pub fn get_absolute_pins(&self) -> impl Iterator<Item = SimplePinGeometry> + '_ {
78        self.pin_positions
79            .iter()
80            .filter(|(pin_id, _)| !self.non_hit_testable_pins.contains(pin_id))
81            .filter_map(move |(&pin_id, pin_pos)| {
82                let rect = self.node_rects.get(&pin_pos.node_id)?.rect();
83                Some(SimplePinGeometry {
84                    id: pin_id,
85                    x: rect.0 + pin_pos.rel_x,
86                    y: rect.1 + pin_pos.rel_y,
87                })
88            })
89    }
90
91    /// Iterator over absolute link geometries for hit testing
92    pub fn get_absolute_links<'a, I>(
93        &'a self,
94        links: I,
95    ) -> impl Iterator<Item = SimpleLinkGeometry> + 'a
96    where
97        I: Iterator<Item = (i32, i32, i32)> + 'a,
98    {
99        links.filter_map(move |(id, start_pin, end_pin)| {
100            let start_pos = self.pin_positions.get(&start_pin)?;
101            let end_pos = self.pin_positions.get(&end_pin)?;
102
103            let start_rect = self.node_rects.get(&start_pos.node_id)?.rect();
104            let end_rect = self.node_rects.get(&end_pos.node_id)?.rect();
105
106            Some(SimpleLinkGeometry {
107                id,
108                start_x: start_rect.0 + start_pos.rel_x,
109                start_y: start_rect.1 + start_pos.rel_y,
110                end_x: end_rect.0 + end_pos.rel_x,
111                end_y: end_rect.1 + end_pos.rel_y,
112            })
113        })
114    }
115
116    /// Find the nearest hit-testable pin at a world-space position.
117    /// Exact distance ties choose the lowest pin ID.
118    pub fn find_pin_at(&self, x: f32, y: f32, hit_radius: f32) -> i32 {
119        find_pin_at(x, y, self.get_absolute_pins(), hit_radius)
120    }
121
122    /// Find link at position
123    #[allow(clippy::too_many_arguments)]
124    pub fn find_link_at<'a, I>(
125        &'a self,
126        x: f32,
127        y: f32,
128        links: I,
129        hover_distance: f32,
130        zoom: f32,
131        bezier_min_offset: f32,
132        hit_samples: usize,
133    ) -> i32
134    where
135        I: Iterator<Item = (i32, i32, i32)> + 'a,
136    {
137        find_link_at(
138            x,
139            y,
140            self.get_absolute_links(links),
141            hover_distance,
142            zoom,
143            bezier_min_offset,
144            hit_samples,
145        )
146    }
147
148    /// Find a default rendered Bézier route in world coordinates.
149    ///
150    /// The mouse position and `world_hover_distance` are both world-space.
151    /// Routes use the same zoom-independent curve as [`Self::link_curve_world`].
152    #[allow(clippy::too_many_arguments)]
153    pub fn find_bezier_link_at_world<'a, I>(
154        &'a self,
155        world_x: f32,
156        world_y: f32,
157        links: I,
158        world_hover_distance: f32,
159        bezier_min_offset: f32,
160        hit_samples: usize,
161    ) -> i32
162    where
163        I: Iterator<Item = (i32, i32, i32)> + 'a,
164    {
165        let routes = links.filter_map(|(id, start_pin, end_pin)| {
166            Some(BezierLinkRoute {
167                id,
168                curve: self.link_curve_world(start_pin, end_pin, bezier_min_offset)?,
169            })
170        });
171        find_link_route_at(
172            (world_x, world_y),
173            routes,
174            world_hover_distance,
175            hit_samples,
176        )
177    }
178
179    /// Compute nodes in selection box
180    pub fn nodes_in_selection_box(&self, x: f32, y: f32, width: f32, height: f32) -> Vec<i32> {
181        nodes_in_selection_box(x, y, width, height, self.node_rects.values().copied())
182    }
183
184    /// Compute links in selection box
185    pub fn links_in_selection_box<'a, I>(
186        &'a self,
187        x: f32,
188        y: f32,
189        width: f32,
190        height: f32,
191        links: I,
192    ) -> Vec<i32>
193    where
194        I: Iterator<Item = (i32, i32, i32)> + 'a,
195    {
196        links_in_selection_box(x, y, width, height, self.get_absolute_links(links))
197    }
198
199    /// Resolve absolute world-space positions for a link's start and end pins.
200    /// Returns `(start_x, start_y, end_x, end_y)` or `None` if pins/nodes are missing.
201    pub fn resolve_link_endpoints_world(
202        &self,
203        start_pin: i32,
204        end_pin: i32,
205    ) -> Option<(f32, f32, f32, f32)> {
206        let start_pos = self.pin_positions.get(&start_pin)?;
207        let end_pos = self.pin_positions.get(&end_pin)?;
208
209        let start_rect = self.node_rects.get(&start_pos.node_id)?.rect();
210        let end_rect = self.node_rects.get(&end_pos.node_id)?.rect();
211
212        Some((
213            start_rect.0 + start_pos.rel_x,
214            start_rect.1 + start_pos.rel_y,
215            end_rect.0 + end_pos.rel_x,
216            end_rect.1 + end_pos.rel_y,
217        ))
218    }
219
220    /// Compute bezier path in world coordinates with explicit zoom for bezier offset scaling.
221    pub fn compute_link_path(
222        &self,
223        start_pin: i32,
224        end_pin: i32,
225        zoom: f32,
226        bezier_min_offset: f32,
227    ) -> Option<String> {
228        let (sx, sy, ex, ey) = self.resolve_link_endpoints_world(start_pin, end_pin)?;
229        Some(generate_bezier_path(
230            sx,
231            sy,
232            ex,
233            ey,
234            zoom,
235            bezier_min_offset,
236        ))
237    }
238
239    /// Compute bezier path in screen space from world-space cache data.
240    ///
241    /// Transforms world positions to screen: `screen = world * zoom + pan`
242    pub fn compute_link_path_screen(
243        &self,
244        start_pin: i32,
245        end_pin: i32,
246        zoom: f32,
247        pan_x: f32,
248        pan_y: f32,
249        bezier_min_offset: f32,
250    ) -> Option<String> {
251        let (sx, sy, ex, ey) = self.resolve_link_endpoints_world(start_pin, end_pin)?;
252        Some(generate_bezier_path(
253            sx * zoom + pan_x,
254            sy * zoom + pan_y,
255            ex * zoom + pan_x,
256            ey * zoom + pan_y,
257            zoom,
258            bezier_min_offset,
259        ))
260    }
261
262    /// The curve of a link in pure world coordinates (zoom = 1.0).
263    ///
264    /// Used when links are rendered inside a transform-scale container
265    /// that handles zoom visually. Bezier offset is unscaled.
266    pub fn link_curve_world(
267        &self,
268        start_pin: i32,
269        end_pin: i32,
270        bezier_min_offset: f32,
271    ) -> Option<CubicBezier> {
272        let (sx, sy, ex, ey) = self.resolve_link_endpoints_world(start_pin, end_pin)?;
273        Some(CubicBezier::from_endpoints(
274            sx,
275            sy,
276            ex,
277            ey,
278            1.0,
279            bezier_min_offset,
280        ))
281    }
282
283    /// Compute bezier path in pure world coordinates (zoom=1.0).
284    pub fn compute_link_path_world(
285        &self,
286        start_pin: i32,
287        end_pin: i32,
288        bezier_min_offset: f32,
289    ) -> Option<String> {
290        Some(
291            self.link_curve_world(start_pin, end_pin, bezier_min_offset)?
292                .commands_from((0.0, 0.0)),
293        )
294    }
295
296    /// Standard handler for pin position reports from Slint
297    pub fn handle_pin_report(
298        &mut self,
299        pin_id: i32,
300        node_id: i32,
301        pin_type: i32,
302        rel_x: f32,
303        rel_y: f32,
304    ) {
305        self.handle_pin_report_with_hit_testable(pin_id, node_id, pin_type, rel_x, rel_y, true);
306    }
307
308    /// Update a pin and whether it participates in pin hit testing.
309    ///
310    /// Non-hit-testable pins remain available for existing link routing and
311    /// validation. This lets a level-of-detail view hide a pin without making
312    /// its logical connections disappear.
313    pub fn handle_pin_report_with_hit_testable(
314        &mut self,
315        pin_id: i32,
316        node_id: i32,
317        pin_type: i32,
318        rel_x: f32,
319        rel_y: f32,
320        hit_testable: bool,
321    ) {
322        self.pin_positions.insert(
323            pin_id,
324            StoredPin {
325                node_id,
326                pin_type,
327                rel_x,
328                rel_y,
329            },
330        );
331        if hit_testable {
332            self.non_hit_testable_pins.remove(&pin_id);
333        } else {
334            self.non_hit_testable_pins.insert(pin_id);
335        }
336    }
337}
338
339/// Convenience implementation for the default SimpleNodeGeometry
340impl GeometryCache<SimpleNodeGeometry> {
341    /// Update a node's rectangle (shorthand for SimpleNodeGeometry)
342    pub fn update_node_rect(&mut self, id: i32, x: f32, y: f32, width: f32, height: f32) {
343        self.node_rects.insert(
344            id,
345            SimpleNodeGeometry {
346                id,
347                x,
348                y,
349                width,
350                height,
351            },
352        );
353    }
354
355    /// Standard handler for node rect reports from Slint (for SimpleNodeGeometry)
356    pub fn handle_node_rect_report(&mut self, id: i32, x: f32, y: f32, w: f32, h: f32) {
357        self.update_node_rect(id, x, y, w, h);
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364
365    /// Helper to create a test cache with two nodes and pins
366    fn setup_test_cache() -> GeometryCache<SimpleNodeGeometry> {
367        let mut cache = GeometryCache::new();
368
369        // Node 1 at (0, 0) with size 100x50
370        cache.update_node_rect(1, 0.0, 0.0, 100.0, 50.0);
371        // Node 2 at (200, 100) with size 100x50
372        cache.update_node_rect(2, 200.0, 100.0, 100.0, 50.0);
373
374        // Pin 1001: output on node 1 at relative (100, 25) -> absolute (100, 25)
375        cache.handle_pin_report(1001, 1, 2, 100.0, 25.0);
376        // Pin 2001: input on node 2 at relative (0, 25) -> absolute (200, 125)
377        cache.handle_pin_report(2001, 2, 1, 0.0, 25.0);
378
379        cache
380    }
381
382    // ========================================================================
383    // GeometryCache::new() and Default
384    // ========================================================================
385
386    #[test]
387    fn test_new_cache_is_empty() {
388        let cache: GeometryCache<SimpleNodeGeometry> = GeometryCache::new();
389        assert!(cache.node_rects.is_empty());
390        assert!(cache.pin_positions.is_empty());
391    }
392
393    #[test]
394    fn test_default_cache_is_empty() {
395        let cache: GeometryCache<SimpleNodeGeometry> = GeometryCache::default();
396        assert!(cache.node_rects.is_empty());
397        assert!(cache.pin_positions.is_empty());
398    }
399
400    // ========================================================================
401    // handle_pin_report() - State Mutation
402    // ========================================================================
403
404    #[test]
405    fn test_handle_pin_report_inserts_pin() {
406        let mut cache: GeometryCache<SimpleNodeGeometry> = GeometryCache::new();
407        cache.handle_pin_report(1001, 1, 2, 50.0, 25.0);
408
409        let pin = cache.pin_positions.get(&1001).expect("Pin should exist");
410        assert_eq!(pin.node_id, 1);
411        assert_eq!(pin.pin_type, 2);
412        assert_eq!(pin.rel_x, 50.0);
413        assert_eq!(pin.rel_y, 25.0);
414    }
415
416    #[test]
417    fn test_handle_pin_report_overwrites_existing() {
418        let mut cache: GeometryCache<SimpleNodeGeometry> = GeometryCache::new();
419        cache.handle_pin_report(1001, 1, 2, 50.0, 25.0);
420        cache.handle_pin_report(1001, 1, 2, 100.0, 30.0); // Update position
421
422        let pin = cache.pin_positions.get(&1001).expect("Pin should exist");
423        assert_eq!(pin.rel_x, 100.0);
424        assert_eq!(pin.rel_y, 30.0);
425    }
426
427    #[test]
428    fn test_handle_pin_report_negative_coordinates() {
429        let mut cache: GeometryCache<SimpleNodeGeometry> = GeometryCache::new();
430        cache.handle_pin_report(1001, 1, 2, -10.0, -20.0);
431
432        let pin = cache.pin_positions.get(&1001).expect("Pin should exist");
433        assert_eq!(pin.rel_x, -10.0);
434        assert_eq!(pin.rel_y, -20.0);
435    }
436
437    #[test]
438    fn remove_pin_retires_its_geometry() {
439        let mut cache = setup_test_cache();
440
441        assert!(cache.remove_pin(1001));
442        assert!(!cache.remove_pin(1001));
443        assert!(!cache.pin_positions.contains_key(&1001));
444    }
445
446    #[test]
447    fn remove_node_cascades_to_owned_pins() {
448        let mut cache = setup_test_cache();
449
450        let removed_pins = cache.remove_node(1);
451
452        assert_eq!(removed_pins, vec![1001]);
453        assert!(!cache.node_rects.contains_key(&1));
454        assert!(!cache.pin_positions.contains_key(&1001));
455        assert!(cache.node_rects.contains_key(&2));
456        assert!(cache.pin_positions.contains_key(&2001));
457    }
458
459    #[test]
460    fn clear_removes_all_projected_geometry() {
461        let mut cache = setup_test_cache();
462
463        cache.clear();
464
465        assert!(cache.node_rects.is_empty());
466        assert!(cache.pin_positions.is_empty());
467    }
468
469    #[test]
470    fn hidden_pin_routes_but_is_not_hit_testable() {
471        let mut cache = setup_test_cache();
472        cache.handle_pin_report_with_hit_testable(1001, 1, 2, 100.0, 25.0, false);
473
474        assert_eq!(cache.find_pin_at(100.0, 25.0, 10.0), 0);
475        assert!(cache.compute_link_path_world(1001, 2001, 50.0).is_some());
476    }
477
478    // ========================================================================
479    // update_node_rect() - State Mutation
480    // ========================================================================
481
482    #[test]
483    fn test_update_node_rect_inserts_node() {
484        let mut cache = GeometryCache::new();
485        cache.update_node_rect(1, 10.0, 20.0, 100.0, 50.0);
486
487        let node = cache.node_rects.get(&1).expect("Node should exist");
488        assert_eq!(node.id, 1);
489        assert_eq!(node.x, 10.0);
490        assert_eq!(node.y, 20.0);
491        assert_eq!(node.width, 100.0);
492        assert_eq!(node.height, 50.0);
493    }
494
495    #[test]
496    fn test_update_node_rect_overwrites_existing() {
497        let mut cache = GeometryCache::new();
498        cache.update_node_rect(1, 10.0, 20.0, 100.0, 50.0);
499        cache.update_node_rect(1, 50.0, 60.0, 150.0, 80.0);
500
501        let node = cache.node_rects.get(&1).expect("Node should exist");
502        assert_eq!(node.x, 50.0);
503        assert_eq!(node.y, 60.0);
504        assert_eq!(node.width, 150.0);
505        assert_eq!(node.height, 80.0);
506    }
507
508    #[test]
509    fn test_update_node_rect_negative_coordinates() {
510        let mut cache = GeometryCache::new();
511        cache.update_node_rect(1, -100.0, -200.0, 100.0, 50.0);
512
513        let node = cache.node_rects.get(&1).expect("Node should exist");
514        assert_eq!(node.x, -100.0);
515        assert_eq!(node.y, -200.0);
516    }
517
518    // ========================================================================
519    // get_absolute_pins() - Coordinate Transformation
520    // ========================================================================
521
522    #[test]
523    fn test_get_absolute_pins_returns_absolute_positions() {
524        let cache = setup_test_cache();
525        let pins: Vec<SimplePinGeometry> = cache.get_absolute_pins().collect();
526
527        // Find pin 1001: node at (0,0) + rel (100, 25) = (100, 25)
528        let pin1 = pins
529            .iter()
530            .find(|p| p.id == 1001)
531            .expect("Pin 1001 should exist");
532        assert_eq!(pin1.x, 100.0);
533        assert_eq!(pin1.y, 25.0);
534
535        // Find pin 2001: node at (200, 100) + rel (0, 25) = (200, 125)
536        let pin2 = pins
537            .iter()
538            .find(|p| p.id == 2001)
539            .expect("Pin 2001 should exist");
540        assert_eq!(pin2.x, 200.0);
541        assert_eq!(pin2.y, 125.0);
542    }
543
544    #[test]
545    fn test_get_absolute_pins_skips_orphan_pins() {
546        let mut cache = setup_test_cache();
547        // Add a pin referencing non-existent node
548        cache.handle_pin_report(9999, 999, 1, 50.0, 25.0);
549
550        let pins: Vec<SimplePinGeometry> = cache.get_absolute_pins().collect();
551
552        // Should only have 2 valid pins, orphan is skipped
553        assert_eq!(pins.len(), 2);
554        assert!(!pins.iter().any(|p| p.id == 9999));
555    }
556
557    #[test]
558    fn test_get_absolute_pins_empty_cache() {
559        let cache: GeometryCache<SimpleNodeGeometry> = GeometryCache::new();
560        let pins: Vec<SimplePinGeometry> = cache.get_absolute_pins().collect();
561        assert!(pins.is_empty());
562    }
563
564    #[test]
565    fn test_get_absolute_pins_node_at_negative_coords() {
566        let mut cache = GeometryCache::new();
567        cache.update_node_rect(1, -100.0, -50.0, 100.0, 50.0);
568        cache.handle_pin_report(1001, 1, 2, 50.0, 25.0);
569
570        let pins: Vec<SimplePinGeometry> = cache.get_absolute_pins().collect();
571        let pin = pins
572            .iter()
573            .find(|p| p.id == 1001)
574            .expect("Pin should exist");
575        assert_eq!(pin.x, -50.0); // -100 + 50
576        assert_eq!(pin.y, -25.0); // -50 + 25
577    }
578
579    // ========================================================================
580    // get_absolute_links() - Complex Transformation
581    // ========================================================================
582
583    #[test]
584    fn test_get_absolute_links_returns_absolute_positions() {
585        let cache = setup_test_cache();
586        let links_data = vec![(1, 1001, 2001)]; // (id, start_pin, end_pin)
587        let links: Vec<SimpleLinkGeometry> =
588            cache.get_absolute_links(links_data.into_iter()).collect();
589
590        assert_eq!(links.len(), 1);
591        let link = &links[0];
592        assert_eq!(link.id, 1);
593        // Start: pin 1001 -> (100, 25)
594        assert_eq!(link.start_x, 100.0);
595        assert_eq!(link.start_y, 25.0);
596        // End: pin 2001 -> (200, 125)
597        assert_eq!(link.end_x, 200.0);
598        assert_eq!(link.end_y, 125.0);
599    }
600
601    #[test]
602    fn test_get_absolute_links_skips_missing_start_pin() {
603        let cache = setup_test_cache();
604        let links_data = vec![(1, 9999, 2001)]; // Missing start pin
605        let links: Vec<SimpleLinkGeometry> =
606            cache.get_absolute_links(links_data.into_iter()).collect();
607
608        assert!(links.is_empty());
609    }
610
611    #[test]
612    fn test_get_absolute_links_skips_missing_end_pin() {
613        let cache = setup_test_cache();
614        let links_data = vec![(1, 1001, 9999)]; // Missing end pin
615        let links: Vec<SimpleLinkGeometry> =
616            cache.get_absolute_links(links_data.into_iter()).collect();
617
618        assert!(links.is_empty());
619    }
620
621    #[test]
622    fn test_get_absolute_links_skips_missing_start_node() {
623        let mut cache = setup_test_cache();
624        // Add pin referencing non-existent node
625        cache.pin_positions.insert(
626            3001,
627            StoredPin {
628                node_id: 999,
629                pin_type: 1,
630                rel_x: 0.0,
631                rel_y: 25.0,
632            },
633        );
634
635        let links_data = vec![(1, 3001, 2001)];
636        let links: Vec<SimpleLinkGeometry> =
637            cache.get_absolute_links(links_data.into_iter()).collect();
638
639        assert!(links.is_empty());
640    }
641
642    #[test]
643    fn test_get_absolute_links_empty_input() {
644        let cache = setup_test_cache();
645        let links_data: Vec<(i32, i32, i32)> = vec![];
646        let links: Vec<SimpleLinkGeometry> =
647            cache.get_absolute_links(links_data.into_iter()).collect();
648
649        assert!(links.is_empty());
650    }
651
652    #[test]
653    fn test_get_absolute_links_multiple_links() {
654        let mut cache = setup_test_cache();
655        // Add another pin on node 2
656        cache.handle_pin_report(2002, 2, 1, 0.0, 40.0);
657
658        let links_data = vec![(1, 1001, 2001), (2, 1001, 2002)];
659        let links: Vec<SimpleLinkGeometry> =
660            cache.get_absolute_links(links_data.into_iter()).collect();
661
662        assert_eq!(links.len(), 2);
663    }
664
665    // ========================================================================
666    // compute_link_path() - Bezier Path Generation
667    // ========================================================================
668
669    #[test]
670    fn test_compute_link_path_returns_valid_svg() {
671        let cache = setup_test_cache();
672        let path = cache
673            .compute_link_path(1001, 2001, 1.0, 50.0)
674            .expect("Path should be generated");
675
676        assert!(path.starts_with("M "));
677        assert!(path.contains(" C "));
678    }
679
680    #[test]
681    fn test_compute_link_path_returns_none_for_missing_start_pin() {
682        let cache = setup_test_cache();
683        let path = cache.compute_link_path(9999, 2001, 1.0, 50.0);
684        assert!(path.is_none());
685    }
686
687    #[test]
688    fn test_compute_link_path_returns_none_for_missing_end_pin() {
689        let cache = setup_test_cache();
690        let path = cache.compute_link_path(1001, 9999, 1.0, 50.0);
691        assert!(path.is_none());
692    }
693
694    #[test]
695    fn test_compute_link_path_returns_none_for_missing_start_node() {
696        let mut cache = setup_test_cache();
697        cache.pin_positions.insert(
698            3001,
699            StoredPin {
700                node_id: 999,
701                pin_type: 1,
702                rel_x: 0.0,
703                rel_y: 25.0,
704            },
705        );
706
707        let path = cache.compute_link_path(3001, 2001, 1.0, 50.0);
708        assert!(path.is_none());
709    }
710
711    #[test]
712    fn test_compute_link_path_different_zoom_levels() {
713        let cache = setup_test_cache();
714
715        let path1 = cache.compute_link_path(1001, 2001, 1.0, 50.0).unwrap();
716        let path2 = cache.compute_link_path(1001, 2001, 2.0, 50.0).unwrap();
717
718        // Different zoom should produce different paths
719        assert_ne!(path1, path2);
720    }
721
722    // ========================================================================
723    // find_pin_at() - Delegated Hit Testing
724    // ========================================================================
725
726    #[test]
727    fn test_find_pin_at_hits_pin() {
728        let cache = setup_test_cache();
729        // Pin 1001 is at (100, 25)
730        let pin_id = cache.find_pin_at(102.0, 27.0, 10.0);
731        assert_eq!(pin_id, 1001);
732    }
733
734    #[test]
735    fn test_find_pin_at_misses_all() {
736        let cache = setup_test_cache();
737        let pin_id = cache.find_pin_at(500.0, 500.0, 10.0);
738        assert_eq!(pin_id, 0);
739    }
740
741    // ========================================================================
742    // nodes_in_selection_box() - Selection Box Query
743    // ========================================================================
744
745    #[test]
746    fn test_nodes_in_selection_box_finds_intersecting() {
747        let cache = setup_test_cache();
748        // Node 1 is at (0, 0) with size 100x50
749        // Selection box covering it
750        let selected = cache.nodes_in_selection_box(0.0, 0.0, 50.0, 50.0);
751        assert!(selected.contains(&1));
752    }
753
754    #[test]
755    fn test_nodes_in_selection_box_excludes_non_intersecting() {
756        let cache = setup_test_cache();
757        // Selection box that doesn't cover node 1 (at 0,0) or node 2 (at 200,100)
758        let selected = cache.nodes_in_selection_box(500.0, 500.0, 50.0, 50.0);
759        assert!(selected.is_empty());
760    }
761
762    // ========================================================================
763    // links_in_selection_box() - Link Selection Query
764    // ========================================================================
765
766    #[test]
767    fn test_links_in_selection_box_finds_link_with_start_inside() {
768        let cache = setup_test_cache();
769        let links_data = vec![(1, 1001, 2001)];
770
771        // Selection box covering pin 1001 position (100, 25)
772        let selected = cache.links_in_selection_box(90.0, 15.0, 20.0, 20.0, links_data.into_iter());
773        assert!(selected.contains(&1));
774    }
775
776    #[test]
777    fn test_links_in_selection_box_excludes_link_outside() {
778        let cache = setup_test_cache();
779        let links_data = vec![(1, 1001, 2001)];
780
781        // Selection box not covering either pin
782        let selected =
783            cache.links_in_selection_box(500.0, 500.0, 50.0, 50.0, links_data.into_iter());
784        assert!(selected.is_empty());
785    }
786
787    // ========================================================================
788    // compute_link_path_screen() - World→Screen Path Generation
789    // ========================================================================
790
791    #[test]
792    fn test_compute_link_path_screen_zoom1_pan0() {
793        let cache = setup_test_cache();
794        // At zoom=1, pan=0 the screen-space path should equal
795        // node_world + pin_rel (same as compute_link_path at zoom=1)
796        let path = cache
797            .compute_link_path_screen(1001, 2001, 1.0, 0.0, 0.0, 50.0)
798            .expect("Path should be generated");
799        assert!(path.starts_with("M "));
800        assert!(path.contains(" C "));
801    }
802
803    #[test]
804    fn test_compute_link_path_screen_with_pan() {
805        let cache = setup_test_cache();
806        // With pan offset, paths should differ from zero-pan
807        let path_no_pan = cache
808            .compute_link_path_screen(1001, 2001, 1.0, 0.0, 0.0, 50.0)
809            .unwrap();
810        let path_with_pan = cache
811            .compute_link_path_screen(1001, 2001, 1.0, 100.0, 50.0, 50.0)
812            .unwrap();
813        assert_ne!(path_no_pan, path_with_pan);
814    }
815
816    #[test]
817    fn test_compute_link_path_screen_with_zoom() {
818        let cache = setup_test_cache();
819        let path_z1 = cache
820            .compute_link_path_screen(1001, 2001, 1.0, 0.0, 0.0, 50.0)
821            .unwrap();
822        let path_z2 = cache
823            .compute_link_path_screen(1001, 2001, 2.0, 0.0, 0.0, 50.0)
824            .unwrap();
825        assert_ne!(path_z1, path_z2);
826    }
827
828    #[test]
829    fn test_compute_link_path_screen_missing_pin() {
830        let cache = setup_test_cache();
831        assert!(cache
832            .compute_link_path_screen(9999, 2001, 1.0, 0.0, 0.0, 50.0)
833            .is_none());
834    }
835}