graphix-package-gui 0.8.0

A dataflow language for UIs and network programming, GUI package
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
use anyhow::{bail, Context, Result};
use graphix_compiler::expr::{ExprId, ModuleResolver};
use graphix_compiler::BindId;
use graphix_package_core::testing::{self, RegisterFn, TestCtx};
use graphix_rt::{Callable, CompRes, GXEvent, NoExt, Ref};
use netidx::{protocol::valarray::ValArray, publisher::Value};
use poolshark::global::GPooled;
use std::time::Duration;
use tokio::sync::mpsc;

use crate::widgets::{self, GuiW, Message, MessageShell};

mod canvas_test;
mod chart_test;
mod clipboard_test;
mod data_table_test;
mod interaction_test;
mod widgets_test;

const TEST_REGISTER: &[RegisterFn] = &[
    <graphix_package_core::P as graphix_package::Package<NoExt>>::register,
    <graphix_package_array::P as graphix_package::Package<NoExt>>::register,
    <graphix_package_map::P as graphix_package::Package<NoExt>>::register,
    <graphix_package_str::P as graphix_package::Package<NoExt>>::register,
    <graphix_package_sys::P as graphix_package::Package<NoExt>>::register,
    <crate::P as graphix_package::Package<NoExt>>::register,
];

/// Test harness for GUI widget integration tests.
///
/// Compiles graphix code that produces a Widget value, builds the
/// widget tree, and provides helpers for simulating interactions
/// through the reactive loop.
struct GuiTestHarness {
    _ctx: TestCtx,
    gx: graphix_rt::GXHandle<NoExt>,
    #[allow(dead_code)]
    compiled: CompRes<NoExt>,
    rx: mpsc::Receiver<GPooled<Vec<GXEvent>>>,
    widget: GuiW<NoExt>,
    rt_handle: tokio::runtime::Handle,
    watched: fxhash::FxHashMap<ExprId, Value>,
    watch_names: fxhash::FxHashMap<String, ExprId>,
    _refs: Vec<Ref<NoExt>>,
    _callables: Vec<Callable<NoExt>>,
}

impl GuiTestHarness {
    /// Compile graphix code that produces a Widget value.
    ///
    /// `code` is module-level graphix code. The last binding should be
    /// named `result` and evaluate to a Widget value.
    /// Example: `"use gui; let result = gui::text(content: &\"hello\")"`.
    async fn new(code: &str) -> Result<Self> {
        let (tx, mut rx) = mpsc::channel(100);
        let tbl = fxhash::FxHashMap::from_iter([(
            netidx_core::path::Path::from("/test.gx"),
            arcstr::ArcStr::from(code),
        )]);
        let resolver = ModuleResolver::VFS(tbl);
        let ctx = testing::init_with_resolvers(tx, TEST_REGISTER, vec![resolver]).await?;
        let gx = ctx.rt.clone();
        let compiled = gx
            .compile(arcstr::literal!("{ mod test; test::result }"))
            .await
            .context("compile graphix code")?;
        let expr_id = compiled.exprs[0].id;

        // Wait for the initial value
        let initial_value = wait_for_update(&mut rx, expr_id).await?;

        // Compile the widget value into a widget tree
        let widget = widgets::compile(gx.clone(), initial_value)
            .await
            .context("compile widget tree")?;

        let rt_handle = tokio::runtime::Handle::current();

        Ok(Self {
            _ctx: ctx,
            gx,
            compiled,
            rx,
            widget,
            rt_handle,
            watched: fxhash::FxHashMap::default(),
            watch_names: fxhash::FxHashMap::default(),
            _refs: Vec::new(),
            _callables: Vec::new(),
        })
    }

    /// Drain all pending reactive updates into the widget tree.
    /// Returns true if any updates were processed.
    async fn drain(&mut self) -> Result<bool> {
        let mut changed = false;
        let timeout = tokio::time::sleep(Duration::from_millis(100));
        tokio::pin!(timeout);
        loop {
            tokio::select! {
                biased;
                Some(mut batch) = self.rx.recv() => {
                    for event in batch.drain(..) {
                        if let GXEvent::Updated(id, v) = event {
                            if self.watched.contains_key(&id) {
                                self.watched.insert(id, v.clone());
                            }
                            changed |= self.widget.handle_update(
                                &self.rt_handle, id, &v
                            )?;
                        }
                    }
                    // Reset timeout after each batch
                    timeout.as_mut().reset(
                        tokio::time::Instant::now() + Duration::from_millis(50)
                    );
                }
                _ = &mut timeout => break,
            }
        }
        Ok(changed)
    }

