rust_widgets 2.7.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Fills the data-bearing controls with sample data, for the snapshot and census paths.
//!
//! # The gap this closes
//!
//! `WidgetFactory::create(name, geometry, text)` passes **one string**, so every constructor whose doc
//! says "with no rows or columns" produced a control whose own feature was absent from its own snapshot:
//! `list_view.svg` was a filled rectangle, and so were `data_grid.svg`, `grid_table.svg`, `tree_view.svg`,
//! `table_widget.svg` and the rest. A reviewer looking at an empty frame learns nothing about whether the
//! table's columns line up or the tree's indent is right.
//!
//! The charts are **not** in that set: `create_bar_chart`/`create_pie_chart`/`create_line_chart` already
//! seed their own data, which is why their snapshots have 30–2073 shapes. They are the existence proof
//! that seeding is the right fix and the evidence for where it is still missing.
//!
//! # Why this is a separate step and not part of `WidgetFactory::create`
//!
//! `create` is the production construction path: the C ABI, the JSON loader, the designer and every host
//! go through it, and a host that asked for an empty table must get an empty one. Injecting sample rows
//! there would put `Widget / 12 / 12.50 / OK` into a real application's first frame until its own data
//! arrived, and would make "the factory creates what it advertises" untestable because every control would
//! come back pre-populated.
//!
//! So this is applied by the **verification** paths only — `examples/export_control_svgs.rs` and
//! [`crate::widget::census::census_all_controls`] — right after construction and before the first draw.
//! The constructors stay honest and the pictures become informative, which are two requirements that must
//! not be traded against each other.
//!
//! # How the fill reaches a control
//!
//! By **downcast to the concrete type**, through the crate's own
//! [`crate::widget::capability::coercion::widget_as_mut`]. Each control's content API is inherent to it
//! (`Menu::add_action`, `ListBox::add_item`, `CommandPalette::set_entries`) and the crate has never agreed
//! on one property name for "the list of things I hold" — a menu calls them entries, a palette commands, a
//! list items. A property-level fill would have to invent a name and then rewrite every contract to answer
//! it, which is a public-API change made for a snapshot's benefit. The JSON loader reaches these controls
//! by concrete type for the same reason (see its `"combobox"`/`"listbox"` arms), so this follows the
//! established route instead of inventing a second one.
//!
//! The cost is that a newly added data control is not covered until someone writes its arm. That is the
//! honest failure mode — a control whose snapshot stays empty, rather than one silently filled with the
//! wrong shape — and [`apply`] reports how many it filled so the count can be checked rather than assumed.

use crate::compat::Arc;
use crate::widget::capability::coercion::widget_as_mut;
use crate::widget::sample_data as sample;
use crate::widget::Widget;

use crate::compat::{String, Vec};
use crate::widget::advanced_widgets::calendar::Calendar;
use crate::widget::advanced_widgets::tab_bar::TabBar;
use crate::widget::container_widgets::groupbox::GroupBox;
use crate::widget::dialog::bottom_sheet::BottomSheet;
use crate::widget::dialog::dialog_widget::Dialog;
use crate::widget::dialog::message_box::MessageBox;
use crate::widget::dialog::modal_bottom_sheet::ModalBottomSheet;
use crate::widget::display_widgets::slider::{Slider, TickPosition};
use crate::widget::display_widgets::switch::Switch;
use crate::widget::input_widgets::cascader::{Cascader, CascaderOption};
use crate::widget::input_widgets::combobox::ComboBox;
use crate::widget::input_widgets::dropdown::Dropdown;
use crate::widget::input_widgets::editable_combo_box::EditableComboBox;
use crate::widget::input_widgets::font_combo_box::FontComboBox;
use crate::widget::input_widgets::listbox::ListBox;
use crate::widget::input_widgets::multi_select_combo_box::{MultiSelectComboBox, MultiSelectItem};
use crate::widget::menu_toolbar::menu::Menu;
use crate::widget::menu_toolbar::menu_button::{MenuButton, MenuItem};
use crate::widget::special_widgets::command_palette::{CommandEntry, CommandPalette};
use crate::widget::special_widgets::segmented_control::{SegmentItem, SegmentedControl};
use crate::widget::view_widgets::data_grid::DataGrid;
use crate::widget::view_widgets::data_source::IncrementalTableDataSource;
use crate::widget::view_widgets::grid_table::GridTableWidget;
use crate::widget::view_widgets::list_view::{ListView, VecListModel};
use crate::widget::view_widgets::table_widget::{TableModel, TableWidget};
use crate::widget::view_widgets::tree_view::{TreeView, VecTreeModel};
use crate::widget::view_widgets::virtual_table::VirtualTable;

