slint-node-editor 2.0.0

A flexible, generic Slint component library for building visual graph editors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Link management for the node editor.
//!
//! This module provides [`LinkManager`], which handles the synchronization
//! between logical link data and visual link paths for rendering.
//!
//! # Example
//!
//! ```
//! use slint_node_editor::{GeometryTracker, LinkManager, SimpleLink};
//! use slint::Color;
//!
//! let tracker = GeometryTracker::new();
//! let report_node = tracker.node_rect_callback();
//! let report_pin = tracker.pin_position_callback();
//! report_node(1, 0.0, 0.0, 100.0, 50.0);
//! report_node(2, 200.0, 100.0, 100.0, 50.0);
//! report_pin(3, 1, 2, 100.0, 25.0);
//! report_pin(4, 2, 1, 0.0, 25.0);
//!
//! let mut links = LinkManager::new(tracker.cache());
//! links.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(100, 180, 255)));
//! links.update_paths(1.0);
//! assert_eq!(links.ids().collect::<Vec<_>>(), vec![1]);
//! ```

use crate::graph::LinkModel;
use crate::hit_test::NodeGeometry;
use crate::state::GeometryCache;
use slint::{Model, SharedString, VecModel};
use std::cell::RefCell;
use std::rc::Rc;

/// Internal trait for auto-syncing to Slint models.
trait ModelSyncer {
    fn sync(&self, paths: &[LinkPathData]);
}

/// Concrete implementation of ModelSyncer for a specific path type.
struct ConcreteModelSyncer<P, F> {
    model: Rc<VecModel<P>>,
    constructor: F,
}

impl<P, F> ModelSyncer for ConcreteModelSyncer<P, F>
where
    P: Clone + 'static,
    F: Fn(i32, SharedString, slint::Color, f32, i32) -> P,
{
    fn sync(&self, paths: &[LinkPathData]) {
        // Update existing rows or add new ones
        for (i, path) in paths.iter().enumerate() {
            let item = (self.constructor)(
                path.id,
                SharedString::from(path.path_commands.as_str()),
                path.color,
                path.line_width,
                path.status,
            );
            if i < self.model.row_count() {
                self.model.set_row_data(i, item);
            } else {
                self.model.push(item);
            }
        }
        // Remove excess rows
        while self.model.row_count() > paths.len() {
            self.model.remove(self.model.row_count() - 1);
        }
    }
}

/// Manages links and their visual paths for the node editor.
///
/// `LinkManager` maintains a collection of links and automatically computes
/// their bezier path representations for rendering.
///
/// # Auto-Sync Mode
///
/// Use [`bind_model`](Self::bind_model) to enable automatic synchronization
/// to a Slint `VecModel`. After binding, every call to [`update_paths`](Self::update_paths)
/// automatically updates the Slint model.
///
/// This fragment assumes the generated `LinkRow` and window types from the
/// host's Slint UI; the complete binding is application-specific.
///
/// ```text
/// let mut links = LinkManager::new(cache);
/// links.add(SimpleLink::new(1, start_pin, end_pin, color));
///
/// // Bind once - auto-syncs on every update_paths call
/// let model = Rc::new(VecModel::<LinkRow>::default());
/// links.bind_model(model.clone(), |id, path, color, line_width, status| LinkRow { id, path_commands: path, color, line_width, status });
/// window.set_link_paths(ModelRc::from(model));
///
/// // Now just call update_paths - model syncs automatically
/// links.update_paths(zoom);
/// ```
///
/// # Type Parameters
///
/// - `L`: The link data type, must implement [`LinkModel`]
/// - `N`: The node geometry type used by the cache (default: `SimpleNodeGeometry`)
pub struct LinkManager<L, N = crate::hit_test::SimpleNodeGeometry> {
    /// The logical link data
    links: Vec<L>,
    /// Reference to the geometry cache for position lookups
    cache: Rc<RefCell<GeometryCache<N>>>,
    /// The computed paths (id, path_commands, color) for Slint binding
    paths: Rc<RefCell<Vec<LinkPathData>>>,
    /// Current zoom level (cached for updates)
    current_zoom: f32,
    /// Bezier curve offset
    bezier_offset: f32,
    /// Optional auto-sync to Slint model
    syncer: Option<Box<dyn ModelSyncer>>,
}

/// Internal representation of a link path.
#[derive(Clone)]
struct LinkPathData {
    id: i32,
    path_commands: String,
    color: slint::Color,
    line_width: f32,
    status: i32,
}