    /// Watch a graphix variable by name and return its initial value.
    ///
    /// The name should be a module-qualified path like "test::released".
    /// Looks up the BindId in the compiled env and creates a Ref to
    /// track updates. Use `get_watched()` to read the latest value
    /// after calling `drain()`.
    async fn watch(&mut self, name: &str) -> Result<Value> {
        let bid = find_bind_id(&self.compiled.env, name)
            .with_context(|| format!("watch: lookup {name}"))?;
        let r = self
            .gx
            .compile_ref(bid)
            .await
            .with_context(|| format!("watch: compile ref to {name}"))?;
        let initial = r.last.clone().unwrap_or(Value::Null);
        self.watched.insert(r.id, initial.clone());
        self.watch_names.insert(name.to_string(), r.id);
        self._refs.push(r);
        // Drain to pick up the ref's initial update event
        self.drain().await?;
        Ok(initial)
    }

    /// Get the most recent value of a watched variable by name.
    fn get_watched(&self, name: &str) -> Option<&Value> {
        self.watch_names.get(name).and_then(|eid| self.watched.get(eid))
    }

    /// Dispatch iced Messages back through the runtime and widget,
    /// mirroring `GuiHandler::about_to_wait` in src/event_loop.rs so
    /// tests see the same effects as production. Drains resulting
    /// reactive updates at the end.
    async fn dispatch_calls(&mut self, msgs: &[Message]) -> Result<()> {
        // Mirror the event loop: `Call` hits the graphix runtime
        // directly, everything else goes through `on_message` and
        // any follow-up messages the shell emits are fed back in.
        // FIFO (same as the real event loop) so message ordering
        // like CellEdit → CellEditSubmit is preserved.
        let mut pending: std::collections::VecDeque<Message> = msgs.iter().cloned().collect();
        while let Some(msg) = pending.pop_front() {
            match msg {
                Message::Nop => {}
                Message::Call(id, args) => {
                    self.gx.call(id, args)?;
                }
                // ColumnResize messages are host-handled in production
                // (the event loop snapshots the cursor position before
                // dispatch); tests that care invoke widget helpers
                // directly.
                Message::ColumnResizeStart(_)
                | Message::ColumnResizeMove(_)
                | Message::ColumnResizeEnd => {}
                other => {
                    let mut shell = MessageShell::new(iced_core::Point::ORIGIN);
                    self.widget.on_message(&other, &mut shell);
                    pending.extend(shell.out.drain(..));
                }
            }
        }
        self.drain().await?;
        Ok(())
    }

