iced_nodegraph 0.4.0

High-performance node graph editor widget for Iced with SDF-based rendering
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Regression test for #1: NodeGraph must clip the viewport it forwards to
//! child widgets to its own layout bounds. Otherwise widgets nested in nodes
//! (text, sliders, buttons, ...) paint past the graph edge into neighbouring
//! widgets in a `row!`, `pane_grid`, etc.
//!
//! We assert on the `viewport` argument that reaches a leaf child widget. To
//! invoke `Widget::draw` / `Widget::update` we need *something* that satisfies
//! NodeGraph's renderer bounds (`core::Renderer + iced_wgpu::primitive::Renderer`),
//! but we do not need a real renderer: the bug is observable in a single
//! argument value, not in pixel output.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use iced::advanced::widget::{Tree, Widget};
use iced::advanced::{Layout, layout, mouse, renderer};
use iced::{
    Background, Color, Element, Length, Pixels, Point, Rectangle, Size, Theme, Transformation,
    Vector,
};
use iced_wgpu::core::clipboard;
use iced_wgpu::core::image;
use iced_wgpu::core::text;

use crate::{NodeGraph, node};

// ---------------------------------------------------------------------------
// Stub renderer: no-op implementations of every trait NodeGraph requires.
// The test never inspects pixel output, so all methods are empty.
// ---------------------------------------------------------------------------
struct Stub;

thread_local! {
    // Records active clip layers so a child can inspect the innermost clip it
    // is drawn under (push_clip in iced replaces, not intersects, parent clips).
    static LAYER_STACK: RefCell<Vec<Rectangle>> = const { RefCell::new(Vec::new()) };
    // Snapshot of the innermost clip at the moment the recorder child is drawn.
    static CHILD_CLIP: Cell<Option<Rectangle>> = const { Cell::new(None) };
}

impl renderer::Renderer for Stub {
    fn start_layer(&mut self, bounds: Rectangle) {
        LAYER_STACK.with(|s| s.borrow_mut().push(bounds));
    }
    fn end_layer(&mut self) {
        LAYER_STACK.with(|s| {
            s.borrow_mut().pop();
        });
    }
    fn start_transformation(&mut self, _t: Transformation) {}
    fn end_transformation(&mut self) {}
    fn reset(&mut self, _new_bounds: Rectangle) {}
    fn fill_quad(&mut self, _quad: renderer::Quad, _background: impl Into<Background>) {}
    fn allocate_image(
        &mut self,
        _handle: &image::Handle,
        _callback: impl FnOnce(Result<image::Allocation, image::Error>) + Send + 'static,
    ) {
    }
}

impl text::Renderer for Stub {
    type Font = iced::Font;
    // Real (GPU-free) types: iced_core's `()` impls are debug_assertions-gated
    // and break release test builds; these tests never lay out text.
    type Paragraph = iced_wgpu::graphics::text::Paragraph;
    type Editor = iced_wgpu::graphics::text::Editor;

    const ICON_FONT: iced::Font = iced::Font::DEFAULT;
    const CHECKMARK_ICON: char = '0';
    const ARROW_DOWN_ICON: char = '0';
    const SCROLL_UP_ICON: char = '0';
    const SCROLL_DOWN_ICON: char = '0';
    const SCROLL_LEFT_ICON: char = '0';
    const SCROLL_RIGHT_ICON: char = '0';
    const ICED_LOGO: char = '0';

    fn default_font(&self) -> Self::Font {
        iced::Font::default()
    }
    fn default_size(&self) -> Pixels {
        Pixels(16.0)
    }
    fn fill_paragraph(
        &mut self,
        _paragraph: &Self::Paragraph,
        _position: Point,
        _color: Color,
        _clip_bounds: Rectangle,
    ) {
    }
    fn fill_editor(
        &mut self,
        _editor: &Self::Editor,
        _position: Point,
        _color: Color,
        _clip_bounds: Rectangle,
    ) {
    }
    fn fill_text(
        &mut self,
        _text: text::Text,
        _position: Point,
        _color: Color,
        _clip_bounds: Rectangle,
    ) {
    }
}