impl<L, N> LinkManager<L, N>
where
    L: LinkModel,
    N: NodeGeometry + Copy,
{
    /// Create a new LinkManager with the given geometry cache.
    ///
    /// # Arguments
    ///
    /// * `cache` - Reference to the geometry cache for pin position lookups
    pub fn new(cache: Rc<RefCell<GeometryCache<N>>>) -> Self {
        Self {
            links: Vec::new(),
            cache,
            paths: Rc::new(RefCell::new(Vec::new())),
            current_zoom: 1.0,
            bezier_offset: 50.0,
            syncer: None,
        }
    }

    /// Bind to a Slint model for automatic synchronization.
    ///
    /// After binding, every call to [`Self::update_paths`] automatically
    /// updates the Slint model.
    ///
    /// # Arguments
    ///
    /// * `model` - The VecModel to sync to
    /// * `constructor` - Function to create path items from (id, path_commands, color, line_width, status)
    pub fn bind_model<P, F>(&mut self, model: Rc<VecModel<P>>, constructor: F)
    where
        P: Clone + 'static,
        F: Fn(i32, SharedString, slint::Color, f32, i32) -> P + 'static,
    {
        self.syncer = Some(Box::new(ConcreteModelSyncer { model, constructor }));
    }

    /// Add a link to the manager.
    ///
    /// The link's visual path will be computed on the next call to [`Self::update_paths`].
    pub fn add(&mut self, link: L) {
        self.links.push(link);
    }

    /// Remove a link by ID.
    ///
    /// Returns `true` if a link was removed.
    pub fn remove(&mut self, id: i32) -> bool {
        let len_before = self.links.len();
        self.links.retain(|link| link.id() != id);
        self.links.len() != len_before
    }

    /// Remove all links.
    pub fn clear(&mut self) {
        self.links.clear();
        self.paths.borrow_mut().clear();
    }

    /// Get the number of links.
    pub fn len(&self) -> usize {
        self.links.len()
    }

    /// Check if there are no links.
    pub fn is_empty(&self) -> bool {
        self.links.is_empty()
    }

    /// Get a reference to the links.
    pub fn links(&self) -> &[L] {
        &self.links
    }

    /// Get a mutable reference to the links.
    pub fn links_mut(&mut self) -> &mut Vec<L> {
        &mut self.links
    }

    /// Set the bezier curve offset (default: 50.0).
    ///
    /// This controls how curved the link paths are.
    pub fn set_bezier_offset(&mut self, offset: f32) {
        self.bezier_offset = offset;
    }

    /// Update all link paths based on current pin positions.
    ///
    /// Call this whenever:
    /// - Pin positions change (node moved)
    /// - Zoom level changes
    /// - Links are added/removed
    ///
    /// # Arguments
    ///
    /// * `zoom` - Current viewport zoom level
    pub fn update_paths(&mut self, zoom: f32) {
        self.current_zoom = zoom;
        let cache = self.cache.borrow();
        let mut paths = self.paths.borrow_mut();
        paths.clear();

        for link in &self.links {
            if let Some(path) = cache.compute_link_path(
                link.start_pin_id(),
                link.end_pin_id(),
                zoom,
                self.bezier_offset,
            ) {
                paths.push(LinkPathData {
                    id: link.id(),
                    path_commands: path,
                    color: link.color(),
                    line_width: link.line_width(),
                    status: link.status(),
                });
            }
        }

        // Auto-sync to bound model if present
        if let Some(syncer) = &self.syncer {
            syncer.sync(&paths);
        }
    }

    /// Get an iterator over link IDs.
    pub fn ids(&self) -> impl Iterator<Item = i32> + '_ {
        self.links.iter().map(|l| l.id())
    }

    /// Find a link by ID.
    pub fn find(&self, id: i32) -> Option<&L> {
        self.links.iter().find(|l| l.id() == id)
    }

    /// Find a link by ID (mutable).
    pub fn find_mut(&mut self, id: i32) -> Option<&mut L> {
        self.links.iter_mut().find(|l| l.id() == id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::SimpleLink;
    use crate::hit_test::SimpleNodeGeometry;
    use slint::Color;

    fn setup_cache() -> Rc<RefCell<GeometryCache<SimpleNodeGeometry>>> {
        let cache = Rc::new(RefCell::new(GeometryCache::new()));

        // Add two nodes
        cache
            .borrow_mut()
            .update_node_rect(1, 0.0, 0.0, 100.0, 50.0);
        cache
            .borrow_mut()
            .update_node_rect(2, 200.0, 100.0, 100.0, 50.0);

        // Add pins (output on node 1, input on node 2)
        cache.borrow_mut().handle_pin_report(3, 1, 2, 100.0, 25.0); // Node 1 output
        cache.borrow_mut().handle_pin_report(4, 2, 1, 0.0, 25.0); // Node 2 input

        cache
    }

    #[test]
    fn test_new_manager_is_empty() {
        let cache = setup_cache();
        let manager: LinkManager<SimpleLink, _> = LinkManager::new(cache);
        assert!(manager.is_empty());
        assert_eq!(manager.len(), 0);
    }

    #[test]
    fn test_add_link() {
        let cache = setup_cache();
        let mut manager = LinkManager::new(cache);

        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));

        assert_eq!(manager.len(), 1);
        assert!(!manager.is_empty());
    }

    #[test]
    fn test_remove_link() {
        let cache = setup_cache();
        let mut manager = LinkManager::new(cache);

        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));
        manager.add(SimpleLink::new(2, 3, 4, Color::from_rgb_u8(0, 255, 0)));

        assert!(manager.remove(1));
        assert_eq!(manager.len(), 1);
        assert_eq!(manager.links()[0].id(), 2);
    }

    #[test]
    fn test_remove_nonexistent_link() {
        let cache = setup_cache();
        let mut manager = LinkManager::new(cache);

        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));

        assert!(!manager.remove(999));
        assert_eq!(manager.len(), 1);
    }

    #[test]
    fn test_clear() {
        let cache = setup_cache();
        let mut manager = LinkManager::new(cache);

        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));
        manager.add(SimpleLink::new(2, 3, 4, Color::from_rgb_u8(0, 255, 0)));

        manager.clear();

        assert!(manager.is_empty());
    }

    #[test]
    fn test_update_paths() {
        let cache = setup_cache();
        let mut manager = LinkManager::new(cache);

        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));
        manager.update_paths(1.0);

        let paths = manager.paths.borrow();
        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0].id, 1);
        assert!(paths[0].path_commands.starts_with("M "));
    }

    #[test]
    fn test_update_paths_missing_pin() {
        let cache = setup_cache();
        let mut manager = LinkManager::new(cache);

        // Link with non-existent pin
        manager.add(SimpleLink::new(1, 3, 999, Color::from_rgb_u8(255, 0, 0)));
        manager.update_paths(1.0);

        // Should produce no path
        let paths = manager.paths.borrow();
        assert!(paths.is_empty());
    }

    #[test]
    fn test_find() {
        let cache = setup_cache();
        let mut manager = LinkManager::new(cache);

        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));
        manager.add(SimpleLink::new(2, 3, 4, Color::from_rgb_u8(0, 255, 0)));

        let link = manager.find(2);
        assert!(link.is_some());
        assert_eq!(link.unwrap().id(), 2);

        assert!(manager.find(999).is_none());
    }

    #[test]
    fn test_ids() {
        let cache = setup_cache();
        let mut manager = LinkManager::new(cache);

        manager.add(SimpleLink::new(1, 3, 4, Color::from_rgb_u8(255, 0, 0)));
        manager.add(SimpleLink::new(5, 3, 4, Color::from_rgb_u8(0, 255, 0)));
        manager.add(SimpleLink::new(3, 3, 4, Color::from_rgb_u8(0, 0, 255)));

        let ids: Vec<i32> = manager.ids().collect();
        assert_eq!(ids, vec![1, 5, 3]);
    }

    #[test]
    fn test_custom_link_type() {
        #[derive(Clone)]
        struct MyLink {
            id: i32,
            from: i32,
            to: i32,
            label: String,
        }

        impl LinkModel for MyLink {
            fn id(&self) -> i32 {
                self.id
            }
            fn start_pin_id(&self) -> i32 {
                self.from
            }
            fn end_pin_id(&self) -> i32 {
                self.to
            }
            fn color(&self) -> Color {
                Color::from_rgb_u8(128, 128, 128)
            }
        }

        let cache = setup_cache();
        let mut manager = LinkManager::new(cache);

        manager.add(MyLink {
            id: 1,
            from: 3,
            to: 4,
            label: "data flow".to_string(),
        });

        assert_eq!(manager.len(), 1);
        assert_eq!(manager.links()[0].label, "data flow");
    }
}