    /// Call view() on the widget. Panicking here means the widget
    /// tree is in an inconsistent state.
    fn view(&self) -> crate::widgets::IcedElement<'_> {
        self.widget.view()
    }

    /// Mirror what the iced event loop does between a wake and the next
    /// render: flush any deferred per-widget state (e.g. data_table
    /// re-sort triggered by sort-column subscription updates that
    /// arrived since the last drain). Tests that publish values to a
    /// sort column should call this before reading `dt_snapshot()`.
    #[allow(dead_code)]
    fn before_view(&mut self) -> bool {
        self.widget.before_view()
    }

    /// Drain + before_view in a loop until `pred(self)` returns true
    /// or `within` elapses. Panics on timeout with a diagnostic
    /// message — preferred to the fragile manual `for _ in 0..N`
    /// polling pattern because a missed condition produces a clear
    /// failure instead of falling through to an assertion that
    /// doesn't know polling was involved. Every iteration flushes
    /// both the runtime queue and the widget's `before_view` hooks,
    /// so tests see the same state a redraw would.
    #[allow(dead_code)]
    async fn wait_until<F>(&mut self, mut pred: F, within: Duration, why: &str) -> Result<()>
    where
        F: FnMut(&mut Self) -> bool,
    {
        let deadline = tokio::time::Instant::now() + within;
        let mut iters = 0;
        loop {
            self.drain().await?;
            self.before_view();
            iters += 1;
            if pred(self) {
                return Ok(());
            }
            if tokio::time::Instant::now() >= deadline {
                bail!(
                    "wait_until timed out after {iters} iterations / {:?}: {why}",
                    within,
                );
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    }

    /// Get a DataTableSnapshot from the widget, if it is a data table.
    fn dt_snapshot(&self) -> crate::widgets::DataTableSnapshot {
        self.widget
            .data_table_snapshot()
            .expect("widget is not a DataTableW")
    }

    /// Downcast the root widget to `DataTableW<NoExt>` for direct
    /// access to test-only accessors. Panics if the widget is not a
    /// data table — every test using this helper compiles a `data_table`
    /// at the root of its graphix code.
    fn dt(&self) -> &crate::widgets::data_table::DataTableW<NoExt> {
        self.widget
            .as_any()
            .downcast_ref::<crate::widgets::data_table::DataTableW<NoExt>>()
            .expect("widget is not a DataTableW")
    }

    /// Mutable downcast to `DataTableW<NoExt>` — needed by tests that
    /// call the widget's `handle_*` helpers (kept as inherent methods
    /// after `on_message` became the trait entry point).
    fn dt_mut(&mut self) -> &mut crate::widgets::data_table::DataTableW<NoExt> {
        self.widget
            .as_any_mut()
            .downcast_mut::<crate::widgets::data_table::DataTableW<NoExt>>()
            .expect("widget is not a DataTableW")
    }

    /// Dispatch a callback through the runtime by its CallableId and
    /// drain resulting reactive updates. Used by data_table tests to
    /// invoke per-cell callbacks (on_edit/on_click/on_resize) without
    /// going through pixel-layout: the widget itself fires the same
    /// callable internally, so calling it through the bridge mirrors
    /// the runtime's behavior.
    async fn call_callback(
        &mut self,
        id: graphix_rt::CallableId,
        args: ValArray,
    ) -> Result<()> {
        self.gx.call(id, args)?;
        self.drain().await?;
        Ok(())
    }

    /// Compile a graphix-defined function (lambda) by its module-qualified
    /// name into a `CallableId`. Mirrors the existing `watch` lookup but
    /// returns a callable rather than a tracked ref. The `Ref` and
    /// `Callable` are retained on the harness — dropping the
    /// `Callable` immediately sends `DeleteCallable` to the runtime,
    /// invalidating the returned id.
    async fn compile_named_callable(
        &mut self,
        name: &str,
    ) -> Result<graphix_rt::CallableId> {
        let bid = find_bind_id(&self.compiled.env, name)
            .with_context(|| format!("compile_named_callable: lookup {name}"))?;
        let r = self.gx.compile_ref(bid).await
            .with_context(|| format!("compile_named_callable: compile_ref {name}"))?;
        let val = r.last.clone()
            .with_context(|| format!("compile_named_callable: no value for {name}"))?;
        let cb = self.gx.compile_callable(val).await
            .with_context(|| format!("compile_named_callable: compile_callable {name}"))?;
        let id = cb.id();
        self._refs.push(r);
        self._callables.push(cb);
        Ok(id)
    }
}

/// Wait for a specific expression's update, with timeout.
async fn wait_for_update(
    rx: &mut mpsc::Receiver<GPooled<Vec<GXEvent>>>,
    target_id: ExprId,
) -> Result<Value> {
    let timeout = tokio::time::sleep(Duration::from_secs(5));
    tokio::pin!(timeout);
    loop {
        tokio::select! {
            biased;
            Some(mut batch) = rx.recv() => {
                for event in batch.drain(..) {
                    if let GXEvent::Updated(id, v) = event {
                        if id == target_id {
                            return Ok(v);
                        }
                    }
                }
            }
            _ = &mut timeout => bail!("timeout waiting for initial widget value"),
        }
    }
}

/// Find a BindId by a short name like "test::released" in the env.
///
/// The env stores bindings under generated scope prefixes (e.g.
/// `/do1234/test`), so we can't use `lookup_bind` with a root scope.
/// Instead, scan all scopes for one whose suffix matches the module
/// path and contains the variable name.
fn find_bind_id(env: &graphix_compiler::env::Env, name: &str) -> Result<BindId> {
    use netidx::path::Path;
    // Split "test::released" into module = "test", var = "released"
    let parts: Vec<&str> = name.split("::").collect();
    let (module, var) = match parts.as_slice() {
        [module, var] => (*module, *var),
        _ => bail!("expected module::var, got {name}"),
    };
    let suffix = format!("/{module}");
    for (scope, vars) in &env.binds {
        if Path::as_ref(&scope.0).ends_with(&suffix) {
            if let Some(bid) = vars.get(var) {
                return Ok(*bid);
            }
        }
    }
    bail!("no binding {name} found in env")
}

// ── Headless GPU ────────────────────────────────────────────────────

use iced_core::{clipboard, mouse, Event, Point, Size};
use iced_runtime::user_interface::{self, UserInterface};
use iced_wgpu::graphics::Shell;
use iced_wgpu::wgpu;
use tokio::sync::OnceCell;

/// Shared headless wgpu adapter + device. Creating GPU resources is
/// expensive, so we initialize once and share across all tests.
struct HeadlessGpu {
    adapter: wgpu::Adapter,
    device: wgpu::Device,
    queue: wgpu::Queue,
    format: wgpu::TextureFormat,
}

static HEADLESS_GPU: OnceCell<HeadlessGpu> = OnceCell::const_new();

async fn headless_gpu() -> &'static HeadlessGpu {
    HEADLESS_GPU
        .get_or_init(|| async {
            let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
                backends: wgpu::Backends::from_env().unwrap_or(wgpu::Backends::PRIMARY),
                ..Default::default()
            });
            // Try hardware adapter first, fall back to software
            let adapter = match instance
                .request_adapter(&wgpu::RequestAdapterOptions {
                    compatible_surface: None,
                    force_fallback_adapter: false,
                    ..Default::default()
                })
                .await
            {
                Ok(a) => a,
                Err(_) => instance
                    .request_adapter(&wgpu::RequestAdapterOptions {
                        compatible_surface: None,
                        force_fallback_adapter: true,
                        ..Default::default()
                    })
                    .await
                    .expect("no GPU adapter available (not even software fallback)"),
            };
            let (device, queue) = adapter
                .request_device(&wgpu::DeviceDescriptor::default())
                .await
                .expect("failed to create GPU device");
            HeadlessGpu {
                adapter,
                device,
                queue,
                format: wgpu::TextureFormat::Rgba8UnormSrgb,
            }
        })
        .await
}

