Skip to main content

slint_node_editor/
tracking.rs

1//! Convenience helpers for geometry tracking setup.
2//!
3//! This module provides [`GeometryTracker`], a wrapper around [`GeometryCache`]
4//! that supplies callback closures for position tracking.
5//!
6//! # Example
7//!
8//! ```
9//! use slint_node_editor::GeometryTracker;
10//!
11//! let tracker = GeometryTracker::new();
12//! let report_node = tracker.node_rect_callback();
13//! let report_pin = tracker.pin_position_callback();
14//! report_node(1, 10.0, 20.0, 100.0, 60.0);
15//! report_pin(3, 1, 2, 100.0, 30.0);
16//! let cache = tracker.cache();
17//! assert_eq!(cache.borrow().pin_positions[&3].node_id, 1);
18//! ```
19
20use crate::hit_test::{NodeGeometry, SimpleNodeGeometry};
21use crate::state::GeometryCache;
22use std::cell::RefCell;
23use std::rc::Rc;
24
25/// Convenience wrapper for [`GeometryCache`] that provides ready-to-use Slint callbacks.
26///
27/// This eliminates the boilerplate of creating a cache, wrapping it in `Rc<RefCell<_>>`,
28/// and manually wiring up the position tracking callbacks.
29///
30/// # Type Parameter
31///
32/// - `N`: The node geometry type. Defaults to [`SimpleNodeGeometry`] which stores
33///   basic rectangle data (x, y, width, height). For custom node data, implement
34///   [`NodeGeometry`] and use `GeometryTracker::<MyNodeGeometry>::new()`.
35///
36/// # Example
37///
38/// ```
39/// use slint_node_editor::GeometryTracker;
40///
41/// // Create tracker with default SimpleNodeGeometry
42/// let tracker = GeometryTracker::new();
43///
44/// let report_node = tracker.node_rect_callback();
45/// let report_pin = tracker.pin_position_callback();
46/// report_node(1, 10.0, 20.0, 100.0, 60.0);
47/// report_pin(3, 1, 2, 100.0, 30.0);
48///
49/// // Access the cache for hit testing, path computation, etc.
50/// let cache = tracker.cache();
51/// let pin_id = cache.borrow().find_pin_at(110.0, 50.0, 10.0);
52/// assert_eq!(pin_id, 3);
53/// ```
54pub struct GeometryTracker<N = SimpleNodeGeometry> {
55    cache: Rc<RefCell<GeometryCache<N>>>,
56}
57
58impl<N> Default for GeometryTracker<N> {
59    fn default() -> Self {
60        Self::new()
61    }
62}
63
64impl<N> GeometryTracker<N> {
65    /// Create a new geometry tracker with an empty cache.
66    pub fn new() -> Self {
67        Self {
68            cache: Rc::new(RefCell::new(GeometryCache::new())),
69        }
70    }
71
72    /// Create a tracker wrapping an existing cache.
73    ///
74    /// Useful when you need to initialize the cache with data before
75    /// connecting callbacks.
76    pub fn with_cache(cache: Rc<RefCell<GeometryCache<N>>>) -> Self {
77        Self { cache }
78    }
79
80    /// Get a clone of the internal cache reference.
81    ///
82    /// Use this to access the cache for hit testing, path computation,
83    /// and other operations.
84    pub fn cache(&self) -> Rc<RefCell<GeometryCache<N>>> {
85        self.cache.clone()
86    }
87}
88
89impl<N> GeometryTracker<N>
90where
91    N: NodeGeometry + Copy,
92{
93    /// Get a callback for pin position updates.
94    ///
95    /// The returned closure accepts world-space pin data:
96    ///
97    /// ```
98    /// use slint_node_editor::GeometryTracker;
99    /// let tracker: GeometryTracker = GeometryTracker::new();
100    /// let report = tracker.pin_position_callback();
101    /// report(3, 1, 2, 100.0, 30.0);
102    /// ```
103    ///
104    /// The callback signature matches Slint's generated callback:
105    /// `(pin_id: i32, node_id: i32, pin_type: i32, rel_x: f32, rel_y: f32)`
106    pub fn pin_position_callback(&self) -> impl Fn(i32, i32, i32, f32, f32) + Clone {
107        let cache = self.cache.clone();
108        move |pin_id, node_id, pin_type, rel_x, rel_y| {
109            cache
110                .borrow_mut()
111                .handle_pin_report(pin_id, node_id, pin_type, rel_x, rel_y);
112        }
113    }
114}
115
116impl GeometryTracker<SimpleNodeGeometry> {
117    /// Get a callback for node rectangle updates.
118    ///
119    /// The returned closure accepts a world-space node rectangle:
120    ///
121    /// ```
122    /// use slint_node_editor::GeometryTracker;
123    /// let tracker = GeometryTracker::new();
124    /// let report = tracker.node_rect_callback();
125    /// report(1, 10.0, 20.0, 100.0, 60.0);
126    /// ```
127    ///
128    /// The callback signature matches Slint's generated callback:
129    /// `(id: i32, x: f32, y: f32, width: f32, height: f32)`
130    ///
131    /// # Note
132    ///
133    /// This method is only available for `GeometryTracker<SimpleNodeGeometry>`.
134    /// For custom node types, use [`Self::node_rect_callback_with`] instead.
135    pub fn node_rect_callback(&self) -> impl Fn(i32, f32, f32, f32, f32) + Clone {
136        let cache = self.cache.clone();
137        move |id, x, y, width, height| {
138            cache
139                .borrow_mut()
140                .handle_node_rect_report(id, x, y, width, height);
141        }
142    }
143}
144
145impl<N> GeometryTracker<N>
146where
147    N: NodeGeometry + Copy,
148{
149    /// Get a callback for node rectangle updates with a custom conversion function.
150    ///
151    /// Use this when your cache uses a custom `NodeGeometry` type instead of
152    /// `SimpleNodeGeometry`.
153    ///
154    /// # Example
155    ///
156    /// ```
157    /// use slint_node_editor::{GeometryTracker, NodeGeometry};
158    ///
159    /// #[derive(Clone, Copy)]
160    /// struct MyNodeGeometry {
161    ///     id: i32,
162    ///     bounds: (f32, f32, f32, f32),
163    ///     collapsed: bool,
164    /// }
165    ///
166    /// impl NodeGeometry for MyNodeGeometry {
167    ///     fn id(&self) -> i32 { self.id }
168    ///     fn rect(&self) -> (f32, f32, f32, f32) { self.bounds }
169    /// }
170    ///
171    /// let tracker = GeometryTracker::<MyNodeGeometry>::new();
172    /// let report = tracker.node_rect_callback_with(|id, x, y, w, h| {
173    ///     MyNodeGeometry {
174    ///         id,
175    ///         bounds: (x, y, w, h),
176    ///         collapsed: false,
177    ///     }
178    /// });
179    /// report(1, 10.0, 20.0, 100.0, 60.0);
180    /// ```
181    pub fn node_rect_callback_with<F>(&self, convert: F) -> impl Fn(i32, f32, f32, f32, f32) + Clone
182    where
183        F: Fn(i32, f32, f32, f32, f32) -> N + Clone + 'static,
184    {
185        let cache = self.cache.clone();
186        move |id, x, y, width, height| {
187            let node = convert(id, x, y, width, height);
188            cache.borrow_mut().node_rects.insert(id, node);
189        }
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196    use crate::hit_test::SimpleNodeGeometry;
197
198    #[test]
199    fn test_tracker_new_creates_empty_cache() {
200        let tracker: GeometryTracker<SimpleNodeGeometry> = GeometryTracker::new();
201        let cache = tracker.cache();
202        assert!(cache.borrow().node_rects.is_empty());
203        assert!(cache.borrow().pin_positions.is_empty());
204    }
205
206    #[test]
207    fn test_tracker_default_creates_empty_cache() {
208        let tracker: GeometryTracker<SimpleNodeGeometry> = GeometryTracker::default();
209        let cache = tracker.cache();
210        assert!(cache.borrow().node_rects.is_empty());
211    }
212
213    #[test]
214    fn test_tracker_with_existing_cache() {
215        let cache = Rc::new(RefCell::new(GeometryCache::<SimpleNodeGeometry>::new()));
216        cache
217            .borrow_mut()
218            .update_node_rect(1, 10.0, 20.0, 100.0, 50.0);
219
220        let tracker = GeometryTracker::with_cache(cache.clone());
221
222        // Should share the same cache
223        assert!(tracker.cache().borrow().node_rects.contains_key(&1));
224    }
225
226    #[test]
227    fn test_node_rect_callback_updates_cache() {
228        let tracker = GeometryTracker::new();
229        let callback = tracker.node_rect_callback();
230
231        callback(1, 10.0, 20.0, 100.0, 50.0);
232
233        let cache = tracker.cache();
234        let node = cache.borrow().node_rects.get(&1).copied();
235        assert!(node.is_some());
236        let node = node.unwrap();
237        assert_eq!(node.id, 1);
238        assert_eq!(node.x, 10.0);
239        assert_eq!(node.y, 20.0);
240        assert_eq!(node.width, 100.0);
241        assert_eq!(node.height, 50.0);
242    }
243
244    #[test]
245    fn test_pin_position_callback_updates_cache() {
246        let tracker: GeometryTracker<SimpleNodeGeometry> = GeometryTracker::new();
247        let callback = tracker.pin_position_callback();
248
249        callback(1001, 1, 2, 50.0, 25.0);
250
251        let cache = tracker.cache();
252        let pin = cache.borrow().pin_positions.get(&1001).copied();
253        assert!(pin.is_some());
254        let pin = pin.unwrap();
255        assert_eq!(pin.node_id, 1);
256        assert_eq!(pin.pin_type, 2);
257        assert_eq!(pin.rel_x, 50.0);
258        assert_eq!(pin.rel_y, 25.0);
259    }
260
261    #[test]
262    fn test_callbacks_share_same_cache() {
263        let tracker = GeometryTracker::new();
264
265        let node_cb = tracker.node_rect_callback();
266        let pin_cb = tracker.pin_position_callback();
267
268        node_cb(1, 0.0, 0.0, 100.0, 50.0);
269        pin_cb(1001, 1, 2, 50.0, 25.0);
270
271        let cache = tracker.cache();
272        assert_eq!(cache.borrow().node_rects.len(), 1);
273        assert_eq!(cache.borrow().pin_positions.len(), 1);
274    }
275
276    #[test]
277    fn test_multiple_cache_clones_share_data() {
278        let tracker = GeometryTracker::new();
279
280        let cache1 = tracker.cache();
281        let cache2 = tracker.cache();
282
283        cache1
284            .borrow_mut()
285            .update_node_rect(1, 0.0, 0.0, 100.0, 50.0);
286
287        // cache2 should see the update
288        assert!(cache2.borrow().node_rects.contains_key(&1));
289    }
290
291    #[test]
292    fn test_callback_is_clone() {
293        let tracker = GeometryTracker::new();
294
295        let cb1 = tracker.node_rect_callback();
296        let cb2 = cb1.clone();
297
298        cb1(1, 0.0, 0.0, 100.0, 50.0);
299        cb2(2, 100.0, 0.0, 100.0, 50.0);
300
301        let cache = tracker.cache();
302        assert_eq!(cache.borrow().node_rects.len(), 2);
303    }
304
305    #[test]
306    fn test_custom_node_geometry() {
307        #[derive(Clone, Copy)]
308        struct CustomNode {
309            id: i32,
310            x: f32,
311            y: f32,
312            w: f32,
313            h: f32,
314            extra: bool,
315        }
316
317        impl NodeGeometry for CustomNode {
318            fn id(&self) -> i32 {
319                self.id
320            }
321            fn rect(&self) -> (f32, f32, f32, f32) {
322                (self.x, self.y, self.w, self.h)
323            }
324        }
325
326        let tracker = GeometryTracker::<CustomNode>::new();
327        let callback = tracker.node_rect_callback_with(|id, x, y, w, h| CustomNode {
328            id,
329            x,
330            y,
331            w,
332            h,
333            extra: true,
334        });
335
336        callback(1, 10.0, 20.0, 100.0, 50.0);
337
338        let cache = tracker.cache();
339        let node = cache.borrow().node_rects.get(&1).copied();
340        assert!(node.is_some());
341        let node = node.unwrap();
342        assert_eq!(node.id, 1);
343        assert!(node.extra);
344    }
345}