/// Fills `widget` with this crate's sample data, returning `true` when it wrote something.
///
/// `name` is the canonical name the widget was constructed under, taken as an argument rather than read
/// from the widget's kind because 13 kinds are shared by two or more controls: a kind-keyed match would
/// give `split_button` and `tool_button` the same treatment, and `create_table` and `create_table_widget`
/// both build a `TableWidget` and must both be filled.
pub fn apply(name: &str, widget: &mut dyn Widget) -> bool {
    match name {
        // ── A container whose *state* is the feature ──
        //
        // `group_box` ships with `checkable == false`, so the tick is a shape no default
        // construction reaches. This arm turns the flag on so the box is drawn at all, and leaves
        // `checked` at the constructor's default.
        //
        // # Why this no longer forces `set_checked(true)`
        //
        // It used to, reasoning that "the tick was never in any snapshot". That captured the wrong
        // artefact: `GroupBox::new` already starts `checked = true`, so forcing it changed nothing,
        // and the pair `group_box.svg` / `group_box_checked.svg` came out byte-identical — two
        // files proving one thing. The checked state is now an *extra appearance* the exporter
        // declares (`EXTRA_APPEARANCES`), and this arm clears the flag so the default file shows
        // the state a caller actually gets while the extra file shows the toggled one. Both states
        // are then reviewable, and neither is implied by the other's absence.
        "group_box" => match widget_as_mut::<GroupBox>(widget) {
            Some(group_box) => {
                group_box.set_checkable(true);
                group_box.set_checked(false);
                true
            }
            None => false,
        },

        // ── Controls whose *state* is the feature ──
        //
        // `CheckBox`/`Switch`/`Slider` each draw something in one state and nothing in the other, and each
        // shipped in the state that draws nothing. The consequence is not cosmetic: `draw` has a branch for
        // the tick, the travel and the tick marks, and **no snapshot, census colour sample or gate ever made
        // it execute**, so a defect inside those branches was invisible to every automated check the crate
        // has. Turning the state on here is what puts the branch into the picture.
        //
        // This is the same reasoning as the `group_box` arm below, applied to the three controls whose
        // "other half" carries the most drawing. A caller still gets the default state from `create`: this
        // module is only reached from the verification paths (see the module docs).
        "check_box" => match widget_as_mut::<CheckBox>(widget) {
            Some(checkbox) => {
                checkbox.set_checked(true);
                true
            }
            None => false,
        },
        "switch" => match widget_as_mut::<Switch>(widget) {
            Some(switch) => {
                switch.set_checked(true);
                true
            }
            None => false,
        },
        // `Slider` needs `tick_interval > 0` as well as a non-`NoTicks` position: `draw` guards the whole
        // tick loop on both, so setting only the position leaves the marks unrendered and the snapshot
        // would claim a feature that is still not in the picture.
        "slider" => match widget_as_mut::<Slider>(widget) {
            Some(slider) => {
                slider.set_value(30);
                slider.set_tick_position(TickPosition::TicksBelow);
                slider.set_tick_interval(25);
                true
            }
            None => false,
        },

        // ── Controls whose *default* is read from the wall clock ──
        //
        // `Calendar::new` seeds `selected_date` and `display_month` from
        // `chrono::Local::now()`, which is right for a control (a calendar should open on
        // today) and wrong for a **snapshot** (a committed file must be reproducible on any
        // machine, on any day). Without this arm `snapshots/svg/calendar.svg` changed every
        // midnight: the selection highlight is a function of the date, so the file committed
        // on one day did not regenerate on the next and `check_svg_snapshots.sh` reported a
        // diff no edit could explain. It also meant the artifact could only ever be made green
        // by re-committing it — the false-green direction, where a gate passes because the
        // fixture was overwritten rather than because nothing changed.
        //
        // Pinning the date here rather than in the control keeps both halves honest: a host
        // still gets today's date from `create`, and the picture names a fixed day. The date
        // chosen is a Wednesday in a 31-day month shown from a Monday first-day, so the grid's
        // leading blank cells and its full last week are both in the picture.
        "calendar" => match widget_as_mut::<Calendar>(widget) {
            Some(calendar) => {
                match chrono::NaiveDate::from_ymd_opt(2026, 9, 16) {
                    Some(sample_day) => {
                        calendar.set_selected_date(sample_day);
                        // The week-number gutter is turned on for the sample: it is the one of the
                        // four visibility flags that is off by default, so leaving it off means the
                        // census never sees it painted at all -- and a feature no snapshot covers
                        // is a feature nothing can regress.
                        calendar.set_vertical_header_visible(true);
                        true
                    }
                    // The literal is a valid Gregorian date, so this arm is unreachable; it
                    // reports the failure instead of silently leaving the sample date-dependent.
                    None => false,
                }
            }
            None => false,
        },

        // ── Tabular controls that read cells from a source ──
        //
        // `virtual_table` is **not** a `TableWidget`: it is its own type that reads from an
        // `IncrementalTableDataSource` like the two grids. An earlier version of this match listed it with
        // `table`, so the downcast returned `None` and the arm silently did nothing — which the coverage
        // test caught.
        "table" | "table_widget" => match widget_as_mut::<TableWidget>(widget) {
            Some(table) => {
                table.set_model(Arc::new(SampleTableModel));
                true
            }
            None => false,
        },
        "data_grid" => match widget_as_mut::<DataGrid>(widget) {
            Some(grid) => {
                grid.set_data_source(Arc::new(SampleTableSource));
                true
            }
            None => false,
        },
        "grid_table" => match widget_as_mut::<GridTableWidget>(widget) {
            Some(grid) => {
                grid.set_data_source(Arc::new(SampleTableSource));
                true
            }
            None => false,
        },
        "virtual_table" => match widget_as_mut::<VirtualTable>(widget) {
            Some(table) => {
                table.set_data_source(Arc::new(SampleTableSource));
                true
            }
            None => false,
        },

        // ── Single-column lists with their own API ──
        "list_box" => match widget_as_mut::<ListBox>(widget) {
            Some(list) => {
                for item in sample::list_items() {
                    list.add_item(item);
                }
                list.set_current_row(Some(0));
                true
            }
            None => false,
        },
        // ── Combo boxes ──
        //
        // Four *distinct types*, not one type under four names: `EditableComboBox`, `FontComboBox` and
        // `MultiSelectComboBox` are their own structs with their own item shapes. Listing them under one
        // `widget_as_mut::<ComboBox>` arm (as an earlier version did) made three of the four silently do
        // nothing, which the coverage test caught.
        "combo_box" => match widget_as_mut::<ComboBox>(widget) {
            Some(combo) => {
                for item in sample::list_items() {
                    combo.add_item(item);
                }
                combo.set_current_index(Some(0));
                true
            }
            None => false,
        },
        "editable_combo_box" => match widget_as_mut::<EditableComboBox>(widget) {
            Some(combo) => {
                for item in sample::list_items() {
                    combo.add_item(item);
                }
                true
            }
            None => false,
        },
        "font_combo_box" => match widget_as_mut::<FontComboBox>(widget) {
            Some(combo) => {
                // A font combo box holds *font names*, so the sample list here is typeface names rather
                // than the shared business rows — the one place where the sample data is shaped by the
                // control rather than by the table it could have held.
                for name in sample::FONT_NAMES {
                    combo.add_font(name.to_string());
                }
                combo.set_current_index(0);
                true
            }
            None => false,
        },
        "multi_select_combo_box" => match widget_as_mut::<MultiSelectComboBox>(widget) {
            Some(combo) => {
                for (index, item) in sample::list_items().into_iter().enumerate() {
                    combo.add_item(MultiSelectItem::new(index as u64, item));
                }
                true
            }
            None => false,
        },
        "dropdown" => match widget_as_mut::<Dropdown>(widget) {
            Some(dropdown) => {
                dropdown.set_items(sample::list_items());
                dropdown.set_selected_index(0);
                true
            }
            None => false,
        },
        "cascader" => match widget_as_mut::<Cascader>(widget) {
            Some(cascader) => {
                cascader.set_options(sample_cascade());
                // Browse into the **first branch** and open the overlay.
                //
                // # Why both steps are needed, and why this is not just "expand"
                //
                // The tree is drawn only while the overlay is open (`expand`), and the number of columns
                // it draws is `browsed_path.len() + 1` — an open cascader with an **empty** path shows one
                // column, which is indistinguishable from a list box. `expand` alone seeds the browsed path
                // from the *committed selection*, which is empty here, so it drew a single level.
                //
                // Selecting `[0]` is what a user does by clicking the first branch, and it is what makes
                // the control's actual features visible: two level columns side by side and an expanded
                // branch. A snapshot that shows one flat column does not show a cascader.
                cascader.set_selected_path(vec![0]);
                cascader.expand();
                true
            }
            None => false,
        },

        // ── Lists that take a model ──
        //
        // `list_widget` is **not** a registered name: the capability table publishes `list_view` only, and
        // `list_widget` has no entry. Naming it here was dead — the factory can never produce it — which the
        // coverage test caught. The alias list is the registry's business, not this module's.
        "list_view" => match widget_as_mut::<ListView>(widget) {
            Some(list) => {
                list.set_model(Arc::new(VecListModel::new(sample::list_items())));
                list.select_row(0);
                true
            }
            None => false,
        },
        "tree_view" => match widget_as_mut::<TreeView>(widget) {
            Some(tree) => {
                // `node_path` is a *string per visible row*, so the hierarchy is expressed in the text —
                // see `VecTreeModel`. `sample::tree_rows` is the indented form, and the indentation is
                // what makes the snapshot show a tree rather than a flat list under a tree's chrome.
                tree.set_model(Arc::new(VecTreeModel::new(sample::tree_rows())));
                tree.select_node(0);
                true
            }
            None => false,
        },

        // ── Menus, palettes, command lists ──
        //
        // `context_menu` is an **alias** of `menu` in the capability table, not a separate entry, and the
        // factory resolves aliases to the same constructor — so `context_menu` reaches the same `Menu` and
        // is handled by the same arm. It is named here because a caller filtering by the alias would
        // otherwise be able to construct a control that silently is not filled.
        "menu" | "context_menu" => match widget_as_mut::<Menu>(widget) {
            Some(menu) => {
                for item in sample::menu_items() {
                    menu.add_action(item);
                }
                true
            }
            None => false,
        },
        "menu_button" => match widget_as_mut::<MenuButton>(widget) {
            Some(button) => {
                // `MenuItem::new` takes a numeric id as well as its text, so the index is the id here —
                // the control uses it to key the item and nothing in a snapshot depends on the value.
                for (index, item) in sample::menu_items().into_iter().enumerate() {
                    button.add_item(MenuItem::new(index as u64, &item));
                }
                true
            }
            None => false,
        },
        "command_palette" => match widget_as_mut::<CommandPalette>(widget) {
            Some(palette) => {
                palette.set_entries(
                    sample::menu_items()
                        .into_iter()
                        .enumerate()
                        .map(|(index, title)| CommandEntry::new(format!("cmd{index}"), title))
                        .collect(),
                );
                true
            }
            None => false,
        },

        // ── Tabs ──
        //
        // NOT filled. `create_tab_widget` already adds "Tab 1" and "Tab 2" itself, so the control's
        // snapshot was never blank — it was the one data-ish control that already showed its feature. An
        // earlier version of this module appended three more titles, which turned a correct two-tab strip
        // into a five-tab one and made the snapshot disagree with the constructor. Leaving it alone is the
        // fix: the gap being closed is *empty* snapshots, and this control does not have one.
        //
        // `tab_bar`, by contrast, is constructed empty (`create_tab_bar` passes no titles), so it is filled
        // below.
        "tab_bar" => match widget_as_mut::<TabBar>(widget) {
            Some(bar) => {
                for title in sample::tab_titles() {
                    bar.add_tab(title);
                }
                true
            }
            None => false,
        },

        // `segmented_control` is a segmented *set*, so an itemless one paints only its empty bar —
        // which is what its snapshot was: a stadium with no divisions and no selection, i.e. a
        // picture that could not show whether the divider, the label inset or the selection
        // indicator were right. Filling it is what makes the control's own feature reviewable.
        "segmented_control" => match widget_as_mut::<SegmentedControl>(widget) {
            Some(control) => {
                control.set_items(vec![
                    SegmentItem::new("overview", "Overview"),
                    SegmentItem::new("details", "Details"),
                    SegmentItem::new("history", "History"),
                ]);
                true
            }
            None => false,
        },

        // ── Controls whose *closed* state is deliberately blank ──
        //
        // `bottom_sheet`, `modal_bottom_sheet` and `dialog` paint nothing at all while closed: the
        // first two show only a scrim, and a dialog shows a scrim, a frame and a title bar, all of
        // which fade and grow in with its reveal — so a closed sample produces a bare page, which
        // the census reports as "this control painted nothing". That is not what a user sees: a
        // bottom sheet exists *in order to be* opened and a dialog *in order to be* shown, and the
        // state that shows the panel, the handle, the frame and the title strip at full strength is
        // the open one. Opening the sample is what puts the control's own feature into its own
        // picture, exactly as filling the table puts its rows there.
        "bottom_sheet" => match widget_as_mut::<BottomSheet>(widget) {
            Some(sheet) => {
                sheet.open();
                // The rise is what the draw reads, so the sample must be *settled* open rather than
                // merely aimed open — a sheet mid-slide would put a half-arrived panel in the
                // snapshot and make every geometry assertion depend on the frame count.
                while sheet.tick(1000) {}
                true
            }
            None => false,
        },
        "modal_bottom_sheet" => match widget_as_mut::<ModalBottomSheet>(widget) {
            Some(sheet) => {
                sheet.show();
                true
            }
            None => false,
        },
        "dialog" => match widget_as_mut::<Dialog>(widget) {
            Some(dialog) => {
                dialog.open();
                // Same reasoning as the sheet above: the reveal is what the draw reads, so the
                // sample is settled fully shown and not merely aimed there.
                while dialog.tick(1000) {}
                true
            }
            None => false,
        },
        "message_box" => match widget_as_mut::<MessageBox>(widget) {
            Some(message_box) => {
                // A message box is *created hidden* and shown by the runtime
                // (`MessageBoxHandle::show_modal` -> `show_widget`), and a hidden box now paints
                // nothing at all. Showing the sample is what puts a prompt in its own picture, the
                // same remedy as `dialog` above -- the state a message box exists to be seen in is
                // the shown one.
                message_box.show();
                while message_box.tick(1000) {}
                true
            }
            None => false,
        },

        // Everything else has no data concept, or is already seeded by its own constructor (the charts).
        _ => false,
    }
}