impl HeadlessGpu {
    fn create_renderer(&self) -> widgets::Renderer {
        let engine = iced_wgpu::Engine::new(
            &self.adapter,
            self.device.clone(),
            self.queue.clone(),
            self.format,
            None,
            Shell::headless(),
        );
        iced_wgpu::Renderer::new(
            engine,
            iced_core::Font::DEFAULT,
            iced_core::Pixels(16.0),
        )
    }
}

// ── Interaction Harness ─────────────────────────────────────────────

/// Test harness that wraps `GuiTestHarness` with a headless renderer
/// and iced `UserInterface` to simulate user interactions (clicks,
/// typing, drags) and collect the resulting `Message`s.
struct InteractionHarness {
    inner: GuiTestHarness,
    renderer: widgets::Renderer,
    cache: user_interface::Cache,
    viewport: Size,
    cursor_position: Point,
}

impl InteractionHarness {
    async fn new(code: &str) -> Result<Self> {
        Self::with_viewport(code, Size::new(300.0, 50.0)).await
    }

    async fn with_viewport(code: &str, viewport: Size) -> Result<Self> {
        let gpu = headless_gpu().await;
        let renderer = gpu.create_renderer();
        let inner = GuiTestHarness::new(code).await?;
        Ok(Self {
            inner,
            renderer,
            cache: user_interface::Cache::default(),
            viewport,
            cursor_position: Point::ORIGIN,
        })
    }

