rungui 0.4.0

Small portable native GUI library: a thin layer over GTK3, Win32 and Cocoa with hand-declared FFI
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
699
700
701
702
703
704
//! Pure-Rust in-memory backend: selected by feature `mock` and always under `cargo test`.
//! Records everything the core pushes, fakes text metrics (8 px per char) and lets tests act as
//! the "user" (`user_click`, `user_text`, ...) and as the OS (`pump`, `advance`, `resize_window`).
//! All state is thread-local, so parallel test threads are isolated.

use super::*;
use crate::core;
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};

#[derive(Clone, Debug, Default)]
/// The mock's view of one native widget: everything the core pushed to it.
pub struct MockWidget {
    /// The widget kind.
    pub kind: Option<Kind>,
    /// The native parent.
    pub parent: Option<WidgetId>,
    /// Text, title or caption.
    pub text: String,
    /// Tooltip text.
    pub tooltip: String,
    /// Placeholder text.
    pub placeholder: String,
    /// Keyboard accelerator text.
    pub accel: String,
    /// Enabled state as pushed.
    pub enabled: bool,
    /// Visible state as pushed.
    pub visible: bool,
    /// Check state.
    pub checked: bool,
    /// Read-only flag.
    pub readonly: bool,
    /// Busy animation on.
    pub indeterminate: bool,
    /// Focus was requested.
    pub focused: bool,
    /// Slider/spin value or progress fraction.
    pub value: f64,
    /// Range as (min, max, step).
    pub range: (f64, f64, f64),
    /// Items of a combo box or list box.
    pub items: Vec<String>,
    /// Selected item or tab.
    pub selected: Option<usize>,
    /// Last bounds pushed.
    pub bounds: Rect,
    /// The picture shown.
    pub image: Option<ImageData>,
    /// Number of `Prop::Bounds` pushes received (to test change-only updates).
    pub bounds_pushes: u32,
    /// Number of `Prop::Rows` pushes received.
    pub rows_pushes: u32,
    /// Table state as last pushed by the core.
    pub columns: Vec<Column>,
    /// Table rows.
    pub rows: Vec<Vec<String>>,
    /// Table sort arrow as (column, ascending).
    pub sort: Option<(usize, bool)>,
    /// Tree state as last pushed by the core (user_tree_expand mutates `expanded`).
    pub tree_rows: Vec<TreeRow>,
    /// Selected tree node.
    pub tree_selected: Option<u64>,
    /// Sash orientation (`Prop::Orientation`).
    pub orientation: Option<Orientation>,
    /// Fixed-pitch font on.
    pub monospace: bool,
    /// TextArea soft wrap; starts `true` like a native text view.
    pub wrap: bool,
    /// Window screen position (`Prop::Position`) and minimum client size (`Prop::MinSize`).
    pub position: Option<(i32, i32)>,
    /// Minimum client size of a window.
    pub min_size: Size,
    /// ListBox/Table multi-select mode.
    pub multi_select: bool,
    /// The date a Calendar shows.
    pub date: Option<Date>,
    /// The selected rows as last pushed (`Selected` or `Selection`) or set by the simulated user.
    pub selection: Vec<usize>,
}

/// One `Backend::run_modal` call.
#[derive(Clone, Debug, PartialEq)]
pub struct ModalRecord {
    /// The window run modally.
    pub window: WidgetId,
    /// The window it was run over.
    pub parent: Option<WidgetId>,
    /// Was it visible when the simulated user was done (i.e. would a real loop still be running)?
    pub still_open: bool,
}

/// What the core last told the mock about one native widget's accessibility (`a11y_changed`).
#[derive(Clone, Debug, PartialEq)]
pub struct A11yRecord {
    /// The widget.
    pub id: WidgetId,
    /// Accessible name.
    pub name: Option<String>,
    /// Accessible description.
    pub description: Option<String>,
    /// Accessible role.
    pub role: crate::A11yRole,
}

/// One `Backend::popup_menu` call.
#[derive(Clone, Debug, PartialEq)]
pub struct PopupRecord {
    /// The popup menu shown.
    pub menu: WidgetId,
    /// The window it was shown over.
    pub window: Option<WidgetId>,
    /// Window-client position, or `None` for "at the pointer".
    pub at: Option<(i32, i32)>,
    /// Direct children of the menu at show time: (kind, text, enabled).
    pub items: Vec<(Kind, String, bool)>,
}