impl iced_wgpu::primitive::Renderer for Stub {
    fn draw_primitive(&mut self, _bounds: Rectangle, _primitive: impl iced_wgpu::Primitive) {}
}

// ---------------------------------------------------------------------------
// Leaf child widget that records the viewport it was last drawn / updated with.
// ---------------------------------------------------------------------------
#[derive(Clone)]
struct Capture(Rc<Cell<Option<Rectangle>>>);

struct ViewportRecorder {
    on_draw: Capture,
    on_update: Capture,
}

impl<Message> Widget<Message, Theme, Stub> for ViewportRecorder {
    fn size(&self) -> Size<Length> {
        Size::new(Length::Fixed(40.0), Length::Fixed(20.0))
    }
    fn layout(
        &mut self,
        _tree: &mut Tree,
        _renderer: &Stub,
        limits: &layout::Limits,
    ) -> layout::Node {
        layout::Node::new(limits.resolve(Length::Fixed(40.0), Length::Fixed(20.0), Size::ZERO))
    }
    fn draw(
        &self,
        _tree: &Tree,
        _renderer: &mut Stub,
        _theme: &Theme,
        _style: &renderer::Style,
        _layout: Layout<'_>,
        _cursor: mouse::Cursor,
        viewport: &Rectangle,
    ) {
        self.on_draw.0.set(Some(*viewport));
        CHILD_CLIP.with(|c| c.set(LAYER_STACK.with(|s| s.borrow().last().copied())));
    }
    fn update(
        &mut self,
        _tree: &mut Tree,
        _event: &iced::Event,
        _layout: Layout<'_>,
        _cursor: mouse::Cursor,
        _renderer: &Stub,
        _clipboard: &mut dyn clipboard::Clipboard,
        _shell: &mut iced_wgpu::core::Shell<'_, Message>,
        viewport: &Rectangle,
    ) {
        self.on_update.0.set(Some(*viewport));
    }
}

impl<'a, Message: 'a> From<ViewportRecorder> for Element<'a, Message, Theme, Stub> {
    fn from(value: ViewportRecorder) -> Self {
        Element::new(value)
    }
}

// ---------------------------------------------------------------------------
// The actual regression test.
// ---------------------------------------------------------------------------

fn build_graph_with_recorder(
    graph_w: f32,
    graph_h: f32,
    node_world_pos: Point,
) -> (
    NodeGraph<'static, usize, usize, (), (), Theme, Stub>,
    Capture, // on_draw
    Capture, // on_update
) {
    let on_draw = Capture(Rc::new(Cell::new(None)));
    let on_update = Capture(Rc::new(Cell::new(None)));
    let recorder = ViewportRecorder {
        on_draw: on_draw.clone(),
        on_update: on_update.clone(),
    };
    let mut graph: NodeGraph<'static, usize, usize, (), (), Theme, Stub> = NodeGraph::default()
        .width(Length::Fixed(graph_w))
        .height(Length::Fixed(graph_h));
    graph.push_node(node(0_usize, node_world_pos, Element::from(recorder)));
    (graph, on_draw, on_update)
}

#[test]
fn draw_clips_child_viewport_to_graph_bounds() {
    // NodeGraph is 200x200; outer viewport (parent window) is 1024x768. A node
    // sits at world (500, 500), outside the graph's screen bounds. We expect
    // the viewport the child sees to be bounded by the graph, not by the
    // outer window.
    let (mut graph, on_draw, _on_update) =
        build_graph_with_recorder(200.0, 200.0, Point::new(500.0, 500.0));

    let mut tree = Tree::new(&graph as &dyn Widget<(), Theme, Stub>);
    let mut renderer = Stub;
    let layout_node = graph.layout(
        &mut tree,
        &renderer,
        &layout::Limits::new(Size::ZERO, Size::new(1024.0, 768.0)),
    );
    let layout = Layout::new(&layout_node);

    let outer_viewport = Rectangle::new(Point::ORIGIN, Size::new(1024.0, 768.0));
    graph.draw(
        &tree,
        &mut renderer,
        &Theme::Light,
        &renderer::Style {
            text_color: Color::BLACK,
        },
        layout,
        mouse::Cursor::Unavailable,
        &outer_viewport,
    );

    let recorded = on_draw
        .0
        .get()
        .expect("recorder was never drawn — NodeGraph::draw did not reach child");

    // With the fix: clipped_viewport = layout.bounds() ∩ outer_viewport = 200x200
    // (camera default zoom=1, position=0,0, so world dims == screen dims).
    // Without the fix: child sees the full 1024x768 viewport transformed to world.
    assert!(
        recorded.width <= 200.0 && recorded.height <= 200.0,
        "child draw viewport {recorded:?} should be clipped to NodeGraph bounds (200x200)",
    );
}