    /// Build a UserInterface, feed events, and return the messages
    /// produced by widget callbacks.
    fn process_events(&mut self, events: &[Event]) -> Vec<Message> {
        let element = self.inner.widget.view();
        let cache = std::mem::take(&mut self.cache);
        let mut ui =
            UserInterface::build(element, self.viewport, cache, &mut self.renderer);
        let mut messages = Vec::new();
        let mut clipboard = clipboard::Null;
        let cursor = mouse::Cursor::Available(self.cursor_position);
        let (_state, _statuses) =
            ui.update(events, cursor, &mut self.renderer, &mut clipboard, &mut messages);
        self.cache = ui.into_cache();
        messages
    }

    #[allow(dead_code)]
    async fn drain(&mut self) -> Result<bool> {
        self.inner.drain().await
    }

    /// Simulate a window resize. Changes the layout viewport so the
    /// next `process_events`/`view` pass lays out at the new size, and
    /// delivers an empty-events pass so the responsive-wrapped widgets
    /// see the new size immediately.
    #[allow(dead_code)]
    fn resize(&mut self, viewport: Size) {
        self.viewport = viewport;
        // Invalidate the cache; bounds changed, so the cached tree is
        // stale.
        self.cache = user_interface::Cache::default();
        let _ = self.process_events(&[]);
    }