// ---------------------------------------------------------------------------
// The sample sources
// ---------------------------------------------------------------------------

// `CheckBox` is imported here rather than with the other control types because it belongs to the
// `base_widgets` family and the arms above are its only use in this module.
use crate::widget::base_widgets::checkbox::CheckBox;

/// A two-level cascade, so the control draws its branches *and* a leaf rather than one flat list.
///
/// A single level would not show what a cascader is for: the expand affordance and the indent are the
/// features, and a flat list renders identically to a `list_box`.
fn sample_cascade() -> Vec<CascaderOption> {
    let leaves = |options: &[&str]| -> Vec<CascaderOption> {
        options
            .iter()
            .enumerate()
            .map(|(index, label)| CascaderOption::new(format!("leaf{index}"), (*label).to_string()))
            .collect()
    };
    vec![
        CascaderOption::branch("items", "Items", leaves(&["Widget", "Gadget", "Cog"])),
        CascaderOption::branch("parts", "Parts", leaves(&["Bolt", "Nut", "Washer"])),
    ]
}

/// A `TableModel` over [`crate::widget::sample_data::ROWS`].
///
/// # Why a model rather than rows
///
/// `TableWidget` holds no rows of its own — it reads every cell from its model during `draw` — so handing
/// it one is the only way to give it content. That is also why its snapshot was blank: the JSON loader has
/// no `table_model` concept and so cannot fill it at all.
struct SampleTableModel;