#[test]
fn draw_clips_node_content_layer_to_graph_bounds() {
    // A node straddling the graph's right edge: its rect extends past x=200,
    // but the layer the node content (title bar, widgets) is drawn under must
    // be bounded by the graph, not by the node rect. iced's push_clip replaces
    // the parent clip, so the node-content clip has to be intersected with the
    // graph viewport explicitly. The recorder is 40 wide; placed at world
    // x=180 it spans [180, 220], 20px past the 200px graph edge.
    CHILD_CLIP.with(|c| c.set(None));
    let (mut graph, _on_draw, _on_update) =
        build_graph_with_recorder(200.0, 200.0, Point::new(180.0, 50.0));

    let mut tree = Tree::new(&graph as &dyn Widget<(), Theme, Stub>);
    let mut renderer = Stub;
    let layout_node = graph.layout(
        &mut tree,
        &renderer,
        &layout::Limits::new(Size::ZERO, Size::new(1024.0, 768.0)),
    );
    let layout = Layout::new(&layout_node);

    let outer_viewport = Rectangle::new(Point::ORIGIN, Size::new(1024.0, 768.0));
    graph.draw(
        &tree,
        &mut renderer,
        &Theme::Light,
        &renderer::Style {
            text_color: Color::BLACK,
        },
        layout,
        mouse::Cursor::Unavailable,
        &outer_viewport,
    );

    let clip = CHILD_CLIP
        .with(|c| c.get())
        .expect("node content was never drawn under a clip layer");

    // Default camera (zoom 1, no pan, graph at origin): layout space == screen
    // space, so the clip must stay within the 0..200 graph bounds.
    assert!(
        clip.x + clip.width <= 200.5,
        "node content clip {clip:?} must not extend past graph right edge (200)",
    );
}

// ---------------------------------------------------------------------------
// Event-propagation regression: NodeGraph must not consume wheel-scroll events
// when the cursor isn't actually over its bounds. `is_over` returns false
// both for `Levitating` cursors (covered by a sibling above in a `stack`) and
// for cursors geometrically outside the bounds.
// ---------------------------------------------------------------------------

fn wheel_event() -> iced::Event {
    iced::Event::Mouse(mouse::Event::WheelScrolled {
        delta: mouse::ScrollDelta::Lines { x: 0.0, y: 5.0 },
    })
}

fn run_update_with_cursor(graph_w: f32, graph_h: f32, cursor: mouse::Cursor) -> Rc<Cell<bool>> {
    let mut base_graph: NodeGraph<'static, usize, usize, (), (), Theme, Stub> =
        NodeGraph::default()
            .width(Length::Fixed(graph_w))
            .height(Length::Fixed(graph_h));
    base_graph.push_node(node(
        0_usize,
        Point::new(0.0, 0.0),
        Element::<(), _, _>::from(EmptyLeaf),
    ));

    let camera_changed = Rc::new(Cell::new(false));
    let cc = camera_changed.clone();
    let mut graph = base_graph.on_pan(move |_pos, _zoom| cc.set(true));

    let mut tree = Tree::new(&graph as &dyn Widget<(), Theme, Stub>);
    let renderer = Stub;
    let layout_node = graph.layout(
        &mut tree,
        &renderer,
        &layout::Limits::new(Size::ZERO, Size::new(1024.0, 768.0)),
    );
    let layout = Layout::new(&layout_node);

    let mut messages: Vec<()> = Vec::new();
    let mut shell = iced_wgpu::core::Shell::new(&mut messages);
    let mut clipboard = clipboard::Null;
    let viewport = Rectangle::new(Point::ORIGIN, Size::new(1024.0, 768.0));

    graph.update(
        &mut tree,
        &wheel_event(),
        layout,
        cursor,
        &renderer,
        &mut clipboard,
        &mut shell,
        &viewport,
    );

    camera_changed
}