    fn view(&mut self) -> crate::widgets::IcedElement<'_> {
        // Some widgets (notably `data_table`) wrap their view in
        // `iced_widget::responsive`, so size-dependent state like
        // `cached_col_widths` is populated by the closure during
        // layout, not by the `view()` call itself. Run an empty-events
        // pass first so that layout executes — side effects (cache
        // writes through interior mutability) persist even though the
        // first UserInterface is discarded — then return a fresh
        // element for the caller.
        let _ = self.process_events(&[]);
        self.inner.view()
    }

    #[allow(dead_code)]
    fn before_view(&mut self) -> bool {
        self.inner.before_view()
    }

    #[allow(dead_code)]
    fn viewport(&self) -> Size {
        self.viewport
    }

    async fn watch(&mut self, name: &str) -> Result<Value> {
        self.inner.watch(name).await
    }

    fn get_watched(&self, name: &str) -> Option<&Value> {
        self.inner.get_watched(name)
    }

    async fn dispatch_calls(&mut self, msgs: &[Message]) -> Result<()> {
        self.inner.dispatch_calls(msgs).await
    }

    // ── Interaction helpers ─────────────────────────────────────

    fn click(&mut self, pos: Point) -> Vec<Message> {
        self.cursor_position = pos;
        let mut all = Vec::new();
        // Each event needs its own UI frame so widget state machines
        // (pressed → released) transition correctly.
        all.extend(self.process_events(&[Event::Mouse(mouse::Event::CursorMoved {
            position: pos,
        })]));
        all.extend(self.process_events(&[Event::Mouse(mouse::Event::ButtonPressed(
            mouse::Button::Left,
        ))]));
        all.extend(self.process_events(&[Event::Mouse(mouse::Event::ButtonReleased(
            mouse::Button::Left,
        ))]));
        all
    }

    #[allow(dead_code)]
    fn click_center(&mut self) -> Vec<Message> {
        let center = Point::new(self.viewport.width / 2.0, self.viewport.height / 2.0);
        self.click(center)
    }

    #[allow(dead_code)]
    fn click_at(&mut self, frac_x: f32, frac_y: f32) -> Vec<Message> {
        let pos = Point::new(self.viewport.width * frac_x, self.viewport.height * frac_y);
        self.click(pos)
    }

    fn type_text(&mut self, text: &str) -> Vec<Message> {
        use iced_core::keyboard;
        let mut all_msgs = Vec::new();
        for ch in text.chars() {
            let s: iced_core::SmolStr = ch.to_string().into();
            // Each character as a separate frame
            all_msgs.extend(self.process_events(&[Event::Keyboard(
                keyboard::Event::KeyPressed {
                    key: keyboard::Key::Character(s.clone()),
                    modified_key: keyboard::Key::Character(s.clone()),
                    physical_key: keyboard::key::Physical::Unidentified(
                        keyboard::key::NativeCode::Unidentified,
                    ),
                    location: keyboard::Location::Standard,
                    modifiers: keyboard::Modifiers::empty(),
                    text: Some(s),
                    repeat: false,
                },
            )]));
        }
        all_msgs
    }

    fn press_key(&mut self, named: iced_core::keyboard::key::Named) -> Vec<Message> {
        use iced_core::keyboard;
        self.process_events(&[Event::Keyboard(keyboard::Event::KeyPressed {
            key: keyboard::Key::Named(named),
            modified_key: keyboard::Key::Named(named),
            physical_key: keyboard::key::Physical::Unidentified(
                keyboard::key::NativeCode::Unidentified,
            ),
            location: keyboard::Location::Standard,
            modifiers: keyboard::Modifiers::empty(),
            text: None,
            repeat: false,
        })])
    }

    fn release_key(&mut self, named: iced_core::keyboard::key::Named) -> Vec<Message> {
        use iced_core::keyboard;
        self.process_events(&[Event::Keyboard(keyboard::Event::KeyReleased {
            key: keyboard::Key::Named(named),
            modified_key: keyboard::Key::Named(named),
            physical_key: keyboard::key::Physical::Unidentified(
                keyboard::key::NativeCode::Unidentified,
            ),
            location: keyboard::Location::Standard,
            modifiers: keyboard::Modifiers::empty(),
        })])
    }

    fn scroll(&mut self, delta_x: f32, delta_y: f32) -> Vec<Message> {
        self.process_events(&[Event::Mouse(mouse::Event::WheelScrolled {
            delta: mouse::ScrollDelta::Lines { x: delta_x, y: delta_y },
        })])
    }

    fn move_cursor(&mut self, pos: Point) -> Vec<Message> {
        self.cursor_position = pos;
        self.process_events(&[Event::Mouse(mouse::Event::CursorMoved { position: pos })])
    }

    /// Drive `Message::EditorAction` messages through the widget's
    /// `on_message` and collect the `Call` messages the editor
    /// publishes. The matching editor widget publishes a single
    /// `Message::Call(callable_id, [value])` per edit.
    fn process_editor_actions(&mut self, msgs: &[Message]) -> Vec<(CallableId, Value)> {
        let mut out = Vec::new();
        for m in msgs {
            if let Message::EditorAction(_, _) = m {
                let mut shell = MessageShell::new(Point::ORIGIN);
                self.inner.widget.on_message(m, &mut shell);
                for emitted in shell.out.drain(..) {
                    if let Message::Call(cid, args) = emitted {
                        if let Some(v) = args.into_iter().next() {
                            out.push((cid, v));
                        }
                    }
                }
            }
        }
        out
    }

    fn drag_horizontal(&mut self, from: Point, to_x: f32, steps: u32) -> Vec<Message> {
        let mut all_msgs = Vec::new();
        self.cursor_position = from;
        all_msgs.extend(self.process_events(&[Event::Mouse(
            mouse::Event::CursorMoved { position: from },
        )]));
        all_msgs.extend(self.process_events(&[Event::Mouse(
            mouse::Event::ButtonPressed(mouse::Button::Left),
        )]));
        let dx = (to_x - from.x) / steps as f32;
        for i in 1..=steps {
            let pos = Point::new(from.x + dx * i as f32, from.y);
            self.cursor_position = pos;
            all_msgs.extend(self.process_events(&[Event::Mouse(
                mouse::Event::CursorMoved { position: pos },
            )]));
        }
        all_msgs.extend(self.process_events(&[Event::Mouse(
            mouse::Event::ButtonReleased(mouse::Button::Left),
        )]));
        all_msgs
    }
}

// ── Message assertion helpers ───────────────────────────────────────

use graphix_rt::CallableId;

fn expect_call(msgs: &[Message]) -> CallableId {
    let calls: Vec<_> = msgs
        .iter()
        .filter_map(|m| match m {
            Message::Call(id, _) => Some(*id),
            _ => None,
        })
        .collect();
    assert_eq!(calls.len(), 1, "expected exactly one Call message, got {}", calls.len());
    calls[0]
}

fn expect_call_with_args(
    msgs: &[Message],
    pred: impl Fn(&ValArray) -> bool,
) -> CallableId {
    let calls: Vec<_> = msgs
        .iter()
        .filter_map(|m| match m {
            Message::Call(id, args) if pred(args) => Some(*id),
            _ => None,
        })
        .collect();
    assert!(!calls.is_empty(), "expected a Call message matching predicate, got none");
    calls[0]
}