Skip to main content

slint_node_editor/
controller.rs

1//! High-level controller for node editor applications.
2//!
3//! The [`NodeEditorController`] reduces boilerplate by managing geometry tracking,
4//! link path computation, and viewport state in one place.
5//!
6//! # Standard integration
7//!
8//! Construct a [`crate::NodeEditorSetup`] and pass it to
9//! [`crate::wire_node_editor!`]. The macro installs this controller's geometry,
10//! computation, viewport and grid handlers on the generated Slint globals. Its
11//! callback replacement rules and required generated members are documented in
12//! the crate README. The repository's
13//! [compiled quick start](https://github.com/tilladam/slint-node-editor/tree/main/smoke/downstream)
14//! demonstrates model-owned selection, movement, connection and deletion.
15
16use crate::hit_test::{NodeGeometry, SimpleLinkGeometry};
17use crate::state::GeometryCache;
18use slint::SharedString;
19use std::cell::RefCell;
20use std::collections::{HashMap, HashSet};
21use std::rc::Rc;
22
23/// Viewport and configuration state, behind a single `Rc<RefCell<_>>`.
24///
25/// The geometry cache is kept separate (its own `Rc<RefCell<_>>`) because
26/// it is exposed to callers via [`NodeEditorController::cache()`].
27struct ViewportState {
28    zoom: f32,
29    pan_x: f32,
30    pan_y: f32,
31    bezier_offset: f32,
32    dragged_node_id: i32,
33    grid_spacing: f32,
34    /// Links registered for hit testing, keyed by link ID.
35    links: HashMap<i32, (i32, i32)>,
36}
37
38impl ViewportState {
39    fn new() -> Self {
40        Self {
41            zoom: 1.0,
42            pan_x: 0.0,
43            pan_y: 0.0,
44            bezier_offset: 50.0,
45            dragged_node_id: 0,
46            grid_spacing: 24.0,
47            links: HashMap::new(),
48        }
49    }
50
51    /// Clamp zoom to a safe positive value.
52    fn safe_zoom(&self) -> f32 {
53        if self.zoom.is_finite() && self.zoom > 0.0 {
54            self.zoom
55        } else {
56            1.0
57        }
58    }
59}
60
61/// Controller that manages node editor state and provides callback implementations.
62///
63/// This provides a high-level API that handles:
64/// - Geometry caching (node rects, pin positions) in **world space**
65/// - Link path computation (world→screen conversion done internally)
66/// - Hit testing facades (screen-space input, world-space internals)
67/// - Viewport/zoom/pan tracking
68/// - Drag tracking
69///
70/// The cache stores node rects in world coordinates, which are invariant to
71/// zoom/pan changes. This eliminates the O(N) viewport resync loop that was
72/// previously needed when zoom or pan changed.
73///
74/// Clone this controller to share it across callbacks.
75#[derive(Clone)]
76pub struct NodeEditorController {
77    cache: Rc<RefCell<GeometryCache>>,
78    state: Rc<RefCell<ViewportState>>,
79}
80
81impl Default for NodeEditorController {
82    fn default() -> Self {
83        Self::new()
84    }
85}
86
87impl NodeEditorController {
88    /// Create a new controller with default settings.
89    pub fn new() -> Self {
90        Self {
91            cache: Rc::new(RefCell::new(GeometryCache::new())),
92            state: Rc::new(RefCell::new(ViewportState::new())),
93        }
94    }
95
96    /// Set the bezier curve offset for link paths (default: 50.0).
97    pub fn set_bezier_offset(&self, offset: f32) {
98        self.state.borrow_mut().bezier_offset = offset;
99    }
100
101    /// Get the bezier curve offset used for rendered link paths.
102    pub fn bezier_offset(&self) -> f32 {
103        self.state.borrow().bezier_offset
104    }
105
106    /// Set the grid spacing (default: 24.0).
107    pub fn set_grid_spacing(&self, spacing: f32) {
108        self.state.borrow_mut().grid_spacing = spacing;
109    }
110
111    /// Get the grid spacing used by grid generation.
112    pub fn grid_spacing(&self) -> f32 {
113        self.state.borrow().grid_spacing
114    }
115
116    /// Get the current zoom level.
117    pub fn zoom(&self) -> f32 {
118        self.state.borrow().zoom
119    }
120
121    /// Convert a screen-space distance in pixels to world-space units.
122    pub fn screen_distance_to_world(&self, screen_distance: f32) -> f32 {
123        screen_distance / self.state.borrow().safe_zoom()
124    }
125
126    /// Get access to the geometry cache.
127    pub fn cache(&self) -> Rc<RefCell<GeometryCache>> {
128        self.cache.clone()
129    }
130
131    /// Get the ID of the node currently being dragged (0 if none).
132    pub fn dragged_node_id(&self) -> i32 {
133        self.state.borrow().dragged_node_id
134    }
135
136    // === Callback factories ===
137
138    /// Returns a callback for `compute-link-path`.
139    ///
140    /// Computes bezier paths for use inside a scaled container at origin.
141    /// Positions are calculated so that after transform-scale, links appear at correct screen position.
142    ///
143    /// `make_path` receives box-relative commands and the box, and builds the
144    /// `LinkPath` the callback expects — see
145    /// [`CubicBezier::to_link_path`](crate::path::CubicBezier::to_link_path)
146    /// for why the type is not named here. A link whose pins are not in the
147    /// cache yet yields `T::default()`, an empty path at the origin.
148    pub fn compute_link_path_callback<T: Default>(
149        &self,
150        make_path: impl Fn(String, f32, f32, f32, f32) -> T,
151    ) -> impl Fn(i32, i32, i32) -> T {
152        let cache = self.cache.clone();
153        let state = self.state.clone();
154        move |start_pin, end_pin, _version| {
155            let s = state.borrow();
156            match cache
157                .borrow()
158                .link_curve_world(start_pin, end_pin, s.bezier_offset)
159            {
160                Some(curve) => curve.to_link_path(&make_path),
161                None => T::default(),
162            }
163        }
164    }
165
166    /// Returns a callback for `node-drag-started`.
167    pub fn node_drag_started_callback(&self) -> impl Fn(i32) {
168        let state = self.state.clone();
169        move |node_id| {
170            state.borrow_mut().dragged_node_id = node_id;
171        }
172    }
173
174    // === Direct handlers ===
175
176    /// Update cached node rectangle (world coordinates).
177    pub fn handle_node_rect(&self, id: i32, x: f32, y: f32, w: f32, h: f32) {
178        self.cache
179            .borrow_mut()
180            .handle_node_rect_report(id, x, y, w, h);
181    }
182
183    /// Handle a world-space pin geometry report by updating the cache.
184    ///
185    /// The Slint `Pin` component reports `rel_x`/`rel_y` as **world-space**
186    /// offsets relative to the node origin. The Pin component divides by zoom
187    /// internally (`center-x: (self.x + self.width / 2) / zoom`), so the
188    /// values received here are already zoom-invariant.
189    pub fn handle_pin_position(&self, pid: i32, nid: i32, ptype: i32, x: f32, y: f32) {
190        self.cache
191            .borrow_mut()
192            .handle_pin_report(pid, nid, ptype, x, y);
193    }
194
195    /// Update cached pin geometry and its pin-picking eligibility.
196    pub fn handle_pin_position_with_hit_testable(
197        &self,
198        pid: i32,
199        nid: i32,
200        ptype: i32,
201        x: f32,
202        y: f32,
203        hit_testable: bool,
204    ) {
205        self.cache.borrow_mut().handle_pin_report_with_hit_testable(
206            pid,
207            nid,
208            ptype,
209            x,
210            y,
211            hit_testable,
212        );
213    }
214
215    /// Seed a node's world-space rect directly, bypassing screen→world conversion.
216    ///
217    /// Use this to pre-populate the geometry cache for nodes that haven't been
218    /// rendered by Slint yet (e.g. off-screen nodes whose link endpoints are
219    /// visible). The coordinates must be in world space. Direct seeding bypasses
220    /// the component geometry-reporting lifecycle; after seeding a batch, call
221    /// `NodeEditor.refresh-links()` once to invalidate existing route bindings.
222    pub fn seed_node_world_rect(&self, id: i32, x: f32, y: f32, w: f32, h: f32) {
223        self.cache
224            .borrow_mut()
225            .handle_node_rect_report(id, x, y, w, h);
226    }
227
228    /// Handle node-drag-started: track the dragged node.
229    pub fn handle_node_drag_started(&self, node_id: i32) {
230        self.state.borrow_mut().dragged_node_id = node_id;
231    }
232
233    /// Clear controller state after a drag ends or is cancelled.
234    pub fn handle_node_drag_finished(&self) {
235        self.state.borrow_mut().dragged_node_id = 0;
236    }
237
238    /// Set the zoom level (called from update-viewport).
239    #[deprecated(
240        since = "0.2.0",
241        note = "Use set_viewport() which also updates pan state"
242    )]
243    pub fn set_zoom(&self, zoom: f32) {
244        if zoom.is_finite() && zoom > 0.0 {
245            self.state.borrow_mut().zoom = zoom;
246        }
247    }
248
249    /// Set viewport state: zoom, pan_x, pan_y.
250    /// Invalid updates (nonfinite values or nonpositive zoom) are ignored atomically.
251    ///
252    /// Since the cache stores world-space coordinates, changing zoom/pan
253    /// requires no per-node updates.
254    pub fn set_viewport(&self, zoom: f32, pan_x: f32, pan_y: f32) {
255        if !zoom.is_finite() || zoom <= 0.0 || !pan_x.is_finite() || !pan_y.is_finite() {
256            return;
257        }
258        let mut s = self.state.borrow_mut();
259        s.zoom = zoom;
260        s.pan_x = pan_x;
261        s.pan_y = pan_y;
262    }
263
264    /// Register a link for hit testing. Idempotent: re-registering the same ID
265    /// updates the pin pair.
266    pub fn register_link(&self, id: i32, start_pin: i32, end_pin: i32) {
267        self.state
268            .borrow_mut()
269            .links
270            .insert(id, (start_pin, end_pin));
271    }
272
273    /// Unregister a link by ID.
274    pub fn unregister_link(&self, id: i32) {
275        self.state.borrow_mut().links.remove(&id);
276    }
277
278    /// Clear all registered links.
279    pub fn clear_links(&self) {
280        self.state.borrow_mut().links.clear();
281    }
282
283    /// Remove a pin and any registered hit-test links incident on it.
284    pub fn remove_pin(&self, pin_id: i32) -> bool {
285        let removed = self.cache.borrow_mut().remove_pin(pin_id);
286        self.state
287            .borrow_mut()
288            .links
289            .retain(|_, pins| pins.0 != pin_id && pins.1 != pin_id);
290        removed
291    }
292
293    /// Remove a node, its pins, and registered hit-test links using those pins.
294    pub fn remove_node(&self, node_id: i32) -> Vec<i32> {
295        let removed_pins = self.cache.borrow_mut().remove_node(node_id);
296        let removed_pin_set: HashSet<_> = removed_pins.iter().copied().collect();
297        let mut state = self.state.borrow_mut();
298        state.links.retain(|_, pins| {
299            !removed_pin_set.contains(&pins.0) && !removed_pin_set.contains(&pins.1)
300        });
301        if state.dragged_node_id == node_id {
302            state.dragged_node_id = 0;
303        }
304        removed_pins
305    }
306
307    /// Reset geometry and controller-owned topology for a graph switch.
308    pub fn reset_graph(&self) {
309        self.cache.borrow_mut().clear();
310        let mut state = self.state.borrow_mut();
311        state.links.clear();
312        state.dragged_node_id = 0;
313    }
314
315    /// Clear only the geometry cache (node rects and pin positions).
316    ///
317    /// Use [`Self::reset_graph`] when switching graphs so registered hit-test
318    /// links and drag state are retired as well.
319    pub fn clear_geometry(&self) {
320        self.cache.borrow_mut().clear();
321    }
322
323    /// Compute link path for given pins (screen-space output from world-space cache).
324    pub fn compute_link_path(&self, start_pin: i32, end_pin: i32) -> SharedString {
325        let s = self.state.borrow();
326        self.cache
327            .borrow()
328            .compute_link_path_screen(
329                start_pin,
330                end_pin,
331                s.zoom,
332                s.pan_x,
333                s.pan_y,
334                s.bezier_offset,
335            )
336            .unwrap_or_default()
337            .into()
338    }
339
340    /// Generate grid commands for current viewport.
341    pub fn generate_grid(&self, width: f32, height: f32, pan_x: f32, pan_y: f32) -> SharedString {
342        let s = self.state.borrow();
343        crate::generate_grid_commands(width, height, s.zoom, pan_x, pan_y, s.grid_spacing).into()
344    }
345
346    /// Generate grid commands from the controller's current viewport and spacing.
347    pub fn generate_current_grid(&self, width: f32, height: f32) -> SharedString {
348        let s = self.state.borrow();
349        crate::generate_grid_commands(width, height, s.zoom, s.pan_x, s.pan_y, s.grid_spacing)
350            .into()
351    }
352
353    /// Generate initial grid commands (zoom=1, pan=0).
354    pub fn generate_initial_grid(&self, width: f32, height: f32) -> SharedString {
355        let spacing = self.state.borrow().grid_spacing;
356        crate::generate_grid_commands(width, height, 1.0, 0.0, 0.0, spacing).into()
357    }
358
359    // === Hit-testing facades ===
360
361    /// Find the link closest to the given world-space position.
362    ///
363    /// Returns the link ID, or -1 if no link is within
364    /// `world_hover_distance`. The route is the same zoom-independent world
365    /// curve produced by the standard renderer callback.
366    pub fn find_link_at_world(
367        &self,
368        world_x: f32,
369        world_y: f32,
370        world_hover_distance: f32,
371        bezier_min_offset: f32,
372        hit_samples: usize,
373    ) -> i32 {
374        let s = self.state.borrow();
375        let cache = self.cache.borrow();
376        let links = s
377            .links
378            .iter()
379            .map(|(&id, &(start_pin, end_pin))| (id, start_pin, end_pin));
380        cache.find_bezier_link_at_world(
381            world_x,
382            world_y,
383            links,
384            world_hover_distance,
385            bezier_min_offset,
386            hit_samples,
387        )
388    }
389
390    /// Find the link closest to the given screen-space position.
391    ///
392    /// Returns the link ID, or -1 if no link is within the screen-pixel
393    /// `screen_hover_distance`. Converts the point and tolerance to world space
394    /// once, then tests the same world curve used for rendering.
395    pub fn find_link_at_screen(
396        &self,
397        mouse_x: f32,
398        mouse_y: f32,
399        screen_hover_distance: f32,
400        bezier_min_offset: f32,
401        hit_samples: usize,
402    ) -> i32 {
403        let s = self.state.borrow();
404        let zoom = s.safe_zoom();
405        let pan_x = s.pan_x;
406        let pan_y = s.pan_y;
407        drop(s);
408
409        let world_x = (mouse_x - pan_x) / zoom;
410        let world_y = (mouse_y - pan_y) / zoom;
411        let world_hover_distance = screen_hover_distance / zoom;
412        self.find_link_at_world(
413            world_x,
414            world_y,
415            world_hover_distance,
416            bezier_min_offset,
417            hit_samples,
418        )
419    }
420
421    /// Find the pin closest to the given screen-space position.
422    ///
423    /// Returns the nearest hit-testable pin ID, or 0 if no pin is within
424    /// `hit_radius`. Exact distance ties choose the lowest pin ID.
425    pub fn find_pin_at_screen(&self, mouse_x: f32, mouse_y: f32, hit_radius: f32) -> i32 {
426        let s = self.state.borrow();
427        let zoom = s.safe_zoom();
428        let pan_x = s.pan_x;
429        let pan_y = s.pan_y;
430        drop(s);
431        let cache = self.cache.borrow();
432
433        let pins = cache.get_absolute_pins().map(|pin| {
434            // World→screen: pin_world * zoom + pan
435            let sx = pin.x * zoom + pan_x;
436            let sy = pin.y * zoom + pan_y;
437            crate::hit_test::SimplePinGeometry {
438                id: pin.id,
439                x: sx,
440                y: sy,
441            }
442        });
443
444        crate::hit_test::find_pin_at(mouse_x, mouse_y, pins, hit_radius)
445    }
446
447    /// Find all nodes whose world-space rect intersects the given screen-space selection box.
448    ///
449    /// Converts the selection box from screen→world and performs AABB intersection.
450    pub fn nodes_in_selection_box_screen(&self, sx: f32, sy: f32, sw: f32, sh: f32) -> Vec<i32> {
451        let s = self.state.borrow();
452        let z = s.safe_zoom();
453        let world_x = (sx - s.pan_x) / z;
454        let world_y = (sy - s.pan_y) / z;
455        let world_w = sw / z;
456        let world_h = sh / z;
457        drop(s);
458
459        self.cache
460            .borrow()
461            .nodes_in_selection_box(world_x, world_y, world_w, world_h)
462    }
463
464    /// Find all links that have at least one endpoint inside the given world-space selection box.
465    pub fn links_in_selection_box_world(
466        &self,
467        world_x: f32,
468        world_y: f32,
469        world_w: f32,
470        world_h: f32,
471    ) -> Vec<i32> {
472        let s = self.state.borrow();
473        let cache = self.cache.borrow();
474
475        // Compute world-space link endpoints: node_world + pin_rel
476        let link_geometries = s.links.iter().filter_map(|(&id, &(start_pin, end_pin))| {
477            let start_pos = cache.pin_positions.get(&start_pin)?;
478            let end_pos = cache.pin_positions.get(&end_pin)?;
479            let start_rect = cache.node_rects.get(&start_pos.node_id)?.rect();
480            let end_rect = cache.node_rects.get(&end_pos.node_id)?.rect();
481
482            Some(SimpleLinkGeometry {
483                id,
484                start_x: start_rect.0 + start_pos.rel_x,
485                start_y: start_rect.1 + start_pos.rel_y,
486                end_x: end_rect.0 + end_pos.rel_x,
487                end_y: end_rect.1 + end_pos.rel_y,
488            })
489        });
490
491        crate::hit_test::links_in_selection_box(world_x, world_y, world_w, world_h, link_geometries)
492    }
493
494    /// Find all links that have at least one endpoint inside the given screen-space selection box.
495    ///
496    /// Converts the box from screen→world and delegates to [`links_in_selection_box_world`](Self::links_in_selection_box_world).
497    pub fn links_in_selection_box_screen(&self, sx: f32, sy: f32, sw: f32, sh: f32) -> Vec<i32> {
498        let s = self.state.borrow();
499        let z = s.safe_zoom();
500        let world_x = (sx - s.pan_x) / z;
501        let world_y = (sy - s.pan_y) / z;
502        let world_w = sw / z;
503        let world_h = sh / z;
504        drop(s);
505
506        self.links_in_selection_box_world(world_x, world_y, world_w, world_h)
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    #[allow(deprecated)]
513    use super::*;
514    use crate::hit_test::NodeGeometry;
515
516    /// Helper: set up a controller with two nodes and pins, suitable for hit testing.
517    fn setup_controller() -> NodeEditorController {
518        let ctrl = NodeEditorController::new();
519        ctrl.set_viewport(1.0, 0.0, 0.0);
520
521        {
522            let mut cache = ctrl.cache.borrow_mut();
523            // Node 1 at world (0, 0), 100x50
524            cache.handle_node_rect_report(1, 0.0, 0.0, 100.0, 50.0);
525            // Node 2 at world (200, 100), 100x50
526            cache.handle_node_rect_report(2, 200.0, 100.0, 100.0, 50.0);
527            // Pin 1001: output on node 1 at world-relative (100, 25)
528            cache.handle_pin_report(1001, 1, 2, 100.0, 25.0);
529            // Pin 2001: input on node 2 at world-relative (0, 25)
530            cache.handle_pin_report(2001, 2, 1, 0.0, 25.0);
531        }
532
533        // Register a link between the pins
534        ctrl.register_link(1, 1001, 2001);
535        ctrl
536    }
537
538    fn setup_controller_with_link(start: (f32, f32), end: (f32, f32)) -> NodeEditorController {
539        let ctrl = NodeEditorController::new();
540        ctrl.handle_node_rect(1, start.0, start.1, 1.0, 1.0);
541        ctrl.handle_node_rect(2, end.0, end.1, 1.0, 1.0);
542        ctrl.handle_pin_position(1, 1, 2, 0.0, 0.0);
543        ctrl.handle_pin_position(2, 2, 1, 0.0, 0.0);
544        ctrl.register_link(7, 1, 2);
545        ctrl
546    }
547
548    // ========================================================================
549    // Construction and basic accessors
550    // ========================================================================
551
552    #[test]
553    fn test_new_defaults() {
554        let ctrl = NodeEditorController::new();
555        assert_eq!(ctrl.zoom(), 1.0);
556        assert_eq!(ctrl.dragged_node_id(), 0);
557    }
558
559    #[test]
560    fn test_set_viewport() {
561        let ctrl = NodeEditorController::new();
562        ctrl.set_viewport(2.0, 10.0, 20.0);
563        assert_eq!(ctrl.zoom(), 2.0);
564        let s = ctrl.state.borrow();
565        assert_eq!(s.pan_x, 10.0);
566        assert_eq!(s.pan_y, 20.0);
567    }
568
569    #[test]
570    #[allow(deprecated)]
571    fn test_set_zoom_deprecated_still_works() {
572        let ctrl = NodeEditorController::new();
573        ctrl.set_zoom(3.0);
574        assert_eq!(ctrl.zoom(), 3.0);
575    }
576
577    // ========================================================================
578    // Link registration (HashMap-based, idempotent)
579    // ========================================================================
580
581    #[test]
582    fn test_register_link_idempotent() {
583        let ctrl = NodeEditorController::new();
584        ctrl.register_link(1, 100, 200);
585        ctrl.register_link(1, 100, 200); // duplicate
586        assert_eq!(ctrl.state.borrow().links.len(), 1);
587    }
588
589    #[test]
590    fn test_register_link_updates_pins() {
591        let ctrl = NodeEditorController::new();
592        ctrl.register_link(1, 100, 200);
593        ctrl.register_link(1, 300, 400); // same ID, different pins
594        let s = ctrl.state.borrow();
595        assert_eq!(s.links.get(&1), Some(&(300, 400)));
596    }
597
598    #[test]
599    fn test_unregister_link() {
600        let ctrl = NodeEditorController::new();
601        ctrl.register_link(1, 100, 200);
602        ctrl.unregister_link(1);
603        assert!(ctrl.state.borrow().links.is_empty());
604    }
605
606    #[test]
607    fn test_clear_links() {
608        let ctrl = NodeEditorController::new();
609        ctrl.register_link(1, 100, 200);
610        ctrl.register_link(2, 300, 400);
611        ctrl.clear_links();
612        assert!(ctrl.state.borrow().links.is_empty());
613    }
614
615    #[test]
616    fn remove_pin_prunes_registered_links() {
617        let ctrl = setup_controller();
618
619        assert!(ctrl.remove_pin(1001));
620
621        assert!(!ctrl.cache.borrow().pin_positions.contains_key(&1001));
622        assert!(ctrl.state.borrow().links.is_empty());
623    }
624
625    #[test]
626    fn remove_node_cascades_geometry_links_and_drag_state() {
627        let ctrl = setup_controller();
628        ctrl.handle_node_drag_started(1);
629
630        assert_eq!(ctrl.remove_node(1), vec![1001]);
631
632        assert!(!ctrl.cache.borrow().node_rects.contains_key(&1));
633        assert!(!ctrl.cache.borrow().pin_positions.contains_key(&1001));
634        assert!(ctrl.state.borrow().links.is_empty());
635        assert_eq!(ctrl.dragged_node_id(), 0);
636    }
637
638    #[test]
639    fn reset_graph_clears_geometry_topology_and_drag_state() {
640        let ctrl = setup_controller();
641        ctrl.handle_node_drag_started(1);
642
643        ctrl.reset_graph();
644
645        assert!(ctrl.cache.borrow().node_rects.is_empty());
646        assert!(ctrl.cache.borrow().pin_positions.is_empty());
647        assert!(ctrl.state.borrow().links.is_empty());
648        assert_eq!(ctrl.dragged_node_id(), 0);
649    }
650
651    #[test]
652    fn finishing_drag_clears_drag_state() {
653        let ctrl = NodeEditorController::new();
654        ctrl.handle_node_drag_started(1);
655
656        ctrl.handle_node_drag_finished();
657
658        assert_eq!(ctrl.dragged_node_id(), 0);
659    }
660
661    // ========================================================================
662    // handle_node_rect: stores world coordinates directly
663    // ========================================================================
664
665    #[test]
666    fn test_handle_node_rect_stores_directly() {
667        let ctrl = NodeEditorController::new();
668        ctrl.handle_node_rect(1, 100.0, 200.0, 50.0, 30.0);
669        let cache = ctrl.cache.borrow();
670        let rect = cache.node_rects.get(&1).unwrap().rect();
671        assert_eq!(rect, (100.0, 200.0, 50.0, 30.0));
672    }
673
674    // ========================================================================
675    // find_link_at_screen at various zoom levels
676    // ========================================================================
677
678    #[test]
679    fn test_find_link_at_screen_zoom1() {
680        let ctrl = setup_controller();
681        // At zoom=1, pan=0: pin 1001 is at screen (100, 25), pin 2001 at (200, 125)
682        let result = ctrl.find_link_at_screen(100.0, 25.0, 10.0, 50.0, 20);
683        assert_eq!(result, 1);
684    }
685
686    #[test]
687    fn test_find_link_at_screen_miss() {
688        let ctrl = setup_controller();
689        let result = ctrl.find_link_at_screen(500.0, 500.0, 10.0, 50.0, 20);
690        assert_eq!(result, -1);
691    }
692
693    #[test]
694    fn test_find_link_at_screen_zoom2() {
695        let ctrl = setup_controller();
696        ctrl.set_viewport(2.0, 0.0, 0.0);
697        // At zoom=2, pan=0: pin 1001 screen pos = (0+100)*2+0 = 200, (0+25)*2+0 = 50
698        let result = ctrl.find_link_at_screen(200.0, 50.0, 10.0, 50.0, 20);
699        assert_eq!(result, 1);
700    }
701
702    #[test]
703    fn test_find_link_at_screen_with_pan() {
704        let ctrl = setup_controller();
705        ctrl.set_viewport(1.0, 50.0, 30.0);
706        // At zoom=1, pan=(50,30): pin 1001 screen pos = (0+100)*1+50 = 150, (0+25)*1+30 = 55
707        let result = ctrl.find_link_at_screen(150.0, 55.0, 10.0, 50.0, 20);
708        assert_eq!(result, 1);
709    }
710
711    #[test]
712    fn screen_hit_test_uses_the_rendered_world_curve() {
713        let ctrl = NodeEditorController::new();
714        ctrl.handle_node_rect(1, 0.0, 0.0, 1.0, 1.0);
715        ctrl.handle_node_rect(2, 30.0, 100.0, 1.0, 1.0);
716        ctrl.handle_pin_position(1, 1, 2, 0.0, 0.0);
717        ctrl.handle_pin_position(2, 2, 1, 0.0, 0.0);
718        ctrl.register_link(7, 1, 2);
719        ctrl.set_viewport(3.0, 17.0, -11.0);
720        let rendered = crate::path::CubicBezier::from_endpoints(0.0, 0.0, 30.0, 100.0, 1.0, 50.0);
721        let (world_x, world_y) = rendered.eval(0.2);
722
723        assert_eq!(
724            ctrl.find_link_at_screen(world_x * 3.0 + 17.0, world_y * 3.0 - 11.0, 1.0, 50.0, 1000,),
725            7
726        );
727    }
728
729    #[test]
730    fn screen_hit_tolerance_does_not_grow_with_zoom() {
731        let ctrl = NodeEditorController::new();
732        ctrl.handle_node_rect(1, 0.0, 0.0, 1.0, 1.0);
733        ctrl.handle_node_rect(2, 200.0, 0.0, 1.0, 1.0);
734        ctrl.handle_pin_position(1, 1, 2, 0.0, 0.0);
735        ctrl.handle_pin_position(2, 2, 1, 0.0, 0.0);
736        ctrl.register_link(7, 1, 2);
737        ctrl.set_viewport(3.0, 0.0, 0.0);
738
739        assert_eq!(ctrl.find_link_at_screen(300.0, 20.0, 8.0, 50.0, 100), -1);
740    }
741
742    #[test]
743    fn rendered_world_curves_are_pickable_across_viewports_and_edge_shapes() {
744        let edges = [
745            ((0.0, 0.0), (200.0, 0.0), "horizontal"),
746            ((0.0, 0.0), (10.0, 5.0), "short"),
747            ((25.0, -75.0), (25.0, 125.0), "vertical"),
748            ((180.0, 90.0), (-70.0, -30.0), "reversed"),
749        ];
750
751        for (start, end, shape) in edges {
752            let rendered =
753                crate::path::CubicBezier::from_endpoints(start.0, start.1, end.0, end.1, 1.0, 50.0);
754            let ctrl = setup_controller_with_link(start, end);
755
756            for zoom in [0.1, 0.25, 1.0, 3.0] {
757                let pan = (37.0, -29.0);
758                ctrl.set_viewport(zoom, pan.0, pan.1);
759
760                for t in [0.0, 0.2, 0.5, 0.8, 1.0] {
761                    let (world_x, world_y) = rendered.eval(t);
762                    assert_eq!(
763                        ctrl.find_link_at_screen(
764                            world_x * zoom + pan.0,
765                            world_y * zoom + pan.1,
766                            2.0,
767                            50.0,
768                            1000,
769                        ),
770                        7,
771                        "failed to pick {shape} edge at zoom {zoom} and t {t}",
772                    );
773                }
774            }
775        }
776    }
777
778    #[test]
779    fn screen_tolerance_is_constant_across_zoom_levels_and_pan() {
780        let ctrl = setup_controller_with_link((0.0, 0.0), (200.0, 0.0));
781
782        for zoom in [0.1, 0.25, 1.0, 3.0] {
783            let pan = (37.0, -29.0);
784            ctrl.set_viewport(zoom, pan.0, pan.1);
785            let midpoint_screen = (100.0 * zoom + pan.0, pan.1);
786
787            assert_eq!(
788                ctrl.find_link_at_screen(
789                    midpoint_screen.0,
790                    midpoint_screen.1 + 7.0,
791                    8.0,
792                    50.0,
793                    1000,
794                ),
795                7,
796                "seven-screen-pixel offset missed at zoom {zoom}",
797            );
798            assert_eq!(
799                ctrl.find_link_at_screen(
800                    midpoint_screen.0,
801                    midpoint_screen.1 + 9.0,
802                    8.0,
803                    50.0,
804                    1000,
805                ),
806                -1,
807                "nine-screen-pixel offset hit at zoom {zoom}",
808            );
809        }
810    }
811
812    // ========================================================================
813    // find_pin_at_screen at various zoom levels
814    // ========================================================================
815
816    #[test]
817    fn test_find_pin_at_screen_zoom1() {
818        let ctrl = setup_controller();
819        // Pin 1001 at screen (100, 25)
820        let result = ctrl.find_pin_at_screen(102.0, 27.0, 10.0);
821        assert_eq!(result, 1001);
822    }
823
824    #[test]
825    fn test_find_pin_at_screen_miss() {
826        let ctrl = setup_controller();
827        let result = ctrl.find_pin_at_screen(500.0, 500.0, 10.0);
828        assert_eq!(result, 0);
829    }
830
831    #[test]
832    fn test_find_pin_at_screen_zoom2() {
833        let ctrl = setup_controller();
834        ctrl.set_viewport(2.0, 0.0, 0.0);
835        // Pin 1001 screen pos = (0+100)*2 = 200, (0+25)*2 = 50
836        let result = ctrl.find_pin_at_screen(200.0, 50.0, 10.0);
837        assert_eq!(result, 1001);
838    }
839
840    #[test]
841    fn test_find_pin_at_screen_with_pan() {
842        let ctrl = setup_controller();
843        ctrl.set_viewport(1.0, 50.0, 30.0);
844        // Pin 1001 screen pos = 100+50=150, 25+30=55
845        let result = ctrl.find_pin_at_screen(150.0, 55.0, 10.0);
846        assert_eq!(result, 1001);
847    }
848
849    #[test]
850    fn test_find_pin_at_screen_skips_non_hit_testable_pins() {
851        let ctrl = setup_controller();
852        ctrl.handle_pin_position_with_hit_testable(1001, 1, 2, 100.0, 25.0, false);
853
854        assert_eq!(ctrl.find_pin_at_screen(100.0, 25.0, 10.0), 0);
855    }
856
857    // ========================================================================
858    // nodes_in_selection_box_screen
859    // ========================================================================
860
861    #[test]
862    fn test_nodes_in_box_zoom1() {
863        let ctrl = setup_controller();
864        let result = ctrl.nodes_in_selection_box_screen(0.0, 0.0, 50.0, 50.0);
865        assert!(result.contains(&1));
866        assert!(!result.contains(&2));
867    }
868
869    #[test]
870    fn test_nodes_in_box_zoom2() {
871        let ctrl = setup_controller();
872        ctrl.set_viewport(2.0, 0.0, 0.0);
873        // Screen box (0,0,100,100) → world (0,0,50,50) → intersects node 1 at (0,0,100,50)
874        let result = ctrl.nodes_in_selection_box_screen(0.0, 0.0, 100.0, 100.0);
875        assert!(result.contains(&1));
876    }
877
878    // ========================================================================
879    // links_in_selection_box_screen
880    // ========================================================================
881
882    #[test]
883    fn test_links_in_box_zoom1() {
884        let ctrl = setup_controller();
885        // Link 1: start at world (100,25), end at world (200,125)
886        let result = ctrl.links_in_selection_box_screen(90.0, 15.0, 20.0, 20.0);
887        assert!(result.contains(&1));
888    }
889
890    #[test]
891    fn test_links_in_box_miss() {
892        let ctrl = setup_controller();
893        let result = ctrl.links_in_selection_box_screen(500.0, 500.0, 50.0, 50.0);
894        assert!(result.is_empty());
895    }
896
897    // ========================================================================
898    // safe_zoom guard
899    // ========================================================================
900
901    #[test]
902    fn test_safe_zoom_zero() {
903        let ctrl = NodeEditorController::new();
904        ctrl.set_viewport(0.0, 0.0, 0.0);
905        ctrl.handle_node_rect(1, 100.0, 200.0, 50.0, 30.0);
906        let result = ctrl.nodes_in_selection_box_screen(0.0, 0.0, 200.0, 300.0);
907        assert!(result.contains(&1));
908    }
909
910    #[test]
911    fn test_safe_zoom_negative() {
912        let ctrl = NodeEditorController::new();
913        ctrl.set_viewport(-1.0, 0.0, 0.0);
914        ctrl.handle_node_rect(1, 100.0, 200.0, 50.0, 30.0);
915        let _ = ctrl.find_link_at_screen(0.0, 0.0, 10.0, 50.0, 20);
916        let _ = ctrl.find_pin_at_screen(0.0, 0.0, 10.0);
917    }
918}
919
920#[cfg(test)]
921mod viewport_contract_tests {
922    use super::*;
923    #[test]
924    fn invalid_viewport_updates_preserve_the_previous_transform() {
925        let ctrl = NodeEditorController::new();
926        ctrl.set_viewport(2.0, 10.0, 20.0);
927        for (z, x, y) in [
928            (f32::INFINITY, 0.0, 0.0),
929            (f32::NAN, 0.0, 0.0),
930            (0.0, 0.0, 0.0),
931            (-1.0, 0.0, 0.0),
932            (1.0, f32::NAN, 0.0),
933            (1.0, 0.0, f32::INFINITY),
934        ] {
935            ctrl.set_viewport(z, x, y);
936            let s = ctrl.state.borrow();
937            assert_eq!((s.zoom, s.pan_x, s.pan_y), (2.0, 10.0, 20.0));
938        }
939    }
940}