// Minimal no-op leaf (we only need a node to exist so push_node doesn't panic).
struct EmptyLeaf;
impl<Message> Widget<Message, Theme, Stub> for EmptyLeaf {
    fn size(&self) -> Size<Length> {
        Size::new(Length::Fixed(10.0), Length::Fixed(10.0))
    }
    fn layout(&mut self, _: &mut Tree, _: &Stub, limits: &layout::Limits) -> layout::Node {
        layout::Node::new(limits.resolve(Length::Fixed(10.0), Length::Fixed(10.0), Size::ZERO))
    }
    fn draw(
        &self,
        _: &Tree,
        _: &mut Stub,
        _: &Theme,
        _: &renderer::Style,
        _: Layout<'_>,
        _: mouse::Cursor,
        _: &Rectangle,
    ) {
    }
}
impl<'a, Message: 'a> From<EmptyLeaf> for Element<'a, Message, Theme, Stub> {
    fn from(w: EmptyLeaf) -> Self {
        Element::new(w)
    }
}

#[test]
fn wheel_scroll_with_levitating_cursor_does_not_zoom() {
    // Levitating cursor = a sibling above (e.g. an `opaque` overlay) has
    // claimed mouse interaction at this position. NodeGraph must not zoom.
    let changed = run_update_with_cursor(
        200.0,
        200.0,
        mouse::Cursor::Levitating(Point::new(100.0, 100.0)),
    );
    assert!(
        !changed.get(),
        "wheel scroll under a levitating cursor must not change the camera",
    );
}

#[test]
fn wheel_scroll_outside_graph_bounds_does_not_zoom() {
    // Cursor is geometrically outside the NodeGraph's layout bounds (200x200).
    let changed = run_update_with_cursor(
        200.0,
        200.0,
        mouse::Cursor::Available(Point::new(500.0, 500.0)),
    );
    assert!(
        !changed.get(),
        "wheel scroll outside the graph bounds must not change the camera",
    );
}

#[test]
fn wheel_scroll_inside_graph_bounds_zooms() {
    // Happy-path control test: an Available cursor inside the bounds must
    // still drive the camera.
    let changed = run_update_with_cursor(
        200.0,
        200.0,
        mouse::Cursor::Available(Point::new(100.0, 100.0)),
    );
    assert!(
        changed.get(),
        "wheel scroll over the graph must still change the camera",
    );
}

#[test]
fn update_clips_child_viewport_to_graph_bounds() {
    let (mut graph, _on_draw, on_update) =
        build_graph_with_recorder(200.0, 200.0, Point::new(500.0, 500.0));

    let mut tree = Tree::new(&graph as &dyn Widget<(), Theme, Stub>);
    let renderer = Stub;
    let layout_node = graph.layout(
        &mut tree,
        &renderer,
        &layout::Limits::new(Size::ZERO, Size::new(1024.0, 768.0)),
    );
    let layout = Layout::new(&layout_node);

    let outer_viewport = Rectangle::new(Point::ORIGIN, Size::new(1024.0, 768.0));
    let mut shell_messages: Vec<()> = Vec::new();
    let mut shell = iced_wgpu::core::Shell::new(&mut shell_messages);
    let mut clipboard = clipboard::Null;
    let event = iced::Event::Mouse(mouse::Event::CursorMoved {
        position: Point::new(50.0, 50.0),
    });

    graph.update(
        &mut tree,
        &event,
        layout,
        mouse::Cursor::Available(Point::new(50.0, 50.0)),
        &renderer,
        &mut clipboard,
        &mut shell,
        &outer_viewport,
    );

    let recorded = on_update
        .0
        .get()
        .expect("recorder did not see an update event from NodeGraph");

    assert!(
        recorded.width <= 200.0 && recorded.height <= 200.0,
        "child update viewport {recorded:?} should be clipped to NodeGraph bounds (200x200)",
    );
}