#[derive(Default)]
struct State {
    /// Ordered by id, which is creation order (ids are monotonic).
    widgets: BTreeMap<WidgetId, MockWidget>,
    timers: HashMap<u64, (u32, bool, u32)>, // token -> (period, repeat, elapsed)
    answers: VecDeque<Answer>,
    files: VecDeque<Vec<String>>,
    last_message: Option<MessageSpec>,
    last_file_spec: Option<FileSpec>,
    fail_create: bool,
    fail_timer: bool,
    /// Kinds `create` refuses with `Unsupported` (to test optional-widget fallbacks).
    unsupported: Vec<Kind>,
    popups: Vec<PopupRecord>,
    /// Per window: the accessibility metadata of its last `a11y_changed`.
    a11y: HashMap<WidgetId, Vec<A11yRecord>>,
    /// Per popup: the item the simulated user picks (None = dismissed).
    popup_choices: VecDeque<Option<WidgetId>>,
    modal_log: Vec<ModalRecord>,
}

/// What the simulated user does while a modal window is up (see [`queue_modal`]).
type ModalScript = Box<dyn FnOnce(WidgetId)>;

thread_local! {
    static MODAL_SCRIPTS: RefCell<VecDeque<ModalScript>> = const { RefCell::new(VecDeque::new()) };
}

thread_local! {
    static S: RefCell<State> = RefCell::new(State::default());
    /// `Backend::wake` calls made on this thread since `init` (see [`wake_count`]).
    static WAKES: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}
static WOKEN: AtomicBool = AtomicBool::new(false);

fn st<R>(f: impl FnOnce(&mut State) -> R) -> R {
    S.with(|s| f(&mut s.borrow_mut()))
}

/// The headless backend: records what the core pushes and plays the user and the operating system for tests.
pub struct Mock;

