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