use std::cell::RefCell;
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::rc::Rc;
use std::sync::Arc;
use crate::access::AccessibilitySpec;
use crate::artprov::IconRole;
use crate::error::{GuiError, GuiResult};
use crate::pickers::{ColorDialogData, FontDescriptor, FontDialogData};
use crate::toolbar::{ToolbarItem, ToolbarOrientation};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WidgetId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GpuSurfaceCapabilities {
pub vulkan_surface: bool,
pub metal_surface: bool,
pub directx_surface: bool,
pub raw_window_handle: bool,
pub diagnostic_placeholder: bool,
pub headless_emulation: bool,
}
impl GpuSurfaceCapabilities {
pub const fn none() -> Self {
Self {
vulkan_surface: false,
metal_surface: false,
directx_surface: false,
raw_window_handle: false,
diagnostic_placeholder: false,
headless_emulation: false,
}
}
pub const fn all() -> Self {
Self {
vulkan_surface: true,
metal_surface: true,
directx_surface: true,
raw_window_handle: true,
diagnostic_placeholder: true,
headless_emulation: true,
}
}
pub fn supports(self, capability: &str) -> bool {
match capability {
"vulkan_surface" => self.vulkan_surface,
"metal_surface" => self.metal_surface,
"directx_surface" => self.directx_surface,
"raw_window_handle" => self.raw_window_handle,
"diagnostic_placeholder" => self.diagnostic_placeholder,
"headless_emulation" => self.headless_emulation,
"gpu_degradation_fallback" => self.diagnostic_placeholder || self.headless_emulation,
"gpu_surface" => self.vulkan_surface || self.metal_surface || self.directx_surface,
_ => false,
}
}
}
impl Default for GpuSurfaceCapabilities {
fn default() -> Self {
Self::none()
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum GpuDegradationPolicy {
#[default]
StrictFail,
DiagnosticPlaceholder,
Canvas2DFallback,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum WidgetKind {
Window,
Container,
Label,
Button,
#[cfg(feature = "widgets-choice")]
RadioButton,
#[cfg(feature = "widgets-range")]
Slider,
#[cfg(feature = "widgets-range")]
SpinBox,
#[cfg(feature = "widgets-containers")]
Separator,
#[cfg(feature = "widgets-containers")]
GroupBox,
#[cfg(feature = "widgets-containers")]
Tabs,
#[cfg(feature = "widgets-media")]
Image,
#[cfg(feature = "widgets-pickers")]
DatePicker,
#[cfg(feature = "widgets-text")]
LinkLabel,
#[cfg(feature = "widgets-data")]
ListView,
#[cfg(feature = "widgets-data")]
TreeView,
#[cfg(feature = "widgets-containers")]
SplitPane,
#[cfg(feature = "widgets-pickers")]
FileChooserDialog,
#[cfg(feature = "widgets-containers")]
AlertDialog,
#[cfg(feature = "widgets-text")]
TextInput,
#[cfg(feature = "widgets-text")]
TextArea,
#[cfg(feature = "widgets-canvas")]
VulkanCanvas,
#[cfg(feature = "widgets-canvas")]
MetalCanvas,
#[cfg(feature = "widgets-choice")]
Checkbox,
#[cfg(feature = "widgets-choice")]
ComboBox,
#[cfg(feature = "widgets-range")]
ProgressBar,
#[cfg(feature = "widgets-data")]
DataList,
#[cfg(feature = "widgets-data")]
DataGrid,
#[cfg(feature = "widgets-canvas")]
Canvas,
#[cfg(feature = "widgets-pickers")]
ColorDialog,
#[cfg(feature = "widgets-pickers")]
FontDialog,
Toolbar,
#[cfg(feature = "widgets-pickers")]
Calendar,
#[cfg(feature = "widgets-text")]
RichText,
#[cfg(feature = "widgets-choice")]
MultiSelect,
}
pub const ALL_KINDS: &[WidgetKind] = &[
WidgetKind::Window,
WidgetKind::Container,
WidgetKind::Label,
WidgetKind::Button,
#[cfg(feature = "widgets-choice")]
WidgetKind::RadioButton,
#[cfg(feature = "widgets-range")]
WidgetKind::Slider,
#[cfg(feature = "widgets-range")]
WidgetKind::SpinBox,
#[cfg(feature = "widgets-containers")]
WidgetKind::Separator,
#[cfg(feature = "widgets-containers")]
WidgetKind::GroupBox,
#[cfg(feature = "widgets-containers")]
WidgetKind::Tabs,
#[cfg(feature = "widgets-media")]
WidgetKind::Image,
#[cfg(feature = "widgets-pickers")]
WidgetKind::DatePicker,
#[cfg(feature = "widgets-text")]
WidgetKind::LinkLabel,
#[cfg(feature = "widgets-data")]
WidgetKind::ListView,
#[cfg(feature = "widgets-data")]
WidgetKind::TreeView,
#[cfg(feature = "widgets-containers")]
WidgetKind::SplitPane,
#[cfg(feature = "widgets-pickers")]
WidgetKind::FileChooserDialog,
#[cfg(feature = "widgets-containers")]
WidgetKind::AlertDialog,
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput,
#[cfg(feature = "widgets-text")]
WidgetKind::TextArea,
#[cfg(feature = "widgets-canvas")]
WidgetKind::VulkanCanvas,
#[cfg(feature = "widgets-canvas")]
WidgetKind::MetalCanvas,
#[cfg(feature = "widgets-choice")]
WidgetKind::Checkbox,
#[cfg(feature = "widgets-choice")]
WidgetKind::ComboBox,
#[cfg(feature = "widgets-range")]
WidgetKind::ProgressBar,
#[cfg(feature = "widgets-data")]
WidgetKind::DataList,
#[cfg(feature = "widgets-data")]
WidgetKind::DataGrid,
#[cfg(feature = "widgets-canvas")]
WidgetKind::Canvas,
#[cfg(feature = "widgets-pickers")]
WidgetKind::ColorDialog,
#[cfg(feature = "widgets-pickers")]
WidgetKind::FontDialog,
WidgetKind::Toolbar,
#[cfg(feature = "widgets-pickers")]
WidgetKind::Calendar,
#[cfg(feature = "widgets-text")]
WidgetKind::RichText,
#[cfg(feature = "widgets-choice")]
WidgetKind::MultiSelect,
];
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WidgetProperty {
Checked,
Value,
Range,
Step,
SelectedIndex,
TabItems,
SelectedIndices,
RowDrag,
DataListItems,
ListViewColumns,
ListViewRows,
DataGridRows,
DataGridModel,
DataGridRowHeight,
DataGridColWidth,
DataGridFrozenPanes,
DataGridSelection,
TreeItems,
AlertLevel,
ImageSource,
ImageFit,
ButtonIcon,
FileChooserMode,
ColorDialogData,
FontDialogData,
ToolbarItems,
ToolbarOrientation,
DateValue,
LinkUrl,
TextSelection,
TextCompletion,
PlaceholderText,
ContainerDirection,
ContainerWrap,
ContainerScroll,
ContainerGap,
ContainerPadding,
CanvasScene,
CanvasSurface,
CloseGuard,
LayoutRoot,
WindowCallback,
NativeHandle,
DrawDemoCube,
CopyToClipboard,
PasteFromClipboard,
KeyedRows,
ClearSelection,
VisibleAnchor,
CalendarDates,
CalendarBounds,
CalendarFirstDayOfWeek,
CalendarSelectionMode,
LabelAlignment,
LabelWrap,
RichTextRuns,
RichTextImages,
Monospace,
MetalHandle,
Font,
RowIcons,
}
impl WidgetProperty {
pub const ALL: &'static [WidgetProperty] = &[
WidgetProperty::Checked,
WidgetProperty::Value,
WidgetProperty::Range,
WidgetProperty::Step,
WidgetProperty::SelectedIndex,
WidgetProperty::TabItems,
WidgetProperty::SelectedIndices,
WidgetProperty::RowDrag,
WidgetProperty::DataListItems,
WidgetProperty::ListViewColumns,
WidgetProperty::ListViewRows,
WidgetProperty::DataGridRows,
WidgetProperty::DataGridModel,
WidgetProperty::DataGridRowHeight,
WidgetProperty::DataGridColWidth,
WidgetProperty::DataGridFrozenPanes,
WidgetProperty::DataGridSelection,
WidgetProperty::TreeItems,
WidgetProperty::AlertLevel,
WidgetProperty::ImageSource,
WidgetProperty::ImageFit,
WidgetProperty::ButtonIcon,
WidgetProperty::FileChooserMode,
WidgetProperty::ColorDialogData,
WidgetProperty::FontDialogData,
WidgetProperty::ToolbarItems,
WidgetProperty::ToolbarOrientation,
WidgetProperty::DateValue,
WidgetProperty::LinkUrl,
WidgetProperty::TextSelection,
WidgetProperty::TextCompletion,
WidgetProperty::ContainerDirection,
WidgetProperty::ContainerWrap,
WidgetProperty::ContainerScroll,
WidgetProperty::ContainerGap,
WidgetProperty::ContainerPadding,
WidgetProperty::CanvasScene,
WidgetProperty::CanvasSurface,
WidgetProperty::CloseGuard,
WidgetProperty::LayoutRoot,
WidgetProperty::WindowCallback,
WidgetProperty::NativeHandle,
WidgetProperty::DrawDemoCube,
WidgetProperty::CopyToClipboard,
WidgetProperty::PasteFromClipboard,
WidgetProperty::KeyedRows,
WidgetProperty::ClearSelection,
WidgetProperty::VisibleAnchor,
WidgetProperty::CalendarDates,
WidgetProperty::CalendarBounds,
WidgetProperty::CalendarFirstDayOfWeek,
WidgetProperty::CalendarSelectionMode,
WidgetProperty::LabelAlignment,
WidgetProperty::LabelWrap,
WidgetProperty::RichTextRuns,
WidgetProperty::PlaceholderText,
WidgetProperty::RichTextImages,
WidgetProperty::Monospace,
WidgetProperty::MetalHandle,
WidgetProperty::Font,
WidgetProperty::RowIcons,
];
pub const fn applicable_kinds(self) -> &'static [WidgetKind] {
match self {
#[cfg(feature = "widgets-choice")]
WidgetProperty::Checked => &[WidgetKind::Checkbox, WidgetKind::RadioButton],
#[cfg(not(feature = "widgets-choice"))]
WidgetProperty::Checked => &[],
#[cfg(feature = "widgets-range")]
WidgetProperty::Value => &[
WidgetKind::Slider,
WidgetKind::SpinBox,
WidgetKind::ProgressBar,
],
#[cfg(not(feature = "widgets-range"))]
WidgetProperty::Value => &[],
#[cfg(feature = "widgets-range")]
WidgetProperty::Range | WidgetProperty::Step => {
&[WidgetKind::Slider, WidgetKind::SpinBox]
}
#[cfg(not(feature = "widgets-range"))]
WidgetProperty::Range | WidgetProperty::Step => &[],
WidgetProperty::SelectedIndex => {
const KINDS: &[WidgetKind] = &[
#[cfg(feature = "widgets-containers")]
WidgetKind::Tabs,
#[cfg(feature = "widgets-choice")]
WidgetKind::ComboBox,
#[cfg(feature = "widgets-data")]
WidgetKind::DataList,
#[cfg(feature = "widgets-data")]
WidgetKind::ListView,
];
KINDS
}
#[cfg(feature = "widgets-containers")]
WidgetProperty::TabItems => &[WidgetKind::Tabs],
#[cfg(not(feature = "widgets-containers"))]
WidgetProperty::TabItems => &[],
#[cfg(all(feature = "widgets-choice", feature = "widgets-data"))]
WidgetProperty::SelectedIndices => &[
WidgetKind::ListView,
WidgetKind::DataList,
WidgetKind::TreeView,
WidgetKind::MultiSelect,
],
#[cfg(all(feature = "widgets-choice", not(feature = "widgets-data")))]
WidgetProperty::SelectedIndices => &[WidgetKind::MultiSelect],
#[cfg(all(not(feature = "widgets-choice"), feature = "widgets-data"))]
WidgetProperty::SelectedIndices => &[
WidgetKind::ListView,
WidgetKind::DataList,
WidgetKind::TreeView,
],
#[cfg(all(not(feature = "widgets-choice"), not(feature = "widgets-data")))]
WidgetProperty::SelectedIndices => &[],
#[cfg(feature = "widgets-data")]
WidgetProperty::RowDrag => &[
WidgetKind::ListView,
WidgetKind::DataList,
WidgetKind::DataGrid,
WidgetKind::TreeView,
],
#[cfg(not(feature = "widgets-data"))]
WidgetProperty::RowDrag => &[],
#[cfg(all(feature = "widgets-choice", feature = "widgets-data"))]
WidgetProperty::DataListItems => &[
WidgetKind::DataList,
WidgetKind::ListView,
WidgetKind::MultiSelect,
],
#[cfg(all(feature = "widgets-choice", not(feature = "widgets-data")))]
WidgetProperty::DataListItems => &[WidgetKind::MultiSelect],
#[cfg(all(not(feature = "widgets-choice"), feature = "widgets-data"))]
WidgetProperty::DataListItems => &[WidgetKind::DataList, WidgetKind::ListView],
#[cfg(all(not(feature = "widgets-choice"), not(feature = "widgets-data")))]
WidgetProperty::DataListItems => &[],
#[cfg(feature = "widgets-data")]
WidgetProperty::ListViewColumns | WidgetProperty::ListViewRows => {
&[WidgetKind::ListView]
}
#[cfg(not(feature = "widgets-data"))]
WidgetProperty::ListViewColumns | WidgetProperty::ListViewRows => &[],
#[cfg(feature = "widgets-data")]
WidgetProperty::DataGridRows
| WidgetProperty::DataGridModel
| WidgetProperty::DataGridRowHeight
| WidgetProperty::DataGridColWidth
| WidgetProperty::DataGridFrozenPanes
| WidgetProperty::DataGridSelection => &[WidgetKind::DataGrid],
#[cfg(not(feature = "widgets-data"))]
WidgetProperty::DataGridRows
| WidgetProperty::DataGridModel
| WidgetProperty::DataGridRowHeight
| WidgetProperty::DataGridColWidth
| WidgetProperty::DataGridFrozenPanes
| WidgetProperty::DataGridSelection => &[],
#[cfg(feature = "widgets-data")]
WidgetProperty::TreeItems => &[WidgetKind::TreeView],
#[cfg(not(feature = "widgets-data"))]
WidgetProperty::TreeItems => &[],
#[cfg(feature = "widgets-containers")]
WidgetProperty::AlertLevel => &[WidgetKind::AlertDialog],
#[cfg(not(feature = "widgets-containers"))]
WidgetProperty::AlertLevel => &[],
#[cfg(feature = "widgets-media")]
WidgetProperty::ImageSource | WidgetProperty::ImageFit => &[WidgetKind::Image],
#[cfg(not(feature = "widgets-media"))]
WidgetProperty::ImageSource | WidgetProperty::ImageFit => &[],
#[cfg(feature = "widgets-pickers")]
WidgetProperty::ButtonIcon => &[WidgetKind::Button, WidgetKind::FileChooserDialog],
#[cfg(not(feature = "widgets-pickers"))]
WidgetProperty::ButtonIcon => &[WidgetKind::Button],
#[cfg(feature = "widgets-pickers")]
WidgetProperty::FileChooserMode => &[WidgetKind::FileChooserDialog],
#[cfg(not(feature = "widgets-pickers"))]
WidgetProperty::FileChooserMode => &[],
#[cfg(feature = "widgets-pickers")]
WidgetProperty::ColorDialogData => &[WidgetKind::ColorDialog],
#[cfg(not(feature = "widgets-pickers"))]
WidgetProperty::ColorDialogData => &[],
#[cfg(feature = "widgets-pickers")]
WidgetProperty::FontDialogData => &[WidgetKind::FontDialog],
#[cfg(not(feature = "widgets-pickers"))]
WidgetProperty::FontDialogData => &[],
WidgetProperty::ToolbarItems | WidgetProperty::ToolbarOrientation => {
&[WidgetKind::Toolbar]
}
#[cfg(feature = "widgets-pickers")]
WidgetProperty::DateValue => &[WidgetKind::DatePicker],
#[cfg(not(feature = "widgets-pickers"))]
WidgetProperty::DateValue => &[],
#[cfg(feature = "widgets-text")]
WidgetProperty::LinkUrl => &[WidgetKind::LinkLabel],
#[cfg(not(feature = "widgets-text"))]
WidgetProperty::LinkUrl => &[],
#[cfg(feature = "widgets-text")]
WidgetProperty::TextSelection => &[
WidgetKind::TextInput,
WidgetKind::TextArea,
WidgetKind::RichText,
],
#[cfg(not(feature = "widgets-text"))]
WidgetProperty::TextSelection => &[],
#[cfg(feature = "widgets-text")]
WidgetProperty::TextCompletion => &[WidgetKind::TextInput],
#[cfg(not(feature = "widgets-text"))]
WidgetProperty::TextCompletion => &[],
WidgetProperty::ContainerDirection
| WidgetProperty::ContainerWrap
| WidgetProperty::ContainerScroll => {
const KINDS: &[WidgetKind] = &[
WidgetKind::Container,
#[cfg(feature = "widgets-containers")]
WidgetKind::GroupBox,
#[cfg(feature = "widgets-containers")]
WidgetKind::SplitPane,
];
KINDS
}
WidgetProperty::ContainerGap | WidgetProperty::ContainerPadding => {
const KINDS: &[WidgetKind] = &[
WidgetKind::Container,
#[cfg(feature = "widgets-containers")]
WidgetKind::GroupBox,
];
KINDS
}
#[cfg(feature = "widgets-canvas")]
WidgetProperty::CanvasScene | WidgetProperty::CanvasSurface => &[WidgetKind::Canvas],
#[cfg(not(feature = "widgets-canvas"))]
WidgetProperty::CanvasScene | WidgetProperty::CanvasSurface => &[],
WidgetProperty::CloseGuard
| WidgetProperty::LayoutRoot
| WidgetProperty::WindowCallback => &[WidgetKind::Window],
#[cfg(feature = "widgets-canvas")]
WidgetProperty::NativeHandle => &[WidgetKind::VulkanCanvas],
#[cfg(not(feature = "widgets-canvas"))]
WidgetProperty::NativeHandle => &[],
#[cfg(feature = "widgets-canvas")]
WidgetProperty::DrawDemoCube => &[WidgetKind::VulkanCanvas, WidgetKind::MetalCanvas],
#[cfg(not(feature = "widgets-canvas"))]
WidgetProperty::DrawDemoCube => &[],
WidgetProperty::CopyToClipboard | WidgetProperty::PasteFromClipboard => {
const KINDS: &[WidgetKind] = &[
#[cfg(feature = "widgets-data")]
WidgetKind::DataList,
#[cfg(feature = "widgets-data")]
WidgetKind::ListView,
#[cfg(feature = "widgets-data")]
WidgetKind::DataGrid,
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput,
#[cfg(feature = "widgets-text")]
WidgetKind::TextArea,
WidgetKind::Label,
];
KINDS
}
#[cfg(feature = "widgets-data")]
WidgetProperty::KeyedRows | WidgetProperty::VisibleAnchor => &[
WidgetKind::DataList,
WidgetKind::ListView,
WidgetKind::DataGrid,
],
#[cfg(not(feature = "widgets-data"))]
WidgetProperty::KeyedRows | WidgetProperty::VisibleAnchor => &[],
#[cfg(feature = "widgets-data")]
WidgetProperty::ClearSelection => &[
WidgetKind::DataList,
WidgetKind::ListView,
WidgetKind::DataGrid,
WidgetKind::TreeView,
],
#[cfg(not(feature = "widgets-data"))]
WidgetProperty::ClearSelection => &[],
#[cfg(feature = "widgets-pickers")]
WidgetProperty::CalendarDates
| WidgetProperty::CalendarBounds
| WidgetProperty::CalendarFirstDayOfWeek
| WidgetProperty::CalendarSelectionMode => &[WidgetKind::Calendar],
#[cfg(not(feature = "widgets-pickers"))]
WidgetProperty::CalendarDates
| WidgetProperty::CalendarBounds
| WidgetProperty::CalendarFirstDayOfWeek
| WidgetProperty::CalendarSelectionMode => &[],
WidgetProperty::LabelAlignment => &[WidgetKind::Label, WidgetKind::Button],
WidgetProperty::LabelWrap => &[WidgetKind::Label],
#[cfg(feature = "widgets-text")]
WidgetProperty::RichTextRuns | WidgetProperty::RichTextImages => {
&[WidgetKind::RichText]
}
#[cfg(not(feature = "widgets-text"))]
WidgetProperty::RichTextRuns | WidgetProperty::RichTextImages => &[],
#[cfg(feature = "widgets-text")]
WidgetProperty::PlaceholderText => &[WidgetKind::TextInput],
#[cfg(not(feature = "widgets-text"))]
WidgetProperty::PlaceholderText => &[],
WidgetProperty::Monospace => {
const KINDS: &[WidgetKind] = &[
WidgetKind::Label,
#[cfg(feature = "widgets-text")]
WidgetKind::TextArea,
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput,
#[cfg(feature = "widgets-text")]
WidgetKind::RichText,
];
KINDS
}
#[cfg(feature = "widgets-canvas")]
WidgetProperty::MetalHandle => &[WidgetKind::MetalCanvas],
#[cfg(not(feature = "widgets-canvas"))]
WidgetProperty::MetalHandle => &[],
WidgetProperty::Font => {
const KINDS: &[WidgetKind] = &[
WidgetKind::Label,
WidgetKind::Button,
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput,
#[cfg(feature = "widgets-text")]
WidgetKind::TextArea,
];
KINDS
}
#[cfg(feature = "widgets-data")]
WidgetProperty::RowIcons => &[WidgetKind::DataList, WidgetKind::ListView],
#[cfg(not(feature = "widgets-data"))]
WidgetProperty::RowIcons => &[],
}
}
pub const fn operation(self) -> &'static str {
match self {
WidgetProperty::Checked => "set_checked",
WidgetProperty::Value => "set_value",
WidgetProperty::Range => "set_range",
WidgetProperty::Step => "set_step",
WidgetProperty::SelectedIndex => "set_selected_index",
WidgetProperty::TabItems => "set_tab_items",
WidgetProperty::SelectedIndices => "set_selected_indices",
WidgetProperty::RowDrag => "set_row_drag",
WidgetProperty::DataListItems => "set_data_list_items",
WidgetProperty::ListViewColumns => "set_list_columns",
WidgetProperty::ListViewRows => "set_list_rows",
WidgetProperty::DataGridRows => "set_data_grid_rows",
WidgetProperty::DataGridModel => "set_data_grid_model",
WidgetProperty::DataGridRowHeight => "set_data_grid_row_height",
WidgetProperty::DataGridColWidth => "set_data_grid_col_width",
WidgetProperty::DataGridFrozenPanes => "set_data_grid_frozen_panes",
WidgetProperty::DataGridSelection => "set_data_grid_selection",
WidgetProperty::TreeItems => "set_tree_items",
WidgetProperty::AlertLevel => "set_alert_level",
WidgetProperty::ImageSource => "set_image_source",
WidgetProperty::ImageFit => "set_image_fit",
WidgetProperty::ButtonIcon => "set_icon",
WidgetProperty::FileChooserMode => "set_file_chooser_mode",
WidgetProperty::ColorDialogData => "set_color_dialog_data",
WidgetProperty::FontDialogData => "set_font_dialog_data",
WidgetProperty::ToolbarItems => "set_toolbar_items",
WidgetProperty::ToolbarOrientation => "set_toolbar_orientation",
WidgetProperty::DateValue => "set_date_value",
WidgetProperty::LinkUrl => "set_link_url",
WidgetProperty::TextSelection => "set_text_selection",
WidgetProperty::TextCompletion => "set_text_completion_items",
WidgetProperty::ContainerDirection => "set_container_direction",
WidgetProperty::ContainerWrap => "set_container_wrap",
WidgetProperty::ContainerScroll => "set_container_scroll",
WidgetProperty::ContainerGap => "set_container_gap",
WidgetProperty::ContainerPadding => "set_container_padding",
WidgetProperty::CanvasScene => "set_canvas_scene",
WidgetProperty::CanvasSurface => "set_canvas_surface",
WidgetProperty::CloseGuard => "set_close_guard",
WidgetProperty::LayoutRoot => "set_layout_root",
WidgetProperty::WindowCallback => "window_callback",
WidgetProperty::NativeHandle => "native_handle",
WidgetProperty::DrawDemoCube => "draw_demo_cube",
WidgetProperty::CopyToClipboard => "copy_to_clipboard",
WidgetProperty::PasteFromClipboard => "paste_from_clipboard",
WidgetProperty::KeyedRows => "set_rows_keyed",
WidgetProperty::ClearSelection => "clear_selection",
WidgetProperty::VisibleAnchor => "visible_anchor",
WidgetProperty::CalendarDates => "set_calendar_selected_dates",
WidgetProperty::CalendarBounds => "set_calendar_bounds",
WidgetProperty::CalendarFirstDayOfWeek => "set_calendar_first_day_of_week",
WidgetProperty::CalendarSelectionMode => "set_calendar_selection_mode",
WidgetProperty::LabelAlignment => "set_label_alignment",
WidgetProperty::LabelWrap => "set_label_wrap",
WidgetProperty::RichTextRuns => "set_rich_text_runs",
WidgetProperty::PlaceholderText => "set_placeholder_text",
WidgetProperty::RichTextImages => "set_rich_text_images",
WidgetProperty::Monospace => "set_monospace",
WidgetProperty::MetalHandle => "metal_canvas_handle",
WidgetProperty::Font => "set_font",
WidgetProperty::RowIcons => "set_row_icons",
}
}
pub const fn name(self) -> &'static str {
self.operation()
}
pub fn supports(self, kind: WidgetKind) -> bool {
self.applicable_kinds().contains(&kind)
}
}
impl WidgetKind {
pub fn requires_property(self, property: WidgetProperty) -> bool {
property.supports(self)
}
pub fn is_window_like(self) -> bool {
match self {
WidgetKind::Window => true,
#[cfg(feature = "widgets-pickers")]
WidgetKind::FileChooserDialog | WidgetKind::ColorDialog | WidgetKind::FontDialog => {
true
}
#[cfg(feature = "widgets-containers")]
WidgetKind::AlertDialog => true,
_ => false,
}
}
pub fn is_dialog(self) -> bool {
match self {
#[cfg(feature = "widgets-pickers")]
WidgetKind::FileChooserDialog | WidgetKind::ColorDialog | WidgetKind::FontDialog => {
true
}
#[cfg(feature = "widgets-containers")]
WidgetKind::AlertDialog => true,
_ => false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CalendarDate {
pub year: i32,
pub month: u32,
pub day: u32,
}
impl CalendarDate {
pub const fn new(year: i32, month: u32, day: u32) -> Self {
Self { year, month, day }
}
pub fn is_valid(&self) -> bool {
if self.year == 0 || self.month < 1 || self.month > 12 {
return false;
}
let max_days = Self::days_in_month(self.year, self.month);
self.day >= 1 && self.day <= max_days
}
pub const fn is_leap_year(year: i32) -> bool {
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}
pub const fn days_in_month(year: i32, month: u32) -> u32 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => {
if Self::is_leap_year(year) {
29
} else {
28
}
}
_ => 0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CalendarFirstDayOfWeek {
#[default]
LocaleDefault,
Sunday,
Monday,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CalendarSelectionMode {
#[default]
Single,
Range,
Multiple,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LabelAlignment {
#[default]
Left,
Center,
Right,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LabelWrap {
#[default]
None,
Word,
Char,
WordChar,
}
pub type LabelWrapMode = LabelWrap;
impl LabelWrap {
pub const NO_WRAP: Self = Self::None;
#[allow(non_upper_case_globals)]
pub const NoWrap: Self = Self::None;
pub const fn is_wrapping(self) -> bool {
!matches!(self, Self::None)
}
}
impl From<bool> for LabelWrap {
fn from(wrap: bool) -> Self {
if wrap {
Self::Word
} else {
Self::None
}
}
}
impl From<TextAlignment> for LabelAlignment {
fn from(alignment: TextAlignment) -> Self {
match alignment {
TextAlignment::Left => Self::Left,
TextAlignment::Center => Self::Center,
TextAlignment::Right => Self::Right,
}
}
}
impl From<LabelAlignment> for TextAlignment {
fn from(alignment: LabelAlignment) -> Self {
match alignment {
LabelAlignment::Left => Self::Left,
LabelAlignment::Center => Self::Center,
LabelAlignment::Right => Self::Right,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ContainerDirection {
Vertical,
Horizontal,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ContainerWrap {
#[default]
NoWrap,
Wrap,
WrapReverse,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AlertLevel {
Info,
Warning,
Error,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ImageFit {
#[default]
Contain,
Cover,
Fill,
None,
}
impl ImageFit {
pub const fn as_str(self) -> &'static str {
match self {
Self::Contain => "contain",
Self::Cover => "cover",
Self::Fill => "fill",
Self::None => "none",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FileChooserMode {
#[default]
OpenFile,
PickFolder,
SaveFile,
}
impl FileChooserMode {
pub const fn as_str(self) -> &'static str {
match self {
Self::OpenFile => "open-file",
Self::PickFolder => "pick-folder",
Self::SaveFile => "save-file",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
}
impl Color {
pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
Self { r, g, b }
}
}
#[derive(Debug, Clone, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TextStyle {
pub bold: bool,
pub italic: bool,
pub underline: bool,
pub strikethrough: bool,
pub monospace: bool,
pub scale: Option<f32>,
pub fg_color: Option<Color>,
pub bg_color: Option<Color>,
pub link: Option<String>,
pub dimmed: bool,
pub paragraph_indent: u32,
}
impl TextStyle {
pub const fn new() -> Self {
Self {
bold: false,
italic: false,
underline: false,
strikethrough: false,
monospace: false,
scale: None,
fg_color: None,
bg_color: None,
link: None,
dimmed: false,
paragraph_indent: 0,
}
}
pub const fn bold(mut self, bold: bool) -> Self {
self.bold = bold;
self
}
pub const fn italic(mut self, italic: bool) -> Self {
self.italic = italic;
self
}
pub const fn underline(mut self, underline: bool) -> Self {
self.underline = underline;
self
}
pub const fn strikethrough(mut self, strikethrough: bool) -> Self {
self.strikethrough = strikethrough;
self
}
pub const fn monospace(mut self, monospace: bool) -> Self {
self.monospace = monospace;
self
}
pub const fn scale(mut self, scale: f32) -> Self {
self.scale = Some(scale);
self
}
pub const fn fg_color(mut self, color: Color) -> Self {
self.fg_color = Some(color);
self
}
pub const fn bg_color(mut self, color: Color) -> Self {
self.bg_color = Some(color);
self
}
pub fn link(mut self, link: impl Into<String>) -> Self {
self.link = Some(link.into());
self
}
pub const fn dimmed(mut self, dimmed: bool) -> Self {
self.dimmed = dimmed;
self
}
pub const fn paragraph_indent(mut self, indent: u32) -> Self {
self.paragraph_indent = indent;
self
}
}
#[derive(Debug, Clone, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TextRun {
pub range: std::ops::Range<usize>,
pub style: TextStyle,
}
impl TextRun {
pub fn new(range: std::ops::Range<usize>, style: TextStyle) -> Self {
Self { range, style }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RichTextImage {
pub offset: usize,
pub source: String,
pub max_width: Option<u32>,
}
impl RichTextImage {
pub fn new(offset: usize, source: impl Into<String>, max_width: Option<u32>) -> Self {
Self {
offset,
source: source.into(),
max_width,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ClipboardImage {
pub width: u32,
pub height: u32,
pub rgba: Vec<u8>,
pub png_bytes: Vec<u8>,
}
impl ClipboardImage {
pub fn new(width: u32, height: u32, rgba: Vec<u8>) -> Self {
let png_bytes = encode_rgba_to_png(width, height, &rgba);
Self {
width,
height,
rgba,
png_bytes,
}
}
pub fn with_png(width: u32, height: u32, rgba: Vec<u8>, png_bytes: Vec<u8>) -> Self {
Self {
width,
height,
rgba,
png_bytes,
}
}
}
pub fn encode_rgba_to_png(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
fn crc32(data: &[u8]) -> u32 {
let mut crc = 0xFFFF_FFFFu32;
for &byte in data {
crc ^= u32::from(byte);
for _ in 0..8 {
let mask = (crc & 1).wrapping_neg();
crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
}
}
!crc
}
fn adler32(data: &[u8]) -> u32 {
let mut s1 = 1u32;
let mut s2 = 0u32;
for &byte in data {
s1 = (s1 + u32::from(byte)) % 65521;
s2 = (s2 + s1) % 65521;
}
(s2 << 16) | s1
}
let mut out = Vec::new();
out.extend_from_slice(b"\x89PNG\r\n\x1a\n");
let mut ihdr = Vec::with_capacity(13);
ihdr.extend_from_slice(&width.to_be_bytes());
ihdr.extend_from_slice(&height.to_be_bytes());
ihdr.push(8); ihdr.push(6); ihdr.push(0); ihdr.push(0); ihdr.push(0);
let mut ihdr_chunk = Vec::new();
ihdr_chunk.extend_from_slice(b"IHDR");
ihdr_chunk.extend_from_slice(&ihdr);
let ihdr_crc = crc32(&ihdr_chunk);
out.extend_from_slice(&(ihdr.len() as u32).to_be_bytes());
out.extend_from_slice(&ihdr_chunk);
out.extend_from_slice(&ihdr_crc.to_be_bytes());
let w_bytes = (width as usize) * 4;
let mut raw = Vec::with_capacity((height as usize) * (w_bytes + 1));
for y in 0..(height as usize) {
raw.push(0); let start = y * w_bytes;
let end = (start + w_bytes).min(rgba.len());
if start < rgba.len() {
raw.extend_from_slice(&rgba[start..end]);
if end - start < w_bytes {
raw.resize(raw.len() + (w_bytes - (end - start)), 0);
}
} else {
raw.resize(raw.len() + w_bytes, 0);
}
}
let mut zlib = Vec::new();
zlib.push(0x78);
zlib.push(0x01);
let chunks: Vec<&[u8]> = if raw.is_empty() {
vec![&[]]
} else {
raw.chunks(65535).collect()
};
let total_chunks = chunks.len();
for (i, chunk) in chunks.iter().enumerate() {
let is_final = i == total_chunks - 1;
let header = if is_final { 0x01 } else { 0x00 };
zlib.push(header);
let len = chunk.len() as u16;
let nlen = !len;
zlib.extend_from_slice(&len.to_le_bytes());
zlib.extend_from_slice(&nlen.to_le_bytes());
zlib.extend_from_slice(chunk);
}
let adler = adler32(&raw);
zlib.extend_from_slice(&adler.to_be_bytes());
let mut idat_chunk = Vec::new();
idat_chunk.extend_from_slice(b"IDAT");
idat_chunk.extend_from_slice(&zlib);
let idat_crc = crc32(&idat_chunk);
out.extend_from_slice(&(zlib.len() as u32).to_be_bytes());
out.extend_from_slice(&idat_chunk);
out.extend_from_slice(&idat_crc.to_be_bytes());
let mut iend_chunk = Vec::new();
iend_chunk.extend_from_slice(b"IEND");
let iend_crc = crc32(&iend_chunk);
out.extend_from_slice(&0u32.to_be_bytes());
out.extend_from_slice(&iend_chunk);
out.extend_from_slice(&iend_crc.to_be_bytes());
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CanvasRect {
pub x: i32,
pub y: i32,
pub width: i32,
pub height: i32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CanvasSurface {
width: u32,
height: u32,
pixels: Arc<Vec<u8>>,
}
impl CanvasSurface {
pub fn from_rgba(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self, GuiError> {
if width == 0 || height == 0 {
return Err(GuiError::Backend(
"canvas surface dimensions must be non-zero".to_owned(),
));
}
let expected = width as usize * height as usize * 4;
if pixels.len() != expected {
return Err(GuiError::Backend(format!(
"canvas surface expects {expected} bytes, found {}",
pixels.len()
)));
}
Ok(Self {
width,
height,
pixels: Arc::new(pixels),
})
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
pub fn pixels(&self) -> &[u8] {
&self.pixels
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct CanvasScene {
pub primitives: Vec<CanvasPrimitive>,
pub logical_width: f32,
pub logical_height: f32,
}
impl CanvasScene {
pub fn new(logical_width: f32, logical_height: f32) -> Self {
Self {
primitives: Vec::new(),
logical_width,
logical_height,
}
}
pub fn validate(&self) -> GuiResult<()> {
let invalid = !self.logical_width.is_finite()
|| !self.logical_height.is_finite()
|| self.logical_width <= 0.0
|| self.logical_height <= 0.0;
if invalid {
return Err(GuiError::Backend(
"Canvas scene logical size must be finite and positive".to_owned(),
));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CanvasPrimitive {
Rect {
rect: CanvasRect,
fill: Option<Color>,
stroke: Option<Color>,
stroke_width: u8,
},
Line {
from: (i32, i32),
to: (i32, i32),
color: Color,
width: u8,
},
Text {
pos: (i32, i32),
text: String,
color: Color,
size: u8,
},
Image {
rect: CanvasRect,
source: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TreeItem {
pub label: String,
pub children: Vec<TreeItem>,
}
impl TreeItem {
pub fn new(label: impl Into<String>) -> Self {
Self {
label: label.into(),
children: Vec::new(),
}
}
pub fn with_child(mut self, child: TreeItem) -> Self {
self.children.push(child);
self
}
pub fn indented_rows(&self) -> Vec<String> {
let mut rows = Vec::new();
self.collect_rows(0, &mut rows);
rows
}
fn collect_rows(&self, depth: usize, rows: &mut Vec<String>) {
rows.push(format!("{}{}", " ".repeat(depth), self.label));
for child in &self.children {
child.collect_rows(depth + 1, rows);
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnSpec {
pub title: String,
pub width: Option<i32>,
}
impl ColumnSpec {
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into(),
width: None,
}
}
pub fn with_width(mut self, width: i32) -> Self {
self.width = if width > 0 { Some(width) } else { None };
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RowKey(pub u64);
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RowSet {
pub key: RowKey,
pub cells: Vec<String>,
}
impl RowSet {
pub fn new(key: u64, cells: &[&str]) -> Self {
Self {
key: RowKey(key),
cells: cells.iter().map(|cell| (*cell).to_owned()).collect(),
}
}
pub fn text(&self) -> String {
self.cells.first().cloned().unwrap_or_default()
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RowDelta {
pub inserted: usize,
pub updated: usize,
pub removed: usize,
pub moved: usize,
pub unchanged: usize,
}
impl RowDelta {
pub fn is_noop(&self) -> bool {
self.inserted == 0 && self.updated == 0 && self.removed == 0 && self.moved == 0
}
}
pub fn diff_rows(old_rows: &[RowSet], new_rows: &[RowSet]) -> GuiResult<RowDelta> {
let mut new_keys: std::collections::HashSet<u64> =
std::collections::HashSet::with_capacity(new_rows.len());
for row in new_rows {
if !new_keys.insert(row.key.0) {
return Err(GuiError::Backend("duplicate row key".to_owned()));
}
}
let old_index: std::collections::HashMap<u64, usize> = old_rows
.iter()
.enumerate()
.map(|(index, row)| (row.key.0, index))
.collect();
let mut delta = RowDelta::default();
for (new_pos, row) in new_rows.iter().enumerate() {
match old_index.get(&row.key.0) {
None => delta.inserted += 1,
Some(&old_pos) => {
if old_rows[old_pos].cells != row.cells {
delta.updated += 1;
} else if old_pos != new_pos {
delta.moved += 1;
} else {
delta.unchanged += 1;
}
}
}
}
delta.removed = old_rows
.iter()
.filter(|row| !new_keys.contains(&row.key.0))
.count();
Ok(delta)
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum RowOp {
Insert { index: usize, row: RowSet },
Update { index: usize, row: RowSet },
Remove { index: usize, key: RowKey },
Move {
from_index: usize,
to_index: usize,
key: RowKey,
},
Reorder { order: Vec<usize> },
}
pub fn diff_row_ops(
old_rows: &[RowSet],
new_rows: &[RowSet],
delta: &RowDelta,
) -> Option<Vec<RowOp>> {
if old_rows.is_empty() || delta.is_noop() {
return None;
}
if delta.inserted == 0 && delta.removed == 0 && delta.moved == 0 && delta.updated > 0 {
if old_rows.len() != new_rows.len() {
return None;
}
let mut ops = Vec::with_capacity(delta.updated);
for (i, (old, new)) in old_rows.iter().zip(new_rows.iter()).enumerate() {
if old.key != new.key {
return None;
}
if old.cells != new.cells {
ops.push(RowOp::Update {
index: i,
row: new.clone(),
});
}
}
return Some(ops);
}
if delta.inserted == 1 && delta.removed == 0 && delta.updated == 0 {
if new_rows.len() != old_rows.len() + 1 {
return None;
}
let insert_idx = (0..old_rows.len())
.find(|&i| old_rows[i].key != new_rows[i].key)
.unwrap_or(old_rows.len());
if new_rows[insert_idx + 1..] == old_rows[insert_idx..] {
return Some(vec![RowOp::Insert {
index: insert_idx,
row: new_rows[insert_idx].clone(),
}]);
}
return None;
}
if delta.removed == 1 && delta.inserted == 0 && delta.updated == 0 {
if old_rows.len() != new_rows.len() + 1 {
return None;
}
let remove_idx = (0..new_rows.len())
.find(|&i| old_rows[i].key != new_rows[i].key)
.unwrap_or(new_rows.len());
if old_rows[remove_idx + 1..] == new_rows[remove_idx..] {
return Some(vec![RowOp::Remove {
index: remove_idx,
key: old_rows[remove_idx].key,
}]);
}
return None;
}
if delta.moved > 0 && delta.inserted == 0 && delta.removed == 0 && delta.updated == 0 {
if old_rows.len() != new_rows.len() {
return None;
}
let old_index: std::collections::HashMap<u64, usize> = old_rows
.iter()
.enumerate()
.map(|(index, row)| (row.key.0, index))
.collect();
let order: Vec<usize> = new_rows
.iter()
.filter_map(|r| old_index.get(&r.key.0).copied())
.collect();
if order.len() != old_rows.len() {
return None;
}
for (to_idx, &from_idx) in order.iter().enumerate() {
if to_idx == from_idx {
continue;
}
let mut matches = true;
let mut expected = 0;
for (new_i, &old_i) in order.iter().enumerate() {
if new_i == to_idx {
continue;
}
if expected == from_idx {
expected += 1;
}
if old_i != expected {
matches = false;
break;
}
expected += 1;
}
if matches {
return Some(vec![RowOp::Move {
from_index: from_idx,
to_index: to_idx,
key: new_rows[to_idx].key,
}]);
}
}
return Some(vec![RowOp::Reorder { order }]);
}
None
}
pub fn apply_row_ops_to_rows(rows: &mut Vec<RowSet>, ops: &[RowOp]) {
for op in ops {
match op {
RowOp::Update { index, row } => {
if let Some(target) = rows.get_mut(*index) {
*target = row.clone();
}
}
RowOp::Insert { index, row } => {
let idx = (*index).min(rows.len());
rows.insert(idx, row.clone());
}
RowOp::Remove { index, .. } => {
if *index < rows.len() {
rows.remove(*index);
}
}
RowOp::Move {
from_index,
to_index,
..
} => {
if *from_index < rows.len() {
let r = rows.remove(*from_index);
let to = (*to_index).min(rows.len());
rows.insert(to, r);
}
}
RowOp::Reorder { order } => {
if order.len() == rows.len() {
let old = std::mem::take(rows);
rows.reserve(order.len());
let mut old_opt: Vec<Option<RowSet>> = old.into_iter().map(Some).collect();
for &old_idx in order {
if let Some(opt) = old_opt.get_mut(old_idx) {
if let Some(r) = opt.take() {
rows.push(r);
}
}
}
}
}
}
}
}
pub fn apply_row_ops_to_cells(cells: &mut Vec<Vec<String>>, ops: &[RowOp]) {
for op in ops {
match op {
RowOp::Update { index, row } => {
if let Some(target) = cells.get_mut(*index) {
*target = row.cells.clone();
}
}
RowOp::Insert { index, row } => {
let idx = (*index).min(cells.len());
cells.insert(idx, row.cells.clone());
}
RowOp::Remove { index, .. } => {
if *index < cells.len() {
cells.remove(*index);
}
}
RowOp::Move {
from_index,
to_index,
..
} => {
if *from_index < cells.len() {
let c = cells.remove(*from_index);
let to = (*to_index).min(cells.len());
cells.insert(to, c);
}
}
RowOp::Reorder { order } => {
if order.len() == cells.len() {
let old = std::mem::take(cells);
cells.reserve(order.len());
let mut old_opt: Vec<Option<Vec<String>>> = old.into_iter().map(Some).collect();
for &old_idx in order {
if let Some(opt) = old_opt.get_mut(old_idx) {
if let Some(c) = opt.take() {
cells.push(c);
}
}
}
}
}
}
}
}
pub fn apply_row_ops_to_items(items: &mut Vec<String>, ops: &[RowOp]) {
for op in ops {
match op {
RowOp::Update { index, row } => {
if let Some(target) = items.get_mut(*index) {
*target = row.text();
}
}
RowOp::Insert { index, row } => {
let idx = (*index).min(items.len());
items.insert(idx, row.text());
}
RowOp::Remove { index, .. } => {
if *index < items.len() {
items.remove(*index);
}
}
RowOp::Move {
from_index,
to_index,
..
} => {
if *from_index < items.len() {
let item = items.remove(*from_index);
let to = (*to_index).min(items.len());
items.insert(to, item);
}
}
RowOp::Reorder { order } => {
if order.len() == items.len() {
let old = std::mem::take(items);
items.reserve(order.len());
let mut old_opt: Vec<Option<String>> = old.into_iter().map(Some).collect();
for &old_idx in order {
if let Some(opt) = old_opt.get_mut(old_idx) {
if let Some(item) = opt.take() {
items.push(item);
}
}
}
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TextAlignment {
Left,
Center,
Right,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct GridCellAttr {
pub bg_color: Option<Color>,
pub text_color: Option<Color>,
pub alignment: Option<TextAlignment>,
pub font_bold: bool,
pub font_italic: bool,
pub font_size: Option<u8>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum GridCellEditor {
Text,
Boolean,
Enum(Vec<String>),
Number { min: i32, max: i32, step: i32 },
}
#[derive(Debug, Clone, PartialEq)]
pub enum GridCellRenderer {
Text,
Boolean,
Canvas(CanvasScene),
}
pub trait DataGridModel {
fn row_count(&self) -> usize;
fn col_count(&self) -> usize;
fn value_at(&self, row: usize, col: usize) -> String;
fn is_row_resident(&self, _row: usize) -> bool {
true
}
fn pin_visible_band(&self, _first_row: usize, _count: usize) {}
fn clear_pinned_band(&self) {}
fn get_attr(&self, _row: usize, _col: usize) -> Option<GridCellAttr> {
None
}
fn set_value_at(&mut self, _row: usize, _col: usize, _value: String) {}
fn get_editor(&self, _row: usize, _col: usize) -> Option<GridCellEditor> {
None
}
fn get_renderer(&self, _row: usize, _col: usize) -> Option<GridCellRenderer> {
None
}
fn cell_span(&self, _row: usize, _col: usize) -> (usize, usize) {
(1, 1)
}
}
pub struct SimpleDataGridModel {
pub rows: Vec<Vec<String>>,
}
impl DataGridModel for SimpleDataGridModel {
fn row_count(&self) -> usize {
self.rows.len()
}
fn col_count(&self) -> usize {
self.rows.first().map(|r| r.len()).unwrap_or(0)
}
fn value_at(&self, row: usize, col: usize) -> String {
self.rows
.get(row)
.and_then(|r| r.get(col))
.cloned()
.unwrap_or_default()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WindowedDataGridConfig {
pub max_resident_rows: usize,
pub max_resident_bytes: usize,
pub placeholder: String,
}
impl WindowedDataGridConfig {
pub fn new(max_resident_rows: usize, max_resident_bytes: usize) -> Self {
Self {
max_resident_rows: max_resident_rows.max(1),
max_resident_bytes: max_resident_bytes.max(1),
placeholder: "…".to_owned(),
}
}
pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
self.placeholder = placeholder.into();
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WindowedDelivery {
Applied { evicted: Vec<usize> },
Rejected(WindowedDeliveryRejection),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowedDeliveryRejection {
RowOutOfRange,
NotInFlight,
Oversized,
NoEvictableVictim,
}
pub struct WindowedDataGridModel {
handle: WindowedDataGridHandle,
on_fetch_requested: Box<dyn Fn(usize)>,
on_repaint_requested: Box<dyn Fn()>,
}
impl WindowedDataGridModel {
pub fn new(
row_count: usize,
col_count: usize,
config: WindowedDataGridConfig,
on_fetch_requested: impl Fn(usize) + 'static,
on_repaint_requested: impl Fn() + 'static,
) -> Self {
Self {
handle: WindowedDataGridHandle {
row_count,
col_count,
config,
state: Rc::new(RefCell::new(WindowedState::default())),
},
on_fetch_requested: Box::new(on_fetch_requested),
on_repaint_requested: Box::new(on_repaint_requested),
}
}
pub fn handle(&self) -> WindowedDataGridHandle {
self.handle.clone()
}
}
impl DataGridModel for WindowedDataGridModel {
fn row_count(&self) -> usize {
self.handle.row_count
}
fn col_count(&self) -> usize {
self.handle.col_count
}
fn value_at(&self, row: usize, col: usize) -> String {
if row >= self.handle.row_count || col >= self.handle.col_count {
return String::new();
}
let scheduled = {
let mut state = self.handle.state.borrow_mut();
if state.resident.contains_key(&row) {
state.hits += 1;
state.touch(row);
return state
.resident
.get(&row)
.and_then(|resident| resident.cells.get(col))
.cloned()
.unwrap_or_default();
}
state.misses += 1;
if state.in_flight.insert(row) {
state.fetches_requested += 1;
true
} else {
false
}
};
if scheduled {
(self.on_fetch_requested)(row);
(self.on_repaint_requested)();
}
self.handle.config.placeholder.clone()
}
fn is_row_resident(&self, row: usize) -> bool {
row < self.handle.row_count && self.handle.state.borrow().resident.contains_key(&row)
}
fn pin_visible_band(&self, first_row: usize, count: usize) {
self.handle.pin_visible_band(first_row, count);
}
fn clear_pinned_band(&self) {
self.handle.clear_pinned_band();
}
}
impl std::fmt::Debug for WindowedDataGridModel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WindowedDataGridModel")
.field("window", &self.handle)
.finish()
}
}
#[derive(Clone)]
pub struct WindowedDataGridHandle {
row_count: usize,
col_count: usize,
config: WindowedDataGridConfig,
state: Rc<RefCell<WindowedState>>,
}
impl WindowedDataGridHandle {
pub fn deliver_row(&self, row: usize, cells: Vec<String>) -> WindowedDelivery {
if row >= self.row_count {
self.state.borrow_mut().rejected_deliveries += 1;
return WindowedDelivery::Rejected(WindowedDeliveryRejection::RowOutOfRange);
}
let mut cells = cells;
cells.truncate(self.col_count);
let bytes: usize = cells.iter().map(String::len).sum();
let mut state = self.state.borrow_mut();
if !state.in_flight.remove(&row) {
state.rejected_deliveries += 1;
return WindowedDelivery::Rejected(WindowedDeliveryRejection::NotInFlight);
}
if bytes > self.config.max_resident_bytes {
state.rejected_deliveries += 1;
return WindowedDelivery::Rejected(WindowedDeliveryRejection::Oversized);
}
if let Some(previous) = state.resident.remove(&row) {
state.resident_bytes -= previous.bytes;
state.lru.retain(|resident| *resident != row);
}
let mut evicted: Vec<usize> = Vec::new();
while state.resident.len() >= self.config.max_resident_rows
|| state.resident_bytes.saturating_add(bytes) > self.config.max_resident_bytes
{
let victim = state
.lru
.iter()
.copied()
.find(|candidate| !state.is_pinned(*candidate));
let Some(victim) = victim else {
state.rejected_deliveries += 1;
return WindowedDelivery::Rejected(WindowedDeliveryRejection::NoEvictableVictim);
};
state.lru.retain(|resident| *resident != victim);
if let Some(previous) = state.resident.remove(&victim) {
state.resident_bytes -= previous.bytes;
state.evictions += 1;
evicted.push(victim);
}
}
state.resident.insert(row, ResidentRow { cells, bytes });
state.resident_bytes += bytes;
state.lru.push_back(row);
WindowedDelivery::Applied { evicted }
}
pub fn pin_visible_band(&self, first_row: usize, count: usize) {
let mut state = self.state.borrow_mut();
state.pinned_band = if count == 0 {
None
} else {
Some((first_row, count))
};
}
pub fn clear_pinned_band(&self) {
self.state.borrow_mut().pinned_band = None;
}
pub fn pinned_band(&self) -> Option<(usize, usize)> {
self.state.borrow().pinned_band
}
pub fn is_row_resident(&self, row: usize) -> bool {
row < self.row_count && self.state.borrow().resident.contains_key(&row)
}
pub fn is_row_in_flight(&self, row: usize) -> bool {
self.state.borrow().in_flight.contains(&row)
}
pub fn resident_row_count(&self) -> usize {
self.state.borrow().resident.len()
}
pub fn resident_bytes(&self) -> usize {
self.state.borrow().resident_bytes
}
pub fn in_flight_count(&self) -> usize {
self.state.borrow().in_flight.len()
}
pub fn hits(&self) -> usize {
self.state.borrow().hits
}
pub fn misses(&self) -> usize {
self.state.borrow().misses
}
pub fn fetches_requested(&self) -> usize {
self.state.borrow().fetches_requested
}
pub fn evictions(&self) -> usize {
self.state.borrow().evictions
}
pub fn rejected_deliveries(&self) -> usize {
self.state.borrow().rejected_deliveries
}
}
impl std::fmt::Debug for WindowedDataGridHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let state = self.state.borrow();
f.debug_struct("WindowedDataGridHandle")
.field("row_count", &self.row_count)
.field("col_count", &self.col_count)
.field("resident_rows", &state.resident.len())
.field("resident_bytes", &state.resident_bytes)
.field("in_flight", &state.in_flight.len())
.field("hits", &state.hits)
.field("misses", &state.misses)
.field("evictions", &state.evictions)
.finish()
}
}
#[derive(Default)]
struct WindowedState {
resident: HashMap<usize, ResidentRow>,
lru: VecDeque<usize>,
in_flight: BTreeSet<usize>,
pinned_band: Option<(usize, usize)>,
resident_bytes: usize,
hits: usize,
misses: usize,
fetches_requested: usize,
evictions: usize,
rejected_deliveries: usize,
}
impl WindowedState {
fn touch(&mut self, row: usize) {
if let Some(position) = self.lru.iter().position(|resident| *resident == row) {
self.lru.remove(position);
}
self.lru.push_back(row);
}
fn is_pinned(&self, row: usize) -> bool {
match self.pinned_band {
Some((first, count)) => row >= first && row - first < count,
None => false,
}
}
}
struct ResidentRow {
cells: Vec<String>,
bytes: usize,
}
#[derive(Debug, Clone, PartialEq)]
pub struct WidgetSpec {
pub id: WidgetId,
pub kind: WidgetKind,
pub text: Option<String>,
pub text_selection: Option<(usize, usize)>,
pub completion_items: Vec<String>,
pub placeholder_text: Option<String>,
pub parent: Option<WidgetId>,
pub container_direction: Option<ContainerDirection>,
pub container_wrap: Option<ContainerWrap>,
pub container_scroll_vertical: bool,
pub container_scroll_horizontal: bool,
pub container_gap: Option<i32>,
pub container_padding: Option<i32>,
pub size: Option<(i32, i32)>,
pub position: Option<(i32, i32)>,
pub data_list_items: Vec<String>,
pub list_columns: Vec<ColumnSpec>,
pub list_rows: Vec<Vec<String>>,
pub data_grid_rows: Arc<Vec<Vec<String>>>,
pub tree_items: Vec<TreeItem>,
pub background_color: Option<Color>,
pub alert_level: Option<AlertLevel>,
pub checked: Option<bool>,
pub enabled: Option<bool>,
pub range: Option<(i32, i32)>,
pub step: Option<i32>,
pub value: Option<i32>,
pub group_name: Option<String>,
pub tab_items: Vec<String>,
pub selected_index: Option<usize>,
pub selected_indices: Vec<usize>,
pub row_drag_source: bool,
pub row_drop_target: bool,
pub file_drop_target: bool,
pub image_source: Option<String>,
pub image_fit: ImageFit,
pub icon: Option<IconRole>,
pub file_chooser_mode: FileChooserMode,
pub date_value: Option<String>,
pub link_url: Option<String>,
pub tooltip: Option<String>,
pub accessibility: AccessibilitySpec,
pub focusable: Option<bool>,
pub split_ratio: Option<u8>,
pub canvas_scene: Option<CanvasScene>,
pub canvas_surface: Option<CanvasSurface>,
pub color_dialog_data: Option<ColorDialogData>,
pub font_dialog_data: Option<FontDialogData>,
pub toolbar_items: Vec<ToolbarItem>,
pub toolbar_orientation: ToolbarOrientation,
pub calendar_selected_dates: Vec<CalendarDate>,
pub calendar_min_date: Option<CalendarDate>,
pub calendar_max_date: Option<CalendarDate>,
pub calendar_first_day_of_week: CalendarFirstDayOfWeek,
pub calendar_selection_mode: CalendarSelectionMode,
pub label_alignment: LabelAlignment,
pub label_wrap: LabelWrap,
pub rich_text_runs: Vec<TextRun>,
pub rich_text_images: Vec<RichTextImage>,
pub monospace: bool,
pub font: Option<FontDescriptor>,
pub row_icons: Vec<Option<IconRole>>,
}
impl WidgetSpec {
pub fn new(id: WidgetId, kind: WidgetKind) -> Self {
Self {
id,
kind,
text: None,
text_selection: None,
completion_items: Vec::new(),
parent: None,
container_direction: if kind == WidgetKind::Container {
Some(ContainerDirection::Vertical)
} else {
None
},
container_wrap: if kind == WidgetKind::Container {
Some(ContainerWrap::NoWrap)
} else {
None
},
container_scroll_vertical: false,
container_scroll_horizontal: false,
container_gap: None,
container_padding: None,
size: None,
position: None,
data_list_items: Vec::new(),
list_columns: Vec::new(),
list_rows: Vec::new(),
data_grid_rows: Arc::new(Vec::new()),
tree_items: Vec::new(),
background_color: None,
alert_level: {
#[cfg(feature = "widgets-containers")]
{
if kind == WidgetKind::AlertDialog {
Some(AlertLevel::Info)
} else {
None
}
}
#[cfg(not(feature = "widgets-containers"))]
{
None
}
},
checked: None,
enabled: None,
range: None,
step: None,
value: None,
group_name: None,
tab_items: Vec::new(),
selected_index: None,
selected_indices: Vec::new(),
row_drag_source: false,
row_drop_target: false,
file_drop_target: false,
image_source: None,
image_fit: ImageFit::default(),
icon: None,
file_chooser_mode: FileChooserMode::default(),
date_value: None,
link_url: None,
tooltip: None,
accessibility: AccessibilitySpec::for_kind(kind),
focusable: None,
split_ratio: None,
canvas_scene: None,
canvas_surface: None,
color_dialog_data: None,
font_dialog_data: None,
toolbar_items: Vec::new(),
toolbar_orientation: ToolbarOrientation::default(),
calendar_selected_dates: Vec::new(),
calendar_min_date: None,
calendar_max_date: None,
calendar_first_day_of_week: CalendarFirstDayOfWeek::default(),
calendar_selection_mode: CalendarSelectionMode::default(),
label_alignment: match kind {
WidgetKind::Button => LabelAlignment::Center,
_ => LabelAlignment::default(),
},
label_wrap: LabelWrap::default(),
rich_text_runs: Vec::new(),
rich_text_images: Vec::new(),
placeholder_text: None,
monospace: false,
font: None,
row_icons: Vec::new(),
}
}
pub fn ensure_property(&self, property: WidgetProperty) -> GuiResult<()> {
if property.supports(self.kind) {
Ok(())
} else {
Err(GuiError::UnsupportedWidget(property.operation()))
}
}
pub fn requires_property(&self, property: WidgetProperty) -> GuiResult<()> {
self.ensure_property(property)
}
pub fn with_text(mut self, text: impl Into<String>) -> Self {
self.text = Some(text.into());
self
}
pub fn with_completion_items(mut self, items: Vec<String>) -> Self {
self.completion_items = items;
self
}
pub fn with_parent(mut self, parent: WidgetId) -> Self {
self.parent = Some(parent);
self
}
pub fn with_container_direction(mut self, direction: ContainerDirection) -> Self {
self.container_direction = Some(direction);
self
}
pub fn with_container_wrap(mut self, wrap: ContainerWrap) -> Self {
self.container_wrap = Some(wrap);
self
}
pub fn with_container_scroll(mut self, vertical: bool, horizontal: bool) -> Self {
self.container_scroll_vertical = vertical;
self.container_scroll_horizontal = horizontal;
self
}
pub fn with_container_gap(mut self, gap: i32) -> Self {
self.container_gap = Some(gap.max(0));
self
}
pub fn with_container_padding(mut self, padding: i32) -> Self {
self.container_padding = Some(padding.max(0));
self
}
pub fn with_size(mut self, width: i32, height: i32) -> Self {
self.size = Some((width, height));
self
}
pub fn with_position(mut self, x: i32, y: i32) -> Self {
self.position = Some((x, y));
self
}
pub fn with_data_list_items(mut self, items: impl IntoIterator<Item = String>) -> Self {
self.data_list_items = items.into_iter().collect();
self
}
pub fn with_list_columns(mut self, columns: impl IntoIterator<Item = ColumnSpec>) -> Self {
self.list_columns = columns.into_iter().collect();
self
}
pub fn with_list_rows(mut self, rows: impl IntoIterator<Item = Vec<String>>) -> Self {
self.list_rows = rows.into_iter().collect();
self
}
pub fn with_data_grid_rows(mut self, rows: impl IntoIterator<Item = Vec<String>>) -> Self {
self.data_grid_rows = Arc::new(rows.into_iter().collect());
self
}
pub fn with_tree_items(mut self, items: impl IntoIterator<Item = TreeItem>) -> Self {
self.tree_items = items.into_iter().collect();
self
}
pub fn with_background_color(mut self, color: Color) -> Self {
self.background_color = Some(color);
self
}
pub fn with_alert_level(mut self, level: AlertLevel) -> Self {
self.alert_level = Some(level);
self
}
pub fn with_checked(mut self, checked: bool) -> Self {
self.checked = Some(checked);
self
}
pub fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = Some(enabled);
self
}
pub fn with_range(mut self, min: i32, max: i32) -> Self {
self.range = Some((min, max));
self
}
pub fn with_step(mut self, step: i32) -> Self {
self.step = Some(step);
self
}
pub fn with_value(mut self, value: i32) -> Self {
self.value = Some(value);
self
}
pub fn with_selected_indices(mut self, indices: impl IntoIterator<Item = usize>) -> Self {
self.selected_indices = indices.into_iter().collect();
self
}
pub fn with_row_drag_source(mut self, enabled: bool) -> Self {
self.row_drag_source = enabled;
self
}
pub fn with_row_drop_target(mut self, enabled: bool) -> Self {
self.row_drop_target = enabled;
self
}
pub fn with_file_drop_target(mut self, enabled: bool) -> Self {
self.file_drop_target = enabled;
self
}
pub fn with_group_name(mut self, name: impl Into<String>) -> Self {
self.group_name = Some(name.into());
self
}
pub fn with_tab_items(mut self, items: impl IntoIterator<Item = String>) -> Self {
self.tab_items = items.into_iter().collect();
self
}
pub fn with_selected_index(mut self, selected_index: usize) -> Self {
self.selected_index = Some(selected_index);
self
}
pub fn with_image_source(mut self, source: impl Into<String>) -> Self {
self.image_source = Some(source.into());
self
}
pub fn with_image_fit(mut self, fit: ImageFit) -> Self {
self.image_fit = fit;
self
}
pub fn with_file_chooser_mode(mut self, mode: FileChooserMode) -> Self {
self.file_chooser_mode = mode;
self
}
pub fn with_date_value(mut self, date: impl Into<String>) -> Self {
self.date_value = Some(date.into());
self
}
pub fn with_link_url(mut self, url: impl Into<String>) -> Self {
self.link_url = Some(url.into());
self
}
pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
self.tooltip = Some(tooltip.into());
self
}
pub fn with_accessible_name(mut self, name: impl Into<String>) -> Self {
self.accessibility.name = Some(name.into());
self
}
pub fn with_accessible_description(mut self, description: impl Into<String>) -> Self {
self.accessibility.description = Some(description.into());
self
}
pub fn with_focusable(mut self, focusable: bool) -> Self {
self.focusable = Some(focusable);
self
}
pub fn with_split_ratio(mut self, ratio: u8) -> Self {
self.split_ratio = Some(ratio.min(100));
self
}
pub fn with_canvas_scene(mut self, scene: CanvasScene) -> Self {
self.canvas_scene = Some(scene);
self
}
pub fn with_canvas_surface(mut self, surface: CanvasSurface) -> Self {
self.canvas_surface = Some(surface);
self
}
pub fn with_color_dialog_data(mut self, data: ColorDialogData) -> Self {
self.color_dialog_data = Some(data);
self
}
pub fn with_font_dialog_data(mut self, data: FontDialogData) -> Self {
self.font_dialog_data = Some(data);
self
}
pub fn with_toolbar_items(mut self, items: Vec<ToolbarItem>) -> Self {
self.toolbar_items = items;
self
}
pub fn with_toolbar_orientation(mut self, orientation: ToolbarOrientation) -> Self {
self.toolbar_orientation = orientation;
self
}
pub fn with_calendar_selected_dates(
mut self,
dates: impl IntoIterator<Item = CalendarDate>,
) -> Self {
self.calendar_selected_dates = dates.into_iter().collect();
self
}
pub fn with_calendar_bounds(
mut self,
min: Option<CalendarDate>,
max: Option<CalendarDate>,
) -> Self {
self.calendar_min_date = min;
self.calendar_max_date = max;
self
}
pub fn with_calendar_first_day_of_week(mut self, first_day: CalendarFirstDayOfWeek) -> Self {
self.calendar_first_day_of_week = first_day;
self
}
pub fn with_calendar_selection_mode(mut self, mode: CalendarSelectionMode) -> Self {
self.calendar_selection_mode = mode;
self
}
pub fn with_label_alignment(mut self, alignment: impl Into<LabelAlignment>) -> Self {
self.label_alignment = alignment.into();
self
}
pub fn with_label_wrap(mut self, wrap: impl Into<LabelWrap>) -> Self {
self.label_wrap = wrap.into();
self
}
pub fn with_label_wrap_mode(self, wrap: impl Into<LabelWrap>) -> Self {
self.with_label_wrap(wrap)
}
pub fn with_rich_text_runs(mut self, runs: impl IntoIterator<Item = TextRun>) -> Self {
self.rich_text_runs = runs.into_iter().collect();
self
}
pub fn with_rich_text_images(
mut self,
images: impl IntoIterator<Item = RichTextImage>,
) -> Self {
self.rich_text_images = images.into_iter().collect();
self
}
pub fn with_placeholder_text(mut self, text: impl Into<String>) -> Self {
self.placeholder_text = Some(text.into());
self
}
pub fn with_monospace(mut self, monospace: bool) -> Self {
self.monospace = monospace;
self
}
}
pub fn abstractable_widget_types() -> &'static [WidgetKind] {
&[
WidgetKind::Window,
WidgetKind::Container,
WidgetKind::Label,
WidgetKind::Button,
#[cfg(feature = "widgets-choice")]
WidgetKind::RadioButton,
#[cfg(feature = "widgets-range")]
WidgetKind::Slider,
#[cfg(feature = "widgets-range")]
WidgetKind::SpinBox,
#[cfg(feature = "widgets-containers")]
WidgetKind::Separator,
#[cfg(feature = "widgets-containers")]
WidgetKind::GroupBox,
#[cfg(feature = "widgets-containers")]
WidgetKind::Tabs,
#[cfg(feature = "widgets-media")]
WidgetKind::Image,
#[cfg(feature = "widgets-pickers")]
WidgetKind::DatePicker,
#[cfg(feature = "widgets-text")]
WidgetKind::LinkLabel,
#[cfg(feature = "widgets-data")]
WidgetKind::ListView,
#[cfg(feature = "widgets-data")]
WidgetKind::TreeView,
#[cfg(feature = "widgets-containers")]
WidgetKind::SplitPane,
#[cfg(feature = "widgets-pickers")]
WidgetKind::FileChooserDialog,
#[cfg(feature = "widgets-containers")]
WidgetKind::AlertDialog,
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput,
#[cfg(feature = "widgets-text")]
WidgetKind::TextArea,
#[cfg(feature = "widgets-canvas")]
WidgetKind::VulkanCanvas,
#[cfg(feature = "widgets-choice")]
WidgetKind::Checkbox,
#[cfg(feature = "widgets-choice")]
WidgetKind::ComboBox,
#[cfg(feature = "widgets-range")]
WidgetKind::ProgressBar,
#[cfg(feature = "widgets-data")]
WidgetKind::DataList,
#[cfg(feature = "widgets-data")]
WidgetKind::DataGrid,
#[cfg(feature = "widgets-canvas")]
WidgetKind::Canvas,
#[cfg(feature = "widgets-pickers")]
WidgetKind::ColorDialog,
#[cfg(feature = "widgets-pickers")]
WidgetKind::FontDialog,
WidgetKind::Toolbar,
#[cfg(feature = "widgets-pickers")]
WidgetKind::Calendar,
#[cfg(feature = "widgets-choice")]
WidgetKind::MultiSelect,
]
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::sync::mpsc;
use std::time::Duration;
#[test]
fn widget_spec_builder_sets_fields() {
let id = WidgetId(1);
let parent = WidgetId(9);
let spec = WidgetSpec::new(id, WidgetKind::Button)
.with_text("Click me")
.with_parent(parent);
assert_eq!(spec.id, id);
assert_eq!(spec.kind, WidgetKind::Button);
assert_eq!(spec.text.as_deref(), Some("Click me"));
assert_eq!(spec.parent, Some(parent));
assert_eq!(spec.container_direction, None);
assert!(!spec.container_scroll_vertical);
assert!(!spec.container_scroll_horizontal);
assert_eq!(spec.size, None);
assert_eq!(spec.position, None);
assert_eq!(spec.data_list_items, Vec::<String>::new());
assert!(spec.data_grid_rows.is_empty());
assert_eq!(spec.background_color, None);
assert_eq!(spec.alert_level, None);
assert_eq!(spec.checked, None);
assert_eq!(spec.range, None);
assert_eq!(spec.step, None);
assert_eq!(spec.value, None);
assert_eq!(spec.group_name, None);
assert_eq!(spec.tab_items, Vec::<String>::new());
assert_eq!(spec.selected_index, None);
assert_eq!(spec.image_source, None);
assert_eq!(spec.date_value, None);
assert_eq!(spec.link_url, None);
assert_eq!(spec.tooltip, None);
assert_eq!(spec.split_ratio, None);
assert_eq!(spec.label_alignment, LabelAlignment::Center);
assert_eq!(spec.label_wrap, LabelWrap::None);
let spec = spec.with_tooltip("Helpful hint");
assert_eq!(spec.tooltip.as_deref(), Some("Helpful hint"));
}
#[test]
fn widget_spec_builder_sets_size() {
let spec = WidgetSpec::new(WidgetId(5), WidgetKind::Button).with_size(120, 44);
assert_eq!(spec.size, Some((120, 44)));
}
#[test]
fn widget_spec_builder_sets_position() {
let spec = WidgetSpec::new(WidgetId(7), WidgetKind::Button).with_position(32, 48);
assert_eq!(spec.position, Some((32, 48)));
}
#[test]
fn widget_spec_builder_sets_background_color() {
let color = Color::rgb(24, 42, 64);
let spec = WidgetSpec::new(WidgetId(6), WidgetKind::Label).with_background_color(color);
assert_eq!(spec.background_color, Some(color));
}
#[test]
#[cfg(feature = "widgets-data")]
fn widget_spec_builder_sets_data_items() {
let list_spec = WidgetSpec::new(WidgetId(10), WidgetKind::DataList)
.with_data_list_items(vec!["A".to_owned(), "B".to_owned()]);
assert_eq!(
list_spec.data_list_items,
vec!["A".to_owned(), "B".to_owned()]
);
let grid_spec =
WidgetSpec::new(WidgetId(11), WidgetKind::DataGrid).with_data_grid_rows(vec![
vec!["r1c1".to_owned(), "r1c2".to_owned()],
vec!["r2c1".to_owned(), "r2c2".to_owned()],
]);
let expected = vec![
vec!["r1c1".to_owned(), "r1c2".to_owned()],
vec!["r2c1".to_owned(), "r2c2".to_owned()],
];
assert_eq!(grid_spec.data_grid_rows.as_ref(), &expected);
}
#[test]
fn column_spec_width_preference_follows_shared_size_semantics() {
let column = ColumnSpec::new("Name");
assert_eq!(column.title, "Name");
assert_eq!(column.width, None);
assert_eq!(ColumnSpec::new("Name").with_width(80).width, Some(80));
assert_eq!(
ColumnSpec::new("Name").with_width(0).width,
None,
"non-positive width means no preference"
);
assert_eq!(ColumnSpec::new("Name").with_width(-4).width, None);
}
#[test]
#[cfg(feature = "widgets-data")]
fn widget_spec_builder_sets_list_columns_and_rows() {
let spec = WidgetSpec::new(WidgetId(12), WidgetKind::ListView)
.with_list_columns(vec![ColumnSpec::new("Name"), ColumnSpec::new("Size")])
.with_list_rows(vec![
vec!["a.txt".to_owned(), "12 KB".to_owned()],
vec!["folder".to_owned()],
]);
assert_eq!(spec.list_columns.len(), 2);
assert_eq!(spec.list_columns[1].title, "Size");
assert_eq!(spec.list_rows.len(), 2);
assert_eq!(spec.list_rows[1], vec!["folder".to_owned()]);
spec_with_columns(WidgetKind::ListView).expect("ListView accepted");
assert_eq!(
spec_with_columns(WidgetKind::DataList).expect_err("DataList rejected"),
GuiError::UnsupportedWidget("set_list_columns")
);
}
fn spec_with_columns(kind: WidgetKind) -> GuiResult<()> {
WidgetSpec::new(WidgetId(13), kind).ensure_property(WidgetProperty::ListViewColumns)
}
#[test]
fn row_diff_classifies_insert_update_move_keep_and_remove() {
let old = [
RowSet::new(1, &["a"]),
RowSet::new(2, &["b"]),
RowSet::new(3, &["c"]),
];
let new = [
RowSet::new(4, &["d"]),
RowSet::new(2, &["b2"]),
RowSet::new(3, &["c"]),
RowSet::new(1, &["a"]),
];
assert_eq!(
diff_rows(&old, &new).expect("diff"),
RowDelta {
inserted: 1,
updated: 1,
removed: 0,
moved: 1,
unchanged: 1,
}
);
}
#[test]
fn row_diff_counts_removals_reorders_and_duplicates() {
let old = [
RowSet::new(1, &["a"]),
RowSet::new(2, &["b"]),
RowSet::new(3, &["c"]),
];
let new = [RowSet::new(1, &["a"])];
let delta = diff_rows(&old, &new).expect("diff");
assert_eq!(delta.removed, 2);
assert_eq!(delta.unchanged, 1);
assert!(!delta.is_noop());
let reordered = [old[2].clone(), old[0].clone(), old[1].clone()];
let delta = diff_rows(&old, &reordered).expect("diff");
assert_eq!(
delta,
RowDelta {
inserted: 0,
updated: 0,
removed: 0,
moved: 3,
unchanged: 0,
}
);
assert!(diff_rows(&old, &old).expect("diff").is_noop());
let duplicates = [RowSet::new(9, &["x"]), RowSet::new(9, &["y"])];
assert_eq!(
diff_rows(&old, &duplicates),
Err(GuiError::Backend("duplicate row key".to_owned()))
);
}
#[test]
fn row_set_builder_and_single_cell_text() {
let row = RowSet::new(7, &["Name", "12 KB"]);
assert_eq!(row.key, RowKey(7));
assert_eq!(row.cells, vec!["Name".to_owned(), "12 KB".to_owned()]);
assert_eq!(row.text(), "Name");
assert_eq!(RowSet::new(8, &[]).text(), "");
}
#[test]
fn container_defaults_to_vertical_direction() {
let spec = WidgetSpec::new(WidgetId(2), WidgetKind::Container);
assert_eq!(spec.container_direction, Some(ContainerDirection::Vertical));
assert!(!spec.container_scroll_vertical);
assert!(!spec.container_scroll_horizontal);
}
#[test]
fn container_builder_sets_scroll_flags() {
let spec =
WidgetSpec::new(WidgetId(3), WidgetKind::Container).with_container_scroll(true, false);
assert!(spec.container_scroll_vertical);
assert!(!spec.container_scroll_horizontal);
}
#[test]
fn abstractable_widget_types_contains_expected_kinds() {
let list = abstractable_widget_types();
assert!(list.contains(&WidgetKind::Window));
assert!(list.contains(&WidgetKind::Button));
#[cfg(feature = "widgets-choice")]
assert!(list.contains(&WidgetKind::RadioButton));
#[cfg(feature = "widgets-range")]
assert!(list.contains(&WidgetKind::Slider));
#[cfg(feature = "widgets-range")]
assert!(list.contains(&WidgetKind::SpinBox));
#[cfg(feature = "widgets-containers")]
assert!(list.contains(&WidgetKind::Separator));
#[cfg(feature = "widgets-containers")]
assert!(list.contains(&WidgetKind::GroupBox));
#[cfg(feature = "widgets-containers")]
assert!(list.contains(&WidgetKind::Tabs));
#[cfg(feature = "widgets-media")]
assert!(list.contains(&WidgetKind::Image));
#[cfg(feature = "widgets-pickers")]
assert!(list.contains(&WidgetKind::DatePicker));
#[cfg(feature = "widgets-text")]
assert!(list.contains(&WidgetKind::LinkLabel));
#[cfg(feature = "widgets-data")]
assert!(list.contains(&WidgetKind::ListView));
#[cfg(feature = "widgets-data")]
assert!(list.contains(&WidgetKind::TreeView));
#[cfg(feature = "widgets-containers")]
assert!(list.contains(&WidgetKind::SplitPane));
#[cfg(feature = "widgets-pickers")]
assert!(list.contains(&WidgetKind::FileChooserDialog));
#[cfg(feature = "widgets-containers")]
assert!(list.contains(&WidgetKind::AlertDialog));
#[cfg(feature = "widgets-text")]
assert!(list.contains(&WidgetKind::TextArea));
#[cfg(feature = "widgets-canvas")]
assert!(list.contains(&WidgetKind::VulkanCanvas));
#[cfg(feature = "widgets-choice")]
assert!(list.contains(&WidgetKind::Checkbox));
#[cfg(feature = "widgets-choice")]
assert!(list.contains(&WidgetKind::ComboBox));
#[cfg(feature = "widgets-range")]
assert!(list.contains(&WidgetKind::ProgressBar));
#[cfg(feature = "widgets-data")]
assert!(list.contains(&WidgetKind::DataList));
#[cfg(feature = "widgets-data")]
assert!(list.contains(&WidgetKind::DataGrid));
#[cfg(feature = "widgets-canvas")]
assert!(list.contains(&WidgetKind::Canvas));
#[cfg(feature = "widgets-pickers")]
assert!(list.contains(&WidgetKind::ColorDialog));
#[cfg(feature = "widgets-pickers")]
assert!(list.contains(&WidgetKind::FontDialog));
assert!(list.contains(&WidgetKind::Toolbar));
#[cfg(feature = "widgets-pickers")]
assert!(list.contains(&WidgetKind::Calendar));
#[cfg(feature = "widgets-choice")]
assert!(list.contains(&WidgetKind::MultiSelect));
let mut expected_len = 8;
if cfg!(feature = "widgets-containers") {
expected_len += 5;
}
if cfg!(feature = "widgets-choice") {
expected_len += 4;
}
if cfg!(feature = "widgets-data") {
expected_len += 4;
}
if cfg!(feature = "widgets-media") {
expected_len += 1;
}
if cfg!(feature = "widgets-canvas") {
expected_len += 2;
}
if cfg!(feature = "widgets-range") {
expected_len += 3;
}
if cfg!(feature = "widgets-pickers") {
expected_len += 5;
}
assert_eq!(list.len(), expected_len);
}
#[cfg(feature = "widgets-containers")]
#[test]
fn alert_dialog_defaults_to_info_level() {
let spec = WidgetSpec::new(WidgetId(12), WidgetKind::AlertDialog);
assert_eq!(spec.alert_level, Some(AlertLevel::Info));
}
#[cfg(feature = "widgets-containers")]
#[test]
fn alert_dialog_builder_sets_level() {
let spec = WidgetSpec::new(WidgetId(13), WidgetKind::AlertDialog)
.with_alert_level(AlertLevel::Error);
assert_eq!(spec.alert_level, Some(AlertLevel::Error));
}
#[test]
fn extended_builder_metadata_sets_fields() {
let spec = WidgetSpec::new(WidgetId(14), WidgetKind::Button)
.with_checked(true)
.with_range(1, 10)
.with_step(2)
.with_value(7)
.with_group_name("group-a")
.with_tab_items(vec!["One".to_owned(), "Two".to_owned()])
.with_selected_index(1)
.with_image_source("./assets/icon.png")
.with_date_value("2026-03-06")
.with_link_url("https://example.com")
.with_split_ratio(80);
assert_eq!(spec.checked, Some(true));
assert_eq!(spec.range, Some((1, 10)));
assert_eq!(spec.step, Some(2));
assert_eq!(spec.value, Some(7));
assert_eq!(spec.group_name.as_deref(), Some("group-a"));
assert_eq!(spec.tab_items, vec!["One".to_owned(), "Two".to_owned()]);
assert_eq!(spec.selected_index, Some(1));
assert_eq!(spec.image_source.as_deref(), Some("./assets/icon.png"));
assert_eq!(spec.date_value.as_deref(), Some("2026-03-06"));
assert_eq!(spec.link_url.as_deref(), Some("https://example.com"));
assert_eq!(spec.split_ratio, Some(80));
}
#[cfg(feature = "widgets-pickers")]
#[test]
fn calendar_date_and_spec_builder_validation() {
let valid_date = CalendarDate::new(2024, 2, 29);
assert!(valid_date.is_valid(), "2024 is leap year");
let invalid_date = CalendarDate::new(2023, 2, 29);
assert!(!invalid_date.is_valid(), "2023 is not leap year");
let spec = WidgetSpec::new(WidgetId(20), WidgetKind::Calendar)
.with_calendar_selected_dates(vec![valid_date])
.with_calendar_bounds(
Some(CalendarDate::new(2024, 1, 1)),
Some(CalendarDate::new(2024, 12, 31)),
)
.with_calendar_first_day_of_week(CalendarFirstDayOfWeek::Monday)
.with_calendar_selection_mode(CalendarSelectionMode::Range);
assert_eq!(spec.calendar_selected_dates, vec![valid_date]);
assert_eq!(spec.calendar_min_date, Some(CalendarDate::new(2024, 1, 1)));
assert_eq!(
spec.calendar_max_date,
Some(CalendarDate::new(2024, 12, 31))
);
assert_eq!(
spec.calendar_first_day_of_week,
CalendarFirstDayOfWeek::Monday
);
assert_eq!(spec.calendar_selection_mode, CalendarSelectionMode::Range);
}
#[test]
fn widget_spec_builder_sets_label_alignment_and_wrap() {
let default_spec = WidgetSpec::new(WidgetId(21), WidgetKind::Label);
assert_eq!(default_spec.label_alignment, LabelAlignment::Left);
assert_eq!(default_spec.label_wrap, LabelWrap::None);
assert!(!default_spec.label_wrap.is_wrapping());
let spec = WidgetSpec::new(WidgetId(22), WidgetKind::Label)
.with_label_alignment(LabelAlignment::Center)
.with_label_wrap(LabelWrap::Word);
assert_eq!(spec.label_alignment, LabelAlignment::Center);
assert_eq!(spec.label_wrap, LabelWrap::Word);
assert!(spec.label_wrap.is_wrapping());
let right_spec = WidgetSpec::new(WidgetId(23), WidgetKind::Label)
.with_label_alignment(LabelAlignment::Right)
.with_label_wrap(true);
assert_eq!(right_spec.label_alignment, LabelAlignment::Right);
assert_eq!(right_spec.label_wrap, LabelWrap::Word);
let nowrap_spec = WidgetSpec::new(WidgetId(24), WidgetKind::Label).with_label_wrap(false);
assert_eq!(nowrap_spec.label_wrap, LabelWrap::None);
let char_wrap_spec =
WidgetSpec::new(WidgetId(25), WidgetKind::Label).with_label_wrap_mode(LabelWrap::Char);
assert_eq!(char_wrap_spec.label_wrap, LabelWrap::Char);
let word_char_spec =
WidgetSpec::new(WidgetId(26), WidgetKind::Label).with_label_wrap(LabelWrap::WordChar);
assert_eq!(word_char_spec.label_wrap, LabelWrap::WordChar);
assert_eq!(
LabelAlignment::from(TextAlignment::Left),
LabelAlignment::Left
);
assert_eq!(
LabelAlignment::from(TextAlignment::Center),
LabelAlignment::Center
);
assert_eq!(
LabelAlignment::from(TextAlignment::Right),
LabelAlignment::Right
);
assert_eq!(
TextAlignment::from(LabelAlignment::Left),
TextAlignment::Left
);
assert_eq!(
TextAlignment::from(LabelAlignment::Center),
TextAlignment::Center
);
assert_eq!(
TextAlignment::from(LabelAlignment::Right),
TextAlignment::Right
);
let from_text_align = WidgetSpec::new(WidgetId(27), WidgetKind::Label)
.with_label_alignment(TextAlignment::Right);
assert_eq!(from_text_align.label_alignment, LabelAlignment::Right);
assert!(default_spec
.ensure_property(WidgetProperty::LabelAlignment)
.is_ok());
assert!(default_spec
.ensure_property(WidgetProperty::LabelWrap)
.is_ok());
let button_spec = WidgetSpec::new(WidgetId(28), WidgetKind::Button);
assert!(button_spec
.ensure_property(WidgetProperty::LabelAlignment)
.is_ok());
assert_eq!(
button_spec.ensure_property(WidgetProperty::LabelWrap),
Err(GuiError::UnsupportedWidget("set_label_wrap"))
);
}
#[test]
#[cfg(feature = "widgets-text")]
fn rich_text_runs_and_style_widget_spec() {
let style = TextStyle::new()
.bold(true)
.italic(true)
.underline(true)
.strikethrough(true)
.monospace(true)
.scale(1.5)
.fg_color(Color::rgb(255, 0, 0))
.bg_color(Color::rgb(0, 255, 0))
.link("https://example.com")
.dimmed(true)
.paragraph_indent(2);
assert!(style.bold);
assert!(style.italic);
assert!(style.underline);
assert!(style.strikethrough);
assert!(style.monospace);
assert_eq!(style.scale, Some(1.5));
assert_eq!(style.fg_color, Some(Color::rgb(255, 0, 0)));
assert_eq!(style.bg_color, Some(Color::rgb(0, 255, 0)));
assert_eq!(style.link.as_deref(), Some("https://example.com"));
assert!(style.dimmed);
assert_eq!(style.paragraph_indent, 2);
let run = TextRun::new(0..12, style.clone());
assert_eq!(run.range, 0..12);
assert_eq!(run.style, style);
let spec = WidgetSpec::new(WidgetId(29), WidgetKind::RichText)
.with_rich_text_runs(vec![run.clone()]);
assert_eq!(spec.kind, WidgetKind::RichText);
assert_eq!(spec.rich_text_runs, vec![run]);
assert!(spec.ensure_property(WidgetProperty::RichTextRuns).is_ok());
assert!(spec.requires_property(WidgetProperty::RichTextRuns).is_ok());
assert_eq!(WidgetProperty::RichTextRuns.name(), "set_rich_text_runs");
assert_eq!(
WidgetProperty::RichTextRuns.operation(),
"set_rich_text_runs"
);
let button_spec = WidgetSpec::new(WidgetId(30), WidgetKind::Button);
assert_eq!(
button_spec.ensure_property(WidgetProperty::RichTextRuns),
Err(GuiError::UnsupportedWidget("set_rich_text_runs"))
);
assert_eq!(
button_spec.requires_property(WidgetProperty::RichTextRuns),
Err(GuiError::UnsupportedWidget("set_rich_text_runs"))
);
}
#[test]
#[cfg(feature = "widgets-text")]
fn rich_text_images_widget_spec() {
let img = RichTextImage::new(10, "assets/diagram.png", Some(640));
assert_eq!(img.offset, 10);
assert_eq!(img.source, "assets/diagram.png");
assert_eq!(img.max_width, Some(640));
let spec = WidgetSpec::new(WidgetId(31), WidgetKind::RichText)
.with_rich_text_images(vec![img.clone()]);
assert_eq!(spec.kind, WidgetKind::RichText);
assert_eq!(spec.rich_text_images, vec![img]);
assert!(spec.ensure_property(WidgetProperty::RichTextImages).is_ok());
assert!(spec
.requires_property(WidgetProperty::RichTextImages)
.is_ok());
assert_eq!(
WidgetProperty::RichTextImages.name(),
"set_rich_text_images"
);
assert_eq!(
WidgetProperty::RichTextImages.operation(),
"set_rich_text_images"
);
let button_spec = WidgetSpec::new(WidgetId(32), WidgetKind::Button);
assert_eq!(
button_spec.ensure_property(WidgetProperty::RichTextImages),
Err(GuiError::UnsupportedWidget("set_rich_text_images"))
);
assert_eq!(
button_spec.requires_property(WidgetProperty::RichTextImages),
Err(GuiError::UnsupportedWidget("set_rich_text_images"))
);
}
fn variant_index(property: WidgetProperty) -> usize {
match property {
WidgetProperty::Checked => 0,
WidgetProperty::Value => 1,
WidgetProperty::Range => 2,
WidgetProperty::Step => 3,
WidgetProperty::SelectedIndex => 4,
WidgetProperty::TabItems => 5,
WidgetProperty::SelectedIndices => 6,
WidgetProperty::RowDrag => 7,
WidgetProperty::DataListItems => 8,
WidgetProperty::ListViewColumns => 9,
WidgetProperty::ListViewRows => 10,
WidgetProperty::DataGridRows => 11,
WidgetProperty::DataGridModel => 12,
WidgetProperty::DataGridRowHeight => 13,
WidgetProperty::DataGridColWidth => 14,
WidgetProperty::DataGridFrozenPanes => 15,
WidgetProperty::DataGridSelection => 16,
WidgetProperty::TreeItems => 17,
WidgetProperty::AlertLevel => 18,
WidgetProperty::ImageSource => 19,
WidgetProperty::ImageFit => 20,
WidgetProperty::ButtonIcon => 21,
WidgetProperty::FileChooserMode => 22,
WidgetProperty::ColorDialogData => 23,
WidgetProperty::FontDialogData => 24,
WidgetProperty::ToolbarItems => 25,
WidgetProperty::ToolbarOrientation => 26,
WidgetProperty::DateValue => 27,
WidgetProperty::LinkUrl => 28,
WidgetProperty::TextSelection => 29,
WidgetProperty::TextCompletion => 30,
WidgetProperty::ContainerDirection => 31,
WidgetProperty::ContainerScroll => 32,
WidgetProperty::ContainerGap => 33,
WidgetProperty::ContainerPadding => 34,
WidgetProperty::CanvasScene => 35,
WidgetProperty::CanvasSurface => 36,
WidgetProperty::CloseGuard => 37,
WidgetProperty::LayoutRoot => 38,
WidgetProperty::WindowCallback => 39,
WidgetProperty::NativeHandle => 40,
WidgetProperty::DrawDemoCube => 41,
WidgetProperty::CopyToClipboard => 42,
WidgetProperty::PasteFromClipboard => 43,
WidgetProperty::KeyedRows => 44,
WidgetProperty::ClearSelection => 45,
WidgetProperty::VisibleAnchor => 46,
WidgetProperty::CalendarDates => 47,
WidgetProperty::CalendarBounds => 48,
WidgetProperty::CalendarFirstDayOfWeek => 49,
WidgetProperty::CalendarSelectionMode => 50,
WidgetProperty::LabelAlignment => 51,
WidgetProperty::LabelWrap => 52,
WidgetProperty::RichTextRuns => 53,
WidgetProperty::PlaceholderText => 54,
WidgetProperty::RichTextImages => 55,
WidgetProperty::Monospace => 56,
WidgetProperty::MetalHandle => 57,
WidgetProperty::ContainerWrap => 58,
WidgetProperty::Font => 59,
WidgetProperty::RowIcons => 60,
}
}
#[test]
fn property_all_covers_every_declared_variant() {
let mut indices: Vec<usize> = WidgetProperty::ALL
.iter()
.copied()
.map(variant_index)
.collect();
indices.sort_unstable();
assert_eq!(
indices,
(0..WidgetProperty::ALL.len()).collect::<Vec<usize>>(),
"WidgetProperty::ALL must list every variant exactly once"
);
}
#[test]
fn property_table_rows_are_well_formed() {
let mut operations = Vec::new();
for &property in WidgetProperty::ALL {
let row = property.applicable_kinds();
let image_property = matches!(
property,
WidgetProperty::ImageSource | WidgetProperty::ImageFit
);
let canvas_property = matches!(
property,
WidgetProperty::CanvasScene
| WidgetProperty::CanvasSurface
| WidgetProperty::NativeHandle
| WidgetProperty::DrawDemoCube
| WidgetProperty::MetalHandle
);
let range_property = matches!(
property,
WidgetProperty::Value | WidgetProperty::Range | WidgetProperty::Step
);
let choice_property = matches!(property, WidgetProperty::Checked);
let data_property = matches!(property, WidgetProperty::RowIcons);
if (cfg!(feature = "widgets-media") || !image_property)
&& (cfg!(feature = "widgets-canvas") || !canvas_property)
&& (cfg!(feature = "widgets-range") || !range_property)
&& (cfg!(feature = "widgets-choice") || !choice_property)
&& (cfg!(feature = "widgets-data") || !data_property)
{
assert!(
!row.is_empty(),
"{property:?} must accept at least one kind"
);
} else {
assert!(
row.is_empty(),
"{property:?} must have no applicable kind when its feature is off"
);
}
for kind in row {
assert!(
ALL_KINDS.contains(kind),
"{property:?} row names {kind:?}, which ALL_KINDS does not declare"
);
}
let mut unique = row.to_vec();
unique.sort_by_key(|kind| variant_kind_index(*kind));
unique.dedup();
assert_eq!(
unique.len(),
row.len(),
"{property:?} row contains duplicate kinds"
);
let operation = property.operation();
assert!(
!operation.is_empty(),
"{property:?} must have a stable operation name"
);
assert!(
!operations.contains(&operation),
"operation name {operation:?} is used by two properties"
);
operations.push(operation);
}
let mut kinds = ALL_KINDS.to_vec();
kinds.sort_by_key(|kind| variant_kind_index(*kind));
let declared = kinds.len();
kinds.dedup();
assert_eq!(declared, kinds.len(), "ALL_KINDS contains duplicates");
if !cfg!(feature = "widgets-media") {
assert!(ALL_KINDS.iter().all(|kind| {
!WidgetProperty::ImageSource.supports(*kind)
&& !WidgetProperty::ImageFit.supports(*kind)
}));
}
if !cfg!(feature = "widgets-canvas") {
assert!(ALL_KINDS.iter().all(|kind| {
!WidgetProperty::CanvasScene.supports(*kind)
&& !WidgetProperty::CanvasSurface.supports(*kind)
&& !WidgetProperty::NativeHandle.supports(*kind)
&& !WidgetProperty::DrawDemoCube.supports(*kind)
&& !WidgetProperty::MetalHandle.supports(*kind)
}));
}
if !cfg!(feature = "widgets-range") {
assert!(ALL_KINDS.iter().all(|kind| {
!WidgetProperty::Value.supports(*kind)
&& !WidgetProperty::Range.supports(*kind)
&& !WidgetProperty::Step.supports(*kind)
}));
}
if !cfg!(feature = "widgets-choice") {
assert!(ALL_KINDS
.iter()
.all(|kind| { !WidgetProperty::Checked.supports(*kind) }));
}
if !cfg!(feature = "widgets-data") {
assert!(ALL_KINDS
.iter()
.all(|kind| { !WidgetProperty::RowIcons.supports(*kind) }));
}
}
fn variant_kind_index(kind: WidgetKind) -> usize {
ALL_KINDS
.iter()
.position(|candidate| *candidate == kind)
.expect("ALL_KINDS must declare every kind")
}
#[test]
fn ensure_property_accepts_exactly_the_applicability_row() {
for &property in WidgetProperty::ALL {
for &kind in ALL_KINDS {
let spec = WidgetSpec::new(WidgetId(1), kind);
let result = spec.ensure_property(property);
if property.supports(kind) {
assert!(
result.is_ok(),
"{} must accept {kind:?}",
property.operation()
);
} else {
assert_eq!(
result,
Err(GuiError::UnsupportedWidget(property.operation())),
"{} must reject {kind:?} with the typed error",
property.operation()
);
}
}
}
}
struct WindowedProbe {
model: WindowedDataGridModel,
handle: WindowedDataGridHandle,
requested: Rc<RefCell<Vec<usize>>>,
repaints: Rc<Cell<usize>>,
}
fn probe(row_count: usize, col_count: usize, config: WindowedDataGridConfig) -> WindowedProbe {
let requested = Rc::new(RefCell::new(Vec::new()));
let repaints = Rc::new(Cell::new(0usize));
let model = WindowedDataGridModel::new(
row_count,
col_count,
config,
{
let requested = Rc::clone(&requested);
move |row| requested.borrow_mut().push(row)
},
{
let repaints = Rc::clone(&repaints);
move || repaints.set(repaints.get() + 1)
},
);
let handle = model.handle();
WindowedProbe {
model,
handle,
requested,
repaints,
}
}
#[test]
fn windowed_model_schedules_one_fetch_per_row_and_answers_reads_from_the_window() {
let probe = probe(3, 2, WindowedDataGridConfig::new(2, 1024));
assert_eq!(probe.model.value_at(0, 1), "…");
assert_eq!(probe.handle.misses(), 1);
assert_eq!(probe.handle.fetches_requested(), 1);
assert_eq!(*probe.requested.borrow(), vec![0]);
assert_eq!(probe.repaints.get(), 1);
assert!(probe.handle.is_row_in_flight(0));
assert!(!probe.model.is_row_resident(0));
assert_eq!(probe.model.value_at(1, 0), "…");
assert_eq!(probe.model.value_at(1, 1), "…");
assert_eq!(probe.handle.misses(), 3);
assert_eq!(probe.handle.fetches_requested(), 2);
assert_eq!(*probe.requested.borrow(), vec![0, 1]);
assert_eq!(probe.repaints.get(), 2);
assert_eq!(
probe
.handle
.deliver_row(1, vec!["1a".to_owned(), "1b".to_owned()]),
WindowedDelivery::Applied {
evicted: Vec::new()
}
);
assert!(probe.handle.is_row_resident(1));
assert!(probe.model.is_row_resident(1));
assert!(!probe.handle.is_row_in_flight(1));
assert_eq!(probe.model.value_at(1, 1), "1b");
assert_eq!(probe.handle.hits(), 1);
assert_eq!(probe.handle.resident_row_count(), 1);
assert_eq!(probe.model.value_at(3, 0), "");
assert_eq!(probe.model.value_at(1, 2), "");
assert_eq!(probe.handle.misses(), 3);
assert_eq!(probe.handle.hits(), 1);
assert!(
!probe.model.is_row_resident(3),
"out-of-range is not resident"
);
}
#[test]
fn windowed_model_lru_eviction_prefers_the_least_recently_used_row() {
let probe = probe(8, 1, WindowedDataGridConfig::new(2, 1024));
for row in 0..2 {
assert_eq!(probe.model.value_at(row, 0), "…");
assert_eq!(
probe.handle.deliver_row(row, vec![format!("r{row}")]),
WindowedDelivery::Applied {
evicted: Vec::new()
}
);
}
assert_eq!(probe.model.value_at(2, 0), "…");
assert_eq!(
probe.handle.deliver_row(2, vec!["r2".to_owned()]),
WindowedDelivery::Applied { evicted: vec![0] }
);
assert!(!probe.handle.is_row_resident(0));
assert_eq!(probe.handle.resident_row_count(), 2);
assert_eq!(probe.handle.evictions(), 1);
assert_eq!(probe.model.value_at(1, 0), "r1");
assert_eq!(probe.model.value_at(3, 0), "…");
assert_eq!(
probe.handle.deliver_row(3, vec!["r3".to_owned()]),
WindowedDelivery::Applied { evicted: vec![2] }
);
assert!(probe.handle.is_row_resident(1));
assert!(probe.handle.is_row_resident(3));
assert_eq!(probe.handle.evictions(), 2);
}
#[test]
fn windowed_model_evicts_on_the_byte_budget_and_refuses_oversized_rows() {
let probe = probe(8, 1, WindowedDataGridConfig::new(8, 10));
assert_eq!(probe.model.value_at(0, 0), "…");
assert_eq!(
probe.handle.deliver_row(0, vec!["aaaaa".to_owned()]),
WindowedDelivery::Applied {
evicted: Vec::new()
}
);
assert_eq!(probe.model.value_at(1, 0), "…");
assert_eq!(
probe.handle.deliver_row(1, vec!["bbbbb".to_owned()]),
WindowedDelivery::Applied {
evicted: Vec::new()
}
);
assert_eq!(probe.handle.resident_bytes(), 10);
assert_eq!(probe.model.value_at(2, 0), "…");
assert_eq!(
probe.handle.deliver_row(2, vec!["ccccc".to_owned()]),
WindowedDelivery::Applied { evicted: vec![0] }
);
assert_eq!(probe.handle.resident_bytes(), 10);
assert!(!probe.handle.is_row_resident(0));
assert_eq!(probe.model.value_at(3, 0), "…");
assert_eq!(
probe.handle.deliver_row(3, vec!["ccccccccccc".to_owned()]),
WindowedDelivery::Rejected(WindowedDeliveryRejection::Oversized)
);
assert!(!probe.handle.is_row_resident(3));
assert!(!probe.handle.is_row_in_flight(3));
assert_eq!(probe.handle.rejected_deliveries(), 1);
let fetches_before = probe.handle.fetches_requested();
assert_eq!(probe.model.value_at(3, 0), "…");
assert_eq!(probe.handle.fetches_requested(), fetches_before + 1);
}
#[test]
fn windowed_model_visible_band_pins_survive_until_replaced_or_cleared() {
let probe = probe(8, 1, WindowedDataGridConfig::new(3, 1024));
probe.handle.pin_visible_band(0, 2);
assert_eq!(probe.handle.pinned_band(), Some((0, 2)));
for row in 0..3 {
assert_eq!(probe.model.value_at(row, 0), "…");
assert_eq!(
probe.handle.deliver_row(row, vec![format!("r{row}")]),
WindowedDelivery::Applied {
evicted: Vec::new()
}
);
}
assert_eq!(probe.handle.resident_row_count(), 3);
assert_eq!(probe.model.value_at(3, 0), "…");
assert_eq!(
probe.handle.deliver_row(3, vec!["r3".to_owned()]),
WindowedDelivery::Applied { evicted: vec![2] }
);
assert!(probe.handle.is_row_resident(0));
assert!(probe.handle.is_row_resident(1));
assert_eq!(probe.model.value_at(4, 0), "…");
assert_eq!(
probe.handle.deliver_row(4, vec!["r4".to_owned()]),
WindowedDelivery::Applied { evicted: vec![3] }
);
assert!(probe.handle.is_row_resident(0));
assert!(probe.handle.is_row_resident(1));
assert_eq!(probe.handle.resident_row_count(), 3);
probe.handle.clear_pinned_band();
assert_eq!(probe.handle.pinned_band(), None);
assert_eq!(probe.model.value_at(5, 0), "…");
assert_eq!(
probe.handle.deliver_row(5, vec!["r5".to_owned()]),
WindowedDelivery::Applied { evicted: vec![0] }
);
probe.handle.pin_visible_band(1, 1);
assert_eq!(probe.model.value_at(6, 0), "…");
assert_eq!(
probe.handle.deliver_row(6, vec!["r6".to_owned()]),
WindowedDelivery::Applied { evicted: vec![4] }
);
assert!(probe.handle.is_row_resident(1));
assert!(probe.handle.is_row_resident(5));
assert!(probe.handle.is_row_resident(6));
assert_eq!(probe.handle.evictions(), 4);
}
#[test]
fn windowed_model_refuses_delivery_when_every_resident_row_is_pinned() {
let probe = probe(8, 1, WindowedDataGridConfig::new(2, 1024));
probe.handle.pin_visible_band(0, 2);
for row in 0..2 {
assert_eq!(probe.model.value_at(row, 0), "…");
assert_eq!(
probe.handle.deliver_row(row, vec![format!("r{row}")]),
WindowedDelivery::Applied {
evicted: Vec::new()
}
);
}
assert_eq!(probe.model.value_at(2, 0), "…");
assert_eq!(
probe.handle.deliver_row(2, vec!["r2".to_owned()]),
WindowedDelivery::Rejected(WindowedDeliveryRejection::NoEvictableVictim)
);
assert_eq!(probe.handle.rejected_deliveries(), 1);
assert_eq!(probe.handle.evictions(), 0);
assert!(!probe.handle.is_row_resident(2));
assert_eq!(probe.handle.resident_row_count(), 2, "the bound held");
probe.handle.clear_pinned_band();
let fetches_before = probe.handle.fetches_requested();
assert_eq!(probe.model.value_at(2, 0), "…");
assert_eq!(probe.handle.fetches_requested(), fetches_before + 1);
assert_eq!(
probe.handle.deliver_row(2, vec!["r2".to_owned()]),
WindowedDelivery::Applied { evicted: vec![0] }
);
assert!(probe.handle.is_row_resident(2));
}
#[test]
fn data_grid_model_trait_forwards_band_pins_to_the_windowed_handle() {
let probe = probe(8, 1, WindowedDataGridConfig::new(2, 1024));
let model: &dyn DataGridModel = &probe.model;
let eager: &dyn DataGridModel = &SimpleDataGridModel {
rows: vec![vec!["a".to_owned()]],
};
eager.pin_visible_band(0, 8);
eager.clear_pinned_band();
model.pin_visible_band(0, 2);
assert_eq!(probe.handle.pinned_band(), Some((0, 2)));
for row in 0..2 {
assert_eq!(model.value_at(row, 0), "…");
assert_eq!(
probe.handle.deliver_row(row, vec![format!("r{row}")]),
WindowedDelivery::Applied {
evicted: Vec::new()
}
);
}
assert_eq!(model.value_at(2, 0), "…");
assert_eq!(
probe.handle.deliver_row(2, vec!["r2".to_owned()]),
WindowedDelivery::Rejected(WindowedDeliveryRejection::NoEvictableVictim)
);
model.clear_pinned_band();
assert_eq!(probe.handle.pinned_band(), None);
}
#[test]
fn windowed_model_discards_stale_duplicate_and_out_of_range_deliveries() {
let probe = probe(3, 1, WindowedDataGridConfig::new(2, 1024));
assert_eq!(
probe.handle.deliver_row(1, vec!["stale".to_owned()]),
WindowedDelivery::Rejected(WindowedDeliveryRejection::NotInFlight)
);
assert_eq!(
probe.handle.deliver_row(9, vec!["x".to_owned()]),
WindowedDelivery::Rejected(WindowedDeliveryRejection::RowOutOfRange)
);
assert_eq!(probe.model.value_at(0, 0), "…");
assert!(matches!(
probe.handle.deliver_row(0, vec!["r0".to_owned()]),
WindowedDelivery::Applied { .. }
));
assert_eq!(
probe.handle.deliver_row(0, vec!["again".to_owned()]),
WindowedDelivery::Rejected(WindowedDeliveryRejection::NotInFlight)
);
assert_eq!(probe.model.value_at(0, 0), "r0", "no stale overwrite");
assert_eq!(probe.handle.rejected_deliveries(), 3);
}
#[test]
fn windowed_model_drop_closes_the_request_channel_fail_closed() {
let (request_tx, request_rx) = mpsc::channel::<usize>();
let (result_tx, result_rx) = mpsc::channel::<(usize, Vec<String>)>();
let (done_tx, done_rx) = mpsc::channel::<()>();
let worker = std::thread::spawn(move || {
while let Ok(row) = request_rx.recv() {
if result_tx.send((row, vec![format!("row {row}")])).is_err() {
break;
}
}
let _ = done_tx.send(());
});
let model = WindowedDataGridModel::new(
100,
1,
WindowedDataGridConfig::new(4, 4096),
move |row| {
let _ = request_tx.send(row);
},
|| {},
);
assert_eq!(model.value_at(7, 0), "…");
assert!(model.handle().is_row_in_flight(7));
drop(model);
done_rx
.recv_timeout(Duration::from_secs(5))
.expect("the producer must stop once the model's request channel closes");
worker.join().expect("worker thread");
for (row, _) in result_rx.try_iter() {
assert_eq!(row, 7);
}
}
#[test]
fn eager_models_report_every_row_resident_by_default() {
let model = SimpleDataGridModel {
rows: vec![vec!["a".to_owned()]],
};
assert!(model.is_row_resident(0));
assert!(
model.is_row_resident(500),
"the default has no non-resident state; out-of-range reads are still total"
);
}
#[test]
fn row_ops_diff_and_apply_update_insert_remove_move() {
let r1 = RowSet::new(1, &["a", "b"]);
let r2 = RowSet::new(2, &["c", "d"]);
let r3 = RowSet::new(3, &["e", "f"]);
let base = vec![r1.clone(), r2.clone(), r3.clone()];
let mut updated = base.clone();
updated[1] = RowSet::new(2, &["c_mod", "d_mod"]);
let delta = diff_rows(&base, &updated).unwrap();
let ops = diff_row_ops(&base, &updated, &delta).expect("pure update should yield ops");
assert_eq!(ops.len(), 1);
match &ops[0] {
RowOp::Update { index, row } => {
assert_eq!(*index, 1);
assert_eq!(row.cells, vec!["c_mod", "d_mod"]);
}
_ => panic!("expected RowOp::Update"),
}
let mut rows = base.clone();
apply_row_ops_to_rows(&mut rows, &ops);
assert_eq!(rows, updated);
let r_new = RowSet::new(99, &["x", "y"]);
let inserted = vec![r1.clone(), r_new.clone(), r2.clone(), r3.clone()];
let delta = diff_rows(&base, &inserted).unwrap();
let ops = diff_row_ops(&base, &inserted, &delta).expect("single insert should yield ops");
assert_eq!(ops.len(), 1);
match &ops[0] {
RowOp::Insert { index, row } => {
assert_eq!(*index, 1);
assert_eq!(row.key.0, 99);
}
_ => panic!("expected RowOp::Insert"),
}
let mut rows = base.clone();
apply_row_ops_to_rows(&mut rows, &ops);
assert_eq!(rows, inserted);
let removed = vec![r1.clone(), r3.clone()];
let delta = diff_rows(&base, &removed).unwrap();
let ops = diff_row_ops(&base, &removed, &delta).expect("single remove should yield ops");
assert_eq!(ops.len(), 1);
match &ops[0] {
RowOp::Remove { index, key } => {
assert_eq!(*index, 1);
assert_eq!(key.0, 2);
}
_ => panic!("expected RowOp::Remove"),
}
let mut rows = base.clone();
apply_row_ops_to_rows(&mut rows, &ops);
assert_eq!(rows, removed);
let moved = vec![r2.clone(), r3.clone(), r1.clone()];
let delta = diff_rows(&base, &moved).unwrap();
let ops = diff_row_ops(&base, &moved, &delta).expect("single move should yield ops");
assert_eq!(ops.len(), 1);
match &ops[0] {
RowOp::Move {
from_index,
to_index,
key,
} => {
assert_eq!(*from_index, 0);
assert_eq!(*to_index, 2);
assert_eq!(key.0, 1);
}
_ => panic!("expected RowOp::Move"),
}
let mut rows = base.clone();
apply_row_ops_to_rows(&mut rows, &ops);
assert_eq!(rows, moved);
let mut cells = vec![
vec!["a".to_owned(), "b".to_owned()],
vec!["c".to_owned(), "d".to_owned()],
];
let op = RowOp::Update {
index: 0,
row: RowSet::new(1, &["new_a", "new_b"]),
};
apply_row_ops_to_cells(&mut cells, &[op]);
assert_eq!(cells[0], vec!["new_a", "new_b"]);
let mut items = vec!["item1".to_owned(), "item2".to_owned()];
let op_item = RowOp::Insert {
index: 1,
row: RowSet::new(10, &["inserted"]),
};
apply_row_ops_to_items(&mut items, &[op_item]);
assert_eq!(items, vec!["item1", "inserted", "item2"]);
}
}