// ---------------------------------------------------------------------------
// Node-content clip edge cases: the innermost clip the node content draws under
// must be `node_bounds ∩ graph_viewport`. At the default camera (zoom 1, no
// pan) layout space equals screen space, so we can assert directly in pixels.
// Recorder leaf is 40x20 (see `ViewportRecorder::size`).
// ---------------------------------------------------------------------------

/// Draws a 200x200 graph (at `widget_origin`) holding one recorder node at
/// `node_world`, and returns the innermost clip the node content was drawn
/// under. `None` means the content layer was never reached.
fn content_clip_at(widget_origin: Vector, node_world: Point) -> Option<Rectangle> {
    CHILD_CLIP.with(|c| c.set(None));
    let (mut graph, _on_draw, _on_update) = build_graph_with_recorder(200.0, 200.0, node_world);

    let mut tree = Tree::new(&graph as &dyn Widget<(), Theme, Stub>);
    let mut renderer = Stub;
    let layout_node = graph.layout(
        &mut tree,
        &renderer,
        &layout::Limits::new(Size::ZERO, Size::new(1024.0, 768.0)),
    );
    let layout = Layout::with_offset(widget_origin, &layout_node);
    let outer = Rectangle::new(Point::ORIGIN, Size::new(1024.0, 768.0));
    graph.draw(
        &tree,
        &mut renderer,
        &Theme::Light,
        &renderer::Style {
            text_color: Color::BLACK,
        },
        layout,
        mouse::Cursor::Unavailable,
        &outer,
    );
    CHILD_CLIP.with(|c| c.get())
}

#[test]
fn content_clip_at_left_edge_does_not_go_negative() {
    // Node spans world (-20, 50)..(20, 70): 20px hang past the left edge. The
    // clip must start at the graph left (x=0), not at the node's -20.
    let clip = content_clip_at(Vector::ZERO, Point::new(-20.0, 50.0))
        .expect("node content was never drawn under a clip layer");
    assert!(
        clip.x >= -0.5,
        "left-straddling content clip {clip:?} must not extend past the graph left edge (0)",
    );
}

#[test]
fn content_clip_at_top_edge_does_not_go_negative() {
    // Node spans world (50, -10)..(90, 10): hangs past the top edge.
    let clip = content_clip_at(Vector::ZERO, Point::new(50.0, -10.0))
        .expect("node content was never drawn under a clip layer");
    assert!(
        clip.y >= -0.5,
        "top-straddling content clip {clip:?} must not extend past the graph top edge (0)",
    );
}

#[test]
fn content_clip_fully_inside_is_not_overclipped() {
    // A node well inside must be clipped to its OWN bounds (40x20), not widened
    // to the graph and not shrunk below the node.
    let clip = content_clip_at(Vector::ZERO, Point::new(50.0, 50.0))
        .expect("node content was never drawn under a clip layer");
    assert!(
        (clip.width - 40.0).abs() < 1.0 && (clip.height - 20.0).abs() < 1.0,
        "fully-inside content clip {clip:?} should match the node bounds (40x20)",
    );
}

#[test]
fn content_clip_fully_outside_is_empty() {
    // A node entirely outside the graph: the content layer is still visited, but
    // its clip collapses to zero area (nothing of it may paint).
    let clip = content_clip_at(Vector::ZERO, Point::new(500.0, 500.0))
        .expect("node content was never drawn under a clip layer");
    assert!(
        clip.width == 0.0 && clip.height == 0.0,
        "fully-outside content clip {clip:?} must have zero area",
    );
}

#[test]
fn content_clip_respects_nonzero_widget_origin() {
    // Graph placed at (0, 100) (e.g. below a toolbar); node at world (50, 50)
    // lands at screen (50, 150). The clip must sit within the graph's screen
    // bounds [100, 300] vertically, proving the origin term is carried.
    let clip = content_clip_at(Vector::new(0.0, 100.0), Point::new(50.0, 50.0))
        .expect("node content was never drawn under a clip layer");
    assert!(
        clip.y >= 99.5 && clip.y + clip.height <= 300.5,
        "content clip {clip:?} must stay within the origin-offset graph bounds (y 100..300)",
    );
}