impl Backend for Mock {
    fn init(_app_name: &str) -> Result<()> {
        st(|s| *s = State::default());
        Ok(())
    }
    fn run() {
        pump();
    }
    fn quit() {}
    fn wake() {
        WOKEN.store(true, Ordering::SeqCst);
        let _ = WAKES.try_with(|w| w.set(w.get() + 1));
    }
    fn timer_start(token: u64, millis: u32, repeat: bool) -> Result<()> {
        st(|s| {
            if s.fail_timer {
                s.fail_timer = false;
                return Err(Error::Backend("mock: timer failed".into()));
            }
            s.timers.insert(token, (millis, repeat, 0));
            Ok(())
        })
    }
    fn timer_stop(token: u64) {
        st(|s| s.timers.remove(&token));
    }
    fn create(id: WidgetId, kind: Kind, parent: Option<WidgetId>) -> Result<()> {
        st(|s| {
            if s.fail_create {
                s.fail_create = false;
                return Err(Error::Backend("mock: create failed".into()));
            }
            if s.unsupported.contains(&kind) {
                return Err(Error::Unsupported);
            }
            if let Some(p) = parent {
                if !s.widgets.contains_key(&p) {
                    return Err(Error::Backend("mock: unknown parent".into()));
                }
            }
            s.widgets.insert(
                id,
                MockWidget {
                    kind: Some(kind),
                    parent,
                    enabled: true,
                    visible: kind != Kind::Window,
                    range: (0.0, 100.0, 1.0),
                    wrap: true,
                    ..Default::default()
                },
            );
            Ok(())
        })
    }
    fn destroy(id: WidgetId) {
        st(|s| {
            s.widgets.remove(&id);
            s.a11y.remove(&id);
        });
    }
    fn set(id: WidgetId, prop: &Prop) {
        st(|s| {
            let Some(w) = s.widgets.get_mut(&id) else {
                return;
            };
            if let Some(kind) = w.kind {
                assert!(
                    prop.applies_to(kind),
                    "core sent {prop:?} to a {kind:?}, which does not take it"
                );
            }
            match prop {
                Prop::Text(t) => w.text = t.to_string(),
                Prop::Tooltip(t) => w.tooltip = t.to_string(),
                Prop::Placeholder(t) => w.placeholder = t.to_string(),
                Prop::Enabled(b) => w.enabled = *b,
                Prop::Visible(b) => w.visible = *b,
                Prop::Checked(b) => w.checked = *b,
                Prop::Value(v) => w.value = *v,
                Prop::Range { min, max, step } => w.range = (*min, *max, *step),
                Prop::Items(i) => w.items = i.to_vec(),
                Prop::Selected(i) => {
                    w.selected = *i;
                    w.selection = i.iter().copied().collect();
                }
                Prop::MultiSelect(b) => w.multi_select = *b,
                Prop::Date(d) => w.date = Some(*d),
                Prop::Selection(v) => {
                    w.selection = v.to_vec();
                    w.selected = v.first().copied();
                }
                Prop::Bounds(r) => {
                    w.bounds = *r;
                    w.bounds_pushes += 1;
                }
                Prop::Image(i) => w.image = i.cloned(),
                Prop::Accel(a) => w.accel = a.to_string(),
                Prop::ReadOnly(b) => w.readonly = *b,
                Prop::Indeterminate(b) => w.indeterminate = *b,
                Prop::Focus => w.focused = true,
                Prop::Columns(c) => w.columns = c.to_vec(),
                Prop::Rows(r) => {
                    w.rows = r.to_vec();
                    w.rows_pushes += 1;
                }
                Prop::Cell { row, col, text } => {
                    if let Some(r) = w.rows.get_mut(*row) {
                        // missing cells are empty, as in a `Rows` push
                        if r.len() <= *col {
                            r.resize(*col + 1, String::new());
                        }
                        r[*col] = text.to_string();
                    }
                }
                Prop::SortIndicator(x) => w.sort = *x,
                Prop::TreeRows(r) => w.tree_rows = r.to_vec(),
                Prop::TreeSelected(x) => w.tree_selected = *x,
                Prop::Orientation(o) => w.orientation = Some(*o),
                Prop::Monospace(b) => w.monospace = *b,
                Prop::Wrap(b) => w.wrap = *b,
                Prop::Position { x, y } => w.position = Some((*x, *y)),
                Prop::MinSize(m) => w.min_size = *m,
                _ => {}
            }
        });
    }
    fn a11y_changed(window: WidgetId) {
        let records = crate::a11y::resolve(window).map(|v| {
            v.into_iter()
                .map(|r| A11yRecord {
                    id: r.id,
                    name: r.name,
                    description: r.description,
                    role: r.role,
                })
                .collect()
        });
        st(|s| match records {
            Some(v) => s.a11y.insert(window, v),
            None => s.a11y.remove(&window),
        });
    }
    fn preferred_size(id: WidgetId) -> Size {
        st(|s| {
            let Some(w) = s.widgets.get(&id) else {
                return Size::default();
            };
            let tw = 8 * w.text.chars().count() as i32;
            match w.kind {
                Some(Kind::Label) => Size::new(tw, 16),
                Some(Kind::Button) => Size::new(tw + 24, 28),
                Some(Kind::CheckBox | Kind::RadioButton) => Size::new(tw + 24, 20),
                Some(Kind::TextInput | Kind::PasswordInput) => Size::new(160, 24),
                Some(Kind::TextArea) => Size::new(if w.monospace { 240 } else { 200 }, 100),
                Some(Kind::ComboBox) => Size::new(140, 26),
                Some(Kind::ListBox) => Size::new(160, 100),
                Some(Kind::Table) => Size::new(300, 150),
                Some(Kind::Tree) => Size::new(200, 200),
                Some(Kind::Slider) => Size::new(150, 24),
                Some(Kind::ProgressBar) => Size::new(150, 16),
                Some(Kind::SpinBox) => Size::new(80, 24),
                Some(Kind::Calendar) => Size::new(220, 180),
                Some(Kind::Image) => w
                    .image
                    .as_ref()
                    .map_or(Size::new(32, 32), |i| Size::new(i.w as i32, i.h as i32)),
                _ => Size::default(),
            }
        })
    }
    fn chrome(id: WidgetId) -> Size {
        st(|s| match s.widgets.get(&id).and_then(|w| w.kind) {
            Some(Kind::GroupBox) => Size::new(12, 24),
            Some(Kind::Tabs) => Size::new(4, 28),
            _ => Size::default(),
        })
    }
    fn native_handle(id: WidgetId) -> Option<NativeHandle> {
        st(|s| s.widgets.contains_key(&id)).then_some(NativeHandle::Gtk(id.0 as usize))
    }
    fn message_box(_parent: Option<WidgetId>, spec: &MessageSpec) -> Answer {
        st(|s| {
            s.last_message = Some(spec.clone());
            s.answers.pop_front().unwrap_or(Answer::Ok)
        })
    }
    fn file_dialog(_parent: Option<WidgetId>, spec: &FileSpec) -> Vec<String> {
        st(|s| {
            s.last_file_spec = Some(spec.clone());
            s.files.pop_front().unwrap_or_default()
        })
    }
    fn run_modal(window: WidgetId, parent: Option<WidgetId>) {
        // the simulated user acts while the "nested loop" runs, then the loop would be idle
        if let Some(script) = MODAL_SCRIPTS.with(|q| q.borrow_mut().pop_front()) {
            script(window);
            core::drain_posted();
        }
        let still_open = st(|s| s.widgets.get(&window).is_some_and(|w| w.visible));
        st(|s| {
            s.modal_log.push(ModalRecord {
                window,
                parent,
                still_open,
            })
        });
    }
    fn popup_menu(menu: WidgetId, parent_window: Option<WidgetId>, at: Option<(i32, i32)>) {
        let choice = st(|s| {
            let items = s
                .widgets
                .values()
                .filter(|w| w.parent == Some(menu))
                .map(|w| (w.kind.unwrap_or(Kind::Spacer), w.text.clone(), w.enabled))
                .collect();
            s.popups.push(PopupRecord {
                menu,
                window: parent_window,
                at,
                items,
            });
            s.popup_choices.pop_front().flatten()
        });
        // the simulated user picks an item (enabled, a descendant of this menu) like a real nested loop would
        let Some(item) = choice else { return };
        let (kind, checked, ok) = st(|s| {
            // enabled item whose parent chain reaches `menu` through enabled submenus
            let mut ok = false;
            let mut cur = Some(item);
            while let Some(c) = cur {
                let Some(w) = s.widgets.get(&c) else { break };
                if !w.enabled {
                    break;
                }
                if w.parent == Some(menu) {
                    ok = true;
                    break;
                }
                cur = w.parent;
            }
            let w = s.widgets.get(&item);
            (w.and_then(|w| w.kind), w.is_some_and(|w| w.checked), ok)
        });
        if !ok {
            return;
        }
        match kind {
            Some(Kind::MenuItem) => user(item, Event::Click),
            Some(Kind::CheckMenuItem) => user(item, Event::Toggled(!checked)),
            _ => {}
        }
    }
}

