Skip to main content

slint_node_editor/
links.rs

1//! Link management for the node editor.
2//!
3//! This module provides [`LinkManager`], which handles the synchronization
4//! between logical link data and visual link paths for rendering.
5//!
6//! # Example
7//!
8//! ```
9//! use slint_node_editor::{GeometryTracker, LinkManager, SimpleLink};
10//! use slint::Color;
11//!
12//! let tracker = GeometryTracker::new();
13//! let report_node = tracker.node_rect_callback();
14//! let report_pin = tracker.pin_position_callback();
15//! report_node(1, 0.0, 0.0, 100.0, 50.0);
16//! report_node(2, 200.0, 100.0, 100.0, 50.0);
17//! report_pin(3, 1, 2, 100.0, 25.0);
18//! report_pin(4, 2, 1, 0.0, 25.0);
19//!
20//! let mut links = LinkManager::new(tracker.cache());
21//! links.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(100, 180, 255)));
22//! links.update_paths(1.0);
23//! assert_eq!(links.ids().collect::<Vec<_>>(), vec![1]);
24//! ```
25
26use crate::graph::LinkModel;
27use crate::hit_test::NodeGeometry;
28use crate::state::GeometryCache;
29use slint::{Model, SharedString, VecModel};
30use std::cell::RefCell;
31use std::rc::Rc;
32
33/// Internal trait for auto-syncing to Slint models.
34trait ModelSyncer {
35    fn sync(&self, paths: &[LinkPathData]);
36}
37
38/// Concrete implementation of ModelSyncer for a specific path type.
39struct ConcreteModelSyncer<P, F> {
40    model: Rc<VecModel<P>>,
41    constructor: F,
42}
43
44impl<P, F> ModelSyncer for ConcreteModelSyncer<P, F>
45where
46    P: Clone + 'static,
47    F: Fn(i32, SharedString, slint::Color, f32, i32) -> P,
48{
49    fn sync(&self, paths: &[LinkPathData]) {
50        // Update existing rows or add new ones
51        for (i, path) in paths.iter().enumerate() {
52            let item = (self.constructor)(
53                path.id,
54                SharedString::from(path.path_commands.as_str()),
55                path.color,
56                path.line_width,
57                path.status,
58            );
59            if i < self.model.row_count() {
60                self.model.set_row_data(i, item);
61            } else {
62                self.model.push(item);
63            }
64        }
65        // Remove excess rows
66        while self.model.row_count() > paths.len() {
67            self.model.remove(self.model.row_count() - 1);
68        }
69    }
70}
71
72/// Manages links and their visual paths for the node editor.
73///
74/// `LinkManager` maintains a collection of links and automatically computes
75/// their bezier path representations for rendering.
76///
77/// # Auto-Sync Mode
78///
79/// Use [`bind_model`](Self::bind_model) to enable automatic synchronization
80/// to a Slint `VecModel`. After binding, every call to [`update_paths`](Self::update_paths)
81/// automatically updates the Slint model.
82///
83/// This fragment assumes the generated `LinkRow` and window types from the
84/// host's Slint UI; the complete binding is application-specific.
85///
86/// ```text
87/// let mut links = LinkManager::new(cache);
88/// links.add(SimpleLink::new(1, start_pin, end_pin, color));
89///
90/// // Bind once - auto-syncs on every update_paths call
91/// let model = Rc::new(VecModel::<LinkRow>::default());
92/// links.bind_model(model.clone(), |id, path, color, line_width, status| LinkRow { id, path_commands: path, color, line_width, status });
93/// window.set_link_paths(ModelRc::from(model));
94///
95/// // Now just call update_paths - model syncs automatically
96/// links.update_paths(zoom);
97/// ```
98///
99/// # Type Parameters
100///
101/// - `L`: The link data type, must implement [`LinkModel`]
102/// - `N`: The node geometry type used by the cache (default: `SimpleNodeGeometry`)
103pub struct LinkManager<L, N = crate::hit_test::SimpleNodeGeometry> {
104    /// The logical link data
105    links: Vec<L>,
106    /// Reference to the geometry cache for position lookups
107    cache: Rc<RefCell<GeometryCache<N>>>,
108    /// The computed paths (id, path_commands, color) for Slint binding
109    paths: Rc<RefCell<Vec<LinkPathData>>>,
110    /// Current zoom level (cached for updates)
111    current_zoom: f32,
112    /// Bezier curve offset
113    bezier_offset: f32,
114    /// Optional auto-sync to Slint model
115    syncer: Option<Box<dyn ModelSyncer>>,
116}
117
118/// Internal representation of a link path.
119#[derive(Clone)]
120struct LinkPathData {
121    id: i32,
122    path_commands: String,
123    color: slint::Color,
124    line_width: f32,
125    status: i32,
126}
127
128impl<L, N> LinkManager<L, N>
129where
130    L: LinkModel,
131    N: NodeGeometry + Copy,
132{
133    /// Create a new LinkManager with the given geometry cache.
134    ///
135    /// # Arguments
136    ///
137    /// * `cache` - Reference to the geometry cache for pin position lookups
138    pub fn new(cache: Rc<RefCell<GeometryCache<N>>>) -> Self {
139        Self {
140            links: Vec::new(),
141            cache,
142            paths: Rc::new(RefCell::new(Vec::new())),
143            current_zoom: 1.0,
144            bezier_offset: 50.0,
145            syncer: None,
146        }
147    }
148
149    /// Bind to a Slint model for automatic synchronization.
150    ///
151    /// After binding, every call to [`Self::update_paths`] automatically
152    /// updates the Slint model.
153    ///
154    /// # Arguments
155    ///
156    /// * `model` - The VecModel to sync to
157    /// * `constructor` - Function to create path items from (id, path_commands, color, line_width, status)
158    pub fn bind_model<P, F>(&mut self, model: Rc<VecModel<P>>, constructor: F)
159    where
160        P: Clone + 'static,
161        F: Fn(i32, SharedString, slint::Color, f32, i32) -> P + 'static,
162    {
163        self.syncer = Some(Box::new(ConcreteModelSyncer { model, constructor }));
164    }
165
166    /// Add a link to the manager.
167    ///
168    /// The link's visual path will be computed on the next call to [`Self::update_paths`].
169    pub fn add(&mut self, link: L) {
170        self.links.push(link);
171    }
172
173    /// Remove a link by ID.
174    ///
175    /// Returns `true` if a link was removed.
176    pub fn remove(&mut self, id: i32) -> bool {
177        let len_before = self.links.len();
178        self.links.retain(|link| link.id() != id);
179        self.links.len() != len_before
180    }
181
182    /// Remove all links.
183    pub fn clear(&mut self) {
184        self.links.clear();
185        self.paths.borrow_mut().clear();
186    }
187
188    /// Get the number of links.
189    pub fn len(&self) -> usize {
190        self.links.len()
191    }
192
193    /// Check if there are no links.
194    pub fn is_empty(&self) -> bool {
195        self.links.is_empty()
196    }
197
198    /// Get a reference to the links.
199    pub fn links(&self) -> &[L] {
200        &self.links
201    }
202
203    /// Get a mutable reference to the links.
204    pub fn links_mut(&mut self) -> &mut Vec<L> {
205        &mut self.links
206    }
207
208    /// Set the bezier curve offset (default: 50.0).
209    ///
210    /// This controls how curved the link paths are.
211    pub fn set_bezier_offset(&mut self, offset: f32) {
212        self.bezier_offset = offset;
213    }
214
215    /// Update all link paths based on current pin positions.
216    ///
217    /// Call this whenever:
218    /// - Pin positions change (node moved)
219    /// - Zoom level changes
220    /// - Links are added/removed
221    ///
222    /// # Arguments
223    ///
224    /// * `zoom` - Current viewport zoom level
225    pub fn update_paths(&mut self, zoom: f32) {
226        self.current_zoom = zoom;
227        let cache = self.cache.borrow();
228        let mut paths = self.paths.borrow_mut();
229        paths.clear();
230
231        for link in &self.links {
232            if let Some(path) = cache.compute_link_path(
233                link.start_pin_id(),
234                link.end_pin_id(),
235                zoom,
236                self.bezier_offset,
237            ) {
238                paths.push(LinkPathData {
239                    id: link.id(),
240                    path_commands: path,
241                    color: link.color(),
242                    line_width: link.line_width(),
243                    status: link.status(),
244                });
245            }
246        }
247
248        // Auto-sync to bound model if present
249        if let Some(syncer) = &self.syncer {
250            syncer.sync(&paths);
251        }
252    }
253
254    /// Get an iterator over link IDs.
255    pub fn ids(&self) -> impl Iterator<Item = i32> + '_ {
256        self.links.iter().map(|l| l.id())
257    }
258
259    /// Find a link by ID.
260    pub fn find(&self, id: i32) -> Option<&L> {
261        self.links.iter().find(|l| l.id() == id)
262    }
263
264    /// Find a link by ID (mutable).
265    pub fn find_mut(&mut self, id: i32) -> Option<&mut L> {
266        self.links.iter_mut().find(|l| l.id() == id)
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use crate::graph::SimpleLink;
274    use crate::hit_test::SimpleNodeGeometry;
275    use slint::Color;
276
277    fn setup_cache() -> Rc<RefCell<GeometryCache<SimpleNodeGeometry>>> {
278        let cache = Rc::new(RefCell::new(GeometryCache::new()));
279
280        // Add two nodes
281        cache
282            .borrow_mut()
283            .update_node_rect(1, 0.0, 0.0, 100.0, 50.0);
284        cache
285            .borrow_mut()
286            .update_node_rect(2, 200.0, 100.0, 100.0, 50.0);
287
288        // Add pins (output on node 1, input on node 2)
289        cache.borrow_mut().handle_pin_report(3, 1, 2, 100.0, 25.0); // Node 1 output
290        cache.borrow_mut().handle_pin_report(4, 2, 1, 0.0, 25.0); // Node 2 input
291
292        cache
293    }
294
295    #[test]
296    fn test_new_manager_is_empty() {
297        let cache = setup_cache();
298        let manager: LinkManager<SimpleLink, _> = LinkManager::new(cache);
299        assert!(manager.is_empty());
300        assert_eq!(manager.len(), 0);
301    }
302
303    #[test]
304    fn test_add_link() {
305        let cache = setup_cache();
306        let mut manager = LinkManager::new(cache);
307
308        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));
309
310        assert_eq!(manager.len(), 1);
311        assert!(!manager.is_empty());
312    }
313
314    #[test]
315    fn test_remove_link() {
316        let cache = setup_cache();
317        let mut manager = LinkManager::new(cache);
318
319        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));
320        manager.add(SimpleLink::new(2, 3, 4, Color::from_rgb_u8(0, 255, 0)));
321
322        assert!(manager.remove(1));
323        assert_eq!(manager.len(), 1);
324        assert_eq!(manager.links()[0].id(), 2);
325    }
326
327    #[test]
328    fn test_remove_nonexistent_link() {
329        let cache = setup_cache();
330        let mut manager = LinkManager::new(cache);
331
332        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));
333
334        assert!(!manager.remove(999));
335        assert_eq!(manager.len(), 1);
336    }
337
338    #[test]
339    fn test_clear() {
340        let cache = setup_cache();
341        let mut manager = LinkManager::new(cache);
342
343        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));
344        manager.add(SimpleLink::new(2, 3, 4, Color::from_rgb_u8(0, 255, 0)));
345
346        manager.clear();
347
348        assert!(manager.is_empty());
349    }
350
351    #[test]
352    fn test_update_paths() {
353        let cache = setup_cache();
354        let mut manager = LinkManager::new(cache);
355
356        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));
357        manager.update_paths(1.0);
358
359        let paths = manager.paths.borrow();
360        assert_eq!(paths.len(), 1);
361        assert_eq!(paths[0].id, 1);
362        assert!(paths[0].path_commands.starts_with("M "));
363    }
364
365    #[test]
366    fn test_update_paths_missing_pin() {
367        let cache = setup_cache();
368        let mut manager = LinkManager::new(cache);
369
370        // Link with non-existent pin
371        manager.add(SimpleLink::new(1, 3, 999, Color::from_rgb_u8(255, 0, 0)));
372        manager.update_paths(1.0);
373
374        // Should produce no path
375        let paths = manager.paths.borrow();
376        assert!(paths.is_empty());
377    }
378
379    #[test]
380    fn test_find() {
381        let cache = setup_cache();
382        let mut manager = LinkManager::new(cache);
383
384        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));
385        manager.add(SimpleLink::new(2, 3, 4, Color::from_rgb_u8(0, 255, 0)));
386
387        let link = manager.find(2);
388        assert!(link.is_some());
389        assert_eq!(link.unwrap().id(), 2);
390
391        assert!(manager.find(999).is_none());
392    }
393
394    #[test]
395    fn test_ids() {
396        let cache = setup_cache();
397        let mut manager = LinkManager::new(cache);
398
399        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));
400        manager.add(SimpleLink::new(5, 3, 4, Color::from_rgb_u8(0, 255, 0)));
401        manager.add(SimpleLink::new(3, 3, 4, Color::from_rgb_u8(0, 0, 255)));
402
403        let ids: Vec<i32> = manager.ids().collect();
404        assert_eq!(ids, vec![1, 5, 3]);
405    }
406
407    #[test]
408    fn test_custom_link_type() {
409        #[derive(Clone)]
410        struct MyLink {
411            id: i32,
412            from: i32,
413            to: i32,
414            label: String,
415        }
416
417        impl LinkModel for MyLink {
418            fn id(&self) -> i32 {
419                self.id
420            }
421            fn start_pin_id(&self) -> i32 {
422                self.from
423            }
424            fn end_pin_id(&self) -> i32 {
425                self.to
426            }
427            fn color(&self) -> Color {
428                Color::from_rgb_u8(128, 128, 128)
429            }
430        }
431
432        let cache = setup_cache();
433        let mut manager = LinkManager::new(cache);
434
435        manager.add(MyLink {
436            id: 1,
437            from: 3,
438            to: 4,
439            label: "data flow".to_string(),
440        });
441
442        assert_eq!(manager.len(), 1);
443        assert_eq!(manager.links()[0].label, "data flow");
444    }
445}