impl TableModel for SampleTableModel {
    fn row_count(&self) -> usize {
        sample::ROWS.len()
    }

    fn column_count(&self) -> usize {
        sample::HEADERS.len()
    }

    fn data(&self, row: usize, column: usize) -> Option<String> {
        sample::ROWS.get(row).and_then(|cells| cells.get(column)).map(|cell| (*cell).to_string())
    }
}

/// An `IncrementalTableDataSource` over the same rows, for the two controls that read from one.
///
/// Deliberately the same data as [`SampleTableModel`]: `data_grid.svg` and `table_widget.svg` are then two
/// renderings of one table, so a difference between them is a difference in **layout**, which is what a
/// reviewer is looking for. Two datasets would make every comparison a comparison of content as well.
struct SampleTableSource;

impl IncrementalTableDataSource for SampleTableSource {
    fn row_count(&self) -> usize {
        sample::ROWS.len()
    }

    fn column_count(&self) -> usize {
        sample::HEADERS.len()
    }

    fn data(&self, row: usize, column: usize) -> Option<String> {
        SampleTableModel.data(row, column)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widget::WidgetFactory;

    /// Every name [`apply`] claims to know actually reaches a control that exists.
    ///
    /// # Why this is the load-bearing test
    ///
    /// The fill is by **downcast**: `apply` matches a canonical name, then tries `widget_as_mut` on one
    /// concrete type. If a control is renamed in the registry, or moves to a different type with the same
    /// name, the match arm is still reached and the downcast simply returns `None` — the fill silently
    /// stops working and the snapshot quietly goes back to being an empty frame. That is exactly the defect
    /// this module exists to fix, so it must not be able to return unnoticed.
    ///
    /// Building each named control through the real factory is what closes the loop: the downcast has to
    /// succeed against the type the *registry* actually constructs.
    #[test]
    fn every_filled_name_downcasts_to_the_type_the_registry_builds() {
        let factory = WidgetFactory::new_with_defaults();
        // The names `apply` handles, listed here so a name whose arm stops matching is caught. The list is
        // deliberately literal rather than derived: it is the claim being checked.
        let claimed = [
            "table",
            "table_widget",
            "virtual_table",
            "data_grid",
            "grid_table",
            "list_box",
            "combo_box",
            "editable_combo_box",
            "dropdown",
            "font_combo_box",
            "multi_select_combo_box",
            "cascader",
            "list_view",
            "tree_view",
            "menu",
            "context_menu",
            "menu_button",
            "command_palette",
            "tab_bar",
            "segmented_control",
            "calendar",
        ];
        for name in claimed {
            let Some(mut widget) =
                factory.create(name, crate::widget::census::CENSUS_RECT, "Sample")
            else {
                panic!("{name} is claimed as fillable but the factory cannot build it");
            };
            assert!(
                apply(name, widget.as_mut()),
                "{name}: the fill matched nothing, so its snapshot would be an empty frame again"
            );
        }
    }

    /// A name with no data concept is left alone, and the call reports it.
    ///
    /// The negative half matters as much as the positive: a fill that returned `true` for everything would
    /// make the exporter's `sample-filled` count meaningless, and a control whose content was written by the
    /// wrong arm would be counted as a success.
    /// A control with no *data* concept is not filled by [`apply`].
    ///
    /// # Why `slider` is no longer in this list
    ///
    /// It was, and correctly: `slider` has no data to load. But it does have a **feature** that is
    /// invisible in its default state — its tick marks are guarded on both a non-`NoTicks` position
    /// and a non-zero interval, and the constructor sets neither, so the marks belonged to no
    /// snapshot. The module fills it for the same reason it fills `group_box`'s tick, which is a
    /// different question from "does it hold data"; `slider` therefore moved out of this list and
    /// into the feature list covered by [`a_state_feature_is_switched_on_for_its_own_snapshot`].
    #[test]
    fn a_control_without_a_data_concept_is_not_filled() {
        let factory = WidgetFactory::new_with_defaults();
        for name in ["button", "label", "divider", "line_edit"] {
            let Some(mut widget) =
                factory.create(name, crate::widget::census::CENSUS_RECT, "Sample")
            else {
                continue;
            };
            assert!(!apply(name, widget.as_mut()), "{name} has no data to fill");
        }
    }

    /// Each control whose *state* is the feature has that state switched on for its snapshot.
    ///
    /// # Why this needs its own assertion
    ///
    /// A control that draws something in one state and nothing in the other makes every check the
    /// crate has agree on a picture that shows no feature: the tick branch, the travel branch and
    /// the tick-mark branch are all unreachable in the default state, so a defect inside them is
    /// invisible to the snapshot, the census colour sample and every gate. This pins the set that
    /// has been switched on, so a control dropping out of it is a failure rather than a quietly
    /// emptier picture.
    #[test]
    fn a_state_feature_is_switched_on_for_its_own_snapshot() {
        use crate::widget::display_widgets::slider::{Slider, TickPosition};
        use crate::widget::display_widgets::switch::Switch;

        let factory = WidgetFactory::new_with_defaults();
        for name in ["check_box", "switch", "slider", "group_box"] {
            let Some(mut widget) =
                factory.create(name, crate::widget::census::CENSUS_RECT, "Sample")
            else {
                panic!("{name} is published by the registry but could not be built");
            };
            assert!(apply(name, widget.as_mut()), "{name} owns a state feature");
        }

        // The state each one depends on is genuinely on, rather than the fill merely returning
        // `true`: a `Slider` needs both halves of its guard, and the constructor sets neither.
        let mut slider = Slider::new(crate::core::Rect::new(0, 0, 120, 8));
        assert_eq!(slider.tick_position(), TickPosition::NoTicks, "the constructor default");
        assert!(apply("slider", &mut slider));
        assert_ne!(slider.tick_position(), TickPosition::NoTicks, "and the fill moved it");
        assert!(slider.tick_interval() > 0, "or the draw guard still refuses the marks");

        let mut switch = Switch::new(crate::core::Rect::new(0, 0, 60, 30));
        assert!(!switch.is_checked(), "the constructor default");
        assert!(apply("switch", &mut switch));
        assert!(switch.is_checked(), "and the fill turned it on");
    }

    /// The calendar's snapshot is reproducible: its date comes from the fill, not the clock.
    ///
    /// # The defect this pins
    ///
    /// `Calendar::new` seeds `selected_date`/`display_month` from `chrono::Local::now()`. That is
    /// right for the control and fatal for a committed artifact: the selection highlight is a
    /// function of the date, so `snapshots/svg/calendar.svg` changed at every midnight and
    /// `check_svg_snapshots.sh` reported a diff on the day after it was committed — a red gate no
    /// edit could explain, which the only available repair (re-commit the regenerated file)
    /// turned into the false-green direction.
    ///
    /// The assertion is what a *snapshot* needs rather than what a *control* needs: the fill must
    /// land on a fixed day, and it must land there from every starting date. The control's own
    /// today-default is asserted alongside, so a fix that pinned the constructor instead of the
    /// sample cannot pass this.
    #[test]
    fn the_calendar_sample_is_pinned_to_a_fixed_day() {
        let rect = crate::core::Rect::new(0, 0, 240, 120);
        let mut calendar = Calendar::new(rect);
        assert_eq!(
            calendar.selected_date(),
            chrono::Local::now().date_naive(),
            "the constructor still opens on today, which a host depends on"
        );
        assert!(apply("calendar", &mut calendar), "the calendar owns a clock-derived default");
        assert_eq!(
            calendar.selected_date(),
            chrono::NaiveDate::from_ymd_opt(2026, 9, 16).expect("a valid literal date"),
            "the sample must name a fixed day or the snapshot changes every midnight"
        );
        // The displayed month follows the selection, so the grid shows the pinned month too.
        assert_eq!(calendar.display_month(), calendar.selected_date());
    }

    /// The table's two routes expose the same data, so `data_grid.svg` and `table_widget.svg` differ only
    /// by layout.
    ///
    /// Two datasets would make every comparison between those snapshots a comparison of content as well,
    /// which is how a layout regression gets read as "the data changed".
    #[test]
    fn both_table_routes_expose_the_same_cells() {
        for row in 0..sample::ROWS.len() {
            for column in 0..sample::HEADERS.len() {
                assert_eq!(
                    SampleTableModel.data(row, column),
                    SampleTableSource.data(row, column),
                    "row {row} column {column} disagrees between the two table routes"
                );
            }
        }
        assert_eq!(SampleTableModel.row_count(), SampleTableSource.row_count());
        assert_eq!(SampleTableModel.column_count(), SampleTableSource.column_count());
        // And an out-of-range cell is absent rather than fabricated.
        assert_eq!(SampleTableModel.data(99, 0), None);
        assert_eq!(SampleTableSource.data(0, 99), None);
    }
}