// ---------------------------------------------------------------- test/driver helpers

/// The native children of `id`, in creation order.
pub fn children_of(id: WidgetId) -> Vec<WidgetId> {
    st(|s| {
        s.widgets
            .iter()
            .filter(|(_, w)| w.parent == Some(id))
            .map(|(c, _)| *c)
            .collect()
    })
}
/// Snapshot of the mock's view of a widget.
pub fn widget(id: WidgetId) -> Option<MockWidget> {
    core::flush_models(); // table/tree models reach the backend at the next loop turn
    st(|s| s.widgets.get(&id).cloned())
}
/// The accessibility records pushed for `window` by its last `a11y_changed`, in layout order.
pub fn a11y(window: WidgetId) -> Option<Vec<A11yRecord>> {
    core::flush_models();
    st(|s| s.a11y.get(&window).cloned())
}
/// How many times the core asked the backend to wake the loop on this thread. The core collapses a
/// burst of changes into one wake-up until the loop has run ([`pump`]).
pub fn wake_count() -> u32 {
    WAKES.with(|w| w.get())
}
/// Make the next `timer_start` fail.
pub fn fail_next_timer() {
    st(|s| s.fail_timer = true);
}
/// How many native widgets exist.
pub fn widget_count() -> usize {
    st(|s| s.widgets.len())
}
/// Run what the OS loop would: process posted closures and layout if `wake` was called.
pub fn pump() {
    WOKEN.store(false, Ordering::SeqCst);
    core::drain_posted(); // per-thread queue, so unconditional is safe under parallel tests
}
/// Advance virtual time, firing due timers.
pub fn advance(ms: u32) {
    let due: Vec<u64> = st(|s| {
        let mut due = vec![];
        for (tok, (period, _, el)) in s.timers.iter_mut() {
            *el += ms;
            while *el >= *period {
                *el -= *period;
                due.push(*tok);
                if *period == 0 {
                    break;
                }
            }
        }
        due
    });
    for tok in due {
        core::timer_fired(tok);
    }
}
/// How many timers are running.
pub fn timer_count() -> usize {
    st(|s| s.timers.len())
}
/// Simulate the user (state change + event). `Text`/`Toggled`/`Selected`/`Value` are mirrored first.
pub fn user(id: WidgetId, ev: Event) {
    st(|s| {
        if let Some(w) = s.widgets.get_mut(&id) {
            match &ev {
                Event::Text(t) => w.text = t.clone(),
                Event::Toggled(b) => w.checked = *b,
                Event::Selected(i) => {
                    w.selected = *i;
                    w.selection = i.iter().copied().collect();
                }
                Event::Selection(v) => {
                    w.selection = v.clone();
                    w.selected = v.first().copied();
                }
                Event::Value(v) => w.value = *v,
                _ => {}
            }
        }
    });
    core::event(id, ev);
}
/// The user clicks a button or menu item.
pub fn user_click(id: WidgetId) {
    user(id, Event::Click)
}
/// The user types `t` into a text widget (the whole new content).
pub fn user_text(id: WidgetId, t: &str) {
    user(id, Event::Text(t.into()))
}
/// Simulate the user resizing a window's client area.
pub fn resize_window(id: WidgetId, w: i32, h: i32) {
    st(|s| {
        if let Some(x) = s.widgets.get_mut(&id) {
            x.bounds = Rect::new(0, 0, w, h);
        }
    });
    core::event(id, Event::Resized { w, h });
}
/// Simulate the title-bar close button.
pub fn user_close(id: WidgetId) {
    core::close_requested(id)
}
/// Queue the answer the next message box returns (default: OK).
pub fn queue_answer(a: Answer) {
    st(|s| s.answers.push_back(a));
}
/// Queue the paths the next file dialog returns (default: none, i.e. cancelled).
pub fn queue_files(f: &[&str]) {
    st(|s| s.files.push_back(f.iter().map(|x| x.to_string()).collect()));
}
/// The most recent message box request.
pub fn last_message() -> Option<MessageSpec> {
    st(|s| s.last_message.clone())
}
/// The most recent file dialog request.
pub fn last_file_spec() -> Option<FileSpec> {
    st(|s| s.last_file_spec.clone())
}
/// Queue what the simulated user does in the next `popup_menu`: `Some(item)` picks it, `None` dismisses.
pub fn queue_popup_choice(item: Option<WidgetId>) {
    st(|s| s.popup_choices.push_back(item));
}
/// Every popup menu shown so far.
pub fn popup_log() -> Vec<PopupRecord> {
    st(|s| s.popups.clone())
}
/// The most recent popup menu.
pub fn last_popup() -> Option<PopupRecord> {
    st(|s| s.popups.last().cloned())
}
/// Forget the recorded popups.
pub fn clear_popup_log() {
    st(|s| s.popups.clear());
}
/// Simulate a right-click / Menu key at window-client (x, y) on `id`.
pub fn user_context_menu(id: WidgetId, x: i32, y: i32) {
    core::event(id, Event::ContextMenu { x, y })
}
/// Queue what the simulated user does in the next [`Window::run_modal`](crate::Window::run_modal):
/// `script` gets the modal window and may click, type, close. Afterwards queued closures run and
/// the call returns, even if the window is still open (see [`modal_log`]); without a queued script
/// it returns at once.
pub fn queue_modal(script: impl FnOnce(WidgetId) + 'static) {
    MODAL_SCRIPTS.with(|q| q.borrow_mut().push_back(Box::new(script)));
}
/// Every `run_modal` so far.
pub fn modal_log() -> Vec<ModalRecord> {
    st(|s| s.modal_log.clone())
}
/// The user picks a date in a calendar.
pub fn user_pick_date(id: WidgetId, d: Date) {
    st(|s| {
        if let Some(w) = s.widgets.get_mut(&id) {
            w.date = Some(d);
        }
    });
    core::event(id, Event::DateChanged(d))
}
/// The user presses Enter in a text field.
pub fn user_submit(id: WidgetId) {
    core::event(id, Event::Submit)
}
/// The user presses Escape in a window.
pub fn user_cancel(window: WidgetId) {
    core::event(window, Event::Cancel)
}
/// The user selects these rows of a multi-select list box or table.
pub fn user_select_rows(id: WidgetId, rows: &[usize]) {
    user(id, Event::Selection(rows.to_vec()))
}
/// Simulate the user selecting table row `row` (None = clear).
pub fn user_select_row(id: WidgetId, row: Option<usize>) {
    user(id, Event::Selected(row))
}
/// The user double-clicks (or presses Enter on) a table row.
pub fn user_activate_row(id: WidgetId, row: usize) {
    core::event(id, Event::Activated(row))
}
/// The user clicks a table column header.
pub fn user_click_column(id: WidgetId, col: usize) {
    core::event(id, Event::ColumnClicked(col))
}
/// The user selects a tree node (`None` clears).
pub fn user_tree_select(id: WidgetId, node: Option<u64>) {
    st(|s| {
        if let Some(w) = s.widgets.get_mut(&id) {
            w.tree_selected = node;
        }
    });
    core::event(id, Event::TreeSelected(node))
}
/// The user double-clicks a tree node.
pub fn user_tree_activate(id: WidgetId, node: u64) {
    core::event(id, Event::TreeActivated(node))
}
/// Simulate the user expanding/collapsing a tree node (native state first, then the event).
pub fn user_tree_expand(id: WidgetId, node: u64, expanded: bool) {
    st(|s| {
        if let Some(r) = s
            .widgets
            .get_mut(&id)
            .and_then(|w| w.tree_rows.iter_mut().find(|r| r.node == node))
        {
            r.expanded = expanded;
        }
    });
    core::event(id, Event::TreeExpanded(node, expanded))
}
/// Make `create` of these kinds fail with `Unsupported` from now on (empty = none), like a
/// backend that has not implemented them.
pub fn set_unsupported(kinds: &[Kind]) {
    st(|s| s.unsupported = kinds.to_vec());
}
/// The native sash of a splitter (None if the backend refused to create one).
pub fn sash_of(splitter: WidgetId) -> Option<WidgetId> {
    core::read(splitter, |n| n.split().and_then(|s| s.sash)).flatten()
}
/// Simulate the user dragging `splitter`'s sash so that its leading edge is at `pos`
/// (native-parent client coordinates, like its bounds). No-op without a sash.
pub fn user_drag_sash(splitter: WidgetId, pos: i32) {
    if let Some(s) = sash_of(splitter) {
        core::event(s, Event::SashDragged(pos));
    }
}
/// Simulate a drag by `delta` pixels along the splitter's axis from where the sash is now.
pub fn user_drag_sash_by(splitter: WidgetId, delta: i32) {
    let Some(s) = sash_of(splitter) else { return };
    let Some(w) = widget(s) else { return };
    let start = if w.orientation == Some(Orientation::Vertical) {
        w.bounds.y
    } else {
        w.bounds.x
    };
    core::event(s, Event::SashDragged(start + delta));
}
/// Simulate a key press on `splitter`'s focused sash (see [`SashKey`]).
pub fn user_sash_key(splitter: WidgetId, key: super::SashKey) {
    if let Some(s) = sash_of(splitter) {
        core::event(s, Event::SashKey(key));
    }
}
/// Simulate the user moving a window to screen position (x, y).
pub fn user_move_window(id: WidgetId, x: i32, y: i32) {
    st(|s| {
        if let Some(w) = s.widgets.get_mut(&id) {
            w.position = Some((x, y));
        }
    });
    core::event(id, Event::Moved { x, y });
}
/// Make the next `create` fail with a backend error.
pub fn fail_next_create() {
    st(|s| s.fail_create = true);
}
/// Indented text rendering of the native widget tree (handy in examples).
pub fn dump() -> String {
    st(|s| {
        fn rec(s: &State, id: WidgetId, depth: usize, out: &mut String) {
            let Some(w) = s.widgets.get(&id) else { return };
            let b = w.bounds;
            out.push_str(&format!(
                "{}{:?} {:?} [{},{} {}x{}]{}{}\n",
                "  ".repeat(depth),
                w.kind.unwrap_or(Kind::Spacer),
                w.text,
                b.x,
                b.y,
                b.w,
                b.h,
                if w.visible { "" } else { " hidden" },
                if w.enabled { "" } else { " disabled" },
            ));
            for (c, _) in s.widgets.iter().filter(|(_, x)| x.parent == Some(id)) {
                rec(s, *c, depth + 1, out);
            }
        }
        let mut out = String::new();
        for (id, _) in s.widgets.iter().filter(|(_, w)| w.parent.is_none()) {
            rec(s, *id, 0, &mut out);
        }
        out
    })
}