Skip to main content

native_gui_core/
widgets.rs

1use std::cell::RefCell;
2use std::collections::{BTreeSet, HashMap, VecDeque};
3use std::rc::Rc;
4use std::sync::Arc;
5
6use crate::access::AccessibilitySpec;
7use crate::artprov::IconRole;
8use crate::error::{GuiError, GuiResult};
9use crate::pickers::{ColorDialogData, FontDescriptor, FontDialogData};
10use crate::toolbar::{ToolbarItem, ToolbarOrientation};
11
12/// Opaque identifier for a widget instance managed by [`crate::Ui`].
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub struct WidgetId(pub u64);
15
16/// Host GPU surfaces that a backend can expose to an external renderer.
17///
18/// These flags describe host-surface integration, not the presence of a
19/// Vulkan SDK, device, or driver. `raw_window_handle` is true only when the
20/// backend returns descriptors compatible with `raw-window-handle`.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub struct GpuSurfaceCapabilities {
23    pub vulkan_surface: bool,
24    pub metal_surface: bool,
25    pub directx_surface: bool,
26    pub raw_window_handle: bool,
27    pub diagnostic_placeholder: bool,
28    pub headless_emulation: bool,
29}
30
31impl GpuSurfaceCapabilities {
32    /// Returns a capability set with all flags cleared.
33    pub const fn none() -> Self {
34        Self {
35            vulkan_surface: false,
36            metal_surface: false,
37            directx_surface: false,
38            raw_window_handle: false,
39            diagnostic_placeholder: false,
40            headless_emulation: false,
41        }
42    }
43
44    /// Returns a capability set with every currently defined flag enabled.
45    pub const fn all() -> Self {
46        Self {
47            vulkan_surface: true,
48            metal_surface: true,
49            directx_surface: true,
50            raw_window_handle: true,
51            diagnostic_placeholder: true,
52            headless_emulation: true,
53        }
54    }
55
56    /// Tests a standard GPU-surface capability identifier. Unknown identifiers
57    /// return `false`.
58    pub fn supports(self, capability: &str) -> bool {
59        match capability {
60            "vulkan_surface" => self.vulkan_surface,
61            "metal_surface" => self.metal_surface,
62            "directx_surface" => self.directx_surface,
63            "raw_window_handle" => self.raw_window_handle,
64            "diagnostic_placeholder" => self.diagnostic_placeholder,
65            "headless_emulation" => self.headless_emulation,
66            "gpu_degradation_fallback" => self.diagnostic_placeholder || self.headless_emulation,
67            "gpu_surface" => self.vulkan_surface || self.metal_surface || self.directx_surface,
68            _ => false,
69        }
70    }
71}
72
73impl Default for GpuSurfaceCapabilities {
74    fn default() -> Self {
75        Self::none()
76    }
77}
78
79/// Behavior requested when a Vulkan canvas cannot obtain a host surface.
80#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
81pub enum GpuDegradationPolicy {
82    /// Return `GuiError::UnsupportedCapability("vulkan_surface")`.
83    #[default]
84    StrictFail,
85    /// Substitute a diagnostic placeholder when the backend implements it.
86    DiagnosticPlaceholder,
87    /// Substitute a 2D canvas when the backend implements it.
88    Canvas2DFallback,
89}
90
91/// Cross-platform widget kinds supported by the abstraction layer.
92#[non_exhaustive]
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
95pub enum WidgetKind {
96    Window,
97    Container,
98    Label,
99    Button,
100    #[cfg(feature = "widgets-choice")]
101    RadioButton,
102    #[cfg(feature = "widgets-range")]
103    Slider,
104    #[cfg(feature = "widgets-range")]
105    SpinBox,
106    #[cfg(feature = "widgets-containers")]
107    Separator,
108    #[cfg(feature = "widgets-containers")]
109    GroupBox,
110    #[cfg(feature = "widgets-containers")]
111    Tabs,
112    #[cfg(feature = "widgets-media")]
113    Image,
114    #[cfg(feature = "widgets-pickers")]
115    DatePicker,
116    #[cfg(feature = "widgets-text")]
117    LinkLabel,
118    #[cfg(feature = "widgets-data")]
119    ListView,
120    #[cfg(feature = "widgets-data")]
121    TreeView,
122    #[cfg(feature = "widgets-containers")]
123    SplitPane,
124    #[cfg(feature = "widgets-pickers")]
125    FileChooserDialog,
126    #[cfg(feature = "widgets-containers")]
127    AlertDialog,
128    #[cfg(feature = "widgets-text")]
129    TextInput,
130    #[cfg(feature = "widgets-text")]
131    TextArea,
132    #[cfg(feature = "widgets-canvas")]
133    VulkanCanvas,
134    #[cfg(feature = "widgets-canvas")]
135    /// Native Apple Metal rendering surface backed by `CAMetalLayer` on macOS.
136    MetalCanvas,
137    #[cfg(feature = "widgets-choice")]
138    Checkbox,
139    #[cfg(feature = "widgets-choice")]
140    ComboBox,
141    #[cfg(feature = "widgets-range")]
142    ProgressBar,
143    #[cfg(feature = "widgets-data")]
144    DataList,
145    #[cfg(feature = "widgets-data")]
146    DataGrid,
147    #[cfg(feature = "widgets-canvas")]
148    Canvas,
149    /// Portable colour picker; the native dialog mappings land in
150    /// a later step, so lanes without them report the typed unsupported error.
151    #[cfg(feature = "widgets-pickers")]
152    ColorDialog,
153    /// Portable font picker; the native dialog mappings land in
154    /// a later step, so lanes without them report the typed unsupported error.
155    #[cfg(feature = "widgets-pickers")]
156    FontDialog,
157    /// Portable toolbar: stable tool ids, separators, checkable and
158    /// radio tools, and dropdown requests. The native compositions land in
159    /// a later step, so lanes without them report the typed unsupported error.
160    Toolbar,
161    /// Portable calendar month grid.
162    #[cfg(feature = "widgets-pickers")]
163    Calendar,
164    /// Editable text widget with styled runs.
165    #[cfg(feature = "widgets-text")]
166    RichText,
167    /// Multiple selection choice list or dropdown.
168    #[cfg(feature = "widgets-choice")]
169    MultiSelect,
170}
171
172/// Every [`WidgetKind`] variant, in declaration order.
173///
174/// The applicability rows of [`WidgetProperty`] and the table-driven
175/// guard-matrix test walk this list, so adding a kind here makes every row
176/// re-considered instead of silently stale.
177pub const ALL_KINDS: &[WidgetKind] = &[
178    WidgetKind::Window,
179    WidgetKind::Container,
180    WidgetKind::Label,
181    WidgetKind::Button,
182    #[cfg(feature = "widgets-choice")]
183    WidgetKind::RadioButton,
184    #[cfg(feature = "widgets-range")]
185    WidgetKind::Slider,
186    #[cfg(feature = "widgets-range")]
187    WidgetKind::SpinBox,
188    #[cfg(feature = "widgets-containers")]
189    WidgetKind::Separator,
190    #[cfg(feature = "widgets-containers")]
191    WidgetKind::GroupBox,
192    #[cfg(feature = "widgets-containers")]
193    WidgetKind::Tabs,
194    #[cfg(feature = "widgets-media")]
195    WidgetKind::Image,
196    #[cfg(feature = "widgets-pickers")]
197    WidgetKind::DatePicker,
198    #[cfg(feature = "widgets-text")]
199    WidgetKind::LinkLabel,
200    #[cfg(feature = "widgets-data")]
201    WidgetKind::ListView,
202    #[cfg(feature = "widgets-data")]
203    WidgetKind::TreeView,
204    #[cfg(feature = "widgets-containers")]
205    WidgetKind::SplitPane,
206    #[cfg(feature = "widgets-pickers")]
207    WidgetKind::FileChooserDialog,
208    #[cfg(feature = "widgets-containers")]
209    WidgetKind::AlertDialog,
210    #[cfg(feature = "widgets-text")]
211    WidgetKind::TextInput,
212    #[cfg(feature = "widgets-text")]
213    WidgetKind::TextArea,
214    #[cfg(feature = "widgets-canvas")]
215    WidgetKind::VulkanCanvas,
216    #[cfg(feature = "widgets-canvas")]
217    WidgetKind::MetalCanvas,
218    #[cfg(feature = "widgets-choice")]
219    WidgetKind::Checkbox,
220    #[cfg(feature = "widgets-choice")]
221    WidgetKind::ComboBox,
222    #[cfg(feature = "widgets-range")]
223    WidgetKind::ProgressBar,
224    #[cfg(feature = "widgets-data")]
225    WidgetKind::DataList,
226    #[cfg(feature = "widgets-data")]
227    WidgetKind::DataGrid,
228    #[cfg(feature = "widgets-canvas")]
229    WidgetKind::Canvas,
230    #[cfg(feature = "widgets-pickers")]
231    WidgetKind::ColorDialog,
232    #[cfg(feature = "widgets-pickers")]
233    WidgetKind::FontDialog,
234    WidgetKind::Toolbar,
235    #[cfg(feature = "widgets-pickers")]
236    WidgetKind::Calendar,
237    #[cfg(feature = "widgets-text")]
238    WidgetKind::RichText,
239    #[cfg(feature = "widgets-choice")]
240    WidgetKind::MultiSelect,
241];
242
243/// A kind-restricted widget property, shared by [`crate::Ui`] and the backends.
244///
245/// `WidgetSpec` is a flat struct, so a property that only makes sense for some
246/// kinds (say `range` on a `Slider`) is rejected at runtime with
247/// [`GuiError::UnsupportedWidget`]. This enum single-sources those rejections —
248/// ADR decision 1-2 in the `adr-widgetspec-typing.md` decision record: every `Ui::set_*` guard
249/// and backend kind guard asks [`WidgetProperty::supports`] (through
250/// [`WidgetSpec::ensure_property`]) instead of repeating `matches!` lists, and
251/// the table-driven guard-matrix test asserts that every setter rejects every
252/// kind outside its row with the typed error.
253///
254/// Two families stay out of the table on purpose:
255///
256/// - universally applicable properties (`text`, `size`, `position`,
257///   `background_color`, `enabled`, `focusable`, `tooltip`, accessibility
258///   metadata) carry no kind restriction to encode, and
259/// - per-lane mapping limits (Cocoa's control-scoped `enabled`/`focusable`,
260///   the theme-override text kinds) are backend capabilities, not model
261///   applicability. A lane that cannot map a valid property reports
262///   [`GuiError::UnsupportedCapability`] rather than a kind error.
263#[non_exhaustive]
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
265pub enum WidgetProperty {
266    /// Checked state (`Checkbox`, `RadioButton`).
267    Checked,
268    /// Numeric value (`Slider`, `SpinBox`, `ProgressBar`).
269    Value,
270    /// Numeric `(min, max)` range (`Slider`, `SpinBox`).
271    Range,
272    /// Numeric step (`Slider`, `SpinBox`).
273    Step,
274    /// Selected item/page index (`Tabs`, `ComboBox`, `DataList`, `ListView`).
275    SelectedIndex,
276    /// Tab page labels (`Tabs`).
277    TabItems,
278    /// Multi-selection indices (`ListView`, `DataList`, `TreeView`).
279    SelectedIndices,
280    /// Row drag source/drop target flags (`ListView`, `DataList`, `DataGrid`,
281    /// `TreeView`).
282    RowDrag,
283    /// Row strings (`DataList`, `ListView`).
284    DataListItems,
285    /// Column headers for the columned list contract (`ListView`).
286    ListViewColumns,
287    /// Row cells for the columned list contract (`ListView`).
288    ListViewRows,
289    /// Row-major cell values (`DataGrid`).
290    DataGridRows,
291    /// Virtual data model (`DataGrid`).
292    DataGridModel,
293    /// Per-row height override (`DataGrid`).
294    DataGridRowHeight,
295    /// Per-column width override (`DataGrid`).
296    DataGridColWidth,
297    /// Frozen row/column counts (`DataGrid`).
298    DataGridFrozenPanes,
299    /// Cell selection overrides (`DataGrid`).
300    DataGridSelection,
301    /// Hierarchical items (`TreeView`).
302    TreeItems,
303    /// Alert severity (`AlertDialog`).
304    AlertLevel,
305    /// Raster image source (`Image`).
306    ImageSource,
307    /// Image scaling mode (`Image`).
308    ImageFit,
309    /// Button art: optional stock-art role rendered beside the label
310    /// (`Button`, `FileChooserDialog`).
311    ButtonIcon,
312    /// File chooser pick mode (`FileChooserDialog`).
313    FileChooserMode,
314    /// Colour-dialog preferences (`ColorDialog`).
315    ColorDialogData,
316    /// Font-dialog preferences (`FontDialog`).
317    FontDialogData,
318    /// Toolbar tools and separators (`Toolbar`).
319    ToolbarItems,
320    /// Toolbar stacking orientation (`Toolbar`).
321    ToolbarOrientation,
322    /// Date value (`DatePicker`).
323    DateValue,
324    /// Link URL (`LinkLabel`).
325    LinkUrl,
326    /// Text selection range in characters (`TextInput`, `TextArea`).
327    TextSelection,
328    /// Text completion/suggestion items (`TextInput`).
329    TextCompletion,
330    /// Placeholder/hint text (`TextInput`).
331    PlaceholderText,
332    /// Container stacking direction (`Container`, `GroupBox`, `SplitPane`).
333    ContainerDirection,
334    /// Container wrapping mode (`Container`, `GroupBox`, `SplitPane`).
335    ContainerWrap,
336    /// Container scroll flags (`Container`, `GroupBox`, `SplitPane`).
337    ContainerScroll,
338    /// Spacing between flow children (`Container`, `GroupBox`).
339    ContainerGap,
340    /// Inset between the container edges and its flow children (`Container`,
341    /// `GroupBox`).
342    ContainerPadding,
343    /// Retained drawing scene (`Canvas`).
344    CanvasScene,
345    /// Raster paint surface (`Canvas`).
346    CanvasSurface,
347    /// Close-request interception (`Window`).
348    CloseGuard,
349    /// Declarative layout root (`Window`).
350    LayoutRoot,
351    /// Window event callbacks (`Window`).
352    WindowCallback,
353    /// Backend-native Vulkan handle (`VulkanCanvas`).
354    NativeHandle,
355    /// Built-in Vulkan demo scene (`VulkanCanvas`).
356    DrawDemoCube,
357    /// Clipboard copy sources (`DataList`, `ListView`, `DataGrid`, `TextInput`,
358    /// `TextArea`, `Label`).
359    CopyToClipboard,
360    /// Clipboard paste targets (`DataList`, `ListView`, `DataGrid`,
361    /// `TextInput`, `TextArea`, `Label`).
362    PasteFromClipboard,
363    /// Keyed row updates (`DataList`, `ListView`, `DataGrid`).
364    KeyedRows,
365    /// Selection clearing on row widgets (`DataList`, `ListView`,
366    /// `DataGrid`, `TreeView`).
367    ClearSelection,
368    /// Topmost-visible-row anchor query (`DataList`, `ListView`, `DataGrid`).
369    VisibleAnchor,
370    /// Calendar selected dates (`Calendar`).
371    CalendarDates,
372    /// Calendar min/max selectable bounds (`Calendar`).
373    CalendarBounds,
374    /// Calendar first day of week convention (`Calendar`).
375    CalendarFirstDayOfWeek,
376    /// Calendar selection mode (`Calendar`).
377    CalendarSelectionMode,
378    /// Label text alignment (`Label`).
379    LabelAlignment,
380    /// Label line wrap mode (`Label`).
381    LabelWrap,
382    /// Rich text styled runs (`RichText`).
383    RichTextRuns,
384    /// Inline images in rich text (`RichText`).
385    RichTextImages,
386    /// Monospace (code/fixed-pitch) font rendering (`TextArea`, `TextInput`, `Label`, `RichText`).
387    Monospace,
388    /// Backend-native Metal handle (`MetalCanvas`).
389    MetalHandle,
390    /// Explicit widget font family, point size, weight, and slant (`Label`, `Button`, `TextInput`, `TextArea`).
391    Font,
392    /// Per-row stock-art icon roles for list controls (`DataList`, `ListView`).
393    RowIcons,
394}
395
396impl WidgetProperty {
397    /// Every property row, in declaration order.
398    pub const ALL: &'static [WidgetProperty] = &[
399        WidgetProperty::Checked,
400        WidgetProperty::Value,
401        WidgetProperty::Range,
402        WidgetProperty::Step,
403        WidgetProperty::SelectedIndex,
404        WidgetProperty::TabItems,
405        WidgetProperty::SelectedIndices,
406        WidgetProperty::RowDrag,
407        WidgetProperty::DataListItems,
408        WidgetProperty::ListViewColumns,
409        WidgetProperty::ListViewRows,
410        WidgetProperty::DataGridRows,
411        WidgetProperty::DataGridModel,
412        WidgetProperty::DataGridRowHeight,
413        WidgetProperty::DataGridColWidth,
414        WidgetProperty::DataGridFrozenPanes,
415        WidgetProperty::DataGridSelection,
416        WidgetProperty::TreeItems,
417        WidgetProperty::AlertLevel,
418        WidgetProperty::ImageSource,
419        WidgetProperty::ImageFit,
420        WidgetProperty::ButtonIcon,
421        WidgetProperty::FileChooserMode,
422        WidgetProperty::ColorDialogData,
423        WidgetProperty::FontDialogData,
424        WidgetProperty::ToolbarItems,
425        WidgetProperty::ToolbarOrientation,
426        WidgetProperty::DateValue,
427        WidgetProperty::LinkUrl,
428        WidgetProperty::TextSelection,
429        WidgetProperty::TextCompletion,
430        WidgetProperty::ContainerDirection,
431        WidgetProperty::ContainerWrap,
432        WidgetProperty::ContainerScroll,
433        WidgetProperty::ContainerGap,
434        WidgetProperty::ContainerPadding,
435        WidgetProperty::CanvasScene,
436        WidgetProperty::CanvasSurface,
437        WidgetProperty::CloseGuard,
438        WidgetProperty::LayoutRoot,
439        WidgetProperty::WindowCallback,
440        WidgetProperty::NativeHandle,
441        WidgetProperty::DrawDemoCube,
442        WidgetProperty::CopyToClipboard,
443        WidgetProperty::PasteFromClipboard,
444        WidgetProperty::KeyedRows,
445        WidgetProperty::ClearSelection,
446        WidgetProperty::VisibleAnchor,
447        WidgetProperty::CalendarDates,
448        WidgetProperty::CalendarBounds,
449        WidgetProperty::CalendarFirstDayOfWeek,
450        WidgetProperty::CalendarSelectionMode,
451        WidgetProperty::LabelAlignment,
452        WidgetProperty::LabelWrap,
453        WidgetProperty::RichTextRuns,
454        WidgetProperty::PlaceholderText,
455        WidgetProperty::RichTextImages,
456        WidgetProperty::Monospace,
457        WidgetProperty::MetalHandle,
458        WidgetProperty::Font,
459        WidgetProperty::RowIcons,
460    ];
461
462    /// The kinds this property accepts — the single source of truth for every
463    /// `Ui::set_*` guard and backend kind guard.
464    pub const fn applicable_kinds(self) -> &'static [WidgetKind] {
465        match self {
466            #[cfg(feature = "widgets-choice")]
467            WidgetProperty::Checked => &[WidgetKind::Checkbox, WidgetKind::RadioButton],
468            #[cfg(not(feature = "widgets-choice"))]
469            WidgetProperty::Checked => &[],
470            #[cfg(feature = "widgets-range")]
471            WidgetProperty::Value => &[
472                WidgetKind::Slider,
473                WidgetKind::SpinBox,
474                WidgetKind::ProgressBar,
475            ],
476            #[cfg(not(feature = "widgets-range"))]
477            WidgetProperty::Value => &[],
478            #[cfg(feature = "widgets-range")]
479            WidgetProperty::Range | WidgetProperty::Step => {
480                &[WidgetKind::Slider, WidgetKind::SpinBox]
481            }
482            #[cfg(not(feature = "widgets-range"))]
483            WidgetProperty::Range | WidgetProperty::Step => &[],
484            WidgetProperty::SelectedIndex => {
485                const KINDS: &[WidgetKind] = &[
486                    #[cfg(feature = "widgets-containers")]
487                    WidgetKind::Tabs,
488                    #[cfg(feature = "widgets-choice")]
489                    WidgetKind::ComboBox,
490                    #[cfg(feature = "widgets-data")]
491                    WidgetKind::DataList,
492                    #[cfg(feature = "widgets-data")]
493                    WidgetKind::ListView,
494                ];
495                KINDS
496            }
497            #[cfg(feature = "widgets-containers")]
498            WidgetProperty::TabItems => &[WidgetKind::Tabs],
499            #[cfg(not(feature = "widgets-containers"))]
500            WidgetProperty::TabItems => &[],
501            #[cfg(all(feature = "widgets-choice", feature = "widgets-data"))]
502            WidgetProperty::SelectedIndices => &[
503                WidgetKind::ListView,
504                WidgetKind::DataList,
505                WidgetKind::TreeView,
506                WidgetKind::MultiSelect,
507            ],
508            #[cfg(all(feature = "widgets-choice", not(feature = "widgets-data")))]
509            WidgetProperty::SelectedIndices => &[WidgetKind::MultiSelect],
510            #[cfg(all(not(feature = "widgets-choice"), feature = "widgets-data"))]
511            WidgetProperty::SelectedIndices => &[
512                WidgetKind::ListView,
513                WidgetKind::DataList,
514                WidgetKind::TreeView,
515            ],
516            #[cfg(all(not(feature = "widgets-choice"), not(feature = "widgets-data")))]
517            WidgetProperty::SelectedIndices => &[],
518            #[cfg(feature = "widgets-data")]
519            WidgetProperty::RowDrag => &[
520                WidgetKind::ListView,
521                WidgetKind::DataList,
522                WidgetKind::DataGrid,
523                WidgetKind::TreeView,
524            ],
525            #[cfg(not(feature = "widgets-data"))]
526            WidgetProperty::RowDrag => &[],
527            #[cfg(all(feature = "widgets-choice", feature = "widgets-data"))]
528            WidgetProperty::DataListItems => &[
529                WidgetKind::DataList,
530                WidgetKind::ListView,
531                WidgetKind::MultiSelect,
532            ],
533            #[cfg(all(feature = "widgets-choice", not(feature = "widgets-data")))]
534            WidgetProperty::DataListItems => &[WidgetKind::MultiSelect],
535            #[cfg(all(not(feature = "widgets-choice"), feature = "widgets-data"))]
536            WidgetProperty::DataListItems => &[WidgetKind::DataList, WidgetKind::ListView],
537            #[cfg(all(not(feature = "widgets-choice"), not(feature = "widgets-data")))]
538            WidgetProperty::DataListItems => &[],
539            #[cfg(feature = "widgets-data")]
540            WidgetProperty::ListViewColumns | WidgetProperty::ListViewRows => {
541                &[WidgetKind::ListView]
542            }
543            #[cfg(not(feature = "widgets-data"))]
544            WidgetProperty::ListViewColumns | WidgetProperty::ListViewRows => &[],
545            #[cfg(feature = "widgets-data")]
546            WidgetProperty::DataGridRows
547            | WidgetProperty::DataGridModel
548            | WidgetProperty::DataGridRowHeight
549            | WidgetProperty::DataGridColWidth
550            | WidgetProperty::DataGridFrozenPanes
551            | WidgetProperty::DataGridSelection => &[WidgetKind::DataGrid],
552            #[cfg(not(feature = "widgets-data"))]
553            WidgetProperty::DataGridRows
554            | WidgetProperty::DataGridModel
555            | WidgetProperty::DataGridRowHeight
556            | WidgetProperty::DataGridColWidth
557            | WidgetProperty::DataGridFrozenPanes
558            | WidgetProperty::DataGridSelection => &[],
559            #[cfg(feature = "widgets-data")]
560            WidgetProperty::TreeItems => &[WidgetKind::TreeView],
561            #[cfg(not(feature = "widgets-data"))]
562            WidgetProperty::TreeItems => &[],
563            #[cfg(feature = "widgets-containers")]
564            WidgetProperty::AlertLevel => &[WidgetKind::AlertDialog],
565            #[cfg(not(feature = "widgets-containers"))]
566            WidgetProperty::AlertLevel => &[],
567            #[cfg(feature = "widgets-media")]
568            WidgetProperty::ImageSource | WidgetProperty::ImageFit => &[WidgetKind::Image],
569            #[cfg(not(feature = "widgets-media"))]
570            WidgetProperty::ImageSource | WidgetProperty::ImageFit => &[],
571            #[cfg(feature = "widgets-pickers")]
572            WidgetProperty::ButtonIcon => &[WidgetKind::Button, WidgetKind::FileChooserDialog],
573            #[cfg(not(feature = "widgets-pickers"))]
574            WidgetProperty::ButtonIcon => &[WidgetKind::Button],
575            #[cfg(feature = "widgets-pickers")]
576            WidgetProperty::FileChooserMode => &[WidgetKind::FileChooserDialog],
577            #[cfg(not(feature = "widgets-pickers"))]
578            WidgetProperty::FileChooserMode => &[],
579            #[cfg(feature = "widgets-pickers")]
580            WidgetProperty::ColorDialogData => &[WidgetKind::ColorDialog],
581            #[cfg(not(feature = "widgets-pickers"))]
582            WidgetProperty::ColorDialogData => &[],
583            #[cfg(feature = "widgets-pickers")]
584            WidgetProperty::FontDialogData => &[WidgetKind::FontDialog],
585            #[cfg(not(feature = "widgets-pickers"))]
586            WidgetProperty::FontDialogData => &[],
587            WidgetProperty::ToolbarItems | WidgetProperty::ToolbarOrientation => {
588                &[WidgetKind::Toolbar]
589            }
590            #[cfg(feature = "widgets-pickers")]
591            WidgetProperty::DateValue => &[WidgetKind::DatePicker],
592            #[cfg(not(feature = "widgets-pickers"))]
593            WidgetProperty::DateValue => &[],
594            #[cfg(feature = "widgets-text")]
595            WidgetProperty::LinkUrl => &[WidgetKind::LinkLabel],
596            #[cfg(not(feature = "widgets-text"))]
597            WidgetProperty::LinkUrl => &[],
598            #[cfg(feature = "widgets-text")]
599            WidgetProperty::TextSelection => &[
600                WidgetKind::TextInput,
601                WidgetKind::TextArea,
602                WidgetKind::RichText,
603            ],
604            #[cfg(not(feature = "widgets-text"))]
605            WidgetProperty::TextSelection => &[],
606            #[cfg(feature = "widgets-text")]
607            WidgetProperty::TextCompletion => &[WidgetKind::TextInput],
608            #[cfg(not(feature = "widgets-text"))]
609            WidgetProperty::TextCompletion => &[],
610            WidgetProperty::ContainerDirection
611            | WidgetProperty::ContainerWrap
612            | WidgetProperty::ContainerScroll => {
613                const KINDS: &[WidgetKind] = &[
614                    WidgetKind::Container,
615                    #[cfg(feature = "widgets-containers")]
616                    WidgetKind::GroupBox,
617                    #[cfg(feature = "widgets-containers")]
618                    WidgetKind::SplitPane,
619                ];
620                KINDS
621            }
622            WidgetProperty::ContainerGap | WidgetProperty::ContainerPadding => {
623                const KINDS: &[WidgetKind] = &[
624                    WidgetKind::Container,
625                    #[cfg(feature = "widgets-containers")]
626                    WidgetKind::GroupBox,
627                ];
628                KINDS
629            }
630            #[cfg(feature = "widgets-canvas")]
631            WidgetProperty::CanvasScene | WidgetProperty::CanvasSurface => &[WidgetKind::Canvas],
632            #[cfg(not(feature = "widgets-canvas"))]
633            WidgetProperty::CanvasScene | WidgetProperty::CanvasSurface => &[],
634            WidgetProperty::CloseGuard
635            | WidgetProperty::LayoutRoot
636            | WidgetProperty::WindowCallback => &[WidgetKind::Window],
637            #[cfg(feature = "widgets-canvas")]
638            WidgetProperty::NativeHandle => &[WidgetKind::VulkanCanvas],
639            #[cfg(not(feature = "widgets-canvas"))]
640            WidgetProperty::NativeHandle => &[],
641            #[cfg(feature = "widgets-canvas")]
642            WidgetProperty::DrawDemoCube => &[WidgetKind::VulkanCanvas, WidgetKind::MetalCanvas],
643            #[cfg(not(feature = "widgets-canvas"))]
644            WidgetProperty::DrawDemoCube => &[],
645            WidgetProperty::CopyToClipboard | WidgetProperty::PasteFromClipboard => {
646                const KINDS: &[WidgetKind] = &[
647                    #[cfg(feature = "widgets-data")]
648                    WidgetKind::DataList,
649                    #[cfg(feature = "widgets-data")]
650                    WidgetKind::ListView,
651                    #[cfg(feature = "widgets-data")]
652                    WidgetKind::DataGrid,
653                    #[cfg(feature = "widgets-text")]
654                    WidgetKind::TextInput,
655                    #[cfg(feature = "widgets-text")]
656                    WidgetKind::TextArea,
657                    WidgetKind::Label,
658                ];
659                KINDS
660            }
661            #[cfg(feature = "widgets-data")]
662            WidgetProperty::KeyedRows | WidgetProperty::VisibleAnchor => &[
663                WidgetKind::DataList,
664                WidgetKind::ListView,
665                WidgetKind::DataGrid,
666            ],
667            #[cfg(not(feature = "widgets-data"))]
668            WidgetProperty::KeyedRows | WidgetProperty::VisibleAnchor => &[],
669            #[cfg(feature = "widgets-data")]
670            WidgetProperty::ClearSelection => &[
671                WidgetKind::DataList,
672                WidgetKind::ListView,
673                WidgetKind::DataGrid,
674                WidgetKind::TreeView,
675            ],
676            #[cfg(not(feature = "widgets-data"))]
677            WidgetProperty::ClearSelection => &[],
678            #[cfg(feature = "widgets-pickers")]
679            WidgetProperty::CalendarDates
680            | WidgetProperty::CalendarBounds
681            | WidgetProperty::CalendarFirstDayOfWeek
682            | WidgetProperty::CalendarSelectionMode => &[WidgetKind::Calendar],
683            #[cfg(not(feature = "widgets-pickers"))]
684            WidgetProperty::CalendarDates
685            | WidgetProperty::CalendarBounds
686            | WidgetProperty::CalendarFirstDayOfWeek
687            | WidgetProperty::CalendarSelectionMode => &[],
688            WidgetProperty::LabelAlignment => &[WidgetKind::Label, WidgetKind::Button],
689            WidgetProperty::LabelWrap => &[WidgetKind::Label],
690            #[cfg(feature = "widgets-text")]
691            WidgetProperty::RichTextRuns | WidgetProperty::RichTextImages => {
692                &[WidgetKind::RichText]
693            }
694            #[cfg(not(feature = "widgets-text"))]
695            WidgetProperty::RichTextRuns | WidgetProperty::RichTextImages => &[],
696            #[cfg(feature = "widgets-text")]
697            WidgetProperty::PlaceholderText => &[WidgetKind::TextInput],
698            #[cfg(not(feature = "widgets-text"))]
699            WidgetProperty::PlaceholderText => &[],
700            WidgetProperty::Monospace => {
701                const KINDS: &[WidgetKind] = &[
702                    WidgetKind::Label,
703                    #[cfg(feature = "widgets-text")]
704                    WidgetKind::TextArea,
705                    #[cfg(feature = "widgets-text")]
706                    WidgetKind::TextInput,
707                    #[cfg(feature = "widgets-text")]
708                    WidgetKind::RichText,
709                ];
710                KINDS
711            }
712            #[cfg(feature = "widgets-canvas")]
713            WidgetProperty::MetalHandle => &[WidgetKind::MetalCanvas],
714            #[cfg(not(feature = "widgets-canvas"))]
715            WidgetProperty::MetalHandle => &[],
716            WidgetProperty::Font => {
717                const KINDS: &[WidgetKind] = &[
718                    WidgetKind::Label,
719                    WidgetKind::Button,
720                    #[cfg(feature = "widgets-text")]
721                    WidgetKind::TextInput,
722                    #[cfg(feature = "widgets-text")]
723                    WidgetKind::TextArea,
724                ];
725                KINDS
726            }
727            #[cfg(feature = "widgets-data")]
728            WidgetProperty::RowIcons => &[WidgetKind::DataList, WidgetKind::ListView],
729            #[cfg(not(feature = "widgets-data"))]
730            WidgetProperty::RowIcons => &[],
731        }
732    }
733
734    /// The stable operation name reported by [`GuiError::UnsupportedWidget`];
735    /// it matches the setter that performed the check.
736    pub const fn operation(self) -> &'static str {
737        match self {
738            WidgetProperty::Checked => "set_checked",
739            WidgetProperty::Value => "set_value",
740            WidgetProperty::Range => "set_range",
741            WidgetProperty::Step => "set_step",
742            WidgetProperty::SelectedIndex => "set_selected_index",
743            WidgetProperty::TabItems => "set_tab_items",
744            WidgetProperty::SelectedIndices => "set_selected_indices",
745            WidgetProperty::RowDrag => "set_row_drag",
746            WidgetProperty::DataListItems => "set_data_list_items",
747            WidgetProperty::ListViewColumns => "set_list_columns",
748            WidgetProperty::ListViewRows => "set_list_rows",
749            WidgetProperty::DataGridRows => "set_data_grid_rows",
750            WidgetProperty::DataGridModel => "set_data_grid_model",
751            WidgetProperty::DataGridRowHeight => "set_data_grid_row_height",
752            WidgetProperty::DataGridColWidth => "set_data_grid_col_width",
753            WidgetProperty::DataGridFrozenPanes => "set_data_grid_frozen_panes",
754            WidgetProperty::DataGridSelection => "set_data_grid_selection",
755            WidgetProperty::TreeItems => "set_tree_items",
756            WidgetProperty::AlertLevel => "set_alert_level",
757            WidgetProperty::ImageSource => "set_image_source",
758            WidgetProperty::ImageFit => "set_image_fit",
759            WidgetProperty::ButtonIcon => "set_icon",
760            WidgetProperty::FileChooserMode => "set_file_chooser_mode",
761            WidgetProperty::ColorDialogData => "set_color_dialog_data",
762            WidgetProperty::FontDialogData => "set_font_dialog_data",
763            WidgetProperty::ToolbarItems => "set_toolbar_items",
764            WidgetProperty::ToolbarOrientation => "set_toolbar_orientation",
765            WidgetProperty::DateValue => "set_date_value",
766            WidgetProperty::LinkUrl => "set_link_url",
767            WidgetProperty::TextSelection => "set_text_selection",
768            WidgetProperty::TextCompletion => "set_text_completion_items",
769            WidgetProperty::ContainerDirection => "set_container_direction",
770            WidgetProperty::ContainerWrap => "set_container_wrap",
771            WidgetProperty::ContainerScroll => "set_container_scroll",
772            WidgetProperty::ContainerGap => "set_container_gap",
773            WidgetProperty::ContainerPadding => "set_container_padding",
774            WidgetProperty::CanvasScene => "set_canvas_scene",
775            WidgetProperty::CanvasSurface => "set_canvas_surface",
776            WidgetProperty::CloseGuard => "set_close_guard",
777            WidgetProperty::LayoutRoot => "set_layout_root",
778            WidgetProperty::WindowCallback => "window_callback",
779            WidgetProperty::NativeHandle => "native_handle",
780            WidgetProperty::DrawDemoCube => "draw_demo_cube",
781            WidgetProperty::CopyToClipboard => "copy_to_clipboard",
782            WidgetProperty::PasteFromClipboard => "paste_from_clipboard",
783            WidgetProperty::KeyedRows => "set_rows_keyed",
784            WidgetProperty::ClearSelection => "clear_selection",
785            WidgetProperty::VisibleAnchor => "visible_anchor",
786            WidgetProperty::CalendarDates => "set_calendar_selected_dates",
787            WidgetProperty::CalendarBounds => "set_calendar_bounds",
788            WidgetProperty::CalendarFirstDayOfWeek => "set_calendar_first_day_of_week",
789            WidgetProperty::CalendarSelectionMode => "set_calendar_selection_mode",
790            WidgetProperty::LabelAlignment => "set_label_alignment",
791            WidgetProperty::LabelWrap => "set_label_wrap",
792            WidgetProperty::RichTextRuns => "set_rich_text_runs",
793            WidgetProperty::PlaceholderText => "set_placeholder_text",
794            WidgetProperty::RichTextImages => "set_rich_text_images",
795            WidgetProperty::Monospace => "set_monospace",
796            WidgetProperty::MetalHandle => "metal_canvas_handle",
797            WidgetProperty::Font => "set_font",
798            WidgetProperty::RowIcons => "set_row_icons",
799        }
800    }
801
802    /// The property name, matching its operation name.
803    pub const fn name(self) -> &'static str {
804        self.operation()
805    }
806
807    /// Whether `kind` is inside this property's applicability row.
808    pub fn supports(self, kind: WidgetKind) -> bool {
809        self.applicable_kinds().contains(&kind)
810    }
811}
812
813impl WidgetKind {
814    /// Checks whether this widget kind supports the specified property.
815    pub fn requires_property(self, property: WidgetProperty) -> bool {
816        property.supports(self)
817    }
818
819    /// Checks whether this widget kind represents a top-level window or dialog surface.
820    pub fn is_window_like(self) -> bool {
821        match self {
822            WidgetKind::Window => true,
823            #[cfg(feature = "widgets-pickers")]
824            WidgetKind::FileChooserDialog | WidgetKind::ColorDialog | WidgetKind::FontDialog => {
825                true
826            }
827            #[cfg(feature = "widgets-containers")]
828            WidgetKind::AlertDialog => true,
829            _ => false,
830        }
831    }
832
833    /// Checks whether this widget kind represents a dialog surface.
834    pub fn is_dialog(self) -> bool {
835        match self {
836            #[cfg(feature = "widgets-pickers")]
837            WidgetKind::FileChooserDialog | WidgetKind::ColorDialog | WidgetKind::FontDialog => {
838                true
839            }
840            #[cfg(feature = "widgets-containers")]
841            WidgetKind::AlertDialog => true,
842            _ => false,
843        }
844    }
845}
846
847/// A Gregorian calendar date with year, month (1..=12), and day (1..=31).
848#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
849#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
850pub struct CalendarDate {
851    pub year: i32,
852    pub month: u32,
853    pub day: u32,
854}
855
856impl CalendarDate {
857    /// Creates a calendar date without validating bounds.
858    pub const fn new(year: i32, month: u32, day: u32) -> Self {
859        Self { year, month, day }
860    }
861
862    /// Returns `true` if the date is a valid Gregorian calendar date.
863    pub fn is_valid(&self) -> bool {
864        if self.year == 0 || self.month < 1 || self.month > 12 {
865            return false;
866        }
867        let max_days = Self::days_in_month(self.year, self.month);
868        self.day >= 1 && self.day <= max_days
869    }
870
871    /// Returns `true` if `year` is a leap year in the Gregorian calendar.
872    pub const fn is_leap_year(year: i32) -> bool {
873        (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
874    }
875
876    /// Returns the number of days in `month` for `year`.
877    pub const fn days_in_month(year: i32, month: u32) -> u32 {
878        match month {
879            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
880            4 | 6 | 9 | 11 => 30,
881            2 => {
882                if Self::is_leap_year(year) {
883                    29
884                } else {
885                    28
886                }
887            }
888            _ => 0,
889        }
890    }
891}
892
893/// The first day of the week convention used in calendar views.
894#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
895#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
896pub enum CalendarFirstDayOfWeek {
897    /// Follow host platform or locale default convention.
898    #[default]
899    LocaleDefault,
900    /// Week starts on Sunday (e.g. US standard).
901    Sunday,
902    /// Week starts on Monday (ISO 8601 standard).
903    Monday,
904}
905
906/// Date selection mode supported by a calendar widget.
907#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
908#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
909pub enum CalendarSelectionMode {
910    /// Exactly one date can be selected at a time.
911    #[default]
912    Single,
913    /// A contiguous range of dates between a start and end date can be selected.
914    Range,
915    /// Arbitrary discrete dates can be selected.
916    Multiple,
917}
918
919/// Text alignment for `WidgetKind::Label`.
920#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
921#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
922pub enum LabelAlignment {
923    /// Left-aligned text (default).
924    #[default]
925    Left,
926    /// Horizontally centered text.
927    Center,
928    /// Right-aligned text.
929    Right,
930}
931
932/// Word-wrap behavior for `WidgetKind::Label`.
933#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
934#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
935pub enum LabelWrap {
936    /// No line wrapping (default).
937    #[default]
938    None,
939    /// Wrap lines on word boundaries.
940    Word,
941    /// Wrap lines on character boundaries.
942    Char,
943    /// Wrap lines on word boundaries, breaking words if necessary.
944    WordChar,
945}
946
947/// Convenience alias for [`LabelWrap`].
948pub type LabelWrapMode = LabelWrap;
949
950impl LabelWrap {
951    /// Alias for [`LabelWrap::None`].
952    pub const NO_WRAP: Self = Self::None;
953
954    /// Alias for [`LabelWrap::None`].
955    #[allow(non_upper_case_globals)]
956    pub const NoWrap: Self = Self::None;
957
958    /// Returns `true` if line wrapping is active.
959    pub const fn is_wrapping(self) -> bool {
960        !matches!(self, Self::None)
961    }
962}
963
964impl From<bool> for LabelWrap {
965    fn from(wrap: bool) -> Self {
966        if wrap {
967            Self::Word
968        } else {
969            Self::None
970        }
971    }
972}
973
974impl From<TextAlignment> for LabelAlignment {
975    fn from(alignment: TextAlignment) -> Self {
976        match alignment {
977            TextAlignment::Left => Self::Left,
978            TextAlignment::Center => Self::Center,
979            TextAlignment::Right => Self::Right,
980        }
981    }
982}
983
984impl From<LabelAlignment> for TextAlignment {
985    fn from(alignment: LabelAlignment) -> Self {
986        match alignment {
987            LabelAlignment::Left => Self::Left,
988            LabelAlignment::Center => Self::Center,
989            LabelAlignment::Right => Self::Right,
990        }
991    }
992}
993
994/// Direction used by container widgets to stack their children.
995#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
996#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
997pub enum ContainerDirection {
998    /// Stack children top-to-bottom.
999    Vertical,
1000    /// Stack children left-to-right.
1001    Horizontal,
1002}
1003
1004/// Wrapping behavior along the flex axis for container widgets.
1005#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1006#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1007pub enum ContainerWrap {
1008    /// Children are forced into a single line.
1009    #[default]
1010    NoWrap,
1011    /// Children wrap onto multiple lines along the cross axis.
1012    Wrap,
1013    /// Children wrap onto multiple lines in reverse cross-axis direction.
1014    WrapReverse,
1015}
1016
1017/// Alert severity for `WidgetKind::AlertDialog`.
1018#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1019#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1020pub enum AlertLevel {
1021    Info,
1022    Warning,
1023    Error,
1024}
1025
1026/// How an image scales into its widget bounds.
1027///
1028/// Every mode centers its result; `None` draws at the image's natural size
1029/// (one image pixel per device-independent pixel) and clips to the widget.
1030#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1031#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1032pub enum ImageFit {
1033    /// Scale uniformly so both axes fit (letterbox on the shorter axis).
1034    #[default]
1035    Contain,
1036    /// Scale uniformly to fill both axes, center-cropping the overflow.
1037    Cover,
1038    /// Stretch non-uniformly to both axes (no crop, no letterbox).
1039    Fill,
1040    /// Draw at the image's natural size, centered and clipped.
1041    None,
1042}
1043
1044impl ImageFit {
1045    /// Stable identifier used by docs, diagnostics, and capability errors.
1046    pub const fn as_str(self) -> &'static str {
1047        match self {
1048            Self::Contain => "contain",
1049            Self::Cover => "cover",
1050            Self::Fill => "fill",
1051            Self::None => "none",
1052        }
1053    }
1054}
1055
1056/// What a `WidgetKind::FileChooserDialog` lets the user pick.
1057#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1058#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1059pub enum FileChooserMode {
1060    /// Pick an existing file (the historical behavior).
1061    #[default]
1062    OpenFile,
1063    /// Pick a folder ("Open Folder…").
1064    PickFolder,
1065    /// Choose a (possibly new) file to write ("Save As…").
1066    SaveFile,
1067}
1068
1069impl FileChooserMode {
1070    /// Stable identifier used by docs, diagnostics, and capability errors.
1071    pub const fn as_str(self) -> &'static str {
1072        match self {
1073            Self::OpenFile => "open-file",
1074            Self::PickFolder => "pick-folder",
1075            Self::SaveFile => "save-file",
1076        }
1077    }
1078}
1079
1080/// RGB background color used for widget styling.
1081#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1082#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1083pub struct Color {
1084    pub r: u8,
1085    pub g: u8,
1086    pub b: u8,
1087}
1088
1089impl Color {
1090    /// Creates a color from red, green, and blue channels.
1091    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
1092        Self { r, g, b }
1093    }
1094}
1095
1096/// Visual and semantic style attributes for a text run in a rich text widget.
1097#[derive(Debug, Clone, PartialEq, Default)]
1098#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1099pub struct TextStyle {
1100    pub bold: bool,
1101    pub italic: bool,
1102    pub underline: bool,
1103    pub strikethrough: bool,
1104    pub monospace: bool,
1105    pub scale: Option<f32>,
1106    pub fg_color: Option<Color>,
1107    pub bg_color: Option<Color>,
1108    pub link: Option<String>,
1109    pub dimmed: bool,
1110    pub paragraph_indent: u32,
1111}
1112
1113impl TextStyle {
1114    /// Creates a default text style with all attributes unset.
1115    pub const fn new() -> Self {
1116        Self {
1117            bold: false,
1118            italic: false,
1119            underline: false,
1120            strikethrough: false,
1121            monospace: false,
1122            scale: None,
1123            fg_color: None,
1124            bg_color: None,
1125            link: None,
1126            dimmed: false,
1127            paragraph_indent: 0,
1128        }
1129    }
1130
1131    /// Sets bold styling.
1132    pub const fn bold(mut self, bold: bool) -> Self {
1133        self.bold = bold;
1134        self
1135    }
1136
1137    /// Sets italic styling.
1138    pub const fn italic(mut self, italic: bool) -> Self {
1139        self.italic = italic;
1140        self
1141    }
1142
1143    /// Sets underline styling.
1144    pub const fn underline(mut self, underline: bool) -> Self {
1145        self.underline = underline;
1146        self
1147    }
1148
1149    /// Sets strikethrough styling.
1150    pub const fn strikethrough(mut self, strikethrough: bool) -> Self {
1151        self.strikethrough = strikethrough;
1152        self
1153    }
1154
1155    /// Sets monospace (code) styling.
1156    pub const fn monospace(mut self, monospace: bool) -> Self {
1157        self.monospace = monospace;
1158        self
1159    }
1160
1161    /// Sets relative font scale (1.0 = normal body size).
1162    pub const fn scale(mut self, scale: f32) -> Self {
1163        self.scale = Some(scale);
1164        self
1165    }
1166
1167    /// Sets foreground text color.
1168    pub const fn fg_color(mut self, color: Color) -> Self {
1169        self.fg_color = Some(color);
1170        self
1171    }
1172
1173    /// Sets background highlight color.
1174    pub const fn bg_color(mut self, color: Color) -> Self {
1175        self.bg_color = Some(color);
1176        self
1177    }
1178
1179    /// Sets link target URL.
1180    pub fn link(mut self, link: impl Into<String>) -> Self {
1181        self.link = Some(link.into());
1182        self
1183    }
1184
1185    /// Sets dimmed styling (marker treatment).
1186    pub const fn dimmed(mut self, dimmed: bool) -> Self {
1187        self.dimmed = dimmed;
1188        self
1189    }
1190
1191    /// Sets paragraph indentation level.
1192    pub const fn paragraph_indent(mut self, indent: u32) -> Self {
1193        self.paragraph_indent = indent;
1194        self
1195    }
1196}
1197
1198/// A styled run of text spanning a byte range within a rich text widget.
1199#[derive(Debug, Clone, PartialEq, Default)]
1200#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1201pub struct TextRun {
1202    pub range: std::ops::Range<usize>,
1203    pub style: TextStyle,
1204}
1205
1206impl TextRun {
1207    /// Creates a new styled run covering `range` with `style`.
1208    pub fn new(range: std::ops::Range<usize>, style: TextStyle) -> Self {
1209        Self { range, style }
1210    }
1211}
1212
1213/// An inline image rendered in-flow within a rich text widget.
1214#[derive(Debug, Clone, PartialEq, Eq)]
1215#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1216pub struct RichTextImage {
1217    pub offset: usize,
1218    pub source: String,
1219    pub max_width: Option<u32>,
1220}
1221
1222impl RichTextImage {
1223    /// Creates a new inline image description at `offset` with `source` and optional `max_width`.
1224    pub fn new(offset: usize, source: impl Into<String>, max_width: Option<u32>) -> Self {
1225        Self {
1226            offset,
1227            source: source.into(),
1228            max_width,
1229        }
1230    }
1231}
1232
1233/// Raw image payload from the system clipboard or screenshot buffer.
1234#[derive(Debug, Clone, PartialEq, Eq)]
1235#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1236pub struct ClipboardImage {
1237    pub width: u32,
1238    pub height: u32,
1239    /// Raw RGBA8 pixel bytes (row-major, 4 bytes per pixel: [R, G, B, A, ...]).
1240    pub rgba: Vec<u8>,
1241    /// Encoded PNG image bytes (from native clipboard or encoded on demand).
1242    pub png_bytes: Vec<u8>,
1243}
1244
1245impl ClipboardImage {
1246    /// Creates a new `ClipboardImage` from raw RGBA8 pixels, automatically encoding PNG bytes.
1247    pub fn new(width: u32, height: u32, rgba: Vec<u8>) -> Self {
1248        let png_bytes = encode_rgba_to_png(width, height, &rgba);
1249        Self {
1250            width,
1251            height,
1252            rgba,
1253            png_bytes,
1254        }
1255    }
1256
1257    /// Creates a `ClipboardImage` with pre-encoded PNG bytes.
1258    pub fn with_png(width: u32, height: u32, rgba: Vec<u8>, png_bytes: Vec<u8>) -> Self {
1259        Self {
1260            width,
1261            height,
1262            rgba,
1263            png_bytes,
1264        }
1265    }
1266}
1267
1268/// Pure, dependency-free RGBA to PNG encoder.
1269pub fn encode_rgba_to_png(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
1270    fn crc32(data: &[u8]) -> u32 {
1271        let mut crc = 0xFFFF_FFFFu32;
1272        for &byte in data {
1273            crc ^= u32::from(byte);
1274            for _ in 0..8 {
1275                let mask = (crc & 1).wrapping_neg();
1276                crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
1277            }
1278        }
1279        !crc
1280    }
1281
1282    fn adler32(data: &[u8]) -> u32 {
1283        let mut s1 = 1u32;
1284        let mut s2 = 0u32;
1285        for &byte in data {
1286            s1 = (s1 + u32::from(byte)) % 65521;
1287            s2 = (s2 + s1) % 65521;
1288        }
1289        (s2 << 16) | s1
1290    }
1291
1292    let mut out = Vec::new();
1293    out.extend_from_slice(b"\x89PNG\r\n\x1a\n");
1294
1295    // IHDR
1296    let mut ihdr = Vec::with_capacity(13);
1297    ihdr.extend_from_slice(&width.to_be_bytes());
1298    ihdr.extend_from_slice(&height.to_be_bytes());
1299    ihdr.push(8); // 8-bit depth
1300    ihdr.push(6); // color type 6: RGBA
1301    ihdr.push(0); // compression 0
1302    ihdr.push(0); // filter 0
1303    ihdr.push(0); // interlace 0
1304
1305    let mut ihdr_chunk = Vec::new();
1306    ihdr_chunk.extend_from_slice(b"IHDR");
1307    ihdr_chunk.extend_from_slice(&ihdr);
1308    let ihdr_crc = crc32(&ihdr_chunk);
1309
1310    out.extend_from_slice(&(ihdr.len() as u32).to_be_bytes());
1311    out.extend_from_slice(&ihdr_chunk);
1312    out.extend_from_slice(&ihdr_crc.to_be_bytes());
1313
1314    // Scanlines with filter byte 0 (None)
1315    let w_bytes = (width as usize) * 4;
1316    let mut raw = Vec::with_capacity((height as usize) * (w_bytes + 1));
1317    for y in 0..(height as usize) {
1318        raw.push(0); // Filter type 0
1319        let start = y * w_bytes;
1320        let end = (start + w_bytes).min(rgba.len());
1321        if start < rgba.len() {
1322            raw.extend_from_slice(&rgba[start..end]);
1323            if end - start < w_bytes {
1324                raw.resize(raw.len() + (w_bytes - (end - start)), 0);
1325            }
1326        } else {
1327            raw.resize(raw.len() + w_bytes, 0);
1328        }
1329    }
1330
1331    // zlib stream: 0x78, 0x01 (deflate uncompressed)
1332    let mut zlib = Vec::new();
1333    zlib.push(0x78);
1334    zlib.push(0x01);
1335
1336    let chunks: Vec<&[u8]> = if raw.is_empty() {
1337        vec![&[]]
1338    } else {
1339        raw.chunks(65535).collect()
1340    };
1341    let total_chunks = chunks.len();
1342    for (i, chunk) in chunks.iter().enumerate() {
1343        let is_final = i == total_chunks - 1;
1344        let header = if is_final { 0x01 } else { 0x00 };
1345        zlib.push(header);
1346        let len = chunk.len() as u16;
1347        let nlen = !len;
1348        zlib.extend_from_slice(&len.to_le_bytes());
1349        zlib.extend_from_slice(&nlen.to_le_bytes());
1350        zlib.extend_from_slice(chunk);
1351    }
1352    let adler = adler32(&raw);
1353    zlib.extend_from_slice(&adler.to_be_bytes());
1354
1355    // IDAT
1356    let mut idat_chunk = Vec::new();
1357    idat_chunk.extend_from_slice(b"IDAT");
1358    idat_chunk.extend_from_slice(&zlib);
1359    let idat_crc = crc32(&idat_chunk);
1360
1361    out.extend_from_slice(&(zlib.len() as u32).to_be_bytes());
1362    out.extend_from_slice(&idat_chunk);
1363    out.extend_from_slice(&idat_crc.to_be_bytes());
1364
1365    // IEND
1366    let mut iend_chunk = Vec::new();
1367    iend_chunk.extend_from_slice(b"IEND");
1368    let iend_crc = crc32(&iend_chunk);
1369
1370    out.extend_from_slice(&0u32.to_be_bytes());
1371    out.extend_from_slice(&iend_chunk);
1372    out.extend_from_slice(&iend_crc.to_be_bytes());
1373
1374    out
1375}
1376
1377/// Rectangle geometry used by `CanvasScene` primitives.
1378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1379pub struct CanvasRect {
1380    pub x: i32,
1381    pub y: i32,
1382    pub width: i32,
1383    pub height: i32,
1384}
1385
1386/// Immutable RGBA8 raster surface painted beneath a `WidgetKind::Canvas`
1387/// scene.
1388///
1389/// The buffer is row-major with four bytes per pixel (`width * height * 4`)
1390/// and is shared behind an `Arc`, so cloning a surface into the widget spec,
1391/// the backend, and a paint property is cheap. Backends composite it over the
1392/// canvas background and clip it to the widget; the retained scene draws on
1393/// top. Full typed image resources with source rectangles and sampling remain
1394/// the scope (`docs/design/canvas-api-rfc.md`, superseding note).
1395#[derive(Debug, Clone, PartialEq, Eq)]
1396pub struct CanvasSurface {
1397    width: u32,
1398    height: u32,
1399    pixels: Arc<Vec<u8>>,
1400}
1401
1402impl CanvasSurface {
1403    /// Wraps a row-major RGBA8 buffer after validating its dimensions.
1404    pub fn from_rgba(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self, GuiError> {
1405        if width == 0 || height == 0 {
1406            return Err(GuiError::Backend(
1407                "canvas surface dimensions must be non-zero".to_owned(),
1408            ));
1409        }
1410        let expected = width as usize * height as usize * 4;
1411        if pixels.len() != expected {
1412            return Err(GuiError::Backend(format!(
1413                "canvas surface expects {expected} bytes, found {}",
1414                pixels.len()
1415            )));
1416        }
1417        Ok(Self {
1418            width,
1419            height,
1420            pixels: Arc::new(pixels),
1421        })
1422    }
1423
1424    /// Surface width in pixels.
1425    pub fn width(&self) -> u32 {
1426        self.width
1427    }
1428
1429    /// Surface height in pixels.
1430    pub fn height(&self) -> u32 {
1431        self.height
1432    }
1433
1434    /// Row-major RGBA8 bytes.
1435    pub fn pixels(&self) -> &[u8] {
1436        &self.pixels
1437    }
1438}
1439
1440/// A canvas scene is a logical drawing surface of primitives.
1441#[derive(Debug, Clone, PartialEq)]
1442pub struct CanvasScene {
1443    pub primitives: Vec<CanvasPrimitive>,
1444    pub logical_width: f32,
1445    pub logical_height: f32,
1446}
1447
1448impl CanvasScene {
1449    pub fn new(logical_width: f32, logical_height: f32) -> Self {
1450        Self {
1451            primitives: Vec::new(),
1452            logical_width,
1453            logical_height,
1454        }
1455    }
1456
1457    /// Validates the scene's logical content size before it reaches a backend.
1458    pub fn validate(&self) -> GuiResult<()> {
1459        let invalid = !self.logical_width.is_finite()
1460            || !self.logical_height.is_finite()
1461            || self.logical_width <= 0.0
1462            || self.logical_height <= 0.0;
1463
1464        if invalid {
1465            return Err(GuiError::Backend(
1466                "Canvas scene logical size must be finite and positive".to_owned(),
1467            ));
1468        }
1469        Ok(())
1470    }
1471}
1472
1473/// A primitive in a canvas scene.
1474#[derive(Debug, Clone, PartialEq, Eq)]
1475pub enum CanvasPrimitive {
1476    Rect {
1477        rect: CanvasRect,
1478        fill: Option<Color>,
1479        stroke: Option<Color>,
1480        stroke_width: u8,
1481    },
1482    Line {
1483        from: (i32, i32),
1484        to: (i32, i32),
1485        color: Color,
1486        width: u8,
1487    },
1488    /// Single-line text. `pos` is the top-left corner of the text box in
1489    /// scene coordinates (not the baseline), on every backend.
1490    Text {
1491        pos: (i32, i32),
1492        text: String,
1493        color: Color,
1494        size: u8,
1495    },
1496    Image {
1497        rect: CanvasRect,
1498        source: String,
1499    },
1500}
1501
1502/// Hierarchical item for `WidgetKind::TreeView` content.
1503#[derive(Debug, Clone, PartialEq, Eq)]
1504pub struct TreeItem {
1505    /// Display label for this node.
1506    pub label: String,
1507    /// Child nodes (empty for leaves).
1508    pub children: Vec<TreeItem>,
1509}
1510
1511impl TreeItem {
1512    /// Creates a leaf node.
1513    pub fn new(label: impl Into<String>) -> Self {
1514        Self {
1515            label: label.into(),
1516            children: Vec::new(),
1517        }
1518    }
1519
1520    /// Appends a child node.
1521    pub fn with_child(mut self, child: TreeItem) -> Self {
1522        self.children.push(child);
1523        self
1524    }
1525
1526    /// Flattens the tree into display rows, indented by depth (first cut:
1527    /// tree views render as selectable indented rows).
1528    pub fn indented_rows(&self) -> Vec<String> {
1529        let mut rows = Vec::new();
1530        self.collect_rows(0, &mut rows);
1531        rows
1532    }
1533
1534    fn collect_rows(&self, depth: usize, rows: &mut Vec<String>) {
1535        rows.push(format!("{}{}", "  ".repeat(depth), self.label));
1536        for child in &self.children {
1537            child.collect_rows(depth + 1, rows);
1538        }
1539    }
1540}
1541
1542/// One column of a columned collection widget.
1543///
1544/// This is the shared column vocabulary for `WidgetKind::ListView`'s
1545/// columned contract; the tree-grid and `TreeView` deepening
1546/// designs adopt the same type, so one column list describes any of them.
1547/// Cells are plain strings, mirroring `WidgetSpec::data_grid_rows`.
1548#[derive(Debug, Clone, PartialEq, Eq)]
1549pub struct ColumnSpec {
1550    /// Header text.
1551    pub title: String,
1552    /// Preferred column width in logical pixels; `None` lets the lane pick
1553    /// its default (most lanes size to the header and cell content).
1554    pub width: Option<i32>,
1555}
1556
1557impl ColumnSpec {
1558    /// Creates a column with the given header text and no width preference.
1559    pub fn new(title: impl Into<String>) -> Self {
1560        Self {
1561            title: title.into(),
1562            width: None,
1563        }
1564    }
1565
1566    /// Sets a preferred width in logical pixels. Non-positive values mean
1567    /// "no preference" (the lane picks its default), matching the shared
1568    /// size semantics elsewhere.
1569    pub fn with_width(mut self, width: i32) -> Self {
1570        self.width = if width > 0 { Some(width) } else { None };
1571        self
1572    }
1573}
1574
1575/// Application-owned row identity for keyed collection updates.
1576///
1577/// Keys are stable for a row's lifetime and never minted or reused by the
1578/// model - the same contract as [`crate::ToolId`] - so a keyed
1579/// apply can tell an edit, a move, and a replacement apart.
1580#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1581#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1582pub struct RowKey(pub u64);
1583
1584/// One keyed row: identity plus the cells the widget renders.
1585#[derive(Debug, Clone, PartialEq, Eq)]
1586#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1587pub struct RowSet {
1588    /// Application-owned identity of this row.
1589    pub key: RowKey,
1590    /// The row's cells: one for `DataList`/`ListView`, N for `DataGrid`.
1591    pub cells: Vec<String>,
1592}
1593
1594impl RowSet {
1595    /// Builds a row from a key and its cells.
1596    pub fn new(key: u64, cells: &[&str]) -> Self {
1597        Self {
1598            key: RowKey(key),
1599            cells: cells.iter().map(|cell| (*cell).to_owned()).collect(),
1600        }
1601    }
1602
1603    /// Single-cell rendering used by `DataList`/`ListView`.
1604    pub fn text(&self) -> String {
1605        self.cells.first().cloned().unwrap_or_default()
1606    }
1607}
1608
1609/// What a keyed row update changed.
1610///
1611/// Each new row is classified once: `inserted` when its key is new, `updated`
1612/// when its cells differ (a moved-and-edited row counts as updated), `moved`
1613/// when the cells are identical but the index changed, `unchanged` otherwise;
1614/// `removed` counts previous keys missing from the new set. An all-zero delta
1615/// ([`Self::is_noop`]) means the backend was not touched at all.
1616#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1617pub struct RowDelta {
1618    pub inserted: usize,
1619    pub updated: usize,
1620    pub removed: usize,
1621    pub moved: usize,
1622    pub unchanged: usize,
1623}
1624
1625impl RowDelta {
1626    /// True when keys, order, and cells are all identical to the previous
1627    /// set: a no-op keyed apply performs no backend write.
1628    pub fn is_noop(&self) -> bool {
1629        self.inserted == 0 && self.updated == 0 && self.removed == 0 && self.moved == 0
1630    }
1631}
1632
1633/// Classifies `new_rows` against `old_rows` without touching either.
1634///
1635/// Duplicate keys in `new_rows` are rejected with
1636/// [`GuiError::Backend`]`("duplicate row key")` and nothing is classified;
1637/// the caller keeps its previous rows and selection.
1638///
1639/// ```
1640/// use native_gui_core::widgets::{diff_rows, RowDelta, RowSet};
1641///
1642/// let old = [RowSet::new(1, &["a"]), RowSet::new(2, &["b"])];
1643/// let new = [RowSet::new(2, &["b"]), RowSet::new(3, &["c"])];
1644/// let delta = diff_rows(&old, &new).expect("unique keys");
1645/// assert_eq!(delta, RowDelta { inserted: 1, updated: 0, removed: 1, moved: 1, unchanged: 0 });
1646/// assert!(!delta.is_noop());
1647/// ```
1648pub fn diff_rows(old_rows: &[RowSet], new_rows: &[RowSet]) -> GuiResult<RowDelta> {
1649    let mut new_keys: std::collections::HashSet<u64> =
1650        std::collections::HashSet::with_capacity(new_rows.len());
1651    for row in new_rows {
1652        if !new_keys.insert(row.key.0) {
1653            return Err(GuiError::Backend("duplicate row key".to_owned()));
1654        }
1655    }
1656
1657    let old_index: std::collections::HashMap<u64, usize> = old_rows
1658        .iter()
1659        .enumerate()
1660        .map(|(index, row)| (row.key.0, index))
1661        .collect();
1662
1663    let mut delta = RowDelta::default();
1664    for (new_pos, row) in new_rows.iter().enumerate() {
1665        match old_index.get(&row.key.0) {
1666            None => delta.inserted += 1,
1667            Some(&old_pos) => {
1668                if old_rows[old_pos].cells != row.cells {
1669                    delta.updated += 1;
1670                } else if old_pos != new_pos {
1671                    delta.moved += 1;
1672                } else {
1673                    delta.unchanged += 1;
1674                }
1675            }
1676        }
1677    }
1678    // The duplicate-check set already holds every new key; reuse it instead
1679    // of building a second set of the same contents.
1680    delta.removed = old_rows
1681        .iter()
1682        .filter(|row| !new_keys.contains(&row.key.0))
1683        .count();
1684    Ok(delta)
1685}
1686
1687/// An incremental operation to apply to a row widget.
1688#[derive(Debug, Clone, PartialEq, Eq)]
1689#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1690pub enum RowOp {
1691    /// Inserts a new row at `index`.
1692    Insert { index: usize, row: RowSet },
1693    /// Replaces the cells of the row at `index`.
1694    Update { index: usize, row: RowSet },
1695    /// Removes the row at `index`.
1696    Remove { index: usize, key: RowKey },
1697    /// Moves a row from `from_index` to `to_index`.
1698    Move {
1699        from_index: usize,
1700        to_index: usize,
1701        key: RowKey,
1702    },
1703    /// Reorders all rows according to the specified permutation of original indices.
1704    Reorder { order: Vec<usize> },
1705}
1706
1707/// Computes incremental [`RowOp`]s transforming `old_rows` into `new_rows`.
1708///
1709/// Returns `None` when a full rebuild is preferred (e.g. initial population or complex re-orderings).
1710pub fn diff_row_ops(
1711    old_rows: &[RowSet],
1712    new_rows: &[RowSet],
1713    delta: &RowDelta,
1714) -> Option<Vec<RowOp>> {
1715    if old_rows.is_empty() || delta.is_noop() {
1716        return None;
1717    }
1718
1719    // Case 1: Pure updates (same keys and order, cell modifications only)
1720    if delta.inserted == 0 && delta.removed == 0 && delta.moved == 0 && delta.updated > 0 {
1721        if old_rows.len() != new_rows.len() {
1722            return None;
1723        }
1724        let mut ops = Vec::with_capacity(delta.updated);
1725        for (i, (old, new)) in old_rows.iter().zip(new_rows.iter()).enumerate() {
1726            if old.key != new.key {
1727                return None;
1728            }
1729            if old.cells != new.cells {
1730                ops.push(RowOp::Update {
1731                    index: i,
1732                    row: new.clone(),
1733                });
1734            }
1735        }
1736        return Some(ops);
1737    }
1738
1739    // Case 2: Single row insert
1740    if delta.inserted == 1 && delta.removed == 0 && delta.updated == 0 {
1741        if new_rows.len() != old_rows.len() + 1 {
1742            return None;
1743        }
1744        let insert_idx = (0..old_rows.len())
1745            .find(|&i| old_rows[i].key != new_rows[i].key)
1746            .unwrap_or(old_rows.len());
1747        // Verify tail matches
1748        if new_rows[insert_idx + 1..] == old_rows[insert_idx..] {
1749            return Some(vec![RowOp::Insert {
1750                index: insert_idx,
1751                row: new_rows[insert_idx].clone(),
1752            }]);
1753        }
1754        return None;
1755    }
1756
1757    // Case 3: Single row remove
1758    if delta.removed == 1 && delta.inserted == 0 && delta.updated == 0 {
1759        if old_rows.len() != new_rows.len() + 1 {
1760            return None;
1761        }
1762        let remove_idx = (0..new_rows.len())
1763            .find(|&i| old_rows[i].key != new_rows[i].key)
1764            .unwrap_or(new_rows.len());
1765        // Verify tail matches
1766        if old_rows[remove_idx + 1..] == new_rows[remove_idx..] {
1767            return Some(vec![RowOp::Remove {
1768                index: remove_idx,
1769                key: old_rows[remove_idx].key,
1770            }]);
1771        }
1772        return None;
1773    }
1774
1775    // Case 4: Single row move or reorder
1776    if delta.moved > 0 && delta.inserted == 0 && delta.removed == 0 && delta.updated == 0 {
1777        if old_rows.len() != new_rows.len() {
1778            return None;
1779        }
1780        let old_index: std::collections::HashMap<u64, usize> = old_rows
1781            .iter()
1782            .enumerate()
1783            .map(|(index, row)| (row.key.0, index))
1784            .collect();
1785        let order: Vec<usize> = new_rows
1786            .iter()
1787            .filter_map(|r| old_index.get(&r.key.0).copied())
1788            .collect();
1789        if order.len() != old_rows.len() {
1790            return None;
1791        }
1792
1793        // Check if this permutation is a single element moved
1794        for (to_idx, &from_idx) in order.iter().enumerate() {
1795            if to_idx == from_idx {
1796                continue;
1797            }
1798            let mut matches = true;
1799            let mut expected = 0;
1800            for (new_i, &old_i) in order.iter().enumerate() {
1801                if new_i == to_idx {
1802                    continue;
1803                }
1804                if expected == from_idx {
1805                    expected += 1;
1806                }
1807                if old_i != expected {
1808                    matches = false;
1809                    break;
1810                }
1811                expected += 1;
1812            }
1813            if matches {
1814                return Some(vec![RowOp::Move {
1815                    from_index: from_idx,
1816                    to_index: to_idx,
1817                    key: new_rows[to_idx].key,
1818                }]);
1819            }
1820        }
1821
1822        return Some(vec![RowOp::Reorder { order }]);
1823    }
1824
1825    None
1826}
1827
1828/// Applies [`RowOp`] operations in place to a row buffer.
1829pub fn apply_row_ops_to_rows(rows: &mut Vec<RowSet>, ops: &[RowOp]) {
1830    for op in ops {
1831        match op {
1832            RowOp::Update { index, row } => {
1833                if let Some(target) = rows.get_mut(*index) {
1834                    *target = row.clone();
1835                }
1836            }
1837            RowOp::Insert { index, row } => {
1838                let idx = (*index).min(rows.len());
1839                rows.insert(idx, row.clone());
1840            }
1841            RowOp::Remove { index, .. } => {
1842                if *index < rows.len() {
1843                    rows.remove(*index);
1844                }
1845            }
1846            RowOp::Move {
1847                from_index,
1848                to_index,
1849                ..
1850            } => {
1851                if *from_index < rows.len() {
1852                    let r = rows.remove(*from_index);
1853                    let to = (*to_index).min(rows.len());
1854                    rows.insert(to, r);
1855                }
1856            }
1857            RowOp::Reorder { order } => {
1858                if order.len() == rows.len() {
1859                    let old = std::mem::take(rows);
1860                    rows.reserve(order.len());
1861                    let mut old_opt: Vec<Option<RowSet>> = old.into_iter().map(Some).collect();
1862                    for &old_idx in order {
1863                        if let Some(opt) = old_opt.get_mut(old_idx) {
1864                            if let Some(r) = opt.take() {
1865                                rows.push(r);
1866                            }
1867                        }
1868                    }
1869                }
1870            }
1871        }
1872    }
1873}
1874
1875/// Applies [`RowOp`] operations in place to a cell matrix.
1876pub fn apply_row_ops_to_cells(cells: &mut Vec<Vec<String>>, ops: &[RowOp]) {
1877    for op in ops {
1878        match op {
1879            RowOp::Update { index, row } => {
1880                if let Some(target) = cells.get_mut(*index) {
1881                    *target = row.cells.clone();
1882                }
1883            }
1884            RowOp::Insert { index, row } => {
1885                let idx = (*index).min(cells.len());
1886                cells.insert(idx, row.cells.clone());
1887            }
1888            RowOp::Remove { index, .. } => {
1889                if *index < cells.len() {
1890                    cells.remove(*index);
1891                }
1892            }
1893            RowOp::Move {
1894                from_index,
1895                to_index,
1896                ..
1897            } => {
1898                if *from_index < cells.len() {
1899                    let c = cells.remove(*from_index);
1900                    let to = (*to_index).min(cells.len());
1901                    cells.insert(to, c);
1902                }
1903            }
1904            RowOp::Reorder { order } => {
1905                if order.len() == cells.len() {
1906                    let old = std::mem::take(cells);
1907                    cells.reserve(order.len());
1908                    let mut old_opt: Vec<Option<Vec<String>>> = old.into_iter().map(Some).collect();
1909                    for &old_idx in order {
1910                        if let Some(opt) = old_opt.get_mut(old_idx) {
1911                            if let Some(c) = opt.take() {
1912                                cells.push(c);
1913                            }
1914                        }
1915                    }
1916                }
1917            }
1918        }
1919    }
1920}
1921
1922/// Applies [`RowOp`] operations in place to a text item list.
1923pub fn apply_row_ops_to_items(items: &mut Vec<String>, ops: &[RowOp]) {
1924    for op in ops {
1925        match op {
1926            RowOp::Update { index, row } => {
1927                if let Some(target) = items.get_mut(*index) {
1928                    *target = row.text();
1929                }
1930            }
1931            RowOp::Insert { index, row } => {
1932                let idx = (*index).min(items.len());
1933                items.insert(idx, row.text());
1934            }
1935            RowOp::Remove { index, .. } => {
1936                if *index < items.len() {
1937                    items.remove(*index);
1938                }
1939            }
1940            RowOp::Move {
1941                from_index,
1942                to_index,
1943                ..
1944            } => {
1945                if *from_index < items.len() {
1946                    let item = items.remove(*from_index);
1947                    let to = (*to_index).min(items.len());
1948                    items.insert(to, item);
1949                }
1950            }
1951            RowOp::Reorder { order } => {
1952                if order.len() == items.len() {
1953                    let old = std::mem::take(items);
1954                    items.reserve(order.len());
1955                    let mut old_opt: Vec<Option<String>> = old.into_iter().map(Some).collect();
1956                    for &old_idx in order {
1957                        if let Some(opt) = old_opt.get_mut(old_idx) {
1958                            if let Some(item) = opt.take() {
1959                                items.push(item);
1960                            }
1961                        }
1962                    }
1963                }
1964            }
1965        }
1966    }
1967}
1968
1969/// Text alignment for widgets and grid cells.
1970#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1971#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1972pub enum TextAlignment {
1973    Left,
1974    Center,
1975    Right,
1976}
1977
1978/// Attributes for a `WidgetKind::DataGrid` cell (Phase 2).
1979#[derive(Debug, Clone, PartialEq, Default)]
1980pub struct GridCellAttr {
1981    pub bg_color: Option<Color>,
1982    pub text_color: Option<Color>,
1983    pub alignment: Option<TextAlignment>,
1984    pub font_bold: bool,
1985    pub font_italic: bool,
1986    pub font_size: Option<u8>,
1987}
1988
1989/// Built-in editors for a `WidgetKind::DataGrid` cell (Phase 3).
1990#[derive(Debug, Clone, PartialEq)]
1991pub enum GridCellEditor {
1992    Text,
1993    Boolean,
1994    Enum(Vec<String>),
1995    Number { min: i32, max: i32, step: i32 },
1996}
1997
1998/// Built-in renderers for a `WidgetKind::DataGrid` cell (Phase 4).
1999#[derive(Debug, Clone, PartialEq)]
2000pub enum GridCellRenderer {
2001    Text,
2002    Boolean,
2003    Canvas(CanvasScene),
2004}
2005
2006/// Virtual data model for `WidgetKind::DataGrid` (Phase 1-5 implementation).
2007pub trait DataGridModel {
2008    /// Returns the total number of rows.
2009    fn row_count(&self) -> usize;
2010    /// Returns the total number of columns.
2011    fn col_count(&self) -> usize;
2012    /// Returns the string value for a given cell.
2013    fn value_at(&self, row: usize, col: usize) -> String;
2014
2015    /// Reports whether the row's cells are already resident, so a backend
2016    /// can repaint precisely when a lazily-loaded row arrives instead of on
2017    /// every drain (`docs/design/datagrid-model-tiers.md` §8).
2018    ///
2019    /// The default is `true`: every eager model answers reads immediately,
2020    /// so nothing it serves can be "not loaded yet". A lazy model such as
2021    /// [`WindowedDataGridModel`] overrides this with `false` for in-range
2022    /// rows whose payload has not been applied yet; `value_at` for those
2023    /// rows returns the model's placeholder until the fetch is delivered.
2024    fn is_row_resident(&self, _row: usize) -> bool {
2025        true
2026    }
2027
2028    /// Pins the contiguous visible band `[first_row, first_row + count)` for
2029    /// one read sequence (a paint or hit-test pass), so a lazy model cannot
2030    /// evict a row that the pass is about to read (design
2031    /// `docs/design/datagrid-model-tiers.md` §5.3).
2032    ///
2033    /// A backend brackets its read pass with this and
2034    /// [`DataGridModel::clear_pinned_band`]; `count == 0` clears the band.
2035    /// A later pin replaces the previous band, so a pass never inherits
2036    /// stale protection. The default is a no-op: an eager model keeps every
2037    /// row resident, so nothing can be evicted and the call is free to be
2038    /// ignored. Only a lazy model such as [`WindowedDataGridModel`] carries
2039    /// pin state.
2040    fn pin_visible_band(&self, _first_row: usize, _count: usize) {}
2041
2042    /// Ends the pin scope opened by [`DataGridModel::pin_visible_band`].
2043    /// The default is a no-op (see there).
2044    fn clear_pinned_band(&self) {}
2045
2046    // Phase 2: Formatting
2047    fn get_attr(&self, _row: usize, _col: usize) -> Option<GridCellAttr> {
2048        None
2049    }
2050
2051    // Phase 3: Editing
2052    fn set_value_at(&mut self, _row: usize, _col: usize, _value: String) {}
2053    fn get_editor(&self, _row: usize, _col: usize) -> Option<GridCellEditor> {
2054        None
2055    }
2056
2057    // Phase 4: Custom Renderers
2058    fn get_renderer(&self, _row: usize, _col: usize) -> Option<GridCellRenderer> {
2059        None
2060    }
2061
2062    // Phase 5: Cell Merging
2063    fn cell_span(&self, _row: usize, _col: usize) -> (usize, usize) {
2064        (1, 1)
2065    }
2066}
2067
2068/// A simple in-memory data grid model used for compatibility with `WidgetSpec::data_grid_rows`.
2069pub struct SimpleDataGridModel {
2070    pub rows: Vec<Vec<String>>,
2071}
2072
2073impl DataGridModel for SimpleDataGridModel {
2074    fn row_count(&self) -> usize {
2075        self.rows.len()
2076    }
2077
2078    fn col_count(&self) -> usize {
2079        self.rows.first().map(|r| r.len()).unwrap_or(0)
2080    }
2081
2082    fn value_at(&self, row: usize, col: usize) -> String {
2083        self.rows
2084            .get(row)
2085            .and_then(|r| r.get(col))
2086            .cloned()
2087            .unwrap_or_default()
2088    }
2089}
2090
2091/// Configuration for a [`WindowedDataGridModel`]'s resident window.
2092///
2093/// The resident window is bounded by **count and bytes**; whichever bound is
2094/// reached first forces an eviction, so capacity is never inferred from
2095/// `row_count` (design `docs/design/datagrid-model-tiers.md` §5.2).
2096#[derive(Debug, Clone, PartialEq, Eq)]
2097pub struct WindowedDataGridConfig {
2098    /// Maximum number of rows that may be resident at once. Values below 1
2099    /// are clamped to 1 by [`Self::new`].
2100    pub max_resident_rows: usize,
2101    /// Maximum payload bytes summed across all resident rows. Values below
2102    /// 1 are clamped to 1 by [`Self::new`]. A row's payload is the sum of
2103    /// [`String::len`] over its (truncated to `col_count`) cells.
2104    pub max_resident_bytes: usize,
2105    /// Cell text [`DataGridModel::value_at`] returns for an in-range row
2106    /// whose payload is not resident yet. Out-of-range coordinates return an
2107    /// empty string instead, never the placeholder.
2108    pub placeholder: String,
2109}
2110
2111impl WindowedDataGridConfig {
2112    /// Creates a config with the default `"…"` placeholder.
2113    pub fn new(max_resident_rows: usize, max_resident_bytes: usize) -> Self {
2114        Self {
2115            max_resident_rows: max_resident_rows.max(1),
2116            max_resident_bytes: max_resident_bytes.max(1),
2117            placeholder: "…".to_owned(),
2118        }
2119    }
2120
2121    /// Overrides the placeholder returned for non-resident in-range cells.
2122    pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
2123        self.placeholder = placeholder.into();
2124        self
2125    }
2126}
2127
2128/// Outcome of [`WindowedDataGridHandle::deliver_row`].
2129#[derive(Debug, Clone, PartialEq, Eq)]
2130pub enum WindowedDelivery {
2131    /// The row became resident. `evicted` lists the rows dropped to honor
2132    /// the count/byte bounds, least-recently-used first.
2133    Applied { evicted: Vec<usize> },
2134    /// The row did not become resident. The fetch state is reset, so a later
2135    /// `value_at` for the row requests it again; the bounded window is never
2136    /// exceeded and nothing is partially applied.
2137    Rejected(WindowedDeliveryRejection),
2138}
2139
2140/// Why a delivered row was refused. Every variant is a typed,
2141/// non-panicking refusal.
2142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2143pub enum WindowedDeliveryRejection {
2144    /// `row >= row_count`: the result cannot belong to this model (for
2145    /// example a stale result for a previous model shape).
2146    RowOutOfRange,
2147    /// No fetch was in flight for `row`: a late, duplicated, or foreign
2148    /// result, discarded fail-closed.
2149    NotInFlight,
2150    /// The row's payload alone exceeds `max_resident_bytes`, so it can never
2151    /// be resident (a byte budget that cannot hold one row is a caller
2152    /// configuration error rather than a panic).
2153    Oversized,
2154    /// Making room would require evicting a pinned row: every resident row
2155    /// lies in the active visible band, so the bounded window wins and the
2156    /// delivery is refused until the band is cleared or replaced.
2157    NoEvictableVictim,
2158}
2159
2160/// A lazily-loaded, bounded resident row window over an arbitrary source
2161/// (T1, contract in `docs/design/datagrid-model-tiers.md` §4.2/§5/§8).
2162///
2163/// # Protocol
2164///
2165/// 1. Reads ([`DataGridModel::value_at`]) never block and never fetch: a
2166///    resident row returns its cells; an in-range miss records an in-flight
2167///    request, signals the repaint hook (once per scheduled fetch; repeat
2168///    reads while in flight only return the placeholder), and returns
2169///    [`WindowedDataGridConfig::placeholder`].
2170/// 2. A producer (the app's loader) turns requests into results off the UI
2171///    thread and applies them through a [`WindowedDataGridHandle`] obtained
2172///    with [`Self::handle`] - the drain path described in the design record
2173///    §6 (shape A). [`DataGridModel::is_row_resident`] reports residency so
2174///    a lane can repaint precisely when a row arrives.
2175/// 3. Eviction is LRU over resident rows, bounded by count **and** bytes.
2176///    [`WindowedDataGridHandle::pin_visible_band`] pins the visible band
2177///    for one `value_at` sequence (a paint/hit-test pass) so the row being
2178///    asked for can never be evicted while the pass reads it; pins are
2179///    never time-based and a new band replaces the old one.
2180/// 4. Dropping the model - or replacing it through
2181///    `Ui::set_data_grid_model`, which moves and drops the old one - drops
2182///    the request hook; a producer connected to it observes the closed
2183///    channel and stops (fail-closed), and a late result has no handle left
2184///    to be applied to.
2185///
2186/// The optional [`DataGridModel`] hooks (`get_attr`, editors, renderers,
2187/// spans) keep their trait defaults: a lazy model must not fetch from them
2188/// (design §3). Editing (`set_value_at`) is outside the lazy contract for
2189/// now (design §11 item 4).
2190///
2191/// No capacity or performance claim is attached to this type; a number must
2192/// be measured per the W2-L evidence rules before it is published.
2193///
2194/// ```
2195/// use native_gui_core::widgets::{DataGridModel, WindowedDataGridConfig, WindowedDataGridModel};
2196///
2197/// let requested = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
2198/// let log = std::rc::Rc::clone(&requested);
2199/// let model = WindowedDataGridModel::new(
2200///     500,
2201///     2,
2202///     WindowedDataGridConfig::new(8, 64 * 1024),
2203///     move |row| log.borrow_mut().push(row),
2204///     || {},
2205/// );
2206/// let handle = model.handle();
2207///
2208/// // A read of an un-fetched row is a non-blocking miss.
2209/// assert_eq!(model.value_at(120, 0), "…");
2210/// assert_eq!(*requested.borrow(), vec![120]);
2211/// assert!(!model.is_row_resident(120));
2212///
2213/// // The drain applies the fetched row; the next read sees it.
2214/// handle.deliver_row(120, vec!["a".to_owned(), "b".to_owned()]);
2215/// assert!(model.is_row_resident(120));
2216/// assert_eq!(model.value_at(120, 1), "b");
2217/// ```
2218pub struct WindowedDataGridModel {
2219    handle: WindowedDataGridHandle,
2220    on_fetch_requested: Box<dyn Fn(usize)>,
2221    on_repaint_requested: Box<dyn Fn()>,
2222}
2223
2224impl WindowedDataGridModel {
2225    /// Creates a windowed model with a `row_count` x `col_count` shape.
2226    ///
2227    /// * `on_fetch_requested` is called with the row index on the first miss
2228    ///   for that row. It must schedule work and return promptly (post
2229    ///   through `UiProxy` in production); it runs after the model's state
2230    ///   borrow ends, so it may re-enter the window through a handle.
2231    /// * `on_repaint_requested` is called immediately after, so the layer
2232    ///   that owns the event loop can arrange a repaint: a miss never blocks
2233    ///   the paint. Under Mock, count the calls with
2234    ///   `native_gui_mock::windowed_fixture::RepaintCounter`.
2235    ///
2236    /// The hooks run on the calling (UI) thread and the model is `!Send`,
2237    /// matching the [`DataGridModel`] contract.
2238    pub fn new(
2239        row_count: usize,
2240        col_count: usize,
2241        config: WindowedDataGridConfig,
2242        on_fetch_requested: impl Fn(usize) + 'static,
2243        on_repaint_requested: impl Fn() + 'static,
2244    ) -> Self {
2245        Self {
2246            handle: WindowedDataGridHandle {
2247                row_count,
2248                col_count,
2249                config,
2250                state: Rc::new(RefCell::new(WindowedState::default())),
2251            },
2252            on_fetch_requested: Box::new(on_fetch_requested),
2253            on_repaint_requested: Box::new(on_repaint_requested),
2254        }
2255    }
2256
2257    /// A cloneable handle to this model's window state.
2258    ///
2259    /// The handle is the *apply* path: keep it (for example in the UI
2260    /// thread's task drain) and call [`WindowedDataGridHandle::deliver_row`]
2261    /// when a producer has fetched a row, plus the pinning and counter
2262    /// accessors. The installed model and every handle share one window.
2263    pub fn handle(&self) -> WindowedDataGridHandle {
2264        self.handle.clone()
2265    }
2266}
2267
2268impl DataGridModel for WindowedDataGridModel {
2269    fn row_count(&self) -> usize {
2270        self.handle.row_count
2271    }
2272
2273    fn col_count(&self) -> usize {
2274        self.handle.col_count
2275    }
2276
2277    /// Non-blocking by contract: a resident row returns its cells; an
2278    /// in-range miss returns the configured placeholder after scheduling
2279    /// one fetch and one repaint signal; out-of-range coordinates return an
2280    /// empty string. Reads touch the row's LRU position.
2281    fn value_at(&self, row: usize, col: usize) -> String {
2282        if row >= self.handle.row_count || col >= self.handle.col_count {
2283            return String::new();
2284        }
2285        let scheduled = {
2286            let mut state = self.handle.state.borrow_mut();
2287            if state.resident.contains_key(&row) {
2288                state.hits += 1;
2289                state.touch(row);
2290                return state
2291                    .resident
2292                    .get(&row)
2293                    .and_then(|resident| resident.cells.get(col))
2294                    .cloned()
2295                    .unwrap_or_default();
2296            }
2297            state.misses += 1;
2298            if state.in_flight.insert(row) {
2299                state.fetches_requested += 1;
2300                true
2301            } else {
2302                false
2303            }
2304        };
2305        if scheduled {
2306            // Hooks run after the state borrow ends so a hook may re-enter
2307            // the handle without panicking.
2308            (self.on_fetch_requested)(row);
2309            (self.on_repaint_requested)();
2310        }
2311        self.handle.config.placeholder.clone()
2312    }
2313
2314    /// `false` for an in-range row whose payload is not resident yet (or
2315    /// whose fetch is still in flight); `true` for resident rows. Rows
2316    /// outside `0..row_count` are not resident.
2317    fn is_row_resident(&self, row: usize) -> bool {
2318        row < self.handle.row_count && self.handle.state.borrow().resident.contains_key(&row)
2319    }
2320
2321    /// Forwards the band a backend paint pass opens on the trait object it
2322    /// holds to this model's window: rows in
2323    /// `[first_row, first_row + count)` are refused as eviction victims
2324    /// until [`DataGridModel::clear_pinned_band`].
2325    fn pin_visible_band(&self, first_row: usize, count: usize) {
2326        self.handle.pin_visible_band(first_row, count);
2327    }
2328
2329    /// Forwards [`DataGridModel::pin_visible_band`]'s release.
2330    fn clear_pinned_band(&self) {
2331        self.handle.clear_pinned_band();
2332    }
2333}
2334
2335impl std::fmt::Debug for WindowedDataGridModel {
2336    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2337        f.debug_struct("WindowedDataGridModel")
2338            .field("window", &self.handle)
2339            .finish()
2340    }
2341}
2342
2343/// A cloneable handle to one [`WindowedDataGridModel`]'s resident window.
2344///
2345/// Handles share the model's window: the UI thread's drain applies fetched
2346/// rows with [`Self::deliver_row`], a render path brackets a paint pass with
2347/// [`Self::pin_visible_band`]/[`Self::clear_pinned_band`], and tests read
2348/// the counters. The handle is `!Send` on purpose - the window stays on the
2349/// UI thread (design §6), and a worker only ever posts a request or a result
2350/// *toward* it.
2351#[derive(Clone)]
2352pub struct WindowedDataGridHandle {
2353    row_count: usize,
2354    col_count: usize,
2355    config: WindowedDataGridConfig,
2356    state: Rc<RefCell<WindowedState>>,
2357}
2358
2359impl WindowedDataGridHandle {
2360    /// Applies a fetched row to the window (the drain-side path, design §6
2361    /// shape A). A delivery is only accepted for a row with a fetch in
2362    /// flight, which makes stale, duplicated, or foreign results fail
2363    /// closed; `cells` is truncated to `col_count` because trailing cells
2364    /// are unreachable and must not occupy the byte budget.
2365    ///
2366    /// Nothing is applied on a [`WindowedDelivery::Rejected`] outcome and
2367    /// the fetch state is reset, so a later `value_at` requests the row
2368    /// again - a refusal never exceeds the bounded window.
2369    pub fn deliver_row(&self, row: usize, cells: Vec<String>) -> WindowedDelivery {
2370        if row >= self.row_count {
2371            self.state.borrow_mut().rejected_deliveries += 1;
2372            return WindowedDelivery::Rejected(WindowedDeliveryRejection::RowOutOfRange);
2373        }
2374        let mut cells = cells;
2375        cells.truncate(self.col_count);
2376        let bytes: usize = cells.iter().map(String::len).sum();
2377
2378        let mut state = self.state.borrow_mut();
2379        if !state.in_flight.remove(&row) {
2380            state.rejected_deliveries += 1;
2381            return WindowedDelivery::Rejected(WindowedDeliveryRejection::NotInFlight);
2382        }
2383        if bytes > self.config.max_resident_bytes {
2384            state.rejected_deliveries += 1;
2385            return WindowedDelivery::Rejected(WindowedDeliveryRejection::Oversized);
2386        }
2387
2388        // Defensive replace: the protocol cannot currently deliver a row
2389        // that is resident (a fetch only starts on a miss), but keeping the
2390        // accounting correct here costs nothing if that ever changes.
2391        if let Some(previous) = state.resident.remove(&row) {
2392            state.resident_bytes -= previous.bytes;
2393            state.lru.retain(|resident| *resident != row);
2394        }
2395
2396        let mut evicted: Vec<usize> = Vec::new();
2397        while state.resident.len() >= self.config.max_resident_rows
2398            || state.resident_bytes.saturating_add(bytes) > self.config.max_resident_bytes
2399        {
2400            let victim = state
2401                .lru
2402                .iter()
2403                .copied()
2404                .find(|candidate| !state.is_pinned(*candidate));
2405            let Some(victim) = victim else {
2406                state.rejected_deliveries += 1;
2407                return WindowedDelivery::Rejected(WindowedDeliveryRejection::NoEvictableVictim);
2408            };
2409            state.lru.retain(|resident| *resident != victim);
2410            if let Some(previous) = state.resident.remove(&victim) {
2411                state.resident_bytes -= previous.bytes;
2412                state.evictions += 1;
2413                evicted.push(victim);
2414            }
2415        }
2416
2417        state.resident.insert(row, ResidentRow { cells, bytes });
2418        state.resident_bytes += bytes;
2419        state.lru.push_back(row);
2420        WindowedDelivery::Applied { evicted }
2421    }
2422
2423    /// Pins the contiguous visible band `[first_row, first_row + count)` for
2424    /// one `value_at` sequence (design §5.3).
2425    ///
2426    /// The intended call site is a render path that brackets a paint or
2427    /// hit-test pass: pin before the first read, [`Self::clear_pinned_band`]
2428    /// after the last. A new `pin_visible_band` call *replaces* the previous
2429    /// band, so a later pass never inherits stale protection, and pins never
2430    /// expire on a timer - the bracket is the only scope. `count == 0`
2431    /// clears the band like [`Self::clear_pinned_band`].
2432    pub fn pin_visible_band(&self, first_row: usize, count: usize) {
2433        let mut state = self.state.borrow_mut();
2434        state.pinned_band = if count == 0 {
2435            None
2436        } else {
2437            Some((first_row, count))
2438        };
2439    }
2440
2441    /// Ends the current pin scope (see [`Self::pin_visible_band`]).
2442    pub fn clear_pinned_band(&self) {
2443        self.state.borrow_mut().pinned_band = None;
2444    }
2445
2446    /// The active visible band, when one is pinned.
2447    pub fn pinned_band(&self) -> Option<(usize, usize)> {
2448        self.state.borrow().pinned_band
2449    }
2450
2451    /// Whether `row`'s payload is currently resident.
2452    pub fn is_row_resident(&self, row: usize) -> bool {
2453        row < self.row_count && self.state.borrow().resident.contains_key(&row)
2454    }
2455
2456    /// Whether a fetch for `row` has been requested and not applied yet.
2457    pub fn is_row_in_flight(&self, row: usize) -> bool {
2458        self.state.borrow().in_flight.contains(&row)
2459    }
2460
2461    /// Number of resident rows (never above `max_resident_rows`).
2462    pub fn resident_row_count(&self) -> usize {
2463        self.state.borrow().resident.len()
2464    }
2465
2466    /// Payload bytes currently held by resident rows (never above
2467    /// `max_resident_bytes`).
2468    pub fn resident_bytes(&self) -> usize {
2469        self.state.borrow().resident_bytes
2470    }
2471
2472    /// Number of rows with a fetch requested but not applied yet.
2473    pub fn in_flight_count(&self) -> usize {
2474        self.state.borrow().in_flight.len()
2475    }
2476
2477    /// Reads answered from the resident window.
2478    pub fn hits(&self) -> usize {
2479        self.state.borrow().hits
2480    }
2481
2482    /// In-range reads answered with the placeholder, including repeat reads
2483    /// while the row's fetch is still in flight.
2484    pub fn misses(&self) -> usize {
2485        self.state.borrow().misses
2486    }
2487
2488    /// Fetches scheduled: one per row-load (the fetch hook ran that many
2489    /// times). Repeat reads while in flight do not increment it.
2490    pub fn fetches_requested(&self) -> usize {
2491        self.state.borrow().fetches_requested
2492    }
2493
2494    /// Rows dropped by bounds-driven eviction.
2495    pub fn evictions(&self) -> usize {
2496        self.state.borrow().evictions
2497    }
2498
2499    /// Deliveries refused, for any [`WindowedDeliveryRejection`] reason.
2500    pub fn rejected_deliveries(&self) -> usize {
2501        self.state.borrow().rejected_deliveries
2502    }
2503}
2504
2505impl std::fmt::Debug for WindowedDataGridHandle {
2506    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2507        let state = self.state.borrow();
2508        f.debug_struct("WindowedDataGridHandle")
2509            .field("row_count", &self.row_count)
2510            .field("col_count", &self.col_count)
2511            .field("resident_rows", &state.resident.len())
2512            .field("resident_bytes", &state.resident_bytes)
2513            .field("in_flight", &state.in_flight.len())
2514            .field("hits", &state.hits)
2515            .field("misses", &state.misses)
2516            .field("evictions", &state.evictions)
2517            .finish()
2518    }
2519}
2520
2521#[derive(Default)]
2522struct WindowedState {
2523    resident: HashMap<usize, ResidentRow>,
2524    /// Resident rows in LRU order: front is evicted first, back is MRU.
2525    lru: VecDeque<usize>,
2526    /// Rows requested by `value_at` whose payload was not applied yet.
2527    in_flight: BTreeSet<usize>,
2528    /// The active visible band, replaced (not extended) by each
2529    /// `pin_visible_band` call.
2530    pinned_band: Option<(usize, usize)>,
2531    resident_bytes: usize,
2532    hits: usize,
2533    misses: usize,
2534    fetches_requested: usize,
2535    evictions: usize,
2536    rejected_deliveries: usize,
2537}
2538
2539impl WindowedState {
2540    fn touch(&mut self, row: usize) {
2541        if let Some(position) = self.lru.iter().position(|resident| *resident == row) {
2542            self.lru.remove(position);
2543        }
2544        self.lru.push_back(row);
2545    }
2546
2547    fn is_pinned(&self, row: usize) -> bool {
2548        match self.pinned_band {
2549            Some((first, count)) => row >= first && row - first < count,
2550            None => false,
2551        }
2552    }
2553}
2554
2555struct ResidentRow {
2556    cells: Vec<String>,
2557    bytes: usize,
2558}
2559
2560/// In-memory widget description shared between `Ui` and backends.
2561#[derive(Debug, Clone, PartialEq)]
2562pub struct WidgetSpec {
2563    /// Unique widget identifier.
2564    pub id: WidgetId,
2565    /// The type of widget to create.
2566    pub kind: WidgetKind,
2567    /// Optional display text or initial value.
2568    pub text: Option<String>,
2569    /// Optional text selection range in characters (start inclusive, end
2570    /// exclusive) for `TextInput`/`TextArea`.
2571    pub text_selection: Option<(usize, usize)>,
2572    /// Completion/suggestion items for a `TextInput`.
2573    ///
2574    /// The shared model keeps the full item list; lanes filter it for the
2575    /// current text (case-insensitive prefix by default) and own their
2576    /// popup. Empty means completion is off.
2577    pub completion_items: Vec<String>,
2578    /// Optional placeholder/hint text (`TextInput`).
2579    pub placeholder_text: Option<String>,
2580    /// Parent widget, if attached.
2581    pub parent: Option<WidgetId>,
2582    /// Container orientation (only meaningful for `WidgetKind::Container`).
2583    pub container_direction: Option<ContainerDirection>,
2584    /// Container wrapping mode (`Container`, `GroupBox`, `SplitPane`).
2585    pub container_wrap: Option<ContainerWrap>,
2586    /// Container vertical scroll setting.
2587    pub container_scroll_vertical: bool,
2588    /// Container horizontal scroll setting.
2589    pub container_scroll_horizontal: bool,
2590    /// Uniform spacing between flow children in logical pixels
2591    /// (`Container`, `GroupBox`); negatives clamp to 0.
2592    pub container_gap: Option<i32>,
2593    /// Uniform inset between the container edges and its flow children in
2594    /// logical pixels (`Container`, `GroupBox`); negatives clamp to 0.
2595    pub container_padding: Option<i32>,
2596    /// Preferred widget size as `(width, height)` in logical pixels.
2597    pub size: Option<(i32, i32)>,
2598    /// Preferred widget position as `(x, y)` in logical pixels.
2599    pub position: Option<(i32, i32)>,
2600    /// Rows/items for list widgets.
2601    pub data_list_items: Vec<String>,
2602    /// Column headers for the columned list contract (`ListView`).
2603    /// Empty keeps the shipped single-column row contract,
2604    /// where rows come from [`Self::data_list_items`].
2605    pub list_columns: Vec<ColumnSpec>,
2606    /// Row cells aligned to [`Self::list_columns`] (`ListView`):
2607    /// row `r`, cell `c` renders the header `c` with text
2608    /// `list_rows[r][c]`. Missing trailing cells render empty and cells
2609    /// beyond the column count are ignored.
2610    pub list_rows: Vec<Vec<String>>,
2611    /// Row-major cell values for data grid widgets.
2612    ///
2613    /// Shared behind an [`Arc`] so the manager's spec and the backend hold a
2614    /// single resident allocation instead of each keeping a private copy.
2615    pub data_grid_rows: Arc<Vec<Vec<String>>>,
2616    /// Hierarchical items for `WidgetKind::TreeView`.
2617    pub tree_items: Vec<TreeItem>,
2618    /// Optional background color.
2619    pub background_color: Option<Color>,
2620    /// Alert severity metadata (only meaningful for `WidgetKind::AlertDialog`).
2621    pub alert_level: Option<AlertLevel>,
2622    /// Optional checked state metadata.
2623    pub checked: Option<bool>,
2624    /// Optional enabled/disabled state metadata.
2625    pub enabled: Option<bool>,
2626    /// Optional numeric range metadata as `(min, max)`.
2627    pub range: Option<(i32, i32)>,
2628    /// Optional numeric step metadata.
2629    pub step: Option<i32>,
2630    /// Optional numeric value metadata.
2631    pub value: Option<i32>,
2632    /// Optional grouping metadata (radio-like widgets).
2633    pub group_name: Option<String>,
2634    /// Optional tab labels metadata (`WidgetKind::Tabs`).
2635    ///
2636    /// Tab strip height is dynamically resolved in layout passes from backend measurements
2637    /// or typography scaling, backed by a minimum floor to prevent collapse.
2638    pub tab_items: Vec<String>,
2639    /// Optional selected item index metadata.
2640    pub selected_index: Option<usize>,
2641    /// Optional multi-selection indices metadata (list/tree widgets).
2642    pub selected_indices: Vec<usize>,
2643    /// Row drag source metadata: rows of this list/tree can be dragged out.
2644    pub row_drag_source: bool,
2645    /// Row drop target metadata: rows can be dropped onto this list/tree.
2646    pub row_drop_target: bool,
2647    /// File drop target metadata: external files can be dropped onto this widget.
2648    pub file_drop_target: bool,
2649    /// Optional image source metadata.
2650    pub image_source: Option<String>,
2651    /// How the image scales into its widget bounds.
2652    pub image_fit: ImageFit,
2653    /// Optional stock-art icon role rendered beside the button label:
2654    /// `Button` and `FileChooserDialog` only.
2655    pub icon: Option<IconRole>,
2656    /// What the file chooser dialog lets the user pick.
2657    pub file_chooser_mode: FileChooserMode,
2658    /// Optional date metadata (`YYYY-MM-DD`).
2659    pub date_value: Option<String>,
2660    /// Optional link URL metadata.
2661    pub link_url: Option<String>,
2662    /// Optional tooltip text metadata.
2663    pub tooltip: Option<String>,
2664    /// Portable accessibility metadata: name, description, role.
2665    pub accessibility: AccessibilitySpec,
2666    /// Keyboard focusability override; `None` uses the per-kind
2667    /// default from [`crate::focus::default_focusable`].
2668    pub focusable: Option<bool>,
2669    /// Optional split ratio metadata (`0..=100`).
2670    pub split_ratio: Option<u8>,
2671    /// Optional scene data for `WidgetKind::Canvas`.
2672    pub canvas_scene: Option<CanvasScene>,
2673    /// Optional raster surface painted beneath the canvas scene.
2674    pub canvas_surface: Option<CanvasSurface>,
2675    /// Portable colour-dialog preferences: initial colour, custom
2676    /// palette, and the full-mode/alpha requests.
2677    pub color_dialog_data: Option<ColorDialogData>,
2678    /// Portable font-dialog preferences: initial descriptor,
2679    /// effects, and the size-range restriction.
2680    pub font_dialog_data: Option<FontDialogData>,
2681    /// Portable toolbar rows: tools and separators, in display
2682    /// order. Ids are application-owned and survive rebuilds.
2683    pub toolbar_items: Vec<ToolbarItem>,
2684    /// Toolbar stacking orientation.
2685    pub toolbar_orientation: ToolbarOrientation,
2686    /// Selected dates for calendar widgets.
2687    pub calendar_selected_dates: Vec<CalendarDate>,
2688    /// Minimum selectable date.
2689    pub calendar_min_date: Option<CalendarDate>,
2690    /// Maximum selectable date.
2691    pub calendar_max_date: Option<CalendarDate>,
2692    /// First day of week convention.
2693    pub calendar_first_day_of_week: CalendarFirstDayOfWeek,
2694    /// Selection mode for calendar widgets.
2695    pub calendar_selection_mode: CalendarSelectionMode,
2696    /// Text alignment for label widgets.
2697    pub label_alignment: LabelAlignment,
2698    /// Text wrap mode for label widgets.
2699    pub label_wrap: LabelWrap,
2700    /// Styled text runs for rich text widgets.
2701    pub rich_text_runs: Vec<TextRun>,
2702    /// Inline images for rich text widgets.
2703    pub rich_text_images: Vec<RichTextImage>,
2704    /// Monospace font rendering for text-bearing widgets.
2705    pub monospace: bool,
2706    /// Explicit widget font descriptor (`None` follows theme/platform defaults).
2707    pub font: Option<FontDescriptor>,
2708    /// Per-row stock-art icon roles for `DataList` and `ListView` controls.
2709    pub row_icons: Vec<Option<IconRole>>,
2710}
2711
2712impl WidgetSpec {
2713    /// Creates a new widget specification.
2714    ///
2715    /// Container widgets default to vertical stacking.
2716    pub fn new(id: WidgetId, kind: WidgetKind) -> Self {
2717        Self {
2718            id,
2719            kind,
2720            text: None,
2721            text_selection: None,
2722            completion_items: Vec::new(),
2723            parent: None,
2724            container_direction: if kind == WidgetKind::Container {
2725                Some(ContainerDirection::Vertical)
2726            } else {
2727                None
2728            },
2729            container_wrap: if kind == WidgetKind::Container {
2730                Some(ContainerWrap::NoWrap)
2731            } else {
2732                None
2733            },
2734            container_scroll_vertical: false,
2735            container_scroll_horizontal: false,
2736            container_gap: None,
2737            container_padding: None,
2738            size: None,
2739            position: None,
2740            data_list_items: Vec::new(),
2741            list_columns: Vec::new(),
2742            list_rows: Vec::new(),
2743            data_grid_rows: Arc::new(Vec::new()),
2744            tree_items: Vec::new(),
2745            background_color: None,
2746            alert_level: {
2747                #[cfg(feature = "widgets-containers")]
2748                {
2749                    if kind == WidgetKind::AlertDialog {
2750                        Some(AlertLevel::Info)
2751                    } else {
2752                        None
2753                    }
2754                }
2755                #[cfg(not(feature = "widgets-containers"))]
2756                {
2757                    None
2758                }
2759            },
2760            checked: None,
2761            enabled: None,
2762            range: None,
2763            step: None,
2764            value: None,
2765            group_name: None,
2766            tab_items: Vec::new(),
2767            selected_index: None,
2768            selected_indices: Vec::new(),
2769            row_drag_source: false,
2770            row_drop_target: false,
2771            file_drop_target: false,
2772            image_source: None,
2773            image_fit: ImageFit::default(),
2774            icon: None,
2775            file_chooser_mode: FileChooserMode::default(),
2776            date_value: None,
2777            link_url: None,
2778            tooltip: None,
2779            accessibility: AccessibilitySpec::for_kind(kind),
2780            focusable: None,
2781            split_ratio: None,
2782            canvas_scene: None,
2783            canvas_surface: None,
2784            color_dialog_data: None,
2785            font_dialog_data: None,
2786            toolbar_items: Vec::new(),
2787            toolbar_orientation: ToolbarOrientation::default(),
2788            calendar_selected_dates: Vec::new(),
2789            calendar_min_date: None,
2790            calendar_max_date: None,
2791            calendar_first_day_of_week: CalendarFirstDayOfWeek::default(),
2792            calendar_selection_mode: CalendarSelectionMode::default(),
2793            label_alignment: match kind {
2794                WidgetKind::Button => LabelAlignment::Center,
2795                _ => LabelAlignment::default(),
2796            },
2797            label_wrap: LabelWrap::default(),
2798            rich_text_runs: Vec::new(),
2799            rich_text_images: Vec::new(),
2800            placeholder_text: None,
2801            monospace: false,
2802            font: None,
2803            row_icons: Vec::new(),
2804        }
2805    }
2806
2807    /// Rejects the property when this spec's kind is outside its
2808    /// applicability row, returning the shared typed error.
2809    pub fn ensure_property(&self, property: WidgetProperty) -> GuiResult<()> {
2810        if property.supports(self.kind) {
2811            Ok(())
2812        } else {
2813            Err(GuiError::UnsupportedWidget(property.operation()))
2814        }
2815    }
2816
2817    /// Alias for [`Self::ensure_property`].
2818    pub fn requires_property(&self, property: WidgetProperty) -> GuiResult<()> {
2819        self.ensure_property(property)
2820    }
2821
2822    /// Sets the widget text.
2823    pub fn with_text(mut self, text: impl Into<String>) -> Self {
2824        self.text = Some(text.into());
2825        self
2826    }
2827
2828    /// Sets completion/suggestion items for a `TextInput`.
2829    pub fn with_completion_items(mut self, items: Vec<String>) -> Self {
2830        self.completion_items = items;
2831        self
2832    }
2833
2834    /// Sets the parent widget identifier.
2835    pub fn with_parent(mut self, parent: WidgetId) -> Self {
2836        self.parent = Some(parent);
2837        self
2838    }
2839
2840    /// Sets container direction metadata.
2841    pub fn with_container_direction(mut self, direction: ContainerDirection) -> Self {
2842        self.container_direction = Some(direction);
2843        self
2844    }
2845
2846    /// Sets container wrap metadata.
2847    pub fn with_container_wrap(mut self, wrap: ContainerWrap) -> Self {
2848        self.container_wrap = Some(wrap);
2849        self
2850    }
2851
2852    /// Enables/disables container scrolling metadata.
2853    pub fn with_container_scroll(mut self, vertical: bool, horizontal: bool) -> Self {
2854        self.container_scroll_vertical = vertical;
2855        self.container_scroll_horizontal = horizontal;
2856        self
2857    }
2858
2859    /// Sets the uniform flow spacing between container children.
2860    pub fn with_container_gap(mut self, gap: i32) -> Self {
2861        self.container_gap = Some(gap.max(0));
2862        self
2863    }
2864
2865    /// Sets the uniform inset between the container edges and its flow
2866    /// children.
2867    pub fn with_container_padding(mut self, padding: i32) -> Self {
2868        self.container_padding = Some(padding.max(0));
2869        self
2870    }
2871
2872    /// Sets preferred size metadata for a widget.
2873    pub fn with_size(mut self, width: i32, height: i32) -> Self {
2874        self.size = Some((width, height));
2875        self
2876    }
2877
2878    /// Sets preferred position metadata for a widget.
2879    pub fn with_position(mut self, x: i32, y: i32) -> Self {
2880        self.position = Some((x, y));
2881        self
2882    }
2883
2884    /// Sets list items for `WidgetKind::DataList`.
2885    pub fn with_data_list_items(mut self, items: impl IntoIterator<Item = String>) -> Self {
2886        self.data_list_items = items.into_iter().collect();
2887        self
2888    }
2889
2890    /// Sets column headers for the columned list contract (`ListView`);
2891    /// an empty list keeps the single-column row contract.
2892    pub fn with_list_columns(mut self, columns: impl IntoIterator<Item = ColumnSpec>) -> Self {
2893        self.list_columns = columns.into_iter().collect();
2894        self
2895    }
2896
2897    /// Sets row cells for the columned list contract (`ListView`);
2898    /// see [`Self::list_rows`] for the cell rule.
2899    pub fn with_list_rows(mut self, rows: impl IntoIterator<Item = Vec<String>>) -> Self {
2900        self.list_rows = rows.into_iter().collect();
2901        self
2902    }
2903
2904    /// Sets row-major data for `WidgetKind::DataGrid`.
2905    pub fn with_data_grid_rows(mut self, rows: impl IntoIterator<Item = Vec<String>>) -> Self {
2906        self.data_grid_rows = Arc::new(rows.into_iter().collect());
2907        self
2908    }
2909
2910    /// Sets hierarchical items for `WidgetKind::TreeView`.
2911    pub fn with_tree_items(mut self, items: impl IntoIterator<Item = TreeItem>) -> Self {
2912        self.tree_items = items.into_iter().collect();
2913        self
2914    }
2915
2916    /// Sets optional background color metadata for a widget.
2917    pub fn with_background_color(mut self, color: Color) -> Self {
2918        self.background_color = Some(color);
2919        self
2920    }
2921
2922    /// Sets alert severity metadata for `WidgetKind::AlertDialog`.
2923    pub fn with_alert_level(mut self, level: AlertLevel) -> Self {
2924        self.alert_level = Some(level);
2925        self
2926    }
2927
2928    /// Sets optional checked state metadata.
2929    pub fn with_checked(mut self, checked: bool) -> Self {
2930        self.checked = Some(checked);
2931        self
2932    }
2933
2934    /// Sets optional enabled/disabled state metadata.
2935    pub fn with_enabled(mut self, enabled: bool) -> Self {
2936        self.enabled = Some(enabled);
2937        self
2938    }
2939
2940    /// Sets numeric range metadata.
2941    pub fn with_range(mut self, min: i32, max: i32) -> Self {
2942        self.range = Some((min, max));
2943        self
2944    }
2945
2946    /// Sets numeric step metadata.
2947    pub fn with_step(mut self, step: i32) -> Self {
2948        self.step = Some(step);
2949        self
2950    }
2951
2952    /// Sets numeric value metadata.
2953    pub fn with_value(mut self, value: i32) -> Self {
2954        self.value = Some(value);
2955        self
2956    }
2957
2958    /// Sets multi-selection indices metadata.
2959    pub fn with_selected_indices(mut self, indices: impl IntoIterator<Item = usize>) -> Self {
2960        self.selected_indices = indices.into_iter().collect();
2961        self
2962    }
2963
2964    /// Marks this widget's rows as a drag source.
2965    pub fn with_row_drag_source(mut self, enabled: bool) -> Self {
2966        self.row_drag_source = enabled;
2967        self
2968    }
2969
2970    /// Marks this widget's rows as a drop target.
2971    pub fn with_row_drop_target(mut self, enabled: bool) -> Self {
2972        self.row_drop_target = enabled;
2973        self
2974    }
2975
2976    /// Marks this widget as accepting external file drops from the OS shell.
2977    pub fn with_file_drop_target(mut self, enabled: bool) -> Self {
2978        self.file_drop_target = enabled;
2979        self
2980    }
2981
2982    /// Sets grouping metadata.
2983    pub fn with_group_name(mut self, name: impl Into<String>) -> Self {
2984        self.group_name = Some(name.into());
2985        self
2986    }
2987
2988    /// Sets tab labels metadata.
2989    ///
2990    /// When rendered within a layout, tab strips automatically enforce a dynamic
2991    /// typography- and DPI-aware minimum height floor based on backend measurements
2992    /// (or falling back to 30.0pt), ensuring empty or short tab pages
2993    /// do not collapse the tab header strip.
2994    pub fn with_tab_items(mut self, items: impl IntoIterator<Item = String>) -> Self {
2995        self.tab_items = items.into_iter().collect();
2996        self
2997    }
2998
2999    /// Sets selected index metadata.
3000    pub fn with_selected_index(mut self, selected_index: usize) -> Self {
3001        self.selected_index = Some(selected_index);
3002        self
3003    }
3004
3005    /// Sets image source metadata.
3006    pub fn with_image_source(mut self, source: impl Into<String>) -> Self {
3007        self.image_source = Some(source.into());
3008        self
3009    }
3010
3011    /// Sets how the image scales into its bounds.
3012    pub fn with_image_fit(mut self, fit: ImageFit) -> Self {
3013        self.image_fit = fit;
3014        self
3015    }
3016
3017    /// Sets what the file chooser dialog lets the user pick.
3018    pub fn with_file_chooser_mode(mut self, mode: FileChooserMode) -> Self {
3019        self.file_chooser_mode = mode;
3020        self
3021    }
3022
3023    /// Sets date metadata (`YYYY-MM-DD`).
3024    pub fn with_date_value(mut self, date: impl Into<String>) -> Self {
3025        self.date_value = Some(date.into());
3026        self
3027    }
3028
3029    /// Sets link URL metadata.
3030    pub fn with_link_url(mut self, url: impl Into<String>) -> Self {
3031        self.link_url = Some(url.into());
3032        self
3033    }
3034
3035    /// Sets tooltip text metadata.
3036    pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
3037        self.tooltip = Some(tooltip.into());
3038        self
3039    }
3040
3041    /// Sets the accessible name announced by assistive technology.
3042    pub fn with_accessible_name(mut self, name: impl Into<String>) -> Self {
3043        self.accessibility.name = Some(name.into());
3044        self
3045    }
3046
3047    /// Sets the accessible description announced after the name.
3048    pub fn with_accessible_description(mut self, description: impl Into<String>) -> Self {
3049        self.accessibility.description = Some(description.into());
3050        self
3051    }
3052
3053    /// Overrides whether the widget participates in keyboard focus;
3054    /// `None` (the default) uses the per-kind default.
3055    pub fn with_focusable(mut self, focusable: bool) -> Self {
3056        self.focusable = Some(focusable);
3057        self
3058    }
3059
3060    /// Sets split ratio metadata (`0..=100`).
3061    pub fn with_split_ratio(mut self, ratio: u8) -> Self {
3062        self.split_ratio = Some(ratio.min(100));
3063        self
3064    }
3065
3066    /// Sets the canvas drawing scene for `WidgetKind::Canvas`.
3067    pub fn with_canvas_scene(mut self, scene: CanvasScene) -> Self {
3068        self.canvas_scene = Some(scene);
3069        self
3070    }
3071
3072    /// Sets the raster surface painted beneath the canvas scene.
3073    pub fn with_canvas_surface(mut self, surface: CanvasSurface) -> Self {
3074        self.canvas_surface = Some(surface);
3075        self
3076    }
3077
3078    /// Sets the colour-dialog preferences.
3079    pub fn with_color_dialog_data(mut self, data: ColorDialogData) -> Self {
3080        self.color_dialog_data = Some(data);
3081        self
3082    }
3083
3084    /// Sets the font-dialog preferences.
3085    pub fn with_font_dialog_data(mut self, data: FontDialogData) -> Self {
3086        self.font_dialog_data = Some(data);
3087        self
3088    }
3089
3090    /// Sets the toolbar rows.
3091    pub fn with_toolbar_items(mut self, items: Vec<ToolbarItem>) -> Self {
3092        self.toolbar_items = items;
3093        self
3094    }
3095
3096    /// Sets the toolbar orientation.
3097    pub fn with_toolbar_orientation(mut self, orientation: ToolbarOrientation) -> Self {
3098        self.toolbar_orientation = orientation;
3099        self
3100    }
3101
3102    /// Sets the calendar selected dates.
3103    pub fn with_calendar_selected_dates(
3104        mut self,
3105        dates: impl IntoIterator<Item = CalendarDate>,
3106    ) -> Self {
3107        self.calendar_selected_dates = dates.into_iter().collect();
3108        self
3109    }
3110
3111    /// Sets the calendar selectable min and max bounds.
3112    pub fn with_calendar_bounds(
3113        mut self,
3114        min: Option<CalendarDate>,
3115        max: Option<CalendarDate>,
3116    ) -> Self {
3117        self.calendar_min_date = min;
3118        self.calendar_max_date = max;
3119        self
3120    }
3121
3122    /// Sets the calendar first day of the week convention.
3123    pub fn with_calendar_first_day_of_week(mut self, first_day: CalendarFirstDayOfWeek) -> Self {
3124        self.calendar_first_day_of_week = first_day;
3125        self
3126    }
3127
3128    /// Sets the calendar selection mode.
3129    pub fn with_calendar_selection_mode(mut self, mode: CalendarSelectionMode) -> Self {
3130        self.calendar_selection_mode = mode;
3131        self
3132    }
3133
3134    /// Sets the label text alignment.
3135    pub fn with_label_alignment(mut self, alignment: impl Into<LabelAlignment>) -> Self {
3136        self.label_alignment = alignment.into();
3137        self
3138    }
3139
3140    /// Sets the label text wrap mode.
3141    pub fn with_label_wrap(mut self, wrap: impl Into<LabelWrap>) -> Self {
3142        self.label_wrap = wrap.into();
3143        self
3144    }
3145
3146    /// Sets the label text wrap mode, alias for [`Self::with_label_wrap`].
3147    pub fn with_label_wrap_mode(self, wrap: impl Into<LabelWrap>) -> Self {
3148        self.with_label_wrap(wrap)
3149    }
3150
3151    /// Sets the styled text runs for rich text widgets.
3152    pub fn with_rich_text_runs(mut self, runs: impl IntoIterator<Item = TextRun>) -> Self {
3153        self.rich_text_runs = runs.into_iter().collect();
3154        self
3155    }
3156
3157    /// Sets the inline images for rich text widgets.
3158    pub fn with_rich_text_images(
3159        mut self,
3160        images: impl IntoIterator<Item = RichTextImage>,
3161    ) -> Self {
3162        self.rich_text_images = images.into_iter().collect();
3163        self
3164    }
3165
3166    /// Sets the placeholder/hint text (`TextInput`).
3167    pub fn with_placeholder_text(mut self, text: impl Into<String>) -> Self {
3168        self.placeholder_text = Some(text.into());
3169        self
3170    }
3171
3172    /// Sets monospace font rendering metadata.
3173    pub fn with_monospace(mut self, monospace: bool) -> Self {
3174        self.monospace = monospace;
3175        self
3176    }
3177}
3178
3179/// Returns the set of widgets intended to be portable across backends.
3180pub fn abstractable_widget_types() -> &'static [WidgetKind] {
3181    // This list is intentionally limited to controls that map cleanly to both
3182    // Windows Win32 controls and GTK4 widgets without requiring custom drawing.
3183    &[
3184        WidgetKind::Window,
3185        WidgetKind::Container,
3186        WidgetKind::Label,
3187        WidgetKind::Button,
3188        #[cfg(feature = "widgets-choice")]
3189        WidgetKind::RadioButton,
3190        #[cfg(feature = "widgets-range")]
3191        WidgetKind::Slider,
3192        #[cfg(feature = "widgets-range")]
3193        WidgetKind::SpinBox,
3194        #[cfg(feature = "widgets-containers")]
3195        WidgetKind::Separator,
3196        #[cfg(feature = "widgets-containers")]
3197        WidgetKind::GroupBox,
3198        #[cfg(feature = "widgets-containers")]
3199        WidgetKind::Tabs,
3200        #[cfg(feature = "widgets-media")]
3201        WidgetKind::Image,
3202        #[cfg(feature = "widgets-pickers")]
3203        WidgetKind::DatePicker,
3204        #[cfg(feature = "widgets-text")]
3205        WidgetKind::LinkLabel,
3206        #[cfg(feature = "widgets-data")]
3207        WidgetKind::ListView,
3208        #[cfg(feature = "widgets-data")]
3209        WidgetKind::TreeView,
3210        #[cfg(feature = "widgets-containers")]
3211        WidgetKind::SplitPane,
3212        #[cfg(feature = "widgets-pickers")]
3213        WidgetKind::FileChooserDialog,
3214        #[cfg(feature = "widgets-containers")]
3215        WidgetKind::AlertDialog,
3216        #[cfg(feature = "widgets-text")]
3217        WidgetKind::TextInput,
3218        #[cfg(feature = "widgets-text")]
3219        WidgetKind::TextArea,
3220        #[cfg(feature = "widgets-canvas")]
3221        WidgetKind::VulkanCanvas,
3222        #[cfg(feature = "widgets-choice")]
3223        WidgetKind::Checkbox,
3224        #[cfg(feature = "widgets-choice")]
3225        WidgetKind::ComboBox,
3226        #[cfg(feature = "widgets-range")]
3227        WidgetKind::ProgressBar,
3228        #[cfg(feature = "widgets-data")]
3229        WidgetKind::DataList,
3230        #[cfg(feature = "widgets-data")]
3231        WidgetKind::DataGrid,
3232        #[cfg(feature = "widgets-canvas")]
3233        WidgetKind::Canvas,
3234        #[cfg(feature = "widgets-pickers")]
3235        WidgetKind::ColorDialog,
3236        #[cfg(feature = "widgets-pickers")]
3237        WidgetKind::FontDialog,
3238        WidgetKind::Toolbar,
3239        #[cfg(feature = "widgets-pickers")]
3240        WidgetKind::Calendar,
3241        #[cfg(feature = "widgets-choice")]
3242        WidgetKind::MultiSelect,
3243    ]
3244}
3245
3246#[cfg(test)]
3247mod tests {
3248    use super::*;
3249    use std::cell::Cell;
3250    use std::sync::mpsc;
3251    use std::time::Duration;
3252
3253    #[test]
3254    fn widget_spec_builder_sets_fields() {
3255        let id = WidgetId(1);
3256        let parent = WidgetId(9);
3257        let spec = WidgetSpec::new(id, WidgetKind::Button)
3258            .with_text("Click me")
3259            .with_parent(parent);
3260
3261        assert_eq!(spec.id, id);
3262        assert_eq!(spec.kind, WidgetKind::Button);
3263        assert_eq!(spec.text.as_deref(), Some("Click me"));
3264        assert_eq!(spec.parent, Some(parent));
3265        assert_eq!(spec.container_direction, None);
3266        assert!(!spec.container_scroll_vertical);
3267        assert!(!spec.container_scroll_horizontal);
3268        assert_eq!(spec.size, None);
3269        assert_eq!(spec.position, None);
3270        assert_eq!(spec.data_list_items, Vec::<String>::new());
3271        assert!(spec.data_grid_rows.is_empty());
3272        assert_eq!(spec.background_color, None);
3273        assert_eq!(spec.alert_level, None);
3274        assert_eq!(spec.checked, None);
3275        assert_eq!(spec.range, None);
3276        assert_eq!(spec.step, None);
3277        assert_eq!(spec.value, None);
3278        assert_eq!(spec.group_name, None);
3279        assert_eq!(spec.tab_items, Vec::<String>::new());
3280        assert_eq!(spec.selected_index, None);
3281        assert_eq!(spec.image_source, None);
3282        assert_eq!(spec.date_value, None);
3283        assert_eq!(spec.link_url, None);
3284        assert_eq!(spec.tooltip, None);
3285        assert_eq!(spec.split_ratio, None);
3286        assert_eq!(spec.label_alignment, LabelAlignment::Center);
3287        assert_eq!(spec.label_wrap, LabelWrap::None);
3288
3289        let spec = spec.with_tooltip("Helpful hint");
3290        assert_eq!(spec.tooltip.as_deref(), Some("Helpful hint"));
3291    }
3292
3293    #[test]
3294    fn widget_spec_builder_sets_size() {
3295        let spec = WidgetSpec::new(WidgetId(5), WidgetKind::Button).with_size(120, 44);
3296
3297        assert_eq!(spec.size, Some((120, 44)));
3298    }
3299
3300    #[test]
3301    fn widget_spec_builder_sets_position() {
3302        let spec = WidgetSpec::new(WidgetId(7), WidgetKind::Button).with_position(32, 48);
3303
3304        assert_eq!(spec.position, Some((32, 48)));
3305    }
3306
3307    #[test]
3308    fn widget_spec_builder_sets_background_color() {
3309        let color = Color::rgb(24, 42, 64);
3310        let spec = WidgetSpec::new(WidgetId(6), WidgetKind::Label).with_background_color(color);
3311
3312        assert_eq!(spec.background_color, Some(color));
3313    }
3314
3315    #[test]
3316    #[cfg(feature = "widgets-data")]
3317    fn widget_spec_builder_sets_data_items() {
3318        let list_spec = WidgetSpec::new(WidgetId(10), WidgetKind::DataList)
3319            .with_data_list_items(vec!["A".to_owned(), "B".to_owned()]);
3320        assert_eq!(
3321            list_spec.data_list_items,
3322            vec!["A".to_owned(), "B".to_owned()]
3323        );
3324
3325        let grid_spec =
3326            WidgetSpec::new(WidgetId(11), WidgetKind::DataGrid).with_data_grid_rows(vec![
3327                vec!["r1c1".to_owned(), "r1c2".to_owned()],
3328                vec!["r2c1".to_owned(), "r2c2".to_owned()],
3329            ]);
3330        let expected = vec![
3331            vec!["r1c1".to_owned(), "r1c2".to_owned()],
3332            vec!["r2c1".to_owned(), "r2c2".to_owned()],
3333        ];
3334        assert_eq!(grid_spec.data_grid_rows.as_ref(), &expected);
3335    }
3336
3337    #[test]
3338    fn column_spec_width_preference_follows_shared_size_semantics() {
3339        let column = ColumnSpec::new("Name");
3340        assert_eq!(column.title, "Name");
3341        assert_eq!(column.width, None);
3342        assert_eq!(ColumnSpec::new("Name").with_width(80).width, Some(80));
3343        assert_eq!(
3344            ColumnSpec::new("Name").with_width(0).width,
3345            None,
3346            "non-positive width means no preference"
3347        );
3348        assert_eq!(ColumnSpec::new("Name").with_width(-4).width, None);
3349    }
3350
3351    #[test]
3352    #[cfg(feature = "widgets-data")]
3353    fn widget_spec_builder_sets_list_columns_and_rows() {
3354        let spec = WidgetSpec::new(WidgetId(12), WidgetKind::ListView)
3355            .with_list_columns(vec![ColumnSpec::new("Name"), ColumnSpec::new("Size")])
3356            .with_list_rows(vec![
3357                vec!["a.txt".to_owned(), "12 KB".to_owned()],
3358                vec!["folder".to_owned()],
3359            ]);
3360        assert_eq!(spec.list_columns.len(), 2);
3361        assert_eq!(spec.list_columns[1].title, "Size");
3362        assert_eq!(spec.list_rows.len(), 2);
3363        assert_eq!(spec.list_rows[1], vec!["folder".to_owned()]);
3364
3365        // Both rows apply to `ListView` only; `DataList` stays on its
3366        // single-column list contract.
3367        spec_with_columns(WidgetKind::ListView).expect("ListView accepted");
3368        assert_eq!(
3369            spec_with_columns(WidgetKind::DataList).expect_err("DataList rejected"),
3370            GuiError::UnsupportedWidget("set_list_columns")
3371        );
3372    }
3373
3374    /// `ensure_property` view of the columned rows, used by the test above.
3375    fn spec_with_columns(kind: WidgetKind) -> GuiResult<()> {
3376        WidgetSpec::new(WidgetId(13), kind).ensure_property(WidgetProperty::ListViewColumns)
3377    }
3378
3379    #[test]
3380    fn row_diff_classifies_insert_update_move_keep_and_remove() {
3381        let old = [
3382            RowSet::new(1, &["a"]),
3383            RowSet::new(2, &["b"]),
3384            RowSet::new(3, &["c"]),
3385        ];
3386        let new = [
3387            RowSet::new(4, &["d"]),
3388            RowSet::new(2, &["b2"]),
3389            RowSet::new(3, &["c"]),
3390            RowSet::new(1, &["a"]),
3391        ];
3392        assert_eq!(
3393            diff_rows(&old, &new).expect("diff"),
3394            RowDelta {
3395                inserted: 1,
3396                updated: 1,
3397                removed: 0,
3398                moved: 1,
3399                unchanged: 1,
3400            }
3401        );
3402    }
3403
3404    #[test]
3405    fn row_diff_counts_removals_reorders_and_duplicates() {
3406        let old = [
3407            RowSet::new(1, &["a"]),
3408            RowSet::new(2, &["b"]),
3409            RowSet::new(3, &["c"]),
3410        ];
3411        let new = [RowSet::new(1, &["a"])];
3412        let delta = diff_rows(&old, &new).expect("diff");
3413        assert_eq!(delta.removed, 2);
3414        assert_eq!(delta.unchanged, 1);
3415        assert!(!delta.is_noop());
3416
3417        // Reordering identical content is moves, never updates; an
3418        // identical set is the free no-op.
3419        let reordered = [old[2].clone(), old[0].clone(), old[1].clone()];
3420        let delta = diff_rows(&old, &reordered).expect("diff");
3421        assert_eq!(
3422            delta,
3423            RowDelta {
3424                inserted: 0,
3425                updated: 0,
3426                removed: 0,
3427                moved: 3,
3428                unchanged: 0,
3429            }
3430        );
3431        assert!(diff_rows(&old, &old).expect("diff").is_noop());
3432
3433        // Duplicate keys are rejected before anything is classified.
3434        let duplicates = [RowSet::new(9, &["x"]), RowSet::new(9, &["y"])];
3435        assert_eq!(
3436            diff_rows(&old, &duplicates),
3437            Err(GuiError::Backend("duplicate row key".to_owned()))
3438        );
3439    }
3440
3441    #[test]
3442    fn row_set_builder_and_single_cell_text() {
3443        let row = RowSet::new(7, &["Name", "12 KB"]);
3444        assert_eq!(row.key, RowKey(7));
3445        assert_eq!(row.cells, vec!["Name".to_owned(), "12 KB".to_owned()]);
3446        assert_eq!(row.text(), "Name");
3447        assert_eq!(RowSet::new(8, &[]).text(), "");
3448    }
3449
3450    #[test]
3451    fn container_defaults_to_vertical_direction() {
3452        let spec = WidgetSpec::new(WidgetId(2), WidgetKind::Container);
3453        assert_eq!(spec.container_direction, Some(ContainerDirection::Vertical));
3454        assert!(!spec.container_scroll_vertical);
3455        assert!(!spec.container_scroll_horizontal);
3456    }
3457
3458    #[test]
3459    fn container_builder_sets_scroll_flags() {
3460        let spec =
3461            WidgetSpec::new(WidgetId(3), WidgetKind::Container).with_container_scroll(true, false);
3462        assert!(spec.container_scroll_vertical);
3463        assert!(!spec.container_scroll_horizontal);
3464    }
3465
3466    #[test]
3467    fn abstractable_widget_types_contains_expected_kinds() {
3468        let list = abstractable_widget_types();
3469        assert!(list.contains(&WidgetKind::Window));
3470        assert!(list.contains(&WidgetKind::Button));
3471        #[cfg(feature = "widgets-choice")]
3472        assert!(list.contains(&WidgetKind::RadioButton));
3473        #[cfg(feature = "widgets-range")]
3474        assert!(list.contains(&WidgetKind::Slider));
3475        #[cfg(feature = "widgets-range")]
3476        assert!(list.contains(&WidgetKind::SpinBox));
3477        #[cfg(feature = "widgets-containers")]
3478        assert!(list.contains(&WidgetKind::Separator));
3479        #[cfg(feature = "widgets-containers")]
3480        assert!(list.contains(&WidgetKind::GroupBox));
3481        #[cfg(feature = "widgets-containers")]
3482        assert!(list.contains(&WidgetKind::Tabs));
3483        #[cfg(feature = "widgets-media")]
3484        assert!(list.contains(&WidgetKind::Image));
3485        #[cfg(feature = "widgets-pickers")]
3486        assert!(list.contains(&WidgetKind::DatePicker));
3487        #[cfg(feature = "widgets-text")]
3488        assert!(list.contains(&WidgetKind::LinkLabel));
3489        #[cfg(feature = "widgets-data")]
3490        assert!(list.contains(&WidgetKind::ListView));
3491        #[cfg(feature = "widgets-data")]
3492        assert!(list.contains(&WidgetKind::TreeView));
3493        #[cfg(feature = "widgets-containers")]
3494        assert!(list.contains(&WidgetKind::SplitPane));
3495        #[cfg(feature = "widgets-pickers")]
3496        assert!(list.contains(&WidgetKind::FileChooserDialog));
3497        #[cfg(feature = "widgets-containers")]
3498        assert!(list.contains(&WidgetKind::AlertDialog));
3499        #[cfg(feature = "widgets-text")]
3500        assert!(list.contains(&WidgetKind::TextArea));
3501        #[cfg(feature = "widgets-canvas")]
3502        assert!(list.contains(&WidgetKind::VulkanCanvas));
3503        #[cfg(feature = "widgets-choice")]
3504        assert!(list.contains(&WidgetKind::Checkbox));
3505        #[cfg(feature = "widgets-choice")]
3506        assert!(list.contains(&WidgetKind::ComboBox));
3507        #[cfg(feature = "widgets-range")]
3508        assert!(list.contains(&WidgetKind::ProgressBar));
3509        #[cfg(feature = "widgets-data")]
3510        assert!(list.contains(&WidgetKind::DataList));
3511        #[cfg(feature = "widgets-data")]
3512        assert!(list.contains(&WidgetKind::DataGrid));
3513        #[cfg(feature = "widgets-canvas")]
3514        assert!(list.contains(&WidgetKind::Canvas));
3515        #[cfg(feature = "widgets-pickers")]
3516        assert!(list.contains(&WidgetKind::ColorDialog));
3517        #[cfg(feature = "widgets-pickers")]
3518        assert!(list.contains(&WidgetKind::FontDialog));
3519        assert!(list.contains(&WidgetKind::Toolbar));
3520        #[cfg(feature = "widgets-pickers")]
3521        assert!(list.contains(&WidgetKind::Calendar));
3522        #[cfg(feature = "widgets-choice")]
3523        assert!(list.contains(&WidgetKind::MultiSelect));
3524        let mut expected_len = 8;
3525        if cfg!(feature = "widgets-containers") {
3526            expected_len += 5;
3527        }
3528        if cfg!(feature = "widgets-choice") {
3529            expected_len += 4;
3530        }
3531        if cfg!(feature = "widgets-data") {
3532            expected_len += 4;
3533        }
3534        if cfg!(feature = "widgets-media") {
3535            expected_len += 1;
3536        }
3537        if cfg!(feature = "widgets-canvas") {
3538            expected_len += 2;
3539        }
3540        if cfg!(feature = "widgets-range") {
3541            expected_len += 3;
3542        }
3543        if cfg!(feature = "widgets-pickers") {
3544            expected_len += 5;
3545        }
3546        assert_eq!(list.len(), expected_len);
3547    }
3548
3549    #[cfg(feature = "widgets-containers")]
3550    #[test]
3551    fn alert_dialog_defaults_to_info_level() {
3552        let spec = WidgetSpec::new(WidgetId(12), WidgetKind::AlertDialog);
3553        assert_eq!(spec.alert_level, Some(AlertLevel::Info));
3554    }
3555
3556    #[cfg(feature = "widgets-containers")]
3557    #[test]
3558    fn alert_dialog_builder_sets_level() {
3559        let spec = WidgetSpec::new(WidgetId(13), WidgetKind::AlertDialog)
3560            .with_alert_level(AlertLevel::Error);
3561        assert_eq!(spec.alert_level, Some(AlertLevel::Error));
3562    }
3563
3564    #[test]
3565    fn extended_builder_metadata_sets_fields() {
3566        let spec = WidgetSpec::new(WidgetId(14), WidgetKind::Button)
3567            .with_checked(true)
3568            .with_range(1, 10)
3569            .with_step(2)
3570            .with_value(7)
3571            .with_group_name("group-a")
3572            .with_tab_items(vec!["One".to_owned(), "Two".to_owned()])
3573            .with_selected_index(1)
3574            .with_image_source("./assets/icon.png")
3575            .with_date_value("2026-03-06")
3576            .with_link_url("https://example.com")
3577            .with_split_ratio(80);
3578
3579        assert_eq!(spec.checked, Some(true));
3580        assert_eq!(spec.range, Some((1, 10)));
3581        assert_eq!(spec.step, Some(2));
3582        assert_eq!(spec.value, Some(7));
3583        assert_eq!(spec.group_name.as_deref(), Some("group-a"));
3584        assert_eq!(spec.tab_items, vec!["One".to_owned(), "Two".to_owned()]);
3585        assert_eq!(spec.selected_index, Some(1));
3586        assert_eq!(spec.image_source.as_deref(), Some("./assets/icon.png"));
3587        assert_eq!(spec.date_value.as_deref(), Some("2026-03-06"));
3588        assert_eq!(spec.link_url.as_deref(), Some("https://example.com"));
3589        assert_eq!(spec.split_ratio, Some(80));
3590    }
3591
3592    #[cfg(feature = "widgets-pickers")]
3593    #[test]
3594    fn calendar_date_and_spec_builder_validation() {
3595        let valid_date = CalendarDate::new(2024, 2, 29);
3596        assert!(valid_date.is_valid(), "2024 is leap year");
3597        let invalid_date = CalendarDate::new(2023, 2, 29);
3598        assert!(!invalid_date.is_valid(), "2023 is not leap year");
3599
3600        let spec = WidgetSpec::new(WidgetId(20), WidgetKind::Calendar)
3601            .with_calendar_selected_dates(vec![valid_date])
3602            .with_calendar_bounds(
3603                Some(CalendarDate::new(2024, 1, 1)),
3604                Some(CalendarDate::new(2024, 12, 31)),
3605            )
3606            .with_calendar_first_day_of_week(CalendarFirstDayOfWeek::Monday)
3607            .with_calendar_selection_mode(CalendarSelectionMode::Range);
3608
3609        assert_eq!(spec.calendar_selected_dates, vec![valid_date]);
3610        assert_eq!(spec.calendar_min_date, Some(CalendarDate::new(2024, 1, 1)));
3611        assert_eq!(
3612            spec.calendar_max_date,
3613            Some(CalendarDate::new(2024, 12, 31))
3614        );
3615        assert_eq!(
3616            spec.calendar_first_day_of_week,
3617            CalendarFirstDayOfWeek::Monday
3618        );
3619        assert_eq!(spec.calendar_selection_mode, CalendarSelectionMode::Range);
3620    }
3621
3622    #[test]
3623    fn widget_spec_builder_sets_label_alignment_and_wrap() {
3624        let default_spec = WidgetSpec::new(WidgetId(21), WidgetKind::Label);
3625        assert_eq!(default_spec.label_alignment, LabelAlignment::Left);
3626        assert_eq!(default_spec.label_wrap, LabelWrap::None);
3627        assert!(!default_spec.label_wrap.is_wrapping());
3628
3629        let spec = WidgetSpec::new(WidgetId(22), WidgetKind::Label)
3630            .with_label_alignment(LabelAlignment::Center)
3631            .with_label_wrap(LabelWrap::Word);
3632
3633        assert_eq!(spec.label_alignment, LabelAlignment::Center);
3634        assert_eq!(spec.label_wrap, LabelWrap::Word);
3635        assert!(spec.label_wrap.is_wrapping());
3636
3637        let right_spec = WidgetSpec::new(WidgetId(23), WidgetKind::Label)
3638            .with_label_alignment(LabelAlignment::Right)
3639            .with_label_wrap(true);
3640        assert_eq!(right_spec.label_alignment, LabelAlignment::Right);
3641        assert_eq!(right_spec.label_wrap, LabelWrap::Word);
3642
3643        let nowrap_spec = WidgetSpec::new(WidgetId(24), WidgetKind::Label).with_label_wrap(false);
3644        assert_eq!(nowrap_spec.label_wrap, LabelWrap::None);
3645
3646        let char_wrap_spec =
3647            WidgetSpec::new(WidgetId(25), WidgetKind::Label).with_label_wrap_mode(LabelWrap::Char);
3648        assert_eq!(char_wrap_spec.label_wrap, LabelWrap::Char);
3649
3650        let word_char_spec =
3651            WidgetSpec::new(WidgetId(26), WidgetKind::Label).with_label_wrap(LabelWrap::WordChar);
3652        assert_eq!(word_char_spec.label_wrap, LabelWrap::WordChar);
3653
3654        // Conversions between TextAlignment and LabelAlignment
3655        assert_eq!(
3656            LabelAlignment::from(TextAlignment::Left),
3657            LabelAlignment::Left
3658        );
3659        assert_eq!(
3660            LabelAlignment::from(TextAlignment::Center),
3661            LabelAlignment::Center
3662        );
3663        assert_eq!(
3664            LabelAlignment::from(TextAlignment::Right),
3665            LabelAlignment::Right
3666        );
3667        assert_eq!(
3668            TextAlignment::from(LabelAlignment::Left),
3669            TextAlignment::Left
3670        );
3671        assert_eq!(
3672            TextAlignment::from(LabelAlignment::Center),
3673            TextAlignment::Center
3674        );
3675        assert_eq!(
3676            TextAlignment::from(LabelAlignment::Right),
3677            TextAlignment::Right
3678        );
3679
3680        // with_label_alignment also accepts TextAlignment via Into<LabelAlignment>
3681        let from_text_align = WidgetSpec::new(WidgetId(27), WidgetKind::Label)
3682            .with_label_alignment(TextAlignment::Right);
3683        assert_eq!(from_text_align.label_alignment, LabelAlignment::Right);
3684
3685        // Property applicability checks
3686        assert!(default_spec
3687            .ensure_property(WidgetProperty::LabelAlignment)
3688            .is_ok());
3689        assert!(default_spec
3690            .ensure_property(WidgetProperty::LabelWrap)
3691            .is_ok());
3692        let button_spec = WidgetSpec::new(WidgetId(28), WidgetKind::Button);
3693        assert!(button_spec
3694            .ensure_property(WidgetProperty::LabelAlignment)
3695            .is_ok());
3696        assert_eq!(
3697            button_spec.ensure_property(WidgetProperty::LabelWrap),
3698            Err(GuiError::UnsupportedWidget("set_label_wrap"))
3699        );
3700    }
3701
3702    #[test]
3703    #[cfg(feature = "widgets-text")]
3704    fn rich_text_runs_and_style_widget_spec() {
3705        let style = TextStyle::new()
3706            .bold(true)
3707            .italic(true)
3708            .underline(true)
3709            .strikethrough(true)
3710            .monospace(true)
3711            .scale(1.5)
3712            .fg_color(Color::rgb(255, 0, 0))
3713            .bg_color(Color::rgb(0, 255, 0))
3714            .link("https://example.com")
3715            .dimmed(true)
3716            .paragraph_indent(2);
3717
3718        assert!(style.bold);
3719        assert!(style.italic);
3720        assert!(style.underline);
3721        assert!(style.strikethrough);
3722        assert!(style.monospace);
3723        assert_eq!(style.scale, Some(1.5));
3724        assert_eq!(style.fg_color, Some(Color::rgb(255, 0, 0)));
3725        assert_eq!(style.bg_color, Some(Color::rgb(0, 255, 0)));
3726        assert_eq!(style.link.as_deref(), Some("https://example.com"));
3727        assert!(style.dimmed);
3728        assert_eq!(style.paragraph_indent, 2);
3729
3730        let run = TextRun::new(0..12, style.clone());
3731        assert_eq!(run.range, 0..12);
3732        assert_eq!(run.style, style);
3733
3734        let spec = WidgetSpec::new(WidgetId(29), WidgetKind::RichText)
3735            .with_rich_text_runs(vec![run.clone()]);
3736        assert_eq!(spec.kind, WidgetKind::RichText);
3737        assert_eq!(spec.rich_text_runs, vec![run]);
3738
3739        // Property checks
3740        assert!(spec.ensure_property(WidgetProperty::RichTextRuns).is_ok());
3741        assert!(spec.requires_property(WidgetProperty::RichTextRuns).is_ok());
3742        assert_eq!(WidgetProperty::RichTextRuns.name(), "set_rich_text_runs");
3743        assert_eq!(
3744            WidgetProperty::RichTextRuns.operation(),
3745            "set_rich_text_runs"
3746        );
3747
3748        let button_spec = WidgetSpec::new(WidgetId(30), WidgetKind::Button);
3749        assert_eq!(
3750            button_spec.ensure_property(WidgetProperty::RichTextRuns),
3751            Err(GuiError::UnsupportedWidget("set_rich_text_runs"))
3752        );
3753        assert_eq!(
3754            button_spec.requires_property(WidgetProperty::RichTextRuns),
3755            Err(GuiError::UnsupportedWidget("set_rich_text_runs"))
3756        );
3757    }
3758
3759    #[test]
3760    #[cfg(feature = "widgets-text")]
3761    fn rich_text_images_widget_spec() {
3762        let img = RichTextImage::new(10, "assets/diagram.png", Some(640));
3763        assert_eq!(img.offset, 10);
3764        assert_eq!(img.source, "assets/diagram.png");
3765        assert_eq!(img.max_width, Some(640));
3766
3767        let spec = WidgetSpec::new(WidgetId(31), WidgetKind::RichText)
3768            .with_rich_text_images(vec![img.clone()]);
3769        assert_eq!(spec.kind, WidgetKind::RichText);
3770        assert_eq!(spec.rich_text_images, vec![img]);
3771
3772        // Property checks
3773        assert!(spec.ensure_property(WidgetProperty::RichTextImages).is_ok());
3774        assert!(spec
3775            .requires_property(WidgetProperty::RichTextImages)
3776            .is_ok());
3777        assert_eq!(
3778            WidgetProperty::RichTextImages.name(),
3779            "set_rich_text_images"
3780        );
3781        assert_eq!(
3782            WidgetProperty::RichTextImages.operation(),
3783            "set_rich_text_images"
3784        );
3785
3786        let button_spec = WidgetSpec::new(WidgetId(32), WidgetKind::Button);
3787        assert_eq!(
3788            button_spec.ensure_property(WidgetProperty::RichTextImages),
3789            Err(GuiError::UnsupportedWidget("set_rich_text_images"))
3790        );
3791        assert_eq!(
3792            button_spec.requires_property(WidgetProperty::RichTextImages),
3793            Err(GuiError::UnsupportedWidget("set_rich_text_images"))
3794        );
3795    }
3796
3797    /// Compile-time exhaustive index for [`WidgetProperty`].
3798    ///
3799    /// Adding a variant without listing it here fails to compile, which
3800    /// forces the author to also extend [`WidgetProperty::ALL`]; the
3801    /// `property_all_covers_every_declared_variant` test then fails until
3802    /// the row is registered. This is the drift guard for the property table.
3803    fn variant_index(property: WidgetProperty) -> usize {
3804        match property {
3805            WidgetProperty::Checked => 0,
3806            WidgetProperty::Value => 1,
3807            WidgetProperty::Range => 2,
3808            WidgetProperty::Step => 3,
3809            WidgetProperty::SelectedIndex => 4,
3810            WidgetProperty::TabItems => 5,
3811            WidgetProperty::SelectedIndices => 6,
3812            WidgetProperty::RowDrag => 7,
3813            WidgetProperty::DataListItems => 8,
3814            WidgetProperty::ListViewColumns => 9,
3815            WidgetProperty::ListViewRows => 10,
3816            WidgetProperty::DataGridRows => 11,
3817            WidgetProperty::DataGridModel => 12,
3818            WidgetProperty::DataGridRowHeight => 13,
3819            WidgetProperty::DataGridColWidth => 14,
3820            WidgetProperty::DataGridFrozenPanes => 15,
3821            WidgetProperty::DataGridSelection => 16,
3822            WidgetProperty::TreeItems => 17,
3823            WidgetProperty::AlertLevel => 18,
3824            WidgetProperty::ImageSource => 19,
3825            WidgetProperty::ImageFit => 20,
3826            WidgetProperty::ButtonIcon => 21,
3827            WidgetProperty::FileChooserMode => 22,
3828            WidgetProperty::ColorDialogData => 23,
3829            WidgetProperty::FontDialogData => 24,
3830            WidgetProperty::ToolbarItems => 25,
3831            WidgetProperty::ToolbarOrientation => 26,
3832            WidgetProperty::DateValue => 27,
3833            WidgetProperty::LinkUrl => 28,
3834            WidgetProperty::TextSelection => 29,
3835            WidgetProperty::TextCompletion => 30,
3836            WidgetProperty::ContainerDirection => 31,
3837            WidgetProperty::ContainerScroll => 32,
3838            WidgetProperty::ContainerGap => 33,
3839            WidgetProperty::ContainerPadding => 34,
3840            WidgetProperty::CanvasScene => 35,
3841            WidgetProperty::CanvasSurface => 36,
3842            WidgetProperty::CloseGuard => 37,
3843            WidgetProperty::LayoutRoot => 38,
3844            WidgetProperty::WindowCallback => 39,
3845            WidgetProperty::NativeHandle => 40,
3846            WidgetProperty::DrawDemoCube => 41,
3847            WidgetProperty::CopyToClipboard => 42,
3848            WidgetProperty::PasteFromClipboard => 43,
3849            WidgetProperty::KeyedRows => 44,
3850            WidgetProperty::ClearSelection => 45,
3851            WidgetProperty::VisibleAnchor => 46,
3852            WidgetProperty::CalendarDates => 47,
3853            WidgetProperty::CalendarBounds => 48,
3854            WidgetProperty::CalendarFirstDayOfWeek => 49,
3855            WidgetProperty::CalendarSelectionMode => 50,
3856            WidgetProperty::LabelAlignment => 51,
3857            WidgetProperty::LabelWrap => 52,
3858            WidgetProperty::RichTextRuns => 53,
3859            WidgetProperty::PlaceholderText => 54,
3860            WidgetProperty::RichTextImages => 55,
3861            WidgetProperty::Monospace => 56,
3862            WidgetProperty::MetalHandle => 57,
3863            WidgetProperty::ContainerWrap => 58,
3864            WidgetProperty::Font => 59,
3865            WidgetProperty::RowIcons => 60,
3866        }
3867    }
3868
3869    #[test]
3870    fn property_all_covers_every_declared_variant() {
3871        let mut indices: Vec<usize> = WidgetProperty::ALL
3872            .iter()
3873            .copied()
3874            .map(variant_index)
3875            .collect();
3876        indices.sort_unstable();
3877        assert_eq!(
3878            indices,
3879            (0..WidgetProperty::ALL.len()).collect::<Vec<usize>>(),
3880            "WidgetProperty::ALL must list every variant exactly once"
3881        );
3882    }
3883
3884    #[test]
3885    fn property_table_rows_are_well_formed() {
3886        let mut operations = Vec::new();
3887        for &property in WidgetProperty::ALL {
3888            let row = property.applicable_kinds();
3889            let image_property = matches!(
3890                property,
3891                WidgetProperty::ImageSource | WidgetProperty::ImageFit
3892            );
3893            let canvas_property = matches!(
3894                property,
3895                WidgetProperty::CanvasScene
3896                    | WidgetProperty::CanvasSurface
3897                    | WidgetProperty::NativeHandle
3898                    | WidgetProperty::DrawDemoCube
3899                    | WidgetProperty::MetalHandle
3900            );
3901            let range_property = matches!(
3902                property,
3903                WidgetProperty::Value | WidgetProperty::Range | WidgetProperty::Step
3904            );
3905            let choice_property = matches!(property, WidgetProperty::Checked);
3906            let data_property = matches!(property, WidgetProperty::RowIcons);
3907            if (cfg!(feature = "widgets-media") || !image_property)
3908                && (cfg!(feature = "widgets-canvas") || !canvas_property)
3909                && (cfg!(feature = "widgets-range") || !range_property)
3910                && (cfg!(feature = "widgets-choice") || !choice_property)
3911                && (cfg!(feature = "widgets-data") || !data_property)
3912            {
3913                assert!(
3914                    !row.is_empty(),
3915                    "{property:?} must accept at least one kind"
3916                );
3917            } else {
3918                assert!(
3919                    row.is_empty(),
3920                    "{property:?} must have no applicable kind when its feature is off"
3921                );
3922            }
3923            for kind in row {
3924                assert!(
3925                    ALL_KINDS.contains(kind),
3926                    "{property:?} row names {kind:?}, which ALL_KINDS does not declare"
3927                );
3928            }
3929            let mut unique = row.to_vec();
3930            unique.sort_by_key(|kind| variant_kind_index(*kind));
3931            unique.dedup();
3932            assert_eq!(
3933                unique.len(),
3934                row.len(),
3935                "{property:?} row contains duplicate kinds"
3936            );
3937
3938            let operation = property.operation();
3939            assert!(
3940                !operation.is_empty(),
3941                "{property:?} must have a stable operation name"
3942            );
3943            assert!(
3944                !operations.contains(&operation),
3945                "operation name {operation:?} is used by two properties"
3946            );
3947            operations.push(operation);
3948        }
3949
3950        let mut kinds = ALL_KINDS.to_vec();
3951        kinds.sort_by_key(|kind| variant_kind_index(*kind));
3952        let declared = kinds.len();
3953        kinds.dedup();
3954        assert_eq!(declared, kinds.len(), "ALL_KINDS contains duplicates");
3955
3956        if !cfg!(feature = "widgets-media") {
3957            assert!(ALL_KINDS.iter().all(|kind| {
3958                !WidgetProperty::ImageSource.supports(*kind)
3959                    && !WidgetProperty::ImageFit.supports(*kind)
3960            }));
3961        }
3962
3963        if !cfg!(feature = "widgets-canvas") {
3964            assert!(ALL_KINDS.iter().all(|kind| {
3965                !WidgetProperty::CanvasScene.supports(*kind)
3966                    && !WidgetProperty::CanvasSurface.supports(*kind)
3967                    && !WidgetProperty::NativeHandle.supports(*kind)
3968                    && !WidgetProperty::DrawDemoCube.supports(*kind)
3969                    && !WidgetProperty::MetalHandle.supports(*kind)
3970            }));
3971        }
3972
3973        if !cfg!(feature = "widgets-range") {
3974            assert!(ALL_KINDS.iter().all(|kind| {
3975                !WidgetProperty::Value.supports(*kind)
3976                    && !WidgetProperty::Range.supports(*kind)
3977                    && !WidgetProperty::Step.supports(*kind)
3978            }));
3979        }
3980
3981        if !cfg!(feature = "widgets-choice") {
3982            assert!(ALL_KINDS
3983                .iter()
3984                .all(|kind| { !WidgetProperty::Checked.supports(*kind) }));
3985        }
3986
3987        if !cfg!(feature = "widgets-data") {
3988            assert!(ALL_KINDS
3989                .iter()
3990                .all(|kind| { !WidgetProperty::RowIcons.supports(*kind) }));
3991        }
3992    }
3993
3994    /// Declaration-order index for [`WidgetKind`], used only to build
3995    /// deterministic sort keys in the table tests.
3996    fn variant_kind_index(kind: WidgetKind) -> usize {
3997        ALL_KINDS
3998            .iter()
3999            .position(|candidate| *candidate == kind)
4000            .expect("ALL_KINDS must declare every kind")
4001    }
4002
4003    #[test]
4004    fn ensure_property_accepts_exactly_the_applicability_row() {
4005        for &property in WidgetProperty::ALL {
4006            for &kind in ALL_KINDS {
4007                let spec = WidgetSpec::new(WidgetId(1), kind);
4008                let result = spec.ensure_property(property);
4009                if property.supports(kind) {
4010                    assert!(
4011                        result.is_ok(),
4012                        "{} must accept {kind:?}",
4013                        property.operation()
4014                    );
4015                } else {
4016                    assert_eq!(
4017                        result,
4018                        Err(GuiError::UnsupportedWidget(property.operation())),
4019                        "{} must reject {kind:?} with the typed error",
4020                        property.operation()
4021                    );
4022                }
4023            }
4024        }
4025    }
4026
4027    // -----------------------------------------------------------------
4028    // Windowed lazy DataGridModel adapter
4029    // -----------------------------------------------------------------
4030
4031    /// A windowed model plus recorders for the two hooks it fires.
4032    struct WindowedProbe {
4033        model: WindowedDataGridModel,
4034        handle: WindowedDataGridHandle,
4035        requested: Rc<RefCell<Vec<usize>>>,
4036        repaints: Rc<Cell<usize>>,
4037    }
4038
4039    fn probe(row_count: usize, col_count: usize, config: WindowedDataGridConfig) -> WindowedProbe {
4040        let requested = Rc::new(RefCell::new(Vec::new()));
4041        let repaints = Rc::new(Cell::new(0usize));
4042        let model = WindowedDataGridModel::new(
4043            row_count,
4044            col_count,
4045            config,
4046            {
4047                let requested = Rc::clone(&requested);
4048                move |row| requested.borrow_mut().push(row)
4049            },
4050            {
4051                let repaints = Rc::clone(&repaints);
4052                move || repaints.set(repaints.get() + 1)
4053            },
4054        );
4055        let handle = model.handle();
4056        WindowedProbe {
4057            model,
4058            handle,
4059            requested,
4060            repaints,
4061        }
4062    }
4063
4064    #[test]
4065    fn windowed_model_schedules_one_fetch_per_row_and_answers_reads_from_the_window() {
4066        let probe = probe(3, 2, WindowedDataGridConfig::new(2, 1024));
4067
4068        // In-range miss: placeholder + one scheduled fetch + one repaint.
4069        assert_eq!(probe.model.value_at(0, 1), "…");
4070        assert_eq!(probe.handle.misses(), 1);
4071        assert_eq!(probe.handle.fetches_requested(), 1);
4072        assert_eq!(*probe.requested.borrow(), vec![0]);
4073        assert_eq!(probe.repaints.get(), 1);
4074        assert!(probe.handle.is_row_in_flight(0));
4075        assert!(!probe.model.is_row_resident(0));
4076
4077        // Repeat reads while the fetch is in flight: more misses, no
4078        // duplicate fetch and no extra repaint.
4079        assert_eq!(probe.model.value_at(1, 0), "…");
4080        assert_eq!(probe.model.value_at(1, 1), "…");
4081        assert_eq!(probe.handle.misses(), 3);
4082        assert_eq!(probe.handle.fetches_requested(), 2);
4083        assert_eq!(*probe.requested.borrow(), vec![0, 1]);
4084        assert_eq!(probe.repaints.get(), 2);
4085
4086        // Delivery makes the row resident and a read is now a hit.
4087        assert_eq!(
4088            probe
4089                .handle
4090                .deliver_row(1, vec!["1a".to_owned(), "1b".to_owned()]),
4091            WindowedDelivery::Applied {
4092                evicted: Vec::new()
4093            }
4094        );
4095        assert!(probe.handle.is_row_resident(1));
4096        assert!(probe.model.is_row_resident(1));
4097        assert!(!probe.handle.is_row_in_flight(1));
4098        assert_eq!(probe.model.value_at(1, 1), "1b");
4099        assert_eq!(probe.handle.hits(), 1);
4100        assert_eq!(probe.handle.resident_row_count(), 1);
4101
4102        // Out-of-range reads are total and empty - never the placeholder -
4103        // and they are not window reads, so counters do not move.
4104        assert_eq!(probe.model.value_at(3, 0), "");
4105        assert_eq!(probe.model.value_at(1, 2), "");
4106        assert_eq!(probe.handle.misses(), 3);
4107        assert_eq!(probe.handle.hits(), 1);
4108        assert!(
4109            !probe.model.is_row_resident(3),
4110            "out-of-range is not resident"
4111        );
4112    }
4113
4114    #[test]
4115    fn windowed_model_lru_eviction_prefers_the_least_recently_used_row() {
4116        let probe = probe(8, 1, WindowedDataGridConfig::new(2, 1024));
4117        for row in 0..2 {
4118            assert_eq!(probe.model.value_at(row, 0), "…");
4119            assert_eq!(
4120                probe.handle.deliver_row(row, vec![format!("r{row}")]),
4121                WindowedDelivery::Applied {
4122                    evicted: Vec::new()
4123                }
4124            );
4125        }
4126
4127        // The third row needs room: row 0 is the least recently used.
4128        assert_eq!(probe.model.value_at(2, 0), "…");
4129        assert_eq!(
4130            probe.handle.deliver_row(2, vec!["r2".to_owned()]),
4131            WindowedDelivery::Applied { evicted: vec![0] }
4132        );
4133        assert!(!probe.handle.is_row_resident(0));
4134        assert_eq!(probe.handle.resident_row_count(), 2);
4135        assert_eq!(probe.handle.evictions(), 1);
4136
4137        // A hit refreshes row 1's recency, so row 2 becomes the LRU victim.
4138        assert_eq!(probe.model.value_at(1, 0), "r1");
4139        assert_eq!(probe.model.value_at(3, 0), "…");
4140        assert_eq!(
4141            probe.handle.deliver_row(3, vec!["r3".to_owned()]),
4142            WindowedDelivery::Applied { evicted: vec![2] }
4143        );
4144        assert!(probe.handle.is_row_resident(1));
4145        assert!(probe.handle.is_row_resident(3));
4146        assert_eq!(probe.handle.evictions(), 2);
4147    }
4148
4149    #[test]
4150    fn windowed_model_evicts_on_the_byte_budget_and_refuses_oversized_rows() {
4151        let probe = probe(8, 1, WindowedDataGridConfig::new(8, 10));
4152        assert_eq!(probe.model.value_at(0, 0), "…");
4153        assert_eq!(
4154            probe.handle.deliver_row(0, vec!["aaaaa".to_owned()]),
4155            WindowedDelivery::Applied {
4156                evicted: Vec::new()
4157            }
4158        );
4159        assert_eq!(probe.model.value_at(1, 0), "…");
4160        assert_eq!(
4161            probe.handle.deliver_row(1, vec!["bbbbb".to_owned()]),
4162            WindowedDelivery::Applied {
4163                evicted: Vec::new()
4164            }
4165        );
4166        assert_eq!(probe.handle.resident_bytes(), 10);
4167
4168        // A third 5-byte row needs room: the byte budget evicts the LRU row.
4169        assert_eq!(probe.model.value_at(2, 0), "…");
4170        assert_eq!(
4171            probe.handle.deliver_row(2, vec!["ccccc".to_owned()]),
4172            WindowedDelivery::Applied { evicted: vec![0] }
4173        );
4174        assert_eq!(probe.handle.resident_bytes(), 10);
4175        assert!(!probe.handle.is_row_resident(0));
4176
4177        // A row that alone exceeds the byte budget can never be resident;
4178        // the refusal is typed, leaves the bound intact, and the row stays
4179        // re-requestable.
4180        assert_eq!(probe.model.value_at(3, 0), "…");
4181        assert_eq!(
4182            probe.handle.deliver_row(3, vec!["ccccccccccc".to_owned()]),
4183            WindowedDelivery::Rejected(WindowedDeliveryRejection::Oversized)
4184        );
4185        assert!(!probe.handle.is_row_resident(3));
4186        assert!(!probe.handle.is_row_in_flight(3));
4187        assert_eq!(probe.handle.rejected_deliveries(), 1);
4188        let fetches_before = probe.handle.fetches_requested();
4189        assert_eq!(probe.model.value_at(3, 0), "…");
4190        assert_eq!(probe.handle.fetches_requested(), fetches_before + 1);
4191    }
4192
4193    #[test]
4194    fn windowed_model_visible_band_pins_survive_until_replaced_or_cleared() {
4195        let probe = probe(8, 1, WindowedDataGridConfig::new(3, 1024));
4196        probe.handle.pin_visible_band(0, 2);
4197        assert_eq!(probe.handle.pinned_band(), Some((0, 2)));
4198        for row in 0..3 {
4199            assert_eq!(probe.model.value_at(row, 0), "…");
4200            assert_eq!(
4201                probe.handle.deliver_row(row, vec![format!("r{row}")]),
4202                WindowedDelivery::Applied {
4203                    evicted: Vec::new()
4204                }
4205            );
4206        }
4207        assert_eq!(probe.handle.resident_row_count(), 3);
4208
4209        // Row 2 is the only unpinned resident row: it is the victim even
4210        // though rows 0 and 1 are older.
4211        assert_eq!(probe.model.value_at(3, 0), "…");
4212        assert_eq!(
4213            probe.handle.deliver_row(3, vec!["r3".to_owned()]),
4214            WindowedDelivery::Applied { evicted: vec![2] }
4215        );
4216        assert!(probe.handle.is_row_resident(0));
4217        assert!(probe.handle.is_row_resident(1));
4218
4219        // The band keeps protecting its rows across deliveries.
4220        assert_eq!(probe.model.value_at(4, 0), "…");
4221        assert_eq!(
4222            probe.handle.deliver_row(4, vec!["r4".to_owned()]),
4223            WindowedDelivery::Applied { evicted: vec![3] }
4224        );
4225        assert!(probe.handle.is_row_resident(0));
4226        assert!(probe.handle.is_row_resident(1));
4227        assert_eq!(probe.handle.resident_row_count(), 3);
4228
4229        // Clearing the band returns the window to pure LRU...
4230        probe.handle.clear_pinned_band();
4231        assert_eq!(probe.handle.pinned_band(), None);
4232        assert_eq!(probe.model.value_at(5, 0), "…");
4233        assert_eq!(
4234            probe.handle.deliver_row(5, vec!["r5".to_owned()]),
4235            WindowedDelivery::Applied { evicted: vec![0] }
4236        );
4237
4238        // ...and a new band replaces the old one instead of accumulating
4239        // (pin scope is one pass, not a timer).
4240        probe.handle.pin_visible_band(1, 1);
4241        assert_eq!(probe.model.value_at(6, 0), "…");
4242        assert_eq!(
4243            probe.handle.deliver_row(6, vec!["r6".to_owned()]),
4244            WindowedDelivery::Applied { evicted: vec![4] }
4245        );
4246        assert!(probe.handle.is_row_resident(1));
4247        assert!(probe.handle.is_row_resident(5));
4248        assert!(probe.handle.is_row_resident(6));
4249        assert_eq!(probe.handle.evictions(), 4);
4250    }
4251
4252    #[test]
4253    fn windowed_model_refuses_delivery_when_every_resident_row_is_pinned() {
4254        let probe = probe(8, 1, WindowedDataGridConfig::new(2, 1024));
4255        probe.handle.pin_visible_band(0, 2);
4256        for row in 0..2 {
4257            assert_eq!(probe.model.value_at(row, 0), "…");
4258            assert_eq!(
4259                probe.handle.deliver_row(row, vec![format!("r{row}")]),
4260                WindowedDelivery::Applied {
4261                    evicted: Vec::new()
4262                }
4263            );
4264        }
4265
4266        assert_eq!(probe.model.value_at(2, 0), "…");
4267        assert_eq!(
4268            probe.handle.deliver_row(2, vec!["r2".to_owned()]),
4269            WindowedDelivery::Rejected(WindowedDeliveryRejection::NoEvictableVictim)
4270        );
4271        assert_eq!(probe.handle.rejected_deliveries(), 1);
4272        assert_eq!(probe.handle.evictions(), 0);
4273        assert!(!probe.handle.is_row_resident(2));
4274        assert_eq!(probe.handle.resident_row_count(), 2, "the bound held");
4275
4276        // The refusal released the fetch state: once the band is cleared the
4277        // row can be requested and delivered normally.
4278        probe.handle.clear_pinned_band();
4279        let fetches_before = probe.handle.fetches_requested();
4280        assert_eq!(probe.model.value_at(2, 0), "…");
4281        assert_eq!(probe.handle.fetches_requested(), fetches_before + 1);
4282        assert_eq!(
4283            probe.handle.deliver_row(2, vec!["r2".to_owned()]),
4284            WindowedDelivery::Applied { evicted: vec![0] }
4285        );
4286        assert!(probe.handle.is_row_resident(2));
4287    }
4288
4289    #[test]
4290    fn data_grid_model_trait_forwards_band_pins_to_the_windowed_handle() {
4291        let probe = probe(8, 1, WindowedDataGridConfig::new(2, 1024));
4292        let model: &dyn DataGridModel = &probe.model;
4293
4294        // The trait default is a no-op: an eager model keeps every row
4295        // resident, so a paint bracket is free to be ignored.
4296        let eager: &dyn DataGridModel = &SimpleDataGridModel {
4297            rows: vec![vec!["a".to_owned()]],
4298        };
4299        eager.pin_visible_band(0, 8);
4300        eager.clear_pinned_band();
4301
4302        // The windowed model carries the band through the same trait object a
4303        // backend holds, with the pinned rows refused as eviction victims -
4304        // the bracket a backend paint pass opens.
4305        model.pin_visible_band(0, 2);
4306        assert_eq!(probe.handle.pinned_band(), Some((0, 2)));
4307        for row in 0..2 {
4308            assert_eq!(model.value_at(row, 0), "…");
4309            assert_eq!(
4310                probe.handle.deliver_row(row, vec![format!("r{row}")]),
4311                WindowedDelivery::Applied {
4312                    evicted: Vec::new()
4313                }
4314            );
4315        }
4316        assert_eq!(model.value_at(2, 0), "…");
4317        assert_eq!(
4318            probe.handle.deliver_row(2, vec!["r2".to_owned()]),
4319            WindowedDelivery::Rejected(WindowedDeliveryRejection::NoEvictableVictim)
4320        );
4321
4322        // Releasing through the trait ends the scope.
4323        model.clear_pinned_band();
4324        assert_eq!(probe.handle.pinned_band(), None);
4325    }
4326
4327    #[test]
4328    fn windowed_model_discards_stale_duplicate_and_out_of_range_deliveries() {
4329        let probe = probe(3, 1, WindowedDataGridConfig::new(2, 1024));
4330
4331        // Never requested: a foreign or late result is discarded.
4332        assert_eq!(
4333            probe.handle.deliver_row(1, vec!["stale".to_owned()]),
4334            WindowedDelivery::Rejected(WindowedDeliveryRejection::NotInFlight)
4335        );
4336        // Beyond the model's shape: cannot belong to this model.
4337        assert_eq!(
4338            probe.handle.deliver_row(9, vec!["x".to_owned()]),
4339            WindowedDelivery::Rejected(WindowedDeliveryRejection::RowOutOfRange)
4340        );
4341        // A duplicated result after the row was applied is discarded too.
4342        assert_eq!(probe.model.value_at(0, 0), "…");
4343        assert!(matches!(
4344            probe.handle.deliver_row(0, vec!["r0".to_owned()]),
4345            WindowedDelivery::Applied { .. }
4346        ));
4347        assert_eq!(
4348            probe.handle.deliver_row(0, vec!["again".to_owned()]),
4349            WindowedDelivery::Rejected(WindowedDeliveryRejection::NotInFlight)
4350        );
4351        assert_eq!(probe.model.value_at(0, 0), "r0", "no stale overwrite");
4352        assert_eq!(probe.handle.rejected_deliveries(), 3);
4353    }
4354
4355    #[test]
4356    fn windowed_model_drop_closes_the_request_channel_fail_closed() {
4357        let (request_tx, request_rx) = mpsc::channel::<usize>();
4358        let (result_tx, result_rx) = mpsc::channel::<(usize, Vec<String>)>();
4359        let (done_tx, done_rx) = mpsc::channel::<()>();
4360
4361        let worker = std::thread::spawn(move || {
4362            while let Ok(row) = request_rx.recv() {
4363                if result_tx.send((row, vec![format!("row {row}")])).is_err() {
4364                    break;
4365                }
4366            }
4367            let _ = done_tx.send(());
4368        });
4369
4370        let model = WindowedDataGridModel::new(
4371            100,
4372            1,
4373            WindowedDataGridConfig::new(4, 4096),
4374            move |row| {
4375                let _ = request_tx.send(row);
4376            },
4377            || {},
4378        );
4379
4380        // Request a row but never apply it: the fetch is in flight when the
4381        // model is dropped. Dropping the model drops the request hook, which
4382        // closes the channel; the producer observes the close and stops.
4383        assert_eq!(model.value_at(7, 0), "…");
4384        assert!(model.handle().is_row_in_flight(7));
4385        drop(model);
4386
4387        done_rx
4388            .recv_timeout(Duration::from_secs(5))
4389            .expect("the producer must stop once the model's request channel closes");
4390        worker.join().expect("worker thread");
4391
4392        // Whatever raced out before the close is a result for the in-flight
4393        // row and has no surviving model to be applied to.
4394        for (row, _) in result_rx.try_iter() {
4395            assert_eq!(row, 7);
4396        }
4397    }
4398
4399    #[test]
4400    fn eager_models_report_every_row_resident_by_default() {
4401        let model = SimpleDataGridModel {
4402            rows: vec![vec!["a".to_owned()]],
4403        };
4404        assert!(model.is_row_resident(0));
4405        assert!(
4406            model.is_row_resident(500),
4407            "the default has no non-resident state; out-of-range reads are still total"
4408        );
4409    }
4410
4411    #[test]
4412    fn row_ops_diff_and_apply_update_insert_remove_move() {
4413        let r1 = RowSet::new(1, &["a", "b"]);
4414        let r2 = RowSet::new(2, &["c", "d"]);
4415        let r3 = RowSet::new(3, &["e", "f"]);
4416        let base = vec![r1.clone(), r2.clone(), r3.clone()];
4417
4418        // 1. Update single row
4419        let mut updated = base.clone();
4420        updated[1] = RowSet::new(2, &["c_mod", "d_mod"]);
4421        let delta = diff_rows(&base, &updated).unwrap();
4422        let ops = diff_row_ops(&base, &updated, &delta).expect("pure update should yield ops");
4423        assert_eq!(ops.len(), 1);
4424        match &ops[0] {
4425            RowOp::Update { index, row } => {
4426                assert_eq!(*index, 1);
4427                assert_eq!(row.cells, vec!["c_mod", "d_mod"]);
4428            }
4429            _ => panic!("expected RowOp::Update"),
4430        }
4431        let mut rows = base.clone();
4432        apply_row_ops_to_rows(&mut rows, &ops);
4433        assert_eq!(rows, updated);
4434
4435        // 2. Insert single row
4436        let r_new = RowSet::new(99, &["x", "y"]);
4437        let inserted = vec![r1.clone(), r_new.clone(), r2.clone(), r3.clone()];
4438        let delta = diff_rows(&base, &inserted).unwrap();
4439        let ops = diff_row_ops(&base, &inserted, &delta).expect("single insert should yield ops");
4440        assert_eq!(ops.len(), 1);
4441        match &ops[0] {
4442            RowOp::Insert { index, row } => {
4443                assert_eq!(*index, 1);
4444                assert_eq!(row.key.0, 99);
4445            }
4446            _ => panic!("expected RowOp::Insert"),
4447        }
4448        let mut rows = base.clone();
4449        apply_row_ops_to_rows(&mut rows, &ops);
4450        assert_eq!(rows, inserted);
4451
4452        // 3. Remove single row
4453        let removed = vec![r1.clone(), r3.clone()];
4454        let delta = diff_rows(&base, &removed).unwrap();
4455        let ops = diff_row_ops(&base, &removed, &delta).expect("single remove should yield ops");
4456        assert_eq!(ops.len(), 1);
4457        match &ops[0] {
4458            RowOp::Remove { index, key } => {
4459                assert_eq!(*index, 1);
4460                assert_eq!(key.0, 2);
4461            }
4462            _ => panic!("expected RowOp::Remove"),
4463        }
4464        let mut rows = base.clone();
4465        apply_row_ops_to_rows(&mut rows, &ops);
4466        assert_eq!(rows, removed);
4467
4468        // 4. Move single row
4469        let moved = vec![r2.clone(), r3.clone(), r1.clone()];
4470        let delta = diff_rows(&base, &moved).unwrap();
4471        let ops = diff_row_ops(&base, &moved, &delta).expect("single move should yield ops");
4472        assert_eq!(ops.len(), 1);
4473        match &ops[0] {
4474            RowOp::Move {
4475                from_index,
4476                to_index,
4477                key,
4478            } => {
4479                assert_eq!(*from_index, 0);
4480                assert_eq!(*to_index, 2);
4481                assert_eq!(key.0, 1);
4482            }
4483            _ => panic!("expected RowOp::Move"),
4484        }
4485        let mut rows = base.clone();
4486        apply_row_ops_to_rows(&mut rows, &ops);
4487        assert_eq!(rows, moved);
4488
4489        // Test cell and item mutators
4490        let mut cells = vec![
4491            vec!["a".to_owned(), "b".to_owned()],
4492            vec!["c".to_owned(), "d".to_owned()],
4493        ];
4494        let op = RowOp::Update {
4495            index: 0,
4496            row: RowSet::new(1, &["new_a", "new_b"]),
4497        };
4498        apply_row_ops_to_cells(&mut cells, &[op]);
4499        assert_eq!(cells[0], vec!["new_a", "new_b"]);
4500
4501        let mut items = vec!["item1".to_owned(), "item2".to_owned()];
4502        let op_item = RowOp::Insert {
4503            index: 1,
4504            row: RowSet::new(10, &["inserted"]),
4505        };
4506        apply_row_ops_to_items(&mut items, &[op_item]);
4507        assert_eq!(items, vec!["item1", "inserted", "item2"]);
4508    }
4509}