use std::collections::{HashMap, HashSet, VecDeque};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::access::AccessibilitySpec;
use crate::artprov::{ArtCapabilities, IconRole, IconSize, StockIcon};
#[cfg(feature = "async")]
use crate::async_ui::{
TaskAbortReason, TaskCommand, TaskDrainReport, TaskEvent, UiProxy, DEFAULT_TASK_QUEUE_CAPACITY,
};
use crate::displays::DisplayCapabilities;
#[cfg(feature = "displays")]
use crate::displays::DisplayInfo;
use crate::drag::{
normalize_kinds, DragCapabilities, DragPayloadKind, DragSourceOptions, DragTargetOptions,
DropEffect,
};
use crate::error::{GuiError, GuiResult};
use crate::events::{AccessibleNotification, UiEvent};
use crate::image_resource::{
checked_total_bytes, ImageData, ImageResourceCapabilities, ImageResourceId,
};
use crate::layout::{LayoutNodeId, LayoutTree};
use crate::menus::{MenuId, MenuItemId};
use crate::motion::{ActiveMotion, MotionCapabilities, MotionId, MotionSpec, MOTION_TICK_CADENCE};
use crate::pickers::{ColorDialogData, FontDescriptor, FontDialogData};
#[cfg(feature = "routes")]
use crate::routes::Routes;
use crate::theme::{Theme, ThemeCapabilities, ThemeMode, ThemeOverride};
use crate::timer::{TimerCapabilities, TimerId, TimerSpec, TimerStopPolicy};
use crate::toolbar::{self, ToolId, ToolUpdate, ToolbarItem, ToolbarOrientation};
use crate::tray::{TrayIconId, TrayIconSpec};
#[cfg(feature = "widgets-data")]
use crate::widgets::diff_rows;
use crate::widgets::{
AlertLevel, CalendarDate, CalendarFirstDayOfWeek, CalendarSelectionMode, ClipboardImage, Color,
ColumnSpec, ContainerDirection, ContainerWrap, FileChooserMode, GpuDegradationPolicy,
GpuSurfaceCapabilities, ImageFit, LabelAlignment, LabelWrap, RichTextImage, RowDelta, RowKey,
RowSet, TextRun, TreeItem, WidgetId, WidgetKind, WidgetProperty, WidgetSpec,
};
use crate::windowing::{
ShowEffect, Stacking, WindowCapabilities, WindowFocusPolicy, WindowOptions, WindowPlacement,
WindowRole, WindowShape,
};
type LayoutUpdate = (WidgetId, Option<(i32, i32)>, Option<(i32, i32)>);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VulkanCanvasHandle {
Win32 { hwnd: usize, hinstance: usize },
Wayland { surface: usize, display: usize },
X11 { window: u64, display: usize },
Mock { token: usize },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MetalCanvasHandle {
pub ns_view: usize,
pub ca_metal_layer: usize,
pub mtl_device: usize,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum LoopFlow {
#[default]
Continue,
Exit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunStop {
WindowClosed,
Exit,
TimedOut,
}
pub trait TextMeasure {
fn measure_text(
&self,
widget_id: crate::widgets::WidgetId,
known_dimensions: crate::layout::Size<Option<f32>>,
available_space: crate::layout::Size<crate::layout::AvailableSpace>,
) -> Option<crate::layout::Size<f32>>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
Simulated,
SemanticNative,
HardwareNative,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Capability {
Supported { mode: InputMode },
Unsupported { reason: String },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operation {
Click,
TypeText,
Check,
Text,
Checked,
Press,
Select,
SetValue,
Scroll,
DragTo,
Close,
Screenshot,
}
impl Operation {
pub fn name(self) -> &'static str {
match self {
Self::Click => "e2e.click",
Self::TypeText => "e2e.type_text",
Self::Check => "e2e.check",
Self::Text => "e2e.text",
Self::Checked => "e2e.checked",
Self::Press => "e2e.press",
Self::Select => "e2e.select",
Self::SetValue => "e2e.set_value",
Self::Scroll => "e2e.scroll",
Self::DragTo => "e2e.drag_to",
Self::Close => "e2e.close",
Self::Screenshot => "e2e.screenshot",
}
}
}
pub trait Backend: TextMeasure {
fn create_widget(&mut self, spec: &WidgetSpec) -> GuiResult<()>;
fn create_menu(&mut self, menu_id: MenuId) -> GuiResult<()>;
fn add_submenu(
&mut self,
parent_id: MenuId,
submenu_id: MenuId,
slot_id: MenuItemId,
text: &str,
) -> GuiResult<()>;
fn create_menu_item(
&mut self,
menu_id: MenuId,
item_id: MenuItemId,
text: &str,
shortcut: Option<&str>,
) -> GuiResult<()>;
fn attach_menu_to_window(&mut self, window_id: WidgetId, menu_id: MenuId) -> GuiResult<()>;
fn attach_context_menu(&mut self, widget_id: WidgetId, menu_id: MenuId) -> GuiResult<()>;
fn set_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()>;
fn set_label_alignment(
&mut self,
widget_id: WidgetId,
alignment: LabelAlignment,
) -> GuiResult<()> {
let _ = (widget_id, alignment);
Err(GuiError::UnsupportedCapability(
"label_alignment".to_owned(),
))
}
fn set_label_wrap(&mut self, widget_id: WidgetId, wrap: LabelWrap) -> GuiResult<()> {
let _ = (widget_id, wrap);
Err(GuiError::UnsupportedCapability("label_wrap".to_owned()))
}
fn text_selection(&self, _widget_id: WidgetId) -> GuiResult<(usize, usize)> {
Err(GuiError::UnsupportedCapability("text_selection".to_owned()))
}
fn set_text_selection(
&mut self,
widget_id: WidgetId,
start: usize,
end: usize,
) -> GuiResult<()> {
let _ = (widget_id, start, end);
Err(GuiError::UnsupportedWidget("set_text_selection"))
}
fn set_text_completion_items(
&mut self,
widget_id: WidgetId,
items: &[String],
) -> GuiResult<()> {
let _ = (widget_id, items);
Err(GuiError::UnsupportedCapability(
"text_completion".to_owned(),
))
}
fn set_checked(&mut self, widget_id: WidgetId, checked: bool) -> GuiResult<()>;
fn set_value(&mut self, widget_id: WidgetId, value: i32) -> GuiResult<()>;
fn set_range(&mut self, widget_id: WidgetId, min: i32, max: i32) -> GuiResult<()>;
fn set_step(&mut self, widget_id: WidgetId, step: i32) -> GuiResult<()>;
fn set_selected_index(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()>;
fn set_tab_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()>;
fn set_selected_indices(&mut self, widget_id: WidgetId, indices: &[usize]) -> GuiResult<()>;
fn set_row_drag(&mut self, widget_id: WidgetId, source: bool, target: bool) -> GuiResult<()>;
fn drag_capabilities(&self) -> DragCapabilities {
DragCapabilities::none()
}
fn set_drag_source_options(
&mut self,
widget_id: WidgetId,
options: &DragSourceOptions,
) -> GuiResult<()> {
let _ = widget_id;
if let Some(kind) = options.kinds.first() {
let capability = match kind {
DragPayloadKind::Text => "drag_text",
DragPayloadKind::Custom { .. } => "drag_custom_mime",
};
return Err(GuiError::UnsupportedCapability(capability.to_owned()));
}
Ok(())
}
fn set_drag_target_options(
&mut self,
widget_id: WidgetId,
options: &DragTargetOptions,
) -> GuiResult<()> {
let _ = widget_id;
if let Some(kind) = options.kinds.first() {
let capability = match kind {
DragPayloadKind::Text => "drag_text",
DragPayloadKind::Custom { .. } => "drag_custom_mime",
};
return Err(GuiError::UnsupportedCapability(capability.to_owned()));
}
if options.effect != DropEffect::None {
return Err(GuiError::UnsupportedCapability("drop_feedback".to_owned()));
}
Ok(())
}
fn set_file_drop_target(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
let _ = (widget_id, enabled);
Ok(())
}
fn set_drop_target(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
self.set_file_drop_target(widget_id, enabled)
}
fn set_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()>;
fn set_min_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
let _ = (widget_id, width, height);
Ok(())
}
fn set_layout_size(
&mut self,
widget_id: WidgetId,
width: i32,
height: i32,
expand_width: bool,
expand_height: bool,
) -> GuiResult<()> {
let _ = (expand_width, expand_height);
self.set_size(widget_id, width, height)
}
fn natural_size(&self, widget_id: WidgetId) -> Option<(i32, i32)> {
let _ = widget_id;
None
}
fn min_compressed_size(&self, widget_id: WidgetId) -> Option<(i32, i32)> {
let _ = widget_id;
None
}
fn apply_flow_padding(&mut self, widget_id: WidgetId, padding: [i32; 4]) -> GuiResult<()> {
let _ = (widget_id, padding);
Ok(())
}
fn host_advanced_control(
&mut self,
host: WidgetId,
family: crate::advanced::AdvancedFamily,
) -> GuiResult<crate::advanced::AdvancedHostCapabilities> {
let _ = (host, family);
Err(GuiError::UnsupportedCapability(
"advanced_control".to_owned(),
))
}
fn set_data_list_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()>;
fn set_combo_box_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
let _ = (widget_id, items);
Err(GuiError::UnsupportedCapability(
"combo_box_items".to_owned(),
))
}
fn set_list_columns(&mut self, widget_id: WidgetId, columns: &[ColumnSpec]) -> GuiResult<()> {
let _ = (widget_id, columns);
Err(GuiError::UnsupportedCapability(
"list_view_columns".to_owned(),
))
}
fn set_list_rows(&mut self, widget_id: WidgetId, rows: &[Vec<String>]) -> GuiResult<()> {
let _ = (widget_id, rows);
Err(GuiError::UnsupportedCapability(
"list_view_columns".to_owned(),
))
}
fn clear_selection(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let _ = widget_id;
Err(GuiError::UnsupportedCapability(
"clear_selection".to_owned(),
))
}
fn visible_anchor_index(&self, widget_id: WidgetId) -> GuiResult<Option<usize>> {
let _ = widget_id;
Err(GuiError::UnsupportedCapability("scroll_anchor".to_owned()))
}
fn scroll_to_row(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
let _ = (widget_id, index);
Err(GuiError::UnsupportedCapability("scroll_anchor".to_owned()))
}
fn rows_end_visible(&self, widget_id: WidgetId) -> GuiResult<bool> {
let _ = widget_id;
Err(GuiError::UnsupportedCapability("scroll_anchor".to_owned()))
}
fn apply_row_delta(
&mut self,
widget_id: WidgetId,
ops: &[crate::widgets::RowOp],
) -> GuiResult<()> {
let _ = (widget_id, ops);
Err(GuiError::UnsupportedCapability("row_delta".to_owned()))
}
fn set_data_grid_rows(
&mut self,
widget_id: WidgetId,
rows: Arc<Vec<Vec<String>>>,
) -> GuiResult<()>;
fn set_data_grid_model(
&mut self,
widget_id: WidgetId,
model: Box<dyn crate::widgets::DataGridModel>,
) -> GuiResult<()>;
fn set_data_grid_row_height(
&mut self,
widget_id: WidgetId,
row: usize,
height: i32,
) -> GuiResult<()>;
fn set_data_grid_col_width(
&mut self,
widget_id: WidgetId,
col: usize,
width: i32,
) -> GuiResult<()>;
fn set_data_grid_frozen_panes(
&mut self,
widget_id: WidgetId,
rows: usize,
cols: usize,
) -> GuiResult<()>;
fn set_data_grid_selection(
&mut self,
widget_id: WidgetId,
selection: &[(usize, usize)],
) -> GuiResult<()>;
fn set_tree_items(&mut self, widget_id: WidgetId, items: &[TreeItem]) -> GuiResult<()>;
fn set_position(&mut self, widget_id: WidgetId, x: i32, y: i32) -> GuiResult<()>;
fn set_layout_position(&mut self, widget_id: WidgetId, x: i32, y: i32) -> GuiResult<()> {
self.set_position(widget_id, x, y)
}
fn set_background_color(&mut self, widget_id: WidgetId, color: Color) -> GuiResult<()>;
fn set_alert_level(&mut self, widget_id: WidgetId, level: AlertLevel) -> GuiResult<()>;
fn set_image_source(&mut self, widget_id: WidgetId, source: &str) -> GuiResult<()>;
fn image_resource_capabilities(&self) -> ImageResourceCapabilities {
ImageResourceCapabilities::none()
}
fn load_image_resource(
&mut self,
_resource: ImageResourceId,
_data: &ImageData,
) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"image_resource_rgba".to_owned(),
))
}
fn release_image_resource(&mut self, _resource: ImageResourceId) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"image_resource_rgba".to_owned(),
))
}
fn set_image_fit(&mut self, _widget_id: WidgetId, _fit: ImageFit) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("set_image_fit".to_owned()))
}
fn set_file_chooser_mode(
&mut self,
_widget_id: WidgetId,
_mode: FileChooserMode,
) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"file_chooser_pick_folder".to_owned(),
))
}
fn set_icon(&mut self, _widget_id: WidgetId, _icon: Option<IconRole>) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_icon"))
}
fn set_color_dialog_data(
&mut self,
_widget_id: WidgetId,
_data: &ColorDialogData,
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("color_dialog"))
}
fn set_font_dialog_data(
&mut self,
_widget_id: WidgetId,
_data: &FontDialogData,
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("font_dialog"))
}
fn set_toolbar_items(&mut self, _widget_id: WidgetId, _items: &[ToolbarItem]) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("toolbar"))
}
fn set_toolbar_orientation(
&mut self,
_widget_id: WidgetId,
_orientation: ToolbarOrientation,
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("toolbar"))
}
fn set_calendar_selected_dates(
&mut self,
_widget_id: WidgetId,
_dates: &[CalendarDate],
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("calendar"))
}
fn set_calendar_bounds(
&mut self,
_widget_id: WidgetId,
_min_date: Option<CalendarDate>,
_max_date: Option<CalendarDate>,
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("calendar"))
}
fn set_calendar_first_day_of_week(
&mut self,
_widget_id: WidgetId,
_first_day: CalendarFirstDayOfWeek,
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("calendar"))
}
fn set_calendar_selection_mode(
&mut self,
_widget_id: WidgetId,
_mode: CalendarSelectionMode,
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("calendar"))
}
fn set_date_value(&mut self, widget_id: WidgetId, iso_date: &str) -> GuiResult<()>;
fn set_link_url(&mut self, widget_id: WidgetId, url: &str) -> GuiResult<()>;
fn set_container_direction(
&mut self,
widget_id: WidgetId,
direction: ContainerDirection,
) -> GuiResult<()>;
fn set_container_wrap(&mut self, widget_id: WidgetId, wrap: ContainerWrap) -> GuiResult<()> {
let _ = (widget_id, wrap);
Ok(())
}
fn set_container_scroll(
&mut self,
widget_id: WidgetId,
vertical: bool,
horizontal: bool,
) -> GuiResult<()>;
fn set_container_gap(&mut self, widget_id: WidgetId, gap: i32) -> GuiResult<()>;
fn set_container_padding(&mut self, widget_id: WidgetId, padding: i32) -> GuiResult<()>;
fn draw_demo_cube(&mut self, widget_id: WidgetId) -> GuiResult<()>;
fn create_gpu_fallback(
&mut self,
_spec: &WidgetSpec,
_policy: GpuDegradationPolicy,
) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"gpu_degradation_fallback".to_owned(),
))
}
fn set_canvas_scene(
&mut self,
widget_id: WidgetId,
scene: &crate::CanvasScene,
) -> GuiResult<()>;
fn set_canvas_surface(
&mut self,
_widget_id: WidgetId,
_surface: &crate::CanvasSurface,
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_canvas_surface"))
}
type NativeHandle;
fn native_handle(&self, widget_id: WidgetId) -> GuiResult<Self::NativeHandle>;
fn metal_canvas_handle(&self, _widget_id: WidgetId) -> GuiResult<MetalCanvasHandle> {
Err(GuiError::UnsupportedCapability("metal_surface".to_owned()))
}
fn add_child(&mut self, parent: WidgetId, child: WidgetId) -> GuiResult<()>;
fn reparent(&mut self, child: WidgetId, new_parent: WidgetId) -> GuiResult<()> {
self.add_child(new_parent, child)
}
fn show(&mut self, widget_id: WidgetId) -> GuiResult<()>;
fn hide(&mut self, widget_id: WidgetId) -> GuiResult<()>;
fn remove(&mut self, widget_id: WidgetId) -> GuiResult<()>;
fn set_enabled(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()>;
fn activate(&mut self, widget_id: WidgetId) -> GuiResult<()>;
fn backend_name(&self) -> &'static str {
"unknown"
}
fn capture_window_rgba(
&self,
_widget_id: WidgetId,
_include_decorations: bool,
) -> GuiResult<(u32, u32, Vec<u8>)> {
Err(GuiError::UnsupportedWidget("capture_window_rgba"))
}
fn capture_widget_rgba(&self, _widget_id: WidgetId) -> GuiResult<(u32, u32, Vec<u8>)> {
Err(GuiError::UnsupportedWidget("capture_widget_rgba"))
}
fn native_read_text(&self, _widget_id: WidgetId) -> GuiResult<Option<String>> {
Ok(None)
}
fn native_read_checked(&self, _widget_id: WidgetId) -> GuiResult<Option<bool>> {
Ok(None)
}
fn native_click(&self, _widget_id: WidgetId) -> GuiResult<bool> {
Ok(false)
}
fn native_type_text(&self, _widget_id: WidgetId, _text: &str) -> GuiResult<bool> {
let _ = _text;
Ok(false)
}
fn native_close(&self, _widget_id: WidgetId) -> GuiResult<bool> {
Ok(false)
}
fn e2e_capability(&self, _widget_id: WidgetId, _operation: Operation) -> GuiResult<Capability> {
Ok(Capability::Unsupported {
reason: "This backend has no E2E adapter".into(),
})
}
fn e2e_click(&mut self, _widget_id: WidgetId) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("e2e.click"))
}
fn e2e_type_text(&mut self, _widget_id: WidgetId, _text: &str) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("e2e.type_text"))
}
fn e2e_check(&mut self, _widget_id: WidgetId, _checked: bool) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("e2e.check"))
}
fn e2e_text(&self, _widget_id: WidgetId) -> GuiResult<String> {
Err(GuiError::UnsupportedWidget("e2e.text"))
}
fn e2e_checked(&self, _widget_id: WidgetId) -> GuiResult<bool> {
Err(GuiError::UnsupportedWidget("e2e.checked"))
}
fn e2e_poll_event(&mut self) -> GuiResult<Option<UiEvent>> {
Err(GuiError::UnsupportedWidget("e2e.poll"))
}
fn set_clipboard_text(&mut self, _text: &str) -> GuiResult<()> {
Ok(())
}
fn clipboard_text(&mut self) -> GuiResult<Option<String>> {
Ok(None)
}
fn paste_image_from_clipboard(&mut self) -> GuiResult<Option<ClipboardImage>> {
Ok(None)
}
fn data_dir(&self) -> GuiResult<PathBuf>;
fn set_tooltip(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()>;
fn set_accessible_name(&mut self, _widget_id: WidgetId, _name: &str) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"accessible name".to_owned(),
))
}
fn set_accessible_description(
&mut self,
_widget_id: WidgetId,
_description: &str,
) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"accessible description".to_owned(),
))
}
fn post_accessible_notification(
&mut self,
widget_id: WidgetId,
notification: AccessibleNotification,
) -> GuiResult<()> {
let _ = (widget_id, notification);
Ok(())
}
fn set_focus(&mut self, _widget_id: WidgetId) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("focus".to_owned()))
}
fn set_focusable(&mut self, _widget_id: WidgetId, _focusable: bool) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("focusable".to_owned()))
}
fn set_theme(&mut self, _theme: &Theme) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("theme".to_owned()))
}
fn set_theme_override(
&mut self,
_widget_id: WidgetId,
_theme_override: ThemeOverride,
) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("theme override".to_owned()))
}
fn clear_theme_overrides(&mut self, _widget_id: WidgetId) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("theme override".to_owned()))
}
fn theme_capabilities(&self) -> ThemeCapabilities {
ThemeCapabilities::none()
}
fn system_theme_mode(&self) -> Option<ThemeMode> {
None
}
fn system_high_contrast(&self) -> bool {
false
}
fn art_capabilities(&self) -> ArtCapabilities {
ArtCapabilities::none()
}
fn native_stock_icon(&self, role: IconRole, size: IconSize) -> GuiResult<StockIcon> {
Err(crate::artprov::unsupported_native_icon(
role,
size,
"no native mapping on this backend",
))
}
fn display_capabilities(&self) -> DisplayCapabilities {
DisplayCapabilities::none()
}
fn gpu_surface_capabilities(&self) -> GpuSurfaceCapabilities {
GpuSurfaceCapabilities::none()
}
#[cfg(feature = "displays")]
fn displays(&self) -> GuiResult<Vec<DisplayInfo>> {
Err(GuiError::UnsupportedCapability(
"display_metrics".to_owned(),
))
}
#[cfg(feature = "displays")]
fn primary_display(&self) -> GuiResult<Option<DisplayInfo>> {
Ok(self.displays()?.into_iter().find(|display| display.primary))
}
fn widget_scale_factor(&self, _widget_id: WidgetId) -> f64 {
1.0
}
fn poll_event(&mut self) -> GuiResult<Option<UiEvent>>;
fn wait_event(&mut self) -> GuiResult<UiEvent>;
fn wake_handle(&self) -> Option<std::sync::Arc<dyn Fn() + Send + Sync>> {
None
}
fn show_confirm_dialog(&mut self, token: u64, title: &str, message: &str) -> GuiResult<()>;
fn show_file_dialog(
&mut self,
token: u64,
request: &crate::file_dialog::FileDialog,
) -> GuiResult<()> {
let _ = (token, request);
Err(GuiError::UnsupportedCapability("file_dialog".to_owned()))
}
fn native_window_handle(
&self,
window_id: WidgetId,
) -> GuiResult<crate::window_handle::NativeWindowHandle> {
let _ = window_id;
Err(GuiError::UnsupportedCapability(
"native_window_handle".to_owned(),
))
}
fn set_close_guard(&mut self, _widget_id: WidgetId, _guarded: bool) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"set_close_guard".to_owned(),
))
}
fn window_capabilities(&self) -> WindowCapabilities {
WindowCapabilities::none()
}
fn set_window_options(
&mut self,
widget_id: WidgetId,
options: &WindowOptions,
) -> GuiResult<()> {
let _ = widget_id;
if *options == WindowOptions::default() {
Ok(())
} else {
Err(GuiError::UnsupportedCapability("window_options".to_owned()))
}
}
fn dismiss_popup(&mut self, widget_id: WidgetId) -> GuiResult<()> {
self.hide(widget_id)
}
fn timer_capabilities(&self) -> TimerCapabilities {
TimerCapabilities::none()
}
fn motion_capabilities(&self) -> MotionCapabilities {
MotionCapabilities::none()
}
fn start_timer(&mut self, timer: TimerId, spec: TimerSpec) -> GuiResult<()> {
let _ = (timer, spec);
Err(GuiError::UnsupportedCapability("ui_timer".to_owned()))
}
fn start_widget_timer(
&mut self,
timer: TimerId,
widget_id: WidgetId,
spec: TimerSpec,
stop_policy: TimerStopPolicy,
) -> GuiResult<()> {
let _ = (timer, widget_id, spec, stop_policy);
Err(GuiError::UnsupportedCapability("widget_timer".to_owned()))
}
fn cancel_timer(&mut self, timer: TimerId) -> GuiResult<()> {
let _ = timer;
Err(GuiError::UnsupportedCapability("ui_timer".to_owned()))
}
fn set_menu_item_enabled(&mut self, _item_id: MenuItemId, _enabled: bool) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"set_menu_item_enabled".to_owned(),
))
}
fn set_menu_item_text(&mut self, _item_id: MenuItemId, _text: &str) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"dynamic_menu_items".to_owned(),
))
}
fn insert_menu_item(
&mut self,
_menu_id: MenuId,
_item_id: MenuItemId,
_index: usize,
_text: &str,
_shortcut: Option<&str>,
) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"dynamic_menu_items".to_owned(),
))
}
fn remove_menu_item(&mut self, _item_id: MenuItemId) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"dynamic_menu_items".to_owned(),
))
}
fn remove_submenu(&mut self, _submenu_id: MenuId) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"dynamic_menu_items".to_owned(),
))
}
fn set_window_min_size(&mut self, _widget_id: WidgetId, _w: u32, _h: u32) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"set_window_min_size".to_owned(),
))
}
fn set_resizable(&mut self, _widget_id: WidgetId, _resizable: bool) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("set_resizable".to_owned()))
}
fn set_placeholder_text(&mut self, _widget_id: WidgetId, _text: &str) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"set_placeholder_text".to_owned(),
))
}
fn set_rich_text_runs(&mut self, _widget_id: WidgetId, _runs: &[TextRun]) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability(
"set_rich_text_runs".to_owned(),
))
}
fn set_rich_text_images(
&mut self,
_widget_id: WidgetId,
_images: &[RichTextImage],
) -> GuiResult<()> {
Ok(())
}
fn set_spell_check(&mut self, _widget_id: WidgetId, _enabled: bool) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("spell_check".to_owned()))
}
fn set_monospace(&mut self, _widget_id: WidgetId, _monospace: bool) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_monospace"))
}
fn set_font(&mut self, _widget_id: WidgetId, _font: Option<&FontDescriptor>) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_font"))
}
fn set_row_icons(
&mut self,
_widget_id: WidgetId,
_icons: &[Option<IconRole>],
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_row_icons"))
}
fn create_tray_icon(&mut self, _spec: &TrayIconSpec) -> GuiResult<TrayIconId> {
Err(GuiError::UnsupportedCapability("tray_icon".to_owned()))
}
fn destroy_tray_icon(&mut self, _id: TrayIconId) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("tray_icon".to_owned()))
}
fn set_tray_icon_tooltip(&mut self, _id: TrayIconId, _tooltip: &str) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("tray_icon".to_owned()))
}
fn set_tray_icon_menu(&mut self, _id: TrayIconId, _menu: Option<MenuId>) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("tray_icon".to_owned()))
}
fn set_tray_icon_visible(&mut self, _id: TrayIconId, _visible: bool) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("tray_icon".to_owned()))
}
fn set_tray_icon_icon(
&mut self,
_id: TrayIconId,
_icon_bytes: Option<Vec<u8>>,
) -> GuiResult<()> {
Err(GuiError::UnsupportedCapability("tray_icon".to_owned()))
}
}
type WindowResizeCallback = Box<dyn FnMut(i32, i32)>;
type AutoLayoutFn<B> = fn(&mut Ui<B>, WidgetId, f32, f32) -> GuiResult<()>;
pub const MIN_TABS_HEIGHT: f32 = 30.0;
pub struct Ui<B: Backend> {
backend: B,
widgets: HashMap<WidgetId, WidgetSpec>,
children_index: HashMap<WidgetId, Vec<WidgetId>>,
layout_dirty: std::collections::HashSet<WidgetId>,
layout_geometry_overridden: bool,
keyed_rows: HashMap<WidgetId, Vec<RowSet>>,
keyed_selection: HashMap<WidgetId, Vec<RowKey>>,
menus: HashMap<MenuId, Vec<MenuItemId>>,
menu_item_to_menu: HashMap<MenuItemId, MenuId>,
menu_parents: HashMap<MenuId, MenuId>,
submenu_slots: HashMap<MenuId, MenuItemId>,
next_id: u64,
next_menu_id: u64,
next_menu_item_id: u64,
next_dialog_token: u64,
next_tray_icon_id: u64,
next_timer_id: u64,
next_motion_id: u64,
next_image_resource_id: u64,
image_resources: HashMap<ImageResourceId, usize>,
image_resource_bytes: usize,
motions: HashMap<MotionId, ActiveMotion>,
motion_timers: HashMap<TimerId, MotionId>,
tray_icons: HashMap<TrayIconId, TrayIconSpec>,
on_window_close: HashMap<WidgetId, Vec<Box<dyn FnMut()>>>,
on_window_resize: HashMap<WidgetId, Vec<WindowResizeCallback>>,
on_menu_item_selected: HashMap<MenuItemId, Vec<Box<dyn FnMut()>>>,
clipboard: Option<String>,
focused: Option<WidgetId>,
theme: Theme,
theme_overrides: HashMap<WidgetId, Vec<ThemeOverride>>,
layout_roots: HashSet<WidgetId>,
hidden_widgets: HashSet<WidgetId>,
layout_root_sizes: HashMap<WidgetId, (f32, f32)>,
min_sizes: HashMap<WidgetId, (i32, i32)>,
data_grid_columns: HashMap<WidgetId, Vec<ColumnSpec>>,
data_grid_data: HashMap<WidgetId, Vec<Vec<String>>>,
preferred_widths: HashMap<WidgetId, u32>,
window_min_sizes: HashMap<WidgetId, (u32, u32)>,
window_resizable: HashMap<WidgetId, bool>,
window_options: HashMap<WidgetId, WindowOptions>,
drag_sources: HashMap<WidgetId, DragSourceOptions>,
drag_targets: HashMap<WidgetId, DragTargetOptions>,
gpu_degraded: HashMap<WidgetId, GpuDegradationPolicy>,
gpu_degradation_policy: GpuDegradationPolicy,
pub layout_tree: LayoutTree,
pub layout_nodes: std::collections::HashMap<WidgetId, LayoutNodeId>,
auto_layout_fn: Option<AutoLayoutFn<B>>,
pending_events: VecDeque<UiEvent>,
#[cfg(feature = "async")]
task_channel: Option<(UiProxy, std::sync::mpsc::Receiver<TaskCommand>)>,
#[cfg(feature = "async")]
#[allow(clippy::type_complexity)]
task_completions: Option<(
std::sync::mpsc::Sender<(crate::async_ui::TaskId, Box<dyn std::any::Any + Send>)>,
std::sync::mpsc::Receiver<(crate::async_ui::TaskId, Box<dyn std::any::Any + Send>)>,
)>,
#[cfg(feature = "async")]
#[allow(clippy::type_complexity)]
task_callbacks: std::collections::HashMap<
crate::async_ui::TaskId,
Box<dyn FnOnce(&mut Ui<B>, Box<dyn std::any::Any + Send>) -> GuiResult<()>>,
>,
#[cfg(feature = "async")]
task_handles: std::collections::HashMap<crate::async_ui::TaskId, crate::async_ui::TaskHandle>,
#[cfg(any(feature = "property-grid", feature = "webview"))]
pub(crate) next_operation_id: u64,
pub(crate) pending_operations: std::collections::HashSet<crate::advanced::OperationId>,
#[cfg(feature = "property-grid")]
pub(crate) property_grids: crate::property_grid::PropertyGridRegistry,
#[cfg(feature = "styled-text")]
pub(crate) styled_texts: crate::styled_text::StyledTextRegistry,
#[cfg(feature = "webview")]
pub(crate) webviews: crate::webview::WebViewRegistry,
}
impl<B: Backend> Ui<B> {
pub fn new(backend: B) -> Self {
Self {
backend,
widgets: HashMap::new(),
children_index: HashMap::new(),
layout_dirty: std::collections::HashSet::new(),
layout_geometry_overridden: false,
keyed_rows: HashMap::new(),
keyed_selection: HashMap::new(),
menus: HashMap::new(),
menu_item_to_menu: HashMap::new(),
menu_parents: HashMap::new(),
submenu_slots: HashMap::new(),
next_id: 1,
next_menu_id: 1,
next_menu_item_id: 1,
next_dialog_token: 1,
next_tray_icon_id: 1,
next_timer_id: 1,
next_motion_id: 1,
next_image_resource_id: 1,
image_resources: HashMap::new(),
image_resource_bytes: 0,
motions: HashMap::new(),
motion_timers: HashMap::new(),
tray_icons: HashMap::new(),
on_window_close: HashMap::new(),
on_window_resize: HashMap::new(),
layout_roots: HashSet::new(),
hidden_widgets: HashSet::new(),
min_sizes: HashMap::new(),
data_grid_columns: HashMap::new(),
data_grid_data: HashMap::new(),
preferred_widths: HashMap::new(),
window_min_sizes: HashMap::new(),
window_resizable: HashMap::new(),
window_options: HashMap::new(),
drag_sources: HashMap::new(),
drag_targets: HashMap::new(),
layout_root_sizes: HashMap::new(),
gpu_degraded: HashMap::new(),
gpu_degradation_policy: GpuDegradationPolicy::StrictFail,
on_menu_item_selected: HashMap::new(),
clipboard: None,
focused: None,
theme: Theme::light(),
theme_overrides: HashMap::new(),
layout_tree: LayoutTree::new(),
layout_nodes: std::collections::HashMap::new(),
auto_layout_fn: None,
pending_events: VecDeque::new(),
#[cfg(any(feature = "property-grid", feature = "webview"))]
next_operation_id: 1,
pending_operations: std::collections::HashSet::new(),
#[cfg(feature = "property-grid")]
property_grids: Default::default(),
#[cfg(feature = "styled-text")]
styled_texts: Default::default(),
#[cfg(feature = "webview")]
webviews: Default::default(),
#[cfg(feature = "async")]
task_channel: None,
#[cfg(feature = "async")]
task_completions: None,
#[cfg(feature = "async")]
task_callbacks: std::collections::HashMap::new(),
#[cfg(feature = "async")]
task_handles: std::collections::HashMap::new(),
}
}
pub fn backend(&self) -> &B {
&self.backend
}
pub fn backend_mut(&mut self) -> &mut B {
&mut self.backend
}
pub fn into_backend(self) -> B {
self.backend
}
pub fn create_with(
&mut self,
kind: WidgetKind,
configure: impl FnOnce(&mut WidgetSpec),
) -> GuiResult<WidgetId> {
let id = WidgetId(self.next_id);
self.next_id += 1;
let mut spec = WidgetSpec::new(id, kind);
configure(&mut spec);
spec.id = id;
if let Some(ref text) = spec.text {
Self::reject_embedded_nul(text)?;
}
if let Some(ref placeholder) = spec.placeholder_text {
Self::reject_embedded_nul(placeholder)?;
}
if let Some(ref tooltip) = spec.tooltip {
Self::reject_embedded_nul(tooltip)?;
}
if let Some(ref source) = spec.image_source {
Self::reject_embedded_nul(source)?;
}
let configured_parent = spec.parent;
if let Some(parent) = configured_parent {
if !self.widgets.contains_key(&parent) {
return Err(GuiError::WidgetNotFound(parent.0));
}
if self.widget_depth(parent) + 1 >= crate::layout::box_sizing::MAX_LAYOUT_DEPTH {
return Err(GuiError::Backend(
"maximum layout recursion depth exceeded".to_string(),
));
}
}
let (is_gpu_canvas, capability_name) = match spec.kind {
#[cfg(feature = "widgets-canvas")]
WidgetKind::VulkanCanvas => (true, "vulkan_surface"),
#[cfg(feature = "widgets-canvas")]
WidgetKind::MetalCanvas => (true, "metal_surface"),
_ => (false, ""),
};
let gpu_capabilities = if is_gpu_canvas {
self.backend.gpu_surface_capabilities()
} else {
GpuSurfaceCapabilities::none()
};
let gpu_degraded = match spec.kind {
#[cfg(feature = "widgets-canvas")]
WidgetKind::VulkanCanvas => !gpu_capabilities.vulkan_surface,
#[cfg(feature = "widgets-canvas")]
WidgetKind::MetalCanvas => !gpu_capabilities.metal_surface,
_ => false,
};
if gpu_degraded {
match self.gpu_degradation_policy {
GpuDegradationPolicy::StrictFail => {
return Err(GuiError::UnsupportedCapability(capability_name.to_owned()));
}
policy => {
if !gpu_capabilities.supports("gpu_degradation_fallback") {
return Err(GuiError::UnsupportedCapability(
"gpu_degradation_fallback".to_owned(),
));
}
self.backend.create_gpu_fallback(&spec, policy)?;
self.gpu_degraded.insert(id, policy);
}
}
} else {
self.backend.create_widget(&spec)?;
}
let container_direction = spec.container_direction;
let container_wrap = spec.container_wrap;
self.widgets.insert(id, spec);
let mut owned_style = crate::layout::Style::default();
let direction = container_direction.or(match kind {
WidgetKind::Container => Some(ContainerDirection::Vertical),
#[cfg(feature = "widgets-containers")]
WidgetKind::GroupBox => Some(ContainerDirection::Vertical),
_ => None,
});
if let Some(direction) = direction {
owned_style.flex_direction = match direction {
ContainerDirection::Horizontal => crate::layout::FlexDirection::Row,
ContainerDirection::Vertical => crate::layout::FlexDirection::Column,
};
}
if let Some(wrap) = container_wrap {
owned_style.flex_wrap = match wrap {
ContainerWrap::NoWrap => crate::layout::FlexWrap::NoWrap,
ContainerWrap::Wrap => crate::layout::FlexWrap::Wrap,
ContainerWrap::WrapReverse => crate::layout::FlexWrap::WrapReverse,
};
}
#[cfg(feature = "widgets-containers")]
let is_stretch_container = matches!(
kind,
WidgetKind::Container | WidgetKind::Window | WidgetKind::SplitPane | WidgetKind::Tabs
);
#[cfg(not(feature = "widgets-containers"))]
let is_stretch_container = matches!(kind, WidgetKind::Container | WidgetKind::Window);
if is_stretch_container {
owned_style.align_items = Some(crate::layout::AlignItems::Stretch);
}
let is_intrinsic_leaf = match kind {
WidgetKind::Button => true,
#[cfg(feature = "widgets-pickers")]
WidgetKind::DatePicker => true,
#[cfg(feature = "widgets-choice")]
WidgetKind::Checkbox | WidgetKind::RadioButton => true,
#[cfg(feature = "widgets-range")]
WidgetKind::SpinBox => true,
_ => false,
};
if is_intrinsic_leaf {
owned_style.align_self = Some(crate::layout::AlignSelf::Start);
}
if self.hidden_widgets.contains(&id) {
owned_style.display = crate::layout::Display::None;
}
#[cfg(feature = "widgets-containers")]
if kind == WidgetKind::Tabs {
let min_tabs_h = self.min_tabs_height(id);
owned_style.min_size.height = crate::layout::Dimension::length(min_tabs_h);
}
let owned_node = self.layout_tree.create_node(owned_style);
self.layout_nodes.insert(id, owned_node);
if let Some(parent) = configured_parent {
if let Err(error) = self.backend.add_child(parent, id) {
self.discard_failed_create(id);
return Err(error);
}
self.record_parent_edge(parent, id);
}
if let Some((width, height)) = self.widgets.get(&id).and_then(|spec| spec.size) {
self.sync_layout_size(id, width, height);
}
self.invalidate_layout(id);
Ok(id)
}
pub fn create(&mut self, kind: WidgetKind, text: Option<&str>) -> GuiResult<WidgetId> {
self.create_with(kind, |spec| {
if let Some(value) = text {
spec.text = Some(value.to_owned());
}
})
}
pub fn create_menu(&mut self) -> GuiResult<MenuId> {
let menu_id = MenuId(self.next_menu_id);
self.next_menu_id += 1;
self.backend.create_menu(menu_id)?;
self.menus.insert(menu_id, Vec::new());
Ok(menu_id)
}
pub fn add_submenu(&mut self, parent_id: MenuId, text: &str) -> GuiResult<MenuId> {
Self::reject_embedded_nul(text)?;
let submenu_id = MenuId(self.next_menu_id);
self.next_menu_id += 1;
let slot_id = MenuItemId(self.next_menu_item_id);
self.next_menu_item_id += 1;
self.backend
.add_submenu(parent_id, submenu_id, slot_id, text)?;
self.menus.insert(submenu_id, Vec::new());
self.menu_parents.insert(submenu_id, parent_id);
self.submenu_slots.insert(submenu_id, slot_id);
if let Some(items) = self.menus.get_mut(&parent_id) {
items.push(slot_id);
}
Ok(submenu_id)
}
pub fn add_menu_item(&mut self, menu_id: MenuId, text: &str) -> GuiResult<MenuItemId> {
self.add_menu_item_with_shortcut(menu_id, text, None)
}
pub fn add_menu_item_with_shortcut(
&mut self,
menu_id: MenuId,
text: &str,
shortcut: Option<&str>,
) -> GuiResult<MenuItemId> {
Self::reject_embedded_nul(text)?;
if let Some(shortcut_text) = shortcut {
Self::reject_embedded_nul(shortcut_text)?;
}
if !self.menus.contains_key(&menu_id) {
return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
}
let item_id = MenuItemId(self.next_menu_item_id);
self.next_menu_item_id += 1;
self.backend
.create_menu_item(menu_id, item_id, text, shortcut)?;
if let Some(items) = self.menus.get_mut(&menu_id) {
items.push(item_id);
}
self.menu_item_to_menu.insert(item_id, menu_id);
Ok(item_id)
}
pub fn attach_menu_to_window(&mut self, window_id: WidgetId, menu_id: MenuId) -> GuiResult<()> {
self.ensure_window(window_id, WidgetProperty::WindowCallback)?;
if !self.menus.contains_key(&menu_id) {
return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
}
self.backend.attach_menu_to_window(window_id, menu_id)
}
pub fn set_menu_item_enabled(&mut self, item_id: MenuItemId, enabled: bool) -> GuiResult<()> {
if !self.menu_item_to_menu.contains_key(&item_id) {
return Err(GuiError::Backend(format!(
"Menu item not found: {}",
item_id.0
)));
}
self.backend.set_menu_item_enabled(item_id, enabled)
}
pub fn set_menu_item_text(&mut self, item_id: MenuItemId, text: &str) -> GuiResult<()> {
Self::reject_embedded_nul(text)?;
if !self.menu_item_to_menu.contains_key(&item_id) {
return Err(GuiError::Backend(format!(
"Menu item not found: {}",
item_id.0
)));
}
self.backend.set_menu_item_text(item_id, text)
}
pub fn insert_menu_item(
&mut self,
menu_id: MenuId,
index: usize,
text: &str,
) -> GuiResult<MenuItemId> {
self.insert_menu_item_with_shortcut(menu_id, index, text, None)
}
pub fn insert_menu_item_with_shortcut(
&mut self,
menu_id: MenuId,
index: usize,
text: &str,
shortcut: Option<&str>,
) -> GuiResult<MenuItemId> {
Self::reject_embedded_nul(text)?;
if let Some(shortcut_text) = shortcut {
Self::reject_embedded_nul(shortcut_text)?;
}
if !self.menus.contains_key(&menu_id) {
return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
}
let item_id = MenuItemId(self.next_menu_item_id);
self.next_menu_item_id += 1;
let position = match self.menus.get(&menu_id) {
Some(items) => index.min(items.len()),
None => index,
};
self.backend
.insert_menu_item(menu_id, item_id, position, text, shortcut)?;
if let Some(items) = self.menus.get_mut(&menu_id) {
items.insert(position, item_id);
}
self.menu_item_to_menu.insert(item_id, menu_id);
Ok(item_id)
}
pub fn remove_menu_item(&mut self, item_id: MenuItemId) -> GuiResult<()> {
let Some(menu_id) = self.menu_item_to_menu.get(&item_id).copied() else {
return Err(GuiError::Backend(format!(
"Menu item not found: {}",
item_id.0
)));
};
self.backend.remove_menu_item(item_id)?;
if let Some(items) = self.menus.get_mut(&menu_id) {
items.retain(|item| *item != item_id);
}
self.menu_item_to_menu.remove(&item_id);
self.on_menu_item_selected.remove(&item_id);
Ok(())
}
pub fn remove_submenu(&mut self, submenu_id: MenuId) -> GuiResult<()> {
let Some(parent_id) = self.menu_parents.get(&submenu_id).copied() else {
return Err(GuiError::Backend(format!(
"Submenu not found: {}",
submenu_id.0
)));
};
self.backend.remove_submenu(submenu_id)?;
if let Some(slot) = self.submenu_slots.remove(&submenu_id) {
if let Some(items) = self.menus.get_mut(&parent_id) {
items.retain(|item| *item != slot);
}
}
let mut detached = vec![submenu_id];
let mut index = 0;
while index < detached.len() {
let current = detached[index];
index += 1;
for (child, parent) in &self.menu_parents {
if *parent == current {
detached.push(*child);
}
}
}
for menu_id in detached {
self.menu_parents.remove(&menu_id);
for item in self.menus.remove(&menu_id).unwrap_or_default() {
self.menu_item_to_menu.remove(&item);
self.on_menu_item_selected.remove(&item);
}
}
Ok(())
}
pub fn attach_context_menu(&mut self, widget_id: WidgetId, menu_id: MenuId) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
if !self.menus.contains_key(&menu_id) {
return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
}
self.backend.attach_context_menu(widget_id, menu_id)
}
pub fn create_tray_icon(&mut self, tooltip: &str) -> GuiResult<TrayIconId> {
self.create_tray_icon_with_icon_bytes(tooltip, None)
}
pub fn create_tray_icon_with_icon(
&mut self,
tooltip: &str,
icon_bytes: Vec<u8>,
) -> GuiResult<TrayIconId> {
self.create_tray_icon_with_icon_bytes(tooltip, Some(icon_bytes))
}
fn create_tray_icon_with_icon_bytes(
&mut self,
tooltip: &str,
icon_bytes: Option<Vec<u8>>,
) -> GuiResult<TrayIconId> {
Self::reject_embedded_nul(tooltip)?;
let id = TrayIconId(self.next_tray_icon_id);
self.next_tray_icon_id += 1;
let mut spec = TrayIconSpec::new(id, tooltip);
spec.icon_bytes = icon_bytes;
self.backend.create_tray_icon(&spec)?;
self.tray_icons.insert(id, spec);
Ok(id)
}
pub fn destroy_tray_icon(&mut self, id: TrayIconId) -> GuiResult<()> {
self.backend.destroy_tray_icon(id)?;
self.tray_icons.remove(&id);
Ok(())
}
pub fn set_tray_icon_tooltip(&mut self, id: TrayIconId, tooltip: &str) -> GuiResult<()> {
Self::reject_embedded_nul(tooltip)?;
self.backend.set_tray_icon_tooltip(id, tooltip)?;
if let Some(spec) = self.tray_icons.get_mut(&id) {
spec.tooltip = tooltip.to_owned();
}
Ok(())
}
pub fn set_tray_icon_menu(&mut self, id: TrayIconId, menu: Option<MenuId>) -> GuiResult<()> {
if let Some(menu_id) = menu {
if !self.menus.contains_key(&menu_id) {
return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
}
}
self.backend.set_tray_icon_menu(id, menu)?;
if let Some(spec) = self.tray_icons.get_mut(&id) {
spec.menu = menu;
}
Ok(())
}
pub fn set_tray_icon_visible(&mut self, id: TrayIconId, visible: bool) -> GuiResult<()> {
self.backend.set_tray_icon_visible(id, visible)?;
if let Some(spec) = self.tray_icons.get_mut(&id) {
spec.visible = visible;
}
Ok(())
}
pub fn set_tray_icon_icon(
&mut self,
id: TrayIconId,
icon_bytes: Option<Vec<u8>>,
) -> GuiResult<()> {
self.backend.set_tray_icon_icon(id, icon_bytes.clone())?;
if let Some(spec) = self.tray_icons.get_mut(&id) {
spec.icon_bytes = icon_bytes;
}
Ok(())
}
pub fn tray_icon(&self, id: TrayIconId) -> Option<&TrayIconSpec> {
self.tray_icons.get(&id)
}
pub fn tray_icons(&self) -> &HashMap<TrayIconId, TrayIconSpec> {
&self.tray_icons
}
pub fn show_confirm_dialog(&mut self, title: &str, message: &str) -> GuiResult<u64> {
Self::reject_embedded_nul(title)?;
Self::reject_embedded_nul(message)?;
let announcement_target = self
.focused
.filter(|widget_id| self.widgets.contains_key(widget_id))
.or_else(|| {
self.widgets
.iter()
.find(|(_, spec)| spec.kind == WidgetKind::Window)
.map(|(widget_id, _)| *widget_id)
});
if let Some(widget_id) = announcement_target {
self.backend.post_accessible_notification(
widget_id,
AccessibleNotification::Announcement(format!("{title}. {message}")),
)?;
}
let token = self.next_dialog_token;
self.next_dialog_token = self.next_dialog_token.saturating_add(1);
self.backend.show_confirm_dialog(token, title, message)?;
Ok(token)
}
pub fn show_file_dialog(&mut self, request: crate::file_dialog::FileDialog) -> GuiResult<u64> {
request.validate()?;
let token = self.next_dialog_token;
self.backend.show_file_dialog(token, &request)?;
self.next_dialog_token = self.next_dialog_token.saturating_add(1);
Ok(token)
}
pub fn native_window_handle(
&self,
window_id: WidgetId,
) -> GuiResult<crate::window_handle::NativeWindowHandle> {
let spec = self
.widgets
.get(&window_id)
.ok_or(GuiError::WidgetNotFound(window_id.0))?;
if spec.kind != WidgetKind::Window {
return Err(GuiError::UnsupportedWidget("native_window_handle"));
}
self.backend.native_window_handle(window_id)
}
#[cfg(feature = "raw-window-handle")]
pub fn window_handle(
&self,
window_id: WidgetId,
) -> GuiResult<crate::window_handle::UiWindowHandle<'_>> {
self.native_window_handle(window_id)
.map(crate::window_handle::UiWindowHandle::new)
}
pub fn set_close_guard(&mut self, widget_id: WidgetId, guarded: bool) -> GuiResult<()> {
self.require_property(widget_id, WidgetProperty::CloseGuard)?;
self.backend.set_close_guard(widget_id, guarded)
}
pub fn timer_capabilities(&self) -> TimerCapabilities {
self.backend.timer_capabilities()
}
pub fn motion_capabilities(&self) -> MotionCapabilities {
self.backend.motion_capabilities()
}
pub fn start_motion(&mut self, widget_id: WidgetId, spec: MotionSpec) -> GuiResult<MotionId> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
spec.validate()?;
if !self.backend.motion_capabilities().motions {
return Err(GuiError::UnsupportedCapability("ui_motion".to_owned()));
}
let timer_capabilities = self.backend.timer_capabilities();
if !timer_capabilities.timers {
return Err(GuiError::UnsupportedCapability("ui_timer".to_owned()));
}
if !timer_capabilities.widget_timers {
return Err(GuiError::UnsupportedCapability("widget_timer".to_owned()));
}
let motion = MotionId(self.next_motion_id);
let next_motion_id =
self.next_motion_id
.checked_add(1)
.ok_or(GuiError::ResourceExhausted {
operation: "motion id allocation",
code: None,
})?;
let timer = self.allocate_timer_id()?;
self.backend.start_widget_timer(
timer,
widget_id,
TimerSpec {
first_delay: spec.duration.min(MOTION_TICK_CADENCE),
interval: Some(MOTION_TICK_CADENCE),
coalesce: true,
},
TimerStopPolicy::Remove,
)?;
self.next_motion_id = next_motion_id;
self.motions.insert(
motion,
ActiveMotion {
timer,
widget_id,
spec,
},
);
self.motion_timers.insert(timer, motion);
Ok(motion)
}
pub fn cancel_motion(&mut self, motion: MotionId) -> GuiResult<()> {
let active = self
.motions
.get(&motion)
.copied()
.ok_or_else(|| GuiError::Backend(format!("Motion not found: {}", motion.0)))?;
self.backend.cancel_timer(active.timer)?;
self.motions.remove(&motion);
self.motion_timers.remove(&active.timer);
self.purge_motion_events(motion, active.timer);
Ok(())
}
pub fn start_timer(&mut self, spec: TimerSpec) -> GuiResult<TimerId> {
spec.validate()?;
if !self.backend.timer_capabilities().timers {
return Err(GuiError::UnsupportedCapability("ui_timer".to_owned()));
}
let timer = self.allocate_timer_id()?;
self.backend.start_timer(timer, spec)?;
Ok(timer)
}
pub fn start_widget_timer(
&mut self,
widget_id: WidgetId,
spec: TimerSpec,
stop_policy: TimerStopPolicy,
) -> GuiResult<TimerId> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
spec.validate()?;
let capabilities = self.backend.timer_capabilities();
if !capabilities.timers {
return Err(GuiError::UnsupportedCapability("ui_timer".to_owned()));
}
if !capabilities.widget_timers {
return Err(GuiError::UnsupportedCapability("widget_timer".to_owned()));
}
let timer = self.allocate_timer_id()?;
self.backend
.start_widget_timer(timer, widget_id, spec, stop_policy)?;
Ok(timer)
}
pub fn cancel_timer(&mut self, timer: TimerId) -> GuiResult<()> {
self.backend.cancel_timer(timer)
}
fn allocate_timer_id(&mut self) -> GuiResult<TimerId> {
let timer = TimerId(self.next_timer_id);
self.next_timer_id =
self.next_timer_id
.checked_add(1)
.ok_or(GuiError::ResourceExhausted {
operation: "timer id allocation",
code: None,
})?;
Ok(timer)
}
pub fn window_capabilities(&self) -> WindowCapabilities {
self.backend.window_capabilities()
}
pub fn set_window_options(
&mut self,
widget_id: WidgetId,
options: WindowOptions,
) -> GuiResult<()> {
let spec = self
.widgets
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if spec.kind != WidgetKind::Window {
return Err(GuiError::UnsupportedWidget("set_window_options"));
}
self.validate_window_options(widget_id, &options)?;
self.backend.set_window_options(widget_id, &options)?;
self.window_options.insert(widget_id, options);
Ok(())
}
pub fn window_options(&self, widget_id: WidgetId) -> GuiResult<WindowOptions> {
let spec = self
.widgets
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if spec.kind != WidgetKind::Window {
return Err(GuiError::UnsupportedWidget("window_options"));
}
Ok(self
.window_options
.get(&widget_id)
.copied()
.unwrap_or_default())
}
pub fn dismiss_popup(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let spec = self
.widgets
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if spec.kind != WidgetKind::Window {
return Err(GuiError::UnsupportedWidget("dismiss_popup"));
}
if self
.window_options
.get(&widget_id)
.is_none_or(|options| options.role != WindowRole::Popup)
{
return Err(GuiError::Backend(format!(
"Widget {} is not a popup window",
widget_id.0
)));
}
if !self.backend.window_capabilities().anchored_popups {
return Err(GuiError::UnsupportedCapability("window_popup".to_owned()));
}
self.backend.dismiss_popup(widget_id)?;
self.hidden_widgets.insert(widget_id);
Ok(())
}
fn validate_window_options(
&self,
widget_id: WidgetId,
options: &WindowOptions,
) -> GuiResult<()> {
if !options.opacity.is_finite() || !(0.0..=1.0).contains(&options.opacity) {
return Err(GuiError::Backend(
"Window opacity must be finite and between 0.0 and 1.0".to_owned(),
));
}
if let WindowShape::Rounded { radius } = options.shape {
if radius <= 0 {
return Err(GuiError::Backend(
"Rounded window radius must be positive".to_owned(),
));
}
}
if let WindowPlacement::Anchored {
widget_id: anchor, ..
} = options.placement
{
if !self.widgets.contains_key(&anchor) {
return Err(GuiError::WidgetNotFound(anchor.0));
}
if anchor == widget_id {
return Err(GuiError::Backend(
"A window cannot be anchored to itself".to_owned(),
));
}
}
if let Some(owner) = options.transient_for {
let owner_spec = self
.widgets
.get(&owner)
.ok_or(GuiError::WidgetNotFound(owner.0))?;
if owner == widget_id || owner_spec.kind != WidgetKind::Window {
return Err(GuiError::UnsupportedWidget("window_transient"));
}
let mut cursor = Some(owner);
while let Some(current) = cursor {
if current == widget_id {
return Err(GuiError::Backend(
"Transient window ownership cannot form a cycle".to_owned(),
));
}
cursor = self
.window_options
.get(¤t)
.and_then(|parent| parent.transient_for);
}
}
let capabilities = self.backend.window_capabilities();
if options.role == WindowRole::Popup && !capabilities.anchored_popups {
return Err(GuiError::UnsupportedCapability("window_popup".to_owned()));
}
if options.role == WindowRole::Splash
&& (!capabilities.undecorated
|| !capabilities.always_on_top
|| options.decorations
|| options.stacking != Stacking::AlwaysOnTop
|| options.focus != WindowFocusPolicy::NoTake)
{
return Err(GuiError::UnsupportedCapability("window_splash".to_owned()));
}
if options.dismiss_on_focus_loss && !capabilities.popup_focus_dismissal {
return Err(GuiError::UnsupportedCapability(
"window_popup_focus_dismiss".to_owned(),
));
}
if options.transient_for.is_some() && !capabilities.transient_ownership {
return Err(GuiError::UnsupportedCapability(
"window_transient".to_owned(),
));
}
if !options.decorations && !capabilities.undecorated {
return Err(GuiError::UnsupportedCapability(
"window_undecorated".to_owned(),
));
}
if options.stacking == Stacking::AlwaysOnTop && !capabilities.always_on_top {
return Err(GuiError::UnsupportedCapability(
"window_always_on_top".to_owned(),
));
}
if options.opacity < 1.0 && !capabilities.uniform_translucency {
return Err(GuiError::UnsupportedCapability(
"window_translucent".to_owned(),
));
}
if matches!(options.shape, WindowShape::Rounded { .. }) && !capabilities.shape_rounded {
return Err(GuiError::UnsupportedCapability(
"window_shape_rounded".to_owned(),
));
}
for effect in [options.show_effect, options.hide_effect] {
match effect {
ShowEffect::None => {}
ShowEffect::Fade { .. } if !capabilities.show_fade => {
return Err(GuiError::UnsupportedCapability(
"window_show_fade".to_owned(),
));
}
ShowEffect::Slide { .. } if !capabilities.show_slide => {
return Err(GuiError::UnsupportedCapability(
"window_show_slide".to_owned(),
));
}
_ => {}
}
}
if options.role == WindowRole::Popup
&& (!matches!(options.placement, WindowPlacement::Anchored { .. })
|| options.transient_for.is_none())
{
return Err(GuiError::Backend(
"Popup windows require an anchor and a transient owner".to_owned(),
));
}
if options.dismiss_on_focus_loss && options.role != WindowRole::Popup {
return Err(GuiError::Backend(
"Focus-loss dismissal is only valid for popup windows".to_owned(),
));
}
Ok(())
}
pub fn set_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
Self::reject_embedded_nul(text)?;
let Some(spec) = self.widgets.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let previous_text = spec.text.replace(text.to_owned());
let previous_selection = spec.text_selection;
if let Some((start, end)) = spec.text_selection {
let len = text.chars().count();
spec.text_selection = Some((start.min(len), end.min(len)));
}
if let Err(error) = self.backend.set_text(widget_id, text) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.text = previous_text;
spec.text_selection = previous_selection;
}
return Err(error);
}
self.backend
.post_accessible_notification(widget_id, AccessibleNotification::TextChanged)
}
pub fn set_label_alignment(
&mut self,
widget_id: WidgetId,
alignment: LabelAlignment,
) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::LabelAlignment)?;
self.backend.set_label_alignment(widget_id, alignment)?;
self.widgets
.get_mut(&widget_id)
.expect("widget spec remains present during setter")
.label_alignment = alignment;
Ok(())
}
pub fn set_label_wrap(&mut self, widget_id: WidgetId, wrap: LabelWrap) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::LabelWrap)?;
self.backend.set_label_wrap(widget_id, wrap)?;
self.widgets
.get_mut(&widget_id)
.expect("widget spec remains present during setter")
.label_wrap = wrap;
Ok(())
}
pub fn text_selection(&self, widget_id: WidgetId) -> GuiResult<(usize, usize)> {
let spec = self
.widgets
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
spec.ensure_property(WidgetProperty::TextSelection)?;
self.backend.text_selection(widget_id)
}
pub fn set_text_selection(
&mut self,
widget_id: WidgetId,
start: usize,
end: usize,
) -> GuiResult<()> {
if start > end {
return Err(GuiError::Backend(
"Text selection start must be <= end".to_owned(),
));
}
self.require_property(widget_id, WidgetProperty::TextSelection)?;
self.backend.set_text_selection(widget_id, start, end)?;
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.text_selection = Some((start, end));
}
Ok(())
}
pub fn set_text_completion_items(
&mut self,
widget_id: WidgetId,
items: &[String],
) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::TextCompletion)?;
self.backend.set_text_completion_items(widget_id, items)?;
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.completion_items = items.to_vec();
}
Ok(())
}
pub fn set_placeholder_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
Self::reject_embedded_nul(text)?;
let spec = self.require_property(widget_id, WidgetProperty::PlaceholderText)?;
let previous = spec.placeholder_text.clone();
spec.placeholder_text = if text.is_empty() {
None
} else {
Some(text.to_owned())
};
if let Err(error) = self.backend.set_placeholder_text(widget_id, text) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.placeholder_text = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_monospace(&mut self, widget_id: WidgetId, monospace: bool) -> GuiResult<()> {
self.require_property(widget_id, WidgetProperty::Monospace)?;
self.backend.set_monospace(widget_id, monospace)?;
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.monospace = monospace;
}
Ok(())
}
pub fn set_font(
&mut self,
widget_id: WidgetId,
font: Option<&FontDescriptor>,
) -> GuiResult<()> {
self.require_property(widget_id, WidgetProperty::Font)?;
if let Some(descriptor) = font {
descriptor
.validate()
.map_err(|error| GuiError::Backend(error.to_string()))?;
}
let previous = self
.widgets
.get(&widget_id)
.and_then(|spec| spec.font.clone());
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.font = font.cloned();
}
if let Err(error) = self.backend.set_font(widget_id, font) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.font = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_row_icons(
&mut self,
widget_id: WidgetId,
icons: &[Option<IconRole>],
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::RowIcons)?;
let previous = std::mem::replace(&mut spec.row_icons, icons.to_vec());
if let Err(error) = self.backend.set_row_icons(widget_id, icons) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.row_icons = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_spell_check(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
let Some(spec) = self.widgets.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
#[cfg(feature = "widgets-text")]
let is_text = matches!(spec.kind, WidgetKind::TextArea | WidgetKind::RichText);
#[cfg(not(feature = "widgets-text"))]
let is_text = {
let _ = spec;
false
};
if !is_text {
return Err(GuiError::UnsupportedWidget("set_spell_check"));
}
self.backend.set_spell_check(widget_id, enabled)
}
pub fn set_rich_text_runs(&mut self, widget_id: WidgetId, runs: &[TextRun]) -> GuiResult<()> {
self.require_property(widget_id, WidgetProperty::RichTextRuns)?;
self.backend.set_rich_text_runs(widget_id, runs)?;
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.rich_text_runs = runs.to_vec();
}
Ok(())
}
pub fn set_rich_text_images(
&mut self,
widget_id: WidgetId,
images: &[RichTextImage],
) -> GuiResult<()> {
self.require_property(widget_id, WidgetProperty::RichTextImages)?;
self.backend.set_rich_text_images(widget_id, images)?;
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.rich_text_images = images.to_vec();
}
Ok(())
}
pub fn set_checked(&mut self, widget_id: WidgetId, checked: bool) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::Checked)?;
let previous = spec.checked;
spec.checked = Some(checked);
if let Err(error) = self.backend.set_checked(widget_id, checked) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.checked = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_value(&mut self, widget_id: WidgetId, value: i32) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::Value)?;
let previous = spec.value;
spec.value = Some(value);
if let Err(error) = self.backend.set_value(widget_id, value) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.value = previous;
}
return Err(error);
}
self.backend
.post_accessible_notification(widget_id, AccessibleNotification::ValueChanged)
}
pub fn set_range(&mut self, widget_id: WidgetId, min: i32, max: i32) -> GuiResult<()> {
if min > max {
return Err(GuiError::Backend(
"Widget range min must be <= max".to_owned(),
));
}
let spec = self.require_property(widget_id, WidgetProperty::Range)?;
let previous = spec.range;
spec.range = Some((min, max));
if let Err(error) = self.backend.set_range(widget_id, min, max) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.range = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_step(&mut self, widget_id: WidgetId, step: i32) -> GuiResult<()> {
if step <= 0 {
return Err(GuiError::Backend("Widget step must be positive".to_owned()));
}
let spec = self.require_property(widget_id, WidgetProperty::Step)?;
let previous = spec.step;
spec.step = Some(step);
if let Err(error) = self.backend.set_step(widget_id, step) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.step = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_selected_index(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::SelectedIndex)?;
let previous = spec.selected_index;
spec.selected_index = Some(index);
if let Err(error) = self.backend.set_selected_index(widget_id, index) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.selected_index = previous;
}
return Err(error);
}
self.record_keyed_selection(widget_id, &[index]);
Ok(())
}
pub fn set_tab_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
for item in items {
Self::reject_embedded_nul(item)?;
}
let spec = self.require_property(widget_id, WidgetProperty::TabItems)?;
let previous = spec.tab_items.clone();
spec.tab_items = items.to_vec();
self.invalidate_layout(widget_id);
if let Err(error) = self.backend.set_tab_items(widget_id, items) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.tab_items = previous;
}
return Err(error);
}
Ok(())
}
pub fn min_tabs_height(&self, widget_id: WidgetId) -> f32 {
self.backend
.natural_size(widget_id)
.map(|(_, h)| h as f32)
.filter(|h| *h > 0.0)
.unwrap_or(MIN_TABS_HEIGHT)
}
pub fn tabs_min_height(&self, widget_id: WidgetId) -> f32 {
self.min_tabs_height(widget_id)
}
pub fn set_selected_indices(
&mut self,
widget_id: WidgetId,
indices: &[usize],
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::SelectedIndices)?;
let previous = spec.selected_indices.clone();
spec.selected_indices = indices.to_vec();
if let Err(error) = self.backend.set_selected_indices(widget_id, indices) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.selected_indices = previous;
}
return Err(error);
}
self.record_keyed_selection(widget_id, indices);
Ok(())
}
pub fn set_row_drag(
&mut self,
widget_id: WidgetId,
source: bool,
target: bool,
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::RowDrag)?;
let previous_source = spec.row_drag_source;
let previous_target = spec.row_drop_target;
spec.row_drag_source = source;
spec.row_drop_target = target;
if let Err(error) = self.backend.set_row_drag(widget_id, source, target) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.row_drag_source = previous_source;
spec.row_drop_target = previous_target;
}
return Err(error);
}
Ok(())
}
pub fn set_drag_source(
&mut self,
widget_id: WidgetId,
mut options: DragSourceOptions,
) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
options.kinds = normalize_kinds(options.kinds)?;
let capabilities = self.backend.drag_capabilities();
for kind in &options.kinds {
if !capabilities.supports_kind(kind) {
let identifier = match kind {
DragPayloadKind::Text => "drag_text",
DragPayloadKind::Custom { .. } => "drag_custom_mime",
};
return Err(GuiError::UnsupportedCapability(identifier.to_owned()));
}
}
self.backend.set_drag_source_options(widget_id, &options)?;
self.drag_sources.insert(widget_id, options);
Ok(())
}
pub fn set_drag_target_options(
&mut self,
widget_id: WidgetId,
mut options: DragTargetOptions,
) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
options.kinds = normalize_kinds(options.kinds)?;
let capabilities = self.backend.drag_capabilities();
for kind in &options.kinds {
if !capabilities.supports_kind(kind) {
let identifier = match kind {
DragPayloadKind::Text => "drag_text",
DragPayloadKind::Custom { .. } => "drag_custom_mime",
};
return Err(GuiError::UnsupportedCapability(identifier.to_owned()));
}
}
if options.effect != DropEffect::None && !capabilities.drop_feedback {
return Err(GuiError::UnsupportedCapability("drop_feedback".to_owned()));
}
self.backend.set_drag_target_options(widget_id, &options)?;
self.drag_targets.insert(widget_id, options);
Ok(())
}
pub fn drag_capabilities(&self) -> DragCapabilities {
self.backend.drag_capabilities()
}
pub fn set_file_drop_target(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
self.set_drop_target(widget_id, enabled)
}
pub fn set_drop_target(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.backend.set_drop_target(widget_id, enabled)?;
let spec = self
.widgets
.get_mut(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
spec.file_drop_target = enabled;
Ok(())
}
pub fn set_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
if width <= 0 || height <= 0 {
return Err(GuiError::Backend("Widget size must be positive".to_owned()));
}
let Some(spec) = self.widgets.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let previous_size = spec.size;
spec.size = Some((width, height));
if let Err(error) = self.backend.set_size(widget_id, width, height) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.size = previous_size;
}
return Err(error);
}
self.sync_layout_size(widget_id, width, height);
self.enable_auto_layout();
if self.layout_roots.contains(&widget_id) {
self.layout_root_sizes
.insert(widget_id, (width as f32, height as f32));
self.invalidate_layout(widget_id);
}
Ok(())
}
pub fn set_flex_grow(&mut self, widget_id: WidgetId, grow: f32) -> GuiResult<()> {
if !grow.is_finite() || grow < 0.0 {
return Err(GuiError::Backend(
"Flex grow must be a finite, non-negative number".to_owned(),
));
}
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.enable_auto_layout();
if let Some(&lnode) = self.layout_nodes.get(&widget_id) {
if let Ok(mut lstyle) = self.layout_tree.style(lnode).cloned() {
if lstyle.flex_grow != grow {
lstyle.flex_grow = grow;
let _ = self.layout_tree.set_style(lnode, lstyle);
self.invalidate_layout(widget_id);
}
}
}
Ok(())
}
pub fn flex_grow(&self, widget_id: WidgetId) -> GuiResult<f32> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
let node = self
.layout_nodes
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
self.layout_tree.style(*node).map(|style| style.flex_grow)
}
pub fn set_min_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
if width < 0 || height < 0 {
return Err(GuiError::Backend(
"Minimum size must not be negative".to_owned(),
));
}
if !self.widgets.contains_key(&widget_id) || !self.layout_nodes.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.enable_auto_layout();
self.backend.set_min_size(widget_id, width, height)?;
let previous = if width == 0 && height == 0 {
self.min_sizes.remove(&widget_id)
} else {
self.min_sizes.insert(widget_id, (width, height))
};
if previous.unwrap_or((0, 0)) != (width, height) {
self.invalidate_layout(widget_id);
}
Ok(())
}
pub fn min_size(&self, widget_id: WidgetId) -> GuiResult<(i32, i32)> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
Ok(self.min_sizes.get(&widget_id).copied().unwrap_or((0, 0)))
}
pub fn set_preferred_width(&mut self, widget_id: WidgetId, width: u32) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.enable_auto_layout();
let Some(&lnode) = self.layout_nodes.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
if let Ok(mut lstyle) = self.layout_tree.style(lnode).cloned() {
if width == 0 {
self.preferred_widths.remove(&widget_id);
lstyle.min_size.width = crate::layout::Dimension::length(0.0);
lstyle.min_size.height = crate::layout::Dimension::Auto;
} else {
self.preferred_widths.insert(widget_id, width);
lstyle.min_size.width = crate::layout::Dimension::length(width as f32);
lstyle.min_size.height = crate::layout::Dimension::Auto;
}
let _ = self.layout_tree.set_style(lnode, lstyle);
}
self.invalidate_layout(widget_id);
Ok(())
}
pub fn preferred_width(&self, widget_id: WidgetId) -> GuiResult<Option<u32>> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
Ok(self.preferred_widths.get(&widget_id).copied())
}
pub fn set_layout_style(
&mut self,
widget_id: WidgetId,
style: crate::layout::Style,
) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
let Some(&lnode) = self.layout_nodes.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
self.enable_auto_layout();
style.validate()?;
self.layout_tree.set_style(lnode, style)?;
self.invalidate_layout(widget_id);
Ok(())
}
pub fn layout_style(&self, widget_id: WidgetId) -> GuiResult<crate::layout::Style> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
let Some(&node) = self.layout_nodes.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
self.layout_tree.style(node).cloned()
}
pub fn layout_rect(&self, widget_id: WidgetId) -> GuiResult<crate::layout::LayoutRect> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
let Some(&node) = self.layout_nodes.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let rect = self.layout_tree.layout(node)?;
self.parent_local_layout_rect(widget_id, rect)
}
pub fn debug_layout(&self, root: WidgetId) -> GuiResult<String> {
use std::fmt::Write as _;
if !self.widgets.contains_key(&root) {
return Err(GuiError::WidgetNotFound(root.0));
}
let mut out = String::new();
let mut stack = vec![(root, 0usize)];
while let Some((id, depth)) = stack.pop() {
let Some(spec) = self.widgets.get(&id) else {
continue;
};
let _ = write!(
out,
"{:indent$}#{} {:?}",
"",
id.0,
spec.kind,
indent = depth * 2
);
if let Some(text) = spec.text.as_deref().filter(|text| !text.is_empty()) {
let short: String = text.chars().take(32).collect();
let ellipsis = if text.chars().count() > 32 { "…" } else { "" };
let _ = write!(out, " {short:?}{ellipsis}");
}
match self.layout_rect(id) {
Ok(rect) => {
let _ = write!(
out,
" @({}, {}) {}x{}",
rect.x, rect.y, rect.width, rect.height
);
if !self.is_effectively_hidden(id) && (rect.width <= 0.0 || rect.height <= 0.0)
{
out.push_str(" [ZERO-SIZE]");
}
}
Err(_) => out.push_str(" @(no layout node)"),
}
if self.is_effectively_hidden(id) {
out.push_str(" [hidden]");
}
if let Some(&node) = self.layout_nodes.get(&id) {
if let Ok(style) = self.layout_tree.style(node) {
if style.flex_grow > 0.0 {
let _ = write!(out, " grow={}", style.flex_grow);
}
}
}
if let Some((w, h)) = self.min_sizes.get(&id) {
let _ = write!(out, " min={w}x{h}");
}
out.push('\n');
if let Some(children) = self.children_index.get(&id) {
for child in children.iter().rev() {
stack.push((*child, depth + 1));
}
}
}
Ok(out)
}
fn parent_local_layout_rect(
&self,
widget_id: WidgetId,
rect: crate::layout::LayoutRect,
) -> GuiResult<crate::layout::LayoutRect> {
let spec = self
.widgets
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
let Some(parent_id) = spec.parent else {
return Ok(rect);
};
let parent_node = self
.layout_nodes
.get(&parent_id)
.ok_or(GuiError::WidgetNotFound(parent_id.0))?;
let parent_rect = self.layout_tree.layout(*parent_node)?;
Ok(crate::layout::LayoutRect::new(
rect.x - parent_rect.x,
rect.y - parent_rect.y,
rect.width,
rect.height,
))
}
pub fn set_window_min_size(
&mut self,
widget_id: WidgetId,
width: u32,
height: u32,
) -> GuiResult<()> {
let spec = self
.widgets
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if spec.kind != WidgetKind::Window {
return Err(GuiError::UnsupportedWidget("set_window_min_size"));
}
self.window_min_sizes.insert(widget_id, (width, height));
self.backend.set_window_min_size(widget_id, width, height)
}
pub fn window_min_size(&self, widget_id: WidgetId) -> GuiResult<Option<(u32, u32)>> {
let spec = self
.widgets
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if spec.kind != WidgetKind::Window {
return Err(GuiError::UnsupportedWidget("set_window_min_size"));
}
if let Some(&min) = self.window_min_sizes.get(&widget_id) {
return Ok(Some(min));
}
if self.layout_roots.contains(&widget_id) {
if let Some(children) = self.children_index.get(&widget_id) {
let mut max_min_w: u32 = 0;
let mut max_min_h: u32 = 0;
for &child in children {
let (cw, ch) = self.min_sizes.get(&child).copied().unwrap_or((0, 0));
let pw = self.preferred_widths.get(&child).copied().unwrap_or(0);
let w = (cw as u32).max(pw);
let h = ch as u32;
max_min_w = max_min_w.max(w);
max_min_h = max_min_h.max(h);
}
if max_min_w > 0 || max_min_h > 0 {
return Ok(Some((max_min_w, max_min_h)));
}
}
}
Ok(None)
}
pub fn explicit_window_min_size(&self, widget_id: WidgetId) -> GuiResult<Option<(u32, u32)>> {
let spec = self
.widgets
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if spec.kind != WidgetKind::Window {
return Err(GuiError::UnsupportedWidget("set_window_min_size"));
}
Ok(self.window_min_sizes.get(&widget_id).copied())
}
pub fn set_resizable(&mut self, widget_id: WidgetId, resizable: bool) -> GuiResult<()> {
let spec = self
.widgets
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if spec.kind != WidgetKind::Window {
return Err(GuiError::UnsupportedWidget("set_resizable"));
}
self.window_resizable.insert(widget_id, resizable);
self.backend.set_resizable(widget_id, resizable)
}
pub fn is_resizable(&self, widget_id: WidgetId) -> GuiResult<bool> {
let spec = self
.widgets
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if spec.kind != WidgetKind::Window {
return Err(GuiError::UnsupportedWidget("set_resizable"));
}
Ok(self
.window_resizable
.get(&widget_id)
.copied()
.unwrap_or(true))
}
pub fn resizable(&self, widget_id: WidgetId) -> GuiResult<bool> {
self.is_resizable(widget_id)
}
pub fn native_handle(&self, widget_id: WidgetId) -> GuiResult<B::NativeHandle> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::NativeHandle)?;
self.backend.native_handle(widget_id)
}
pub fn vulkan_canvas_handle(&self, widget_id: WidgetId) -> GuiResult<B::NativeHandle> {
self.native_handle(widget_id)
}
pub fn metal_canvas_handle(&self, widget_id: WidgetId) -> GuiResult<MetalCanvasHandle> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::MetalHandle)?;
self.backend.metal_canvas_handle(widget_id)
}
fn validate_choice_items<S: AsRef<str>>(items: &[S]) -> GuiResult<Vec<String>> {
items
.iter()
.map(|item| {
let item = item.as_ref();
if item.trim().is_empty() {
return Err(GuiError::Backend(
"choice items must not be empty".to_owned(),
));
}
if item.contains('|') || item.contains('\0') {
return Err(GuiError::Backend(format!(
"choice item {item:?} must not contain '|' or NUL"
)));
}
Ok(item.trim().to_owned())
})
.collect()
}
#[cfg(feature = "widgets-choice")]
pub fn create_combo_box<S: AsRef<str>>(&mut self, items: &[S]) -> GuiResult<WidgetId> {
let items = Self::validate_choice_items(items)?;
self.create(WidgetKind::ComboBox, Some(&items.join("|")))
}
pub fn set_items<S: AsRef<str>>(&mut self, widget_id: WidgetId, items: &[S]) -> GuiResult<()> {
#[cfg(feature = "widgets-choice")]
let kind = self.widget_spec(widget_id)?.kind;
#[cfg(not(feature = "widgets-choice"))]
let _ = self.widget_spec(widget_id)?;
#[cfg(feature = "widgets-choice")]
if kind == WidgetKind::ComboBox {
let items = Self::validate_choice_items(items)?;
self.backend.set_combo_box_items(widget_id, &items)?;
let previous = self
.widgets
.get(&widget_id)
.and_then(|spec| spec.selected_index);
let selected = match previous {
Some(index) if index < items.len() => Some(index),
_ if items.is_empty() => None,
_ => Some(0),
};
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.text = Some(items.join("|"));
spec.selected_index = selected;
}
return Ok(());
}
#[cfg(feature = "widgets-choice")]
let is_multi_select = kind == WidgetKind::MultiSelect;
#[cfg(not(feature = "widgets-choice"))]
let is_multi_select = false;
let items: Vec<String> = if is_multi_select {
Self::validate_choice_items(items)?
} else {
items.iter().map(|item| item.as_ref().to_owned()).collect()
};
self.set_data_list_items(widget_id, &items)
}
pub fn items(&self, widget_id: WidgetId) -> GuiResult<Vec<String>> {
let spec = self.widget_spec(widget_id)?;
Ok(match spec.kind {
#[cfg(feature = "widgets-choice")]
WidgetKind::ComboBox | WidgetKind::MultiSelect if spec.data_list_items.is_empty() => {
spec.text
.as_deref()
.unwrap_or("")
.split('|')
.map(str::trim)
.filter(|item| !item.is_empty())
.map(ToOwned::to_owned)
.collect()
}
_ => spec.data_list_items.clone(),
})
}
#[cfg(any(feature = "widgets-data", feature = "widgets-choice"))]
pub fn set_data_list_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::DataListItems)?;
self.backend.set_data_list_items(widget_id, items)?;
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.data_list_items = items.to_vec();
}
Ok(())
}
#[cfg(not(any(feature = "widgets-data", feature = "widgets-choice")))]
pub fn set_data_list_items(
&mut self,
_widget_id: WidgetId,
_items: &[String],
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_data_list_items"))
}
#[cfg(feature = "widgets-data")]
pub fn set_list_columns(
&mut self,
widget_id: WidgetId,
columns: &[ColumnSpec],
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ListViewColumns)?;
let previous = spec.list_columns.clone();
spec.list_columns = columns.to_vec();
if let Err(error) = self.backend.set_list_columns(widget_id, columns) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.list_columns = previous;
}
return Err(error);
}
Ok(())
}
#[cfg(not(feature = "widgets-data"))]
pub fn set_list_columns(
&mut self,
_widget_id: WidgetId,
_columns: &[ColumnSpec],
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_list_columns"))
}
#[cfg(feature = "widgets-data")]
pub fn set_list_rows(&mut self, widget_id: WidgetId, rows: &[Vec<String>]) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ListViewRows)?;
let previous = spec.list_rows.clone();
spec.list_rows = rows.to_vec();
if let Err(error) = self.backend.set_list_rows(widget_id, rows) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.list_rows = previous;
}
return Err(error);
}
Ok(())
}
#[cfg(not(feature = "widgets-data"))]
pub fn set_list_rows(&mut self, _widget_id: WidgetId, _rows: &[Vec<String>]) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_list_rows"))
}
#[cfg(feature = "widgets-data")]
pub fn set_rows_keyed(&mut self, widget_id: WidgetId, rows: &[RowSet]) -> GuiResult<RowDelta> {
let plain_selected_index = self
.require_property(widget_id, WidgetProperty::KeyedRows)?
.selected_index;
let delta = match self.keyed_rows.get(&widget_id) {
Some(previous) => diff_rows(previous, rows)?,
None => diff_rows(&[], rows)?,
};
if delta.is_noop() {
return Ok(delta);
}
let tracked_selection = self
.keyed_selection
.get(&widget_id)
.cloned()
.unwrap_or_default();
let anchor_key = match self.visible_anchor(widget_id) {
Ok(anchor) => anchor,
Err(GuiError::UnsupportedCapability(_)) => None,
Err(error) => return Err(error),
};
let (anchor_old_index, selection_keys) = {
let previous = self.keyed_rows.get(&widget_id);
let anchor_old_index = anchor_key.and_then(|key| {
previous.and_then(|old_rows| old_rows.iter().position(|row| row.key == key))
});
let selection_keys = if tracked_selection.is_empty() {
plain_selected_index
.and_then(|index| previous.and_then(|rows| rows.get(index)))
.map(|row| vec![row.key])
.unwrap_or_default()
} else {
tracked_selection
};
(anchor_old_index, selection_keys)
};
let selection_indices: Vec<usize> = selection_keys
.iter()
.filter_map(|key| rows.iter().position(|row| row.key == *key))
.collect();
let multi_select = self
.widget(widget_id)
.is_some_and(|spec| !spec.selected_indices.is_empty());
let selection_removed = !selection_keys.is_empty() && selection_indices.is_empty();
let mut applied_incrementally = false;
if let Some(previous) = self.keyed_rows.get(&widget_id) {
if let Some(ops) = crate::widgets::diff_row_ops(previous, rows, &delta) {
match self.backend.apply_row_delta(widget_id, &ops) {
Ok(()) => {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
match spec.kind {
WidgetKind::DataGrid => {
let grid_rows = Arc::make_mut(&mut spec.data_grid_rows);
crate::widgets::apply_row_ops_to_cells(grid_rows, &ops);
}
WidgetKind::DataList => {
crate::widgets::apply_row_ops_to_items(
&mut spec.data_list_items,
&ops,
);
}
WidgetKind::ListView => {
if !spec.list_columns.is_empty() {
crate::widgets::apply_row_ops_to_cells(
&mut spec.list_rows,
&ops,
);
} else {
crate::widgets::apply_row_ops_to_items(
&mut spec.data_list_items,
&ops,
);
}
}
_ => {}
}
}
if let Some(baseline) = self.keyed_rows.get_mut(&widget_id) {
crate::widgets::apply_row_ops_to_rows(baseline, &ops);
}
applied_incrementally = true;
}
Err(GuiError::UnsupportedCapability(_)) => {}
Err(error) => return Err(error),
}
}
}
if !applied_incrementally {
match self.widget(widget_id).map(|spec| spec.kind) {
Some(WidgetKind::DataList) => {
let items: Vec<String> = rows.iter().map(RowSet::text).collect();
self.set_data_list_items(widget_id, &items)?;
}
Some(WidgetKind::ListView) => {
let columned = self
.widget(widget_id)
.is_some_and(|spec| !spec.list_columns.is_empty());
if columned {
let cells: Vec<Vec<String>> =
rows.iter().map(|row| row.cells.clone()).collect();
self.set_list_rows(widget_id, &cells)?;
} else {
let items: Vec<String> = rows.iter().map(RowSet::text).collect();
self.set_data_list_items(widget_id, &items)?;
}
}
Some(WidgetKind::DataGrid) => {
let cells: Arc<Vec<Vec<String>>> =
Arc::new(rows.iter().map(|row| row.cells.clone()).collect());
self.set_data_grid_rows_shared(widget_id, cells)?;
}
_ => return Err(GuiError::UnsupportedWidget("set_rows_keyed")),
}
self.keyed_rows.insert(widget_id, rows.to_vec());
}
if selection_removed {
self.clear_selection(widget_id)?;
} else if !selection_keys.is_empty() {
if multi_select {
let current: Vec<usize> = self
.widget(widget_id)
.map(|spec| spec.selected_indices.clone())
.unwrap_or_default();
if current != selection_indices {
self.set_selected_indices(widget_id, &selection_indices)?;
self.pending_events
.push_back(UiEvent::MultiSelectionChanged {
widget_id,
indices: selection_indices.clone(),
});
}
} else if let Some(&index) = selection_indices.first() {
let current = self.widget(widget_id).and_then(|spec| spec.selected_index);
if current != Some(index) {
self.set_selected_index(widget_id, index)?;
self.pending_events.push_back(UiEvent::SelectionChanged {
widget_id,
selected: rows.get(index).map(RowSet::text),
index: Some(index),
});
}
}
}
if let Some(key) = anchor_key {
if !rows.is_empty() {
let new_index = rows
.iter()
.position(|row| row.key == key)
.or(anchor_old_index)
.map(|index| index.min(rows.len() - 1));
if let Some(index) = new_index {
self.backend.scroll_to_row(widget_id, index)?;
}
}
}
let surviving: Vec<RowKey> = selection_keys
.iter()
.copied()
.filter(|key| rows.iter().any(|row| row.key == *key))
.collect();
if surviving.is_empty() {
self.keyed_selection.remove(&widget_id);
} else {
self.keyed_selection.insert(widget_id, surviving);
}
Ok(delta)
}
#[cfg(not(feature = "widgets-data"))]
pub fn set_rows_keyed(
&mut self,
_widget_id: WidgetId,
_rows: &[RowSet],
) -> GuiResult<RowDelta> {
Err(GuiError::UnsupportedWidget("set_rows_keyed"))
}
pub fn clear_selection(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let had_selection = {
let spec = self.require_property(widget_id, WidgetProperty::ClearSelection)?;
spec.selected_index.is_some() || !spec.selected_indices.is_empty()
};
self.backend.clear_selection(widget_id)?;
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.selected_index = None;
spec.selected_indices.clear();
}
self.keyed_selection.remove(&widget_id);
if had_selection {
self.pending_events.push_back(UiEvent::SelectionChanged {
widget_id,
selected: None,
index: None,
});
}
Ok(())
}
pub fn visible_anchor(&self, widget_id: WidgetId) -> GuiResult<Option<RowKey>> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::VisibleAnchor)?;
let index = self.backend.visible_anchor_index(widget_id)?;
Ok(index.and_then(|index| {
self.keyed_rows
.get(&widget_id)
.and_then(|rows| rows.get(index))
.map(|row| row.key)
}))
}
pub fn rows_end_visible(&self, widget_id: WidgetId) -> GuiResult<bool> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::VisibleAnchor)?;
self.backend.rows_end_visible(widget_id)
}
pub fn scroll_to_row(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::VisibleAnchor)?;
self.backend.scroll_to_row(widget_id, index)
}
pub fn selected_row_key(&self, widget_id: WidgetId) -> Option<RowKey> {
self.keyed_selection
.get(&widget_id)
.and_then(|keys| keys.first().copied())
}
fn record_keyed_selection(&mut self, widget_id: WidgetId, indices: &[usize]) {
let Some(rows) = self.keyed_rows.get(&widget_id) else {
return;
};
let keys: Vec<RowKey> = indices
.iter()
.filter_map(|index| rows.get(*index))
.map(|row| row.key)
.collect();
if keys.is_empty() {
self.keyed_selection.remove(&widget_id);
} else {
self.keyed_selection.insert(widget_id, keys);
}
}
#[cfg(feature = "widgets-data")]
pub fn set_data_grid_rows(
&mut self,
widget_id: WidgetId,
rows: &[Vec<String>],
) -> GuiResult<()> {
self.set_data_grid_rows_shared(widget_id, Arc::new(rows.to_vec()))
}
#[cfg(feature = "widgets-data")]
pub fn set_data_grid_columns(
&mut self,
widget_id: WidgetId,
columns: &[ColumnSpec],
) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::DataGridRows)?;
if columns.is_empty() {
self.data_grid_columns.remove(&widget_id);
} else {
self.data_grid_columns.insert(widget_id, columns.to_vec());
}
let data = self
.data_grid_data
.get(&widget_id)
.cloned()
.unwrap_or_default();
self.set_data_grid_data_rows(widget_id, &data)?;
for (index, column) in columns.iter().enumerate() {
if let Some(width) = column.width {
match self.set_data_grid_col_width(widget_id, index, width) {
Ok(()) | Err(GuiError::UnsupportedCapability(_)) => {}
Err(error) => return Err(error),
}
}
}
Ok(())
}
#[cfg(feature = "widgets-data")]
pub fn set_data_grid_data_rows(
&mut self,
widget_id: WidgetId,
rows: &[Vec<String>],
) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::DataGridRows)?;
let mut native = Vec::with_capacity(rows.len() + 1);
if let Some(columns) = self.data_grid_columns.get(&widget_id) {
native.push(columns.iter().map(|column| column.title.clone()).collect());
}
native.extend(rows.iter().cloned());
self.set_data_grid_rows_shared(widget_id, Arc::new(native))?;
self.data_grid_data.insert(widget_id, rows.to_vec());
Ok(())
}
#[cfg(feature = "widgets-data")]
pub fn data_grid_columns(&self, widget_id: WidgetId) -> &[ColumnSpec] {
self.data_grid_columns
.get(&widget_id)
.map(Vec::as_slice)
.unwrap_or(&[])
}
#[cfg(feature = "widgets-data")]
pub fn data_grid_data_row(&self, widget_id: WidgetId, raw_row: usize) -> Option<usize> {
if self.data_grid_columns.contains_key(&widget_id) {
raw_row.checked_sub(1)
} else {
Some(raw_row)
}
}
#[cfg(feature = "widgets-data")]
pub fn select_data_grid_row(
&mut self,
widget_id: WidgetId,
data_row: Option<usize>,
) -> GuiResult<()> {
let header = usize::from(self.data_grid_columns.contains_key(&widget_id));
let columns = self
.data_grid_columns
.get(&widget_id)
.map(Vec::len)
.or_else(|| {
self.widgets
.get(&widget_id)
.and_then(|spec| spec.data_grid_rows.first().map(Vec::len))
})
.unwrap_or(0);
let selection: Vec<(usize, usize)> = match data_row {
Some(row) => (0..columns).map(|col| (row + header, col)).collect(),
None => Vec::new(),
};
self.set_data_grid_selection(widget_id, &selection)
}
#[cfg(feature = "widgets-data")]
fn set_data_grid_rows_shared(
&mut self,
widget_id: WidgetId,
rows: Arc<Vec<Vec<String>>>,
) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::DataGridRows)?;
self.backend
.set_data_grid_rows(widget_id, Arc::clone(&rows))?;
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.data_grid_rows = rows;
}
Ok(())
}
#[cfg(feature = "widgets-data")]
pub fn set_data_grid_model(
&mut self,
widget_id: WidgetId,
model: Box<dyn crate::widgets::DataGridModel>,
) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::DataGridModel)?;
self.backend.set_data_grid_model(widget_id, model)
}
#[cfg(feature = "widgets-data")]
pub fn set_data_grid_row_height(
&mut self,
widget_id: WidgetId,
row: usize,
height: i32,
) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::DataGridRowHeight)?;
self.backend
.set_data_grid_row_height(widget_id, row, height)
}
#[cfg(feature = "widgets-data")]
pub fn set_data_grid_col_width(
&mut self,
widget_id: WidgetId,
col: usize,
width: i32,
) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::DataGridColWidth)?;
self.backend.set_data_grid_col_width(widget_id, col, width)
}
#[cfg(feature = "widgets-data")]
pub fn set_data_grid_frozen_panes(
&mut self,
widget_id: WidgetId,
rows: usize,
cols: usize,
) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::DataGridFrozenPanes)?;
self.backend
.set_data_grid_frozen_panes(widget_id, rows, cols)
}
#[cfg(feature = "widgets-data")]
pub fn set_data_grid_selection(
&mut self,
widget_id: WidgetId,
selection: &[(usize, usize)],
) -> GuiResult<()> {
self.require_property(widget_id, WidgetProperty::DataGridSelection)?;
self.backend.set_data_grid_selection(widget_id, selection)
}
#[cfg(feature = "widgets-data")]
pub fn set_tree_items(&mut self, widget_id: WidgetId, items: &[TreeItem]) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::TreeItems)?;
let previous = spec.tree_items.clone();
spec.tree_items = items.to_vec();
if let Err(error) = self.backend.set_tree_items(widget_id, items) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.tree_items = previous;
}
return Err(error);
}
Ok(())
}
#[cfg(not(feature = "widgets-data"))]
pub fn set_data_grid_rows(
&mut self,
_widget_id: WidgetId,
_rows: &[Vec<String>],
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_data_grid_rows"))
}
#[cfg(not(feature = "widgets-data"))]
pub fn set_data_grid_columns(
&mut self,
_widget_id: WidgetId,
_columns: &[ColumnSpec],
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_data_grid_columns"))
}
#[cfg(not(feature = "widgets-data"))]
pub fn set_data_grid_data_rows(
&mut self,
_widget_id: WidgetId,
_rows: &[Vec<String>],
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_data_grid_data_rows"))
}
#[cfg(not(feature = "widgets-data"))]
pub fn data_grid_columns(&self, _widget_id: WidgetId) -> &[ColumnSpec] {
&[]
}
#[cfg(not(feature = "widgets-data"))]
pub fn data_grid_data_row(&self, _widget_id: WidgetId, _raw_row: usize) -> Option<usize> {
None
}
#[cfg(not(feature = "widgets-data"))]
pub fn select_data_grid_row(
&mut self,
_widget_id: WidgetId,
_data_row: Option<usize>,
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("select_data_grid_row"))
}
#[cfg(not(feature = "widgets-data"))]
pub fn set_data_grid_model(
&mut self,
_widget_id: WidgetId,
_model: Box<dyn crate::widgets::DataGridModel>,
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_data_grid_model"))
}
#[cfg(not(feature = "widgets-data"))]
pub fn set_data_grid_row_height(
&mut self,
_widget_id: WidgetId,
_row: usize,
_height: i32,
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_data_grid_row_height"))
}
#[cfg(not(feature = "widgets-data"))]
pub fn set_data_grid_col_width(
&mut self,
_widget_id: WidgetId,
_col: usize,
_width: i32,
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_data_grid_col_width"))
}
#[cfg(not(feature = "widgets-data"))]
pub fn set_data_grid_frozen_panes(
&mut self,
_widget_id: WidgetId,
_rows: usize,
_cols: usize,
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_data_grid_frozen_panes"))
}
#[cfg(not(feature = "widgets-data"))]
pub fn set_data_grid_selection(
&mut self,
_widget_id: WidgetId,
_selection: &[(usize, usize)],
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_data_grid_selection"))
}
#[cfg(not(feature = "widgets-data"))]
pub fn set_tree_items(&mut self, _widget_id: WidgetId, _items: &[TreeItem]) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("set_tree_items"))
}
pub fn set_canvas_scene(
&mut self,
widget_id: WidgetId,
scene: &crate::CanvasScene,
) -> GuiResult<()> {
if !scene.logical_width.is_finite()
|| !scene.logical_height.is_finite()
|| scene.logical_width <= 0.0
|| scene.logical_height <= 0.0
{
return Err(GuiError::Backend(
"Canvas scene logical size must be finite and positive".to_owned(),
));
}
#[cfg(feature = "widgets-canvas")]
let gpu_canvas_fallback =
self.gpu_degraded.get(&widget_id) == Some(&GpuDegradationPolicy::Canvas2DFallback);
let spec = self
.widgets
.get_mut(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
#[cfg(feature = "widgets-canvas")]
let skip_property_check = spec.kind == WidgetKind::VulkanCanvas && gpu_canvas_fallback;
#[cfg(not(feature = "widgets-canvas"))]
let skip_property_check = false;
if !skip_property_check {
spec.ensure_property(WidgetProperty::CanvasScene)?;
}
let previous = spec.canvas_scene.clone();
spec.canvas_scene = Some(scene.clone());
if let Err(error) = self.backend.set_canvas_scene(widget_id, scene) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.canvas_scene = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_canvas_surface(
&mut self,
widget_id: WidgetId,
surface: &crate::CanvasSurface,
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::CanvasSurface)?;
let previous = spec.canvas_surface.clone();
spec.canvas_surface = Some(surface.clone());
if let Err(error) = self.backend.set_canvas_surface(widget_id, surface) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.canvas_surface = previous;
}
return Err(error);
}
Ok(())
}
pub fn copy_to_clipboard(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let spec = self.widget_spec(widget_id)?;
spec.ensure_property(WidgetProperty::CopyToClipboard)?;
let content = match spec.kind {
#[cfg(feature = "widgets-data")]
WidgetKind::DataList | WidgetKind::ListView => spec.data_list_items.join("\n"),
#[cfg(feature = "widgets-data")]
WidgetKind::DataGrid => serialize_data_grid_rows(&spec.data_grid_rows),
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput | WidgetKind::TextArea => spec.text.clone().unwrap_or_default(),
WidgetKind::Label => spec.text.clone().unwrap_or_default(),
_ => return Err(GuiError::UnsupportedWidget("copy_to_clipboard")),
};
self.clipboard = Some(content.clone());
self.backend.set_clipboard_text(&content)
}
pub fn paste_from_clipboard(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let platform_text = self.backend.clipboard_text()?;
let clipboard = platform_text
.filter(|text| !text.is_empty())
.unwrap_or_else(|| self.clipboard.clone().unwrap_or_default());
let spec = self.widget_spec(widget_id)?;
spec.ensure_property(WidgetProperty::PasteFromClipboard)?;
let kind = spec.kind;
match kind {
#[cfg(feature = "widgets-data")]
WidgetKind::DataList | WidgetKind::ListView => {
let items = parse_data_list_items(&clipboard);
self.set_data_list_items(widget_id, &items)
}
#[cfg(feature = "widgets-data")]
WidgetKind::DataGrid => {
let rows = parse_data_grid_rows(&clipboard);
self.set_data_grid_rows(widget_id, &rows)
}
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput | WidgetKind::TextArea => self.set_text(widget_id, &clipboard),
WidgetKind::Label => self.set_text(widget_id, &clipboard),
_ => Err(GuiError::UnsupportedWidget("paste_from_clipboard")),
}
}
pub fn paste_image_from_clipboard(&mut self) -> GuiResult<Option<ClipboardImage>> {
self.backend.paste_image_from_clipboard()
}
pub fn set_position(&mut self, widget_id: WidgetId, x: i32, y: i32) -> GuiResult<()> {
let Some(spec) = self.widgets.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let previous = spec.position;
spec.position = Some((x, y));
if let Err(error) = self.backend.set_position(widget_id, x, y) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.position = previous;
}
return Err(error);
}
self.layout_geometry_overridden = true;
Ok(())
}
pub fn set_background_color(&mut self, widget_id: WidgetId, color: Color) -> GuiResult<()> {
let Some(spec) = self.widgets.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let previous = spec.background_color;
spec.background_color = Some(color);
if let Err(error) = self.backend.set_background_color(widget_id, color) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.background_color = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_alert_level(&mut self, widget_id: WidgetId, level: AlertLevel) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::AlertLevel)?;
let previous = spec.alert_level;
spec.alert_level = Some(level);
if let Err(error) = self.backend.set_alert_level(widget_id, level) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.alert_level = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_image_source(&mut self, widget_id: WidgetId, source: &str) -> GuiResult<()> {
Self::reject_embedded_nul(source)?;
let spec = self.require_property(widget_id, WidgetProperty::ImageSource)?;
let previous = spec.image_source.clone();
spec.image_source = Some(source.to_owned());
if let Err(error) = self.backend.set_image_source(widget_id, source) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.image_source = previous;
}
return Err(error);
}
Ok(())
}
pub fn image_resource_capabilities(&self) -> ImageResourceCapabilities {
self.backend.image_resource_capabilities()
}
pub fn load_image_resource(&mut self, data: &ImageData) -> GuiResult<ImageResourceId> {
data.validate()?;
if !self.backend.image_resource_capabilities().rgba {
return Err(GuiError::UnsupportedCapability(
"image_resource_rgba".to_owned(),
));
}
let bytes = data.byte_len();
let total_bytes = checked_total_bytes(self.image_resource_bytes, bytes)?;
let resource = ImageResourceId(self.next_image_resource_id);
let next_id =
self.next_image_resource_id
.checked_add(1)
.ok_or(GuiError::ResourceExhausted {
operation: "image resource id allocation",
code: None,
})?;
self.backend.load_image_resource(resource, data)?;
self.image_resources.insert(resource, bytes);
self.image_resource_bytes = total_bytes;
self.next_image_resource_id = next_id;
Ok(resource)
}
pub fn image_resource_is_live(&self, resource: ImageResourceId) -> bool {
self.image_resources.contains_key(&resource)
}
pub fn release_image_resource(&mut self, resource: ImageResourceId) -> GuiResult<()> {
let bytes = self
.image_resources
.get(&resource)
.copied()
.ok_or_else(|| {
GuiError::Backend(format!("Image resource not found: {}", resource.0))
})?;
if !self.backend.image_resource_capabilities().rgba {
return Err(GuiError::UnsupportedCapability(
"image_resource_rgba".to_owned(),
));
}
self.backend.release_image_resource(resource)?;
self.image_resources.remove(&resource);
self.image_resource_bytes -= bytes;
Ok(())
}
pub fn set_image_fit(&mut self, widget_id: WidgetId, fit: ImageFit) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ImageFit)?;
let previous = spec.image_fit;
spec.image_fit = fit;
if let Err(error) = self.backend.set_image_fit(widget_id, fit) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.image_fit = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_file_chooser_mode(
&mut self,
widget_id: WidgetId,
mode: FileChooserMode,
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::FileChooserMode)?;
let previous = spec.file_chooser_mode;
spec.file_chooser_mode = mode;
if let Err(error) = self.backend.set_file_chooser_mode(widget_id, mode) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.file_chooser_mode = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_icon(&mut self, widget_id: WidgetId, icon: Option<IconRole>) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ButtonIcon)?;
let previous = spec.icon;
spec.icon = icon;
if let Err(error) = self.backend.set_icon(widget_id, icon) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.icon = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_color_dialog_data(
&mut self,
widget_id: WidgetId,
data: ColorDialogData,
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ColorDialogData)?;
data.validate()
.map_err(|error| GuiError::Backend(error.to_string()))?;
let previous = spec.color_dialog_data.clone();
spec.color_dialog_data = Some(data.clone());
if let Err(error) = self.backend.set_color_dialog_data(widget_id, &data) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.color_dialog_data = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_font_dialog_data(
&mut self,
widget_id: WidgetId,
data: FontDialogData,
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::FontDialogData)?;
data.validate()
.map_err(|error| GuiError::Backend(error.to_string()))?;
let previous = spec.font_dialog_data.clone();
spec.font_dialog_data = Some(data.clone());
if let Err(error) = self.backend.set_font_dialog_data(widget_id, &data) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.font_dialog_data = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_toolbar_items(
&mut self,
widget_id: WidgetId,
items: Vec<ToolbarItem>,
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ToolbarItems)?;
toolbar::validate_toolbar_items(&items)
.map_err(|error| GuiError::Backend(error.to_string()))?;
let previous = spec.toolbar_items.clone();
spec.toolbar_items = items.clone();
if let Err(error) = self.backend.set_toolbar_items(widget_id, &items) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.toolbar_items = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_toolbar_orientation(
&mut self,
widget_id: WidgetId,
orientation: ToolbarOrientation,
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ToolbarOrientation)?;
let previous = spec.toolbar_orientation;
spec.toolbar_orientation = orientation;
if let Err(error) = self.backend.set_toolbar_orientation(widget_id, orientation) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.toolbar_orientation = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_tool_state(
&mut self,
widget_id: WidgetId,
tool_id: ToolId,
checked: bool,
) -> GuiResult<Vec<(ToolId, bool)>> {
let spec = self.require_property(widget_id, WidgetProperty::ToolbarItems)?;
let mut updated_items = spec.toolbar_items.clone();
let changes = toolbar::set_tool_state(&mut updated_items, tool_id, checked)
.map_err(|error| GuiError::Backend(error.to_string()))?;
if !changes.is_empty() {
self.backend.set_toolbar_items(widget_id, &updated_items)?;
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.toolbar_items = updated_items;
}
}
Ok(changes)
}
pub fn update_tool(
&mut self,
widget_id: WidgetId,
tool_id: ToolId,
update: ToolUpdate,
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ToolbarItems)?;
toolbar::apply_tool_update(&mut spec.toolbar_items, tool_id, &update)
.map_err(|error| GuiError::Backend(error.to_string()))?;
let items = spec.toolbar_items.clone();
self.backend.set_toolbar_items(widget_id, &items)
}
pub fn set_calendar_selected_dates(
&mut self,
widget_id: WidgetId,
dates: &[CalendarDate],
) -> GuiResult<()> {
{
self.require_property(widget_id, WidgetProperty::CalendarDates)?;
for date in dates {
if !date.is_valid() {
return Err(GuiError::Backend(format!(
"Invalid calendar date: {}-{}-{}",
date.year, date.month, date.day
)));
}
}
}
self.backend.set_calendar_selected_dates(widget_id, dates)?;
self.require_property(widget_id, WidgetProperty::CalendarDates)?
.calendar_selected_dates = dates.to_vec();
Ok(())
}
pub fn set_calendar_bounds(
&mut self,
widget_id: WidgetId,
min_date: Option<CalendarDate>,
max_date: Option<CalendarDate>,
) -> GuiResult<()> {
{
self.require_property(widget_id, WidgetProperty::CalendarBounds)?;
if let Some(min) = min_date {
if !min.is_valid() {
return Err(GuiError::Backend(format!(
"Invalid minimum calendar date: {}-{}-{}",
min.year, min.month, min.day
)));
}
}
if let Some(max) = max_date {
if !max.is_valid() {
return Err(GuiError::Backend(format!(
"Invalid maximum calendar date: {}-{}-{}",
max.year, max.month, max.day
)));
}
}
if let (Some(min), Some(max)) = (min_date, max_date) {
if min > max {
return Err(GuiError::Backend(
"Minimum calendar date must not exceed maximum date".to_owned(),
));
}
}
}
self.backend
.set_calendar_bounds(widget_id, min_date, max_date)?;
let spec = self.require_property(widget_id, WidgetProperty::CalendarBounds)?;
spec.calendar_min_date = min_date;
spec.calendar_max_date = max_date;
Ok(())
}
pub fn set_calendar_first_day_of_week(
&mut self,
widget_id: WidgetId,
first_day: CalendarFirstDayOfWeek,
) -> GuiResult<()> {
self.require_property(widget_id, WidgetProperty::CalendarFirstDayOfWeek)?;
self.backend
.set_calendar_first_day_of_week(widget_id, first_day)?;
self.require_property(widget_id, WidgetProperty::CalendarFirstDayOfWeek)?
.calendar_first_day_of_week = first_day;
Ok(())
}
pub fn set_calendar_selection_mode(
&mut self,
widget_id: WidgetId,
mode: CalendarSelectionMode,
) -> GuiResult<()> {
self.require_property(widget_id, WidgetProperty::CalendarSelectionMode)?;
self.backend.set_calendar_selection_mode(widget_id, mode)?;
let spec = self.require_property(widget_id, WidgetProperty::CalendarSelectionMode)?;
spec.calendar_selection_mode = mode;
spec.calendar_selected_dates.clear();
Ok(())
}
pub fn set_date_value(&mut self, widget_id: WidgetId, iso_date: &str) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::DateValue)?;
let previous = spec.date_value.clone();
spec.date_value = Some(iso_date.to_owned());
if let Err(error) = self.backend.set_date_value(widget_id, iso_date) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.date_value = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_link_url(&mut self, widget_id: WidgetId, url: &str) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::LinkUrl)?;
let previous = spec.link_url.clone();
spec.link_url = Some(url.to_owned());
if let Err(error) = self.backend.set_link_url(widget_id, url) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.link_url = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_container_direction(
&mut self,
widget_id: WidgetId,
direction: ContainerDirection,
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ContainerDirection)?;
let previous = spec.container_direction;
spec.container_direction = Some(direction);
if let Err(error) = self.backend.set_container_direction(widget_id, direction) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.container_direction = previous;
}
return Err(error);
}
self.enable_auto_layout();
if let Some(&node) = self.layout_nodes.get(&widget_id) {
if let Ok(mut style) = self.layout_tree.style(node).cloned() {
style.flex_direction = match direction {
ContainerDirection::Horizontal => crate::layout::FlexDirection::Row,
ContainerDirection::Vertical => crate::layout::FlexDirection::Column,
};
let _ = self.layout_tree.set_style(node, style);
}
}
self.invalidate_layout(widget_id);
Ok(())
}
pub fn set_container_wrap(
&mut self,
widget_id: WidgetId,
wrap: ContainerWrap,
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ContainerWrap)?;
let previous = spec.container_wrap;
spec.container_wrap = Some(wrap);
if let Err(error) = self.backend.set_container_wrap(widget_id, wrap) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.container_wrap = previous;
}
return Err(error);
}
self.enable_auto_layout();
if let Some(&node) = self.layout_nodes.get(&widget_id) {
if let Ok(mut style) = self.layout_tree.style(node).cloned() {
style.flex_wrap = match wrap {
ContainerWrap::NoWrap => crate::layout::FlexWrap::NoWrap,
ContainerWrap::Wrap => crate::layout::FlexWrap::Wrap,
ContainerWrap::WrapReverse => crate::layout::FlexWrap::WrapReverse,
};
let _ = self.layout_tree.set_style(node, style);
}
}
self.invalidate_layout(widget_id);
Ok(())
}
pub fn create_flow_container(
&mut self,
parent: Option<WidgetId>,
gap: i32,
) -> GuiResult<WidgetId> {
let id = self.create(WidgetKind::Container, None)?;
self.set_container_direction(id, ContainerDirection::Horizontal)?;
self.set_container_wrap(id, ContainerWrap::Wrap)?;
self.set_container_gap(id, gap)?;
if let Some(p) = parent {
self.attach(p, id)?;
}
Ok(id)
}
pub fn set_container_gap(&mut self, widget_id: WidgetId, gap: i32) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ContainerGap)?;
let previous = spec.container_gap;
let gap = gap.max(0);
spec.container_gap = Some(gap);
self.enable_auto_layout();
if let Some(&node) = self.layout_nodes.get(&widget_id) {
if let Ok(mut style) = self.layout_tree.style(node).cloned() {
let length = crate::layout::LengthPercentage::length(gap as f32);
style.gap = crate::layout::Size {
width: length,
height: length,
};
let _ = self.layout_tree.set_style(node, style);
}
}
if let Err(error) = self.backend.set_container_gap(widget_id, gap) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.container_gap = previous;
}
if let Some(&node) = self.layout_nodes.get(&widget_id) {
if let Ok(mut style) = self.layout_tree.style(node).cloned() {
let prev_gap = previous.unwrap_or(0);
let length = crate::layout::LengthPercentage::length(prev_gap as f32);
style.gap = crate::layout::Size {
width: length,
height: length,
};
let _ = self.layout_tree.set_style(node, style);
}
}
return Err(error);
}
Ok(())
}
pub fn set_container_padding(&mut self, widget_id: WidgetId, padding: i32) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ContainerPadding)?;
let previous = spec.container_padding;
let padding = padding.max(0);
spec.container_padding = Some(padding);
self.enable_auto_layout();
if let Some(&node) = self.layout_nodes.get(&widget_id) {
if let Ok(mut style) = self.layout_tree.style(node).cloned() {
let length = crate::layout::LengthPercentage::length(padding as f32);
style.padding = crate::layout::Rect {
left: length,
right: length,
top: length,
bottom: length,
};
let _ = self.layout_tree.set_style(node, style);
}
}
if let Err(error) = self.backend.set_container_padding(widget_id, padding) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.container_padding = previous;
}
if let Some(&node) = self.layout_nodes.get(&widget_id) {
if let Ok(mut style) = self.layout_tree.style(node).cloned() {
let prev_pad = previous.unwrap_or(0);
let length = crate::layout::LengthPercentage::length(prev_pad as f32);
style.padding = crate::layout::Rect {
left: length,
right: length,
top: length,
bottom: length,
};
let _ = self.layout_tree.set_style(node, style);
}
}
return Err(error);
}
Ok(())
}
pub fn set_container_scroll(
&mut self,
widget_id: WidgetId,
vertical: bool,
horizontal: bool,
) -> GuiResult<()> {
let spec = self.require_property(widget_id, WidgetProperty::ContainerScroll)?;
let previous_vert = spec.container_scroll_vertical;
let previous_horiz = spec.container_scroll_horizontal;
spec.container_scroll_vertical = vertical;
spec.container_scroll_horizontal = horizontal;
if let Err(error) = self
.backend
.set_container_scroll(widget_id, vertical, horizontal)
{
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.container_scroll_vertical = previous_vert;
spec.container_scroll_horizontal = previous_horiz;
}
return Err(error);
}
Ok(())
}
pub fn draw_demo_cube(&mut self, widget_id: WidgetId) -> GuiResult<()> {
self.widget_spec(widget_id)?
.ensure_property(WidgetProperty::DrawDemoCube)?;
self.backend.draw_demo_cube(widget_id)
}
fn enable_auto_layout(&mut self) {
self.auto_layout_fn = Some(Self::compute_layout);
}
pub fn compute_layout(&mut self, root_id: WidgetId, width: f32, height: f32) -> GuiResult<()> {
self.enable_auto_layout();
let Some(root_owned_node) = self.layout_nodes.get(&root_id).copied() else {
return Err(GuiError::WidgetNotFound(root_id.0));
};
if self.layout_roots.contains(&root_id) {
self.layout_root_sizes.insert(root_id, (width, height));
}
let root_width = crate::layout::Dimension::length(width);
let root_height = crate::layout::Dimension::length(height);
if let Ok(mut style) = self.layout_tree.style(root_owned_node).cloned() {
if style.size.width != root_width || style.size.height != root_height {
style.size.width = root_width;
style.size.height = root_height;
let _ = self.layout_tree.set_style(root_owned_node, style);
}
}
if self
.widgets
.get(&root_id)
.is_some_and(|spec| spec.kind == WidgetKind::Window)
{
if let Ok(mut root_style) = self.layout_tree.style(root_owned_node).cloned() {
if root_style.align_items != Some(crate::layout::AlignItems::Stretch) {
root_style.align_items = Some(crate::layout::AlignItems::Stretch);
let _ = self.layout_tree.set_style(root_owned_node, root_style);
}
}
let children: Vec<LayoutNodeId> = self
.layout_tree
.children(root_owned_node)
.map(|c| c.to_vec())
.unwrap_or_default();
for child in children {
let needs_normalizing = self.layout_tree.style(child).is_ok_and(|style| {
style.size.width == crate::layout::Dimension::Auto
&& style.size.height == crate::layout::Dimension::Auto
&& style.flex_grow == 0.0
});
if !needs_normalizing {
continue;
}
if let Ok(mut style) = self.layout_tree.style(child).cloned() {
style.flex_grow = 1.0;
style.align_self = Some(crate::layout::AlignSelf::Stretch);
style.min_size.width = crate::layout::Dimension::length(0.0);
style.min_size.height = crate::layout::Dimension::length(0.0);
let _ = self.layout_tree.set_style(child, style);
}
}
}
let scheduled: Vec<WidgetId> = std::mem::take(&mut self.layout_dirty).into_iter().collect();
let mut pending: std::collections::HashSet<WidgetId> = std::collections::HashSet::new();
for widget_id in scheduled {
if self.chain_reaches_root(widget_id, root_id) {
pending.insert(widget_id);
} else {
self.layout_dirty.insert(widget_id);
}
}
if !pending.is_empty() {
let boundaries: Vec<WidgetId> = pending
.iter()
.copied()
.filter(|widget_id| !self.has_scheduled_ancestor(*widget_id, &pending))
.collect();
for branch_root in boundaries {
self.seed_branch(branch_root, root_id);
}
}
let available_space = crate::layout::Size {
width: crate::layout::AvailableSpace::Definite(width),
height: crate::layout::AvailableSpace::Definite(height),
};
let cache_hits_before = self.layout_tree.metrics().cache_hits;
if let Err(err) = self
.layout_tree
.compute_layout(root_owned_node, available_space)
{
self.layout_dirty.extend(pending);
return Err(err);
}
if self.layout_tree.metrics().cache_hits == cache_hits_before
|| self.layout_geometry_overridden
{
let mut widget_updates: Vec<LayoutUpdate> = Vec::new();
for (id, node) in &self.layout_nodes {
if *id == root_id {
continue;
}
if let Ok(layout) = self.layout_tree.layout(*node) {
let layout = self.parent_local_layout_rect(*id, layout)?;
let is_hidden = self.is_effectively_hidden(*id);
let (w, h) = if is_hidden {
(0, 0)
} else {
(layout.width as i32, layout.height as i32)
};
let (x, y) = (layout.x as i32, layout.y as i32);
let spec = self.widgets.get(id);
let size_changed = if is_hidden {
spec.is_some_and(|spec| spec.size != Some((0, 0)))
} else {
w > 0 && h > 0 && spec.is_some_and(|spec| spec.size != Some((w, h)))
};
let position_changed =
!is_hidden && spec.is_some_and(|spec| spec.position != Some((x, y)));
if size_changed || position_changed {
widget_updates.push((
*id,
size_changed.then_some((w, h)),
position_changed.then_some((x, y)),
));
}
}
}
self.sort_layout_updates_parent_first(&mut widget_updates);
for (id, size, position) in widget_updates {
if let Some((w, h)) = size {
let (expand_width, expand_height) = self.computed_layout_expansion(id);
self.apply_computed_size(id, w, h, expand_width, expand_height);
}
if let Some((x, y)) = position {
self.apply_computed_position(id, x, y);
}
}
self.layout_geometry_overridden = false;
}
Ok(())
}
fn sort_layout_updates_parent_first(&self, updates: &mut [LayoutUpdate]) {
updates.sort_by_cached_key(|(widget_id, _, _)| {
let mut depth = 0;
let mut parent = self.widgets.get(widget_id).and_then(|spec| spec.parent);
while let Some(parent_id) = parent {
depth += 1;
parent = self.widgets.get(&parent_id).and_then(|spec| spec.parent);
}
(depth, widget_id.0)
});
}
fn invalidate_layout(&mut self, widget_id: WidgetId) {
let mut cursor = Some(widget_id);
while let Some(id) = cursor {
if self.layout_dirty.contains(&id) {
return;
}
cursor = self.widgets.get(&id).and_then(|spec| spec.parent);
}
self.layout_dirty.insert(widget_id);
}
fn sync_layout_size(&mut self, widget_id: WidgetId, width: i32, height: i32) {
if let Some(&node) = self.layout_nodes.get(&widget_id) {
if let Ok(mut style) = self.layout_tree.style(node).cloned() {
let size = crate::layout::Size {
width: crate::layout::Dimension::length(width as f32),
height: crate::layout::Dimension::length(height as f32),
};
if style.size != size {
style.size = size;
let _ = self.layout_tree.set_style(node, style);
}
}
}
}
fn apply_computed_size(
&mut self,
widget_id: WidgetId,
width: i32,
height: i32,
expand_width: bool,
expand_height: bool,
) {
let Some(spec) = self.widgets.get_mut(&widget_id) else {
return;
};
spec.size = Some((width, height));
let _ = self
.backend
.set_layout_size(widget_id, width, height, expand_width, expand_height);
}
fn apply_computed_position(&mut self, widget_id: WidgetId, x: i32, y: i32) {
let Some(spec) = self.widgets.get_mut(&widget_id) else {
return;
};
spec.position = Some((x, y));
let _ = self.backend.set_layout_position(widget_id, x, y);
}
fn computed_layout_expansion(&self, widget_id: WidgetId) -> (bool, bool) {
let Some(&node) = self.layout_nodes.get(&widget_id) else {
return (false, false);
};
let Ok(style) = self.layout_tree.style(node) else {
return (false, false);
};
let Ok(Some(parent)) = self.layout_tree.parent(node) else {
return (false, false);
};
let Ok(parent_style) = self.layout_tree.style(parent) else {
return (false, false);
};
let horizontal_main_axis = matches!(
parent_style.flex_direction,
crate::layout::FlexDirection::Row | crate::layout::FlexDirection::RowReverse
);
let cross_axis_stretches = style
.align_self
.or_else(|| {
parent_style
.align_items
.map(crate::layout::flex::to_align_self)
})
.unwrap_or(crate::layout::AlignSelf::Stretch)
== crate::layout::AlignSelf::Stretch;
let width_auto = style.size.width == crate::layout::Dimension::Auto;
let height_auto = style.size.height == crate::layout::Dimension::Auto;
let grow = style.flex_grow > 0.0;
let expand_width = matches!(style.size.width, crate::layout::Dimension::Percent(_))
|| (horizontal_main_axis && grow)
|| (!horizontal_main_axis && width_auto && cross_axis_stretches);
let expand_height = matches!(style.size.height, crate::layout::Dimension::Percent(_))
|| (!horizontal_main_axis && grow)
|| (horizontal_main_axis && height_auto && cross_axis_stretches);
(expand_width, expand_height)
}
fn chain_reaches_root(&self, widget_id: WidgetId, root_id: WidgetId) -> bool {
let mut cursor = Some(widget_id);
while let Some(id) = cursor {
if id == root_id {
return true;
}
cursor = self.widgets.get(&id).and_then(|spec| spec.parent);
}
false
}
fn has_scheduled_ancestor(
&self,
widget_id: WidgetId,
scheduled: &std::collections::HashSet<WidgetId>,
) -> bool {
let mut cursor = self.widgets.get(&widget_id).and_then(|spec| spec.parent);
while let Some(id) = cursor {
if scheduled.contains(&id) {
return true;
}
cursor = self.widgets.get(&id).and_then(|spec| spec.parent);
}
false
}
fn seed_branch(&mut self, branch_root: WidgetId, layout_root: WidgetId) {
let mut stack = vec![branch_root];
let mut row_containers = Vec::new();
let mut floored = HashSet::new();
while let Some(id) = stack.pop() {
if let Some(children) = self.children_index.get(&id) {
stack.extend(children.iter().copied());
}
if id == layout_root {
continue;
}
let Some(&node) = self.layout_nodes.get(&id) else {
continue;
};
let is_leaf = self
.layout_tree
.children(node)
.map(|children| children.is_empty())
.unwrap_or(true);
let Ok(style) = self.layout_tree.style(node).cloned() else {
continue;
};
let parent_row = self
.layout_tree
.parent(node)
.ok()
.flatten()
.and_then(|parent| self.layout_tree.style(parent).ok())
.is_some_and(|style| {
matches!(
style.flex_direction,
crate::layout::FlexDirection::Row
| crate::layout::FlexDirection::RowReverse
)
});
let is_hidden = self.is_effectively_hidden(id);
#[cfg(feature = "widgets-containers")]
let in_split_pane = self
.widgets
.get(&id)
.and_then(|spec| spec.parent)
.and_then(|parent| self.widgets.get(&parent))
.is_some_and(|parent| parent.kind == WidgetKind::SplitPane);
#[cfg(not(feature = "widgets-containers"))]
let in_split_pane = false;
let is_intrinsic_control = self.widgets.get(&id).is_some_and(|spec| match spec.kind {
WidgetKind::Button => true,
#[cfg(feature = "widgets-pickers")]
WidgetKind::DatePicker => true,
#[cfg(feature = "widgets-choice")]
WidgetKind::Checkbox | WidgetKind::RadioButton => true,
#[cfg(feature = "widgets-range")]
WidgetKind::SpinBox => true,
_ => false,
});
let is_toolbar = self
.widgets
.get(&id)
.is_some_and(|spec| spec.kind == WidgetKind::Toolbar);
let wants_width = !in_split_pane
&& (parent_row || is_intrinsic_control)
&& style.size.width == crate::layout::Dimension::Auto;
let wants_height =
!in_split_pane && style.size.height == crate::layout::Dimension::Auto;
let natural = if !is_hidden && is_leaf && (wants_width || wants_height || is_toolbar) {
self.backend.natural_size(id)
} else {
None
};
let is_chrome_toolbar = !is_hidden && is_toolbar && matches!(natural, Some((_, 0)));
let mut next = style;
let mut changed = false;
let expected_display = if is_hidden || is_chrome_toolbar {
crate::layout::Display::None
} else {
crate::layout::Display::Flex
};
if next.display != expected_display {
next.display = expected_display;
changed = true;
}
let (app_min_width, app_min_height) =
self.min_sizes.get(&id).copied().unwrap_or((0, 0));
let min_width = if let Some(&pref_w) = self.preferred_widths.get(&id) {
pref_w as f32
} else {
app_min_width as f32
};
let compressed_floor = if is_leaf && !is_hidden {
self.backend.min_compressed_size(id).map(|(w, h)| {
let cap = |floor: i32, dim: crate::layout::Dimension| match dim {
crate::layout::Dimension::Length(px) => floor.min(px.max(0.0) as i32),
_ => floor,
};
(cap(w, next.size.width), cap(h, next.size.height))
})
} else {
None
};
if compressed_floor.is_some()
&& self.widgets.get(&id).map(|spec| spec.kind) == Some(WidgetKind::Button)
{
floored.insert(node);
}
if !is_leaf
&& !is_hidden
&& matches!(
next.flex_direction,
crate::layout::FlexDirection::Row | crate::layout::FlexDirection::RowReverse
)
{
row_containers.push(node);
}
let min_width = match compressed_floor {
Some((floor, _)) if parent_row && !in_split_pane => {
min_width.max(floor.max(0) as f32)
}
_ => min_width,
};
let owned_min_w = crate::layout::Dimension::length(min_width);
if next.min_size.width != owned_min_w {
next.min_size.width = owned_min_w;
changed = true;
}
#[cfg(feature = "widgets-containers")]
let is_tabs = self.widgets.get(&id).map(|s| s.kind) == Some(WidgetKind::Tabs);
#[cfg(not(feature = "widgets-containers"))]
let is_tabs = false;
if self.preferred_widths.contains_key(&id) && app_min_height == 0 && !is_tabs {
if next.min_size.height != crate::layout::Dimension::Auto {
next.min_size.height = crate::layout::Dimension::Auto;
changed = true;
}
} else {
let min_height = if is_tabs {
self.min_tabs_height(id)
} else {
0.0
}
.max(app_min_height as f32);
let min_height = match compressed_floor {
Some((_, floor)) => min_height.max(floor.max(0) as f32),
None => min_height,
};
let owned_min_h = crate::layout::Dimension::length(min_height);
if next.min_size.height != owned_min_h {
next.min_size.height = owned_min_h;
changed = true;
}
}
if let Some((natural_width, natural_height)) = natural {
if wants_width {
next.size.width = crate::layout::Dimension::length(natural_width as f32);
changed = true;
}
if wants_height {
next.size.height = crate::layout::Dimension::length(natural_height as f32);
changed = true;
}
}
if changed {
let _ = self.layout_tree.set_style(node, next);
}
}
for node in row_containers.into_iter().rev() {
let Ok(children) = self.layout_tree.children(node).map(|c| c.to_vec()) else {
continue;
};
let mut tallest = None::<f32>;
for child in children {
if !floored.contains(&child) {
continue;
}
if let Ok(style) = self.layout_tree.style(child) {
if let crate::layout::Dimension::Length(h) = style.min_size.height {
tallest = Some(tallest.unwrap_or(0.0).max(h));
}
}
}
let Some(tallest) = tallest else {
continue;
};
let Ok(mut style) = self.layout_tree.style(node).cloned() else {
continue;
};
let pad = |value: crate::layout::LengthPercentage| match value {
crate::layout::LengthPercentage::Length(px) => px.max(0.0),
crate::layout::LengthPercentage::Percent(_) => 0.0,
};
let mut floor = tallest + pad(style.padding.top) + pad(style.padding.bottom);
if let crate::layout::Dimension::Length(px) = style.size.height {
floor = floor.min(px.max(0.0));
}
let current = match style.min_size.height {
crate::layout::Dimension::Length(px) => px,
_ => 0.0,
};
if floor > current {
style.min_size.height = crate::layout::Dimension::length(floor);
let _ = self.layout_tree.set_style(node, style);
}
}
}
pub fn attach(&mut self, parent: WidgetId, child: WidgetId) -> GuiResult<()> {
if !self.widgets.contains_key(&parent) {
return Err(GuiError::WidgetNotFound(parent.0));
}
if !self.widgets.contains_key(&child) {
return Err(GuiError::WidgetNotFound(child.0));
}
if self.creates_parent_cycle(child, parent) {
return Err(GuiError::Backend(
"cannot create a widget parent cycle".to_owned(),
));
}
if self.widget_depth(parent) + self.widget_subtree_height(child)
>= crate::layout::box_sizing::MAX_LAYOUT_DEPTH
{
return Err(GuiError::Backend(
"maximum layout recursion depth exceeded".to_string(),
));
}
self.backend.add_child(parent, child)?;
self.record_parent_edge(parent, child);
Ok(())
}
fn discard_failed_create(&mut self, id: WidgetId) {
let _ = self.backend.remove(id);
if let Some(node) = self.layout_nodes.remove(&id) {
let _ = self.layout_tree.remove_node(node);
}
self.widgets.remove(&id);
self.gpu_degraded.remove(&id);
self.layout_dirty.remove(&id);
self.hidden_widgets.remove(&id);
}
fn record_parent_edge(&mut self, parent: WidgetId, child: WidgetId) {
if let Some(previous) = self.widgets.get(&child).and_then(|spec| spec.parent) {
self.detach_child_edge(previous, child);
}
if let Some(child_spec) = self.widgets.get_mut(&child) {
child_spec.parent = Some(parent);
}
self.children_index.entry(parent).or_default().push(child);
if let (Some(&parent_node), Some(&child_node)) = (
self.layout_nodes.get(&parent),
self.layout_nodes.get(&child),
) {
let _ = self.layout_tree.attach_child(parent_node, child_node);
}
#[cfg(feature = "widgets-containers")]
if self.widgets.get(&parent).map(|spec| spec.kind) == Some(WidgetKind::Tabs) {
self.style_tab_page(child);
}
self.invalidate_layout(child);
}
#[cfg(feature = "widgets-containers")]
fn style_tab_page(&mut self, page: WidgetId) {
let Some(&node) = self.layout_nodes.get(&page) else {
return;
};
let Ok(mut style) = self.layout_tree.style(node).cloned() else {
return;
};
let mut changed = false;
if style.size.width == crate::layout::Dimension::Auto {
style.size.width = crate::layout::Dimension::percent(1.0);
changed = true;
}
if style.size.height == crate::layout::Dimension::Auto {
style.size.height = crate::layout::Dimension::percent(1.0);
changed = true;
}
if style.flex_shrink != 0.0 {
style.flex_shrink = 0.0;
changed = true;
}
if changed {
let _ = self.layout_tree.set_style(node, style);
}
}
pub fn reparent(&mut self, child: WidgetId, new_parent: WidgetId) -> GuiResult<()> {
if child == new_parent {
return Err(GuiError::Backend(
"cannot reparent a widget to itself".to_owned(),
));
}
if !self.widgets.contains_key(&child) {
return Err(GuiError::WidgetNotFound(child.0));
}
if !self.widgets.contains_key(&new_parent) {
return Err(GuiError::WidgetNotFound(new_parent.0));
}
if self.creates_parent_cycle(child, new_parent) {
return Err(GuiError::Backend(
"cannot create a widget parent cycle".to_owned(),
));
}
if self.widget_depth(new_parent) + self.widget_subtree_height(child)
>= crate::layout::box_sizing::MAX_LAYOUT_DEPTH
{
return Err(GuiError::Backend(
"maximum layout recursion depth exceeded".to_string(),
));
}
self.backend.reparent(child, new_parent)?;
self.record_parent_edge(new_parent, child);
Ok(())
}
fn creates_parent_cycle(&self, child: WidgetId, new_parent: WidgetId) -> bool {
if child == new_parent {
return true;
}
if self.children_index.get(&child).is_none_or(|c| c.is_empty()) {
return false;
}
let mut cursor = Some(new_parent);
while let Some(id) = cursor {
if id == child {
return true;
}
cursor = self.widgets.get(&id).and_then(|spec| spec.parent);
}
false
}
pub fn widget_depth(&self, widget_id: WidgetId) -> usize {
let mut depth = 0;
let mut parent = self.widgets.get(&widget_id).and_then(|spec| spec.parent);
while let Some(parent_id) = parent {
depth += 1;
parent = self.widgets.get(&parent_id).and_then(|spec| spec.parent);
}
depth
}
pub fn widget_subtree_height(&self, widget_id: WidgetId) -> usize {
let mut max_child_height = 0;
if let Some(children) = self.children_index.get(&widget_id) {
for &child in children {
max_child_height = max_child_height.max(self.widget_subtree_height(child));
}
}
1 + max_child_height
}
fn detach_child_edge(&mut self, parent: WidgetId, child: WidgetId) {
let became_empty = match self.children_index.get_mut(&parent) {
Some(children) => {
if let Some(pos) = children.iter().position(|&id| id == child) {
children.remove(pos);
}
children.is_empty()
}
None => false,
};
if became_empty {
self.children_index.remove(&parent);
}
if let Some(&child_node) = self.layout_nodes.get(&child) {
let _ = self.layout_tree.detach_child(child_node);
}
}
pub fn show(&mut self, widget_id: WidgetId) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
let announcement = self.widgets.get(&widget_id).and_then(|spec| {
#[cfg(feature = "widgets-containers")]
let is_alert = spec.kind == WidgetKind::AlertDialog;
#[cfg(not(feature = "widgets-containers"))]
let is_alert = false;
is_alert
.then(|| {
spec.accessibility
.name
.clone()
.or_else(|| spec.text.clone())
})
.flatten()
});
self.hidden_widgets.remove(&widget_id);
if let Some(&node) = self.layout_nodes.get(&widget_id) {
if let Ok(mut style) = self.layout_tree.style(node).cloned() {
if style.display != crate::layout::Display::Flex {
style.display = crate::layout::Display::Flex;
let _ = self.layout_tree.set_style(node, style);
}
}
}
self.invalidate_layout(widget_id);
if self.widgets.get(&widget_id).map(|s| s.kind) == Some(WidgetKind::Window) {
self.layout_roots.insert(widget_id);
if let Some((w, h)) = self.widgets.get(&widget_id).and_then(|spec| spec.size) {
self.layout_root_sizes
.insert(widget_id, (w as f32, h as f32));
if let Some(compute) = self.auto_layout_fn {
let _ = compute(self, widget_id, w as f32, h as f32);
}
}
}
self.backend.show(widget_id)?;
if let Some(text) = announcement {
self.backend.post_accessible_notification(
widget_id,
AccessibleNotification::Announcement(text),
)?;
}
Ok(())
}
pub fn hide(&mut self, widget_id: WidgetId) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
for popup in self.transient_popups(widget_id) {
self.hide(popup)?;
}
self.hidden_widgets.insert(widget_id);
if let Some(&node) = self.layout_nodes.get(&widget_id) {
if let Ok(mut style) = self.layout_tree.style(node).cloned() {
if style.display != crate::layout::Display::None {
style.display = crate::layout::Display::None;
let _ = self.layout_tree.set_style(node, style);
}
}
}
self.invalidate_layout(widget_id);
self.backend.hide(widget_id)
}
pub fn set_visible(&mut self, widget_id: WidgetId, visible: bool) -> GuiResult<()> {
if visible {
self.show(widget_id)
} else {
self.hide(widget_id)
}
}
pub fn is_visible(&self, widget_id: WidgetId) -> bool {
self.widgets.contains_key(&widget_id) && !self.is_effectively_hidden(widget_id)
}
pub fn is_effectively_hidden(&self, widget_id: WidgetId) -> bool {
if self.hidden_widgets.is_empty() {
return false;
}
let mut cursor = Some(widget_id);
while let Some(id) = cursor {
if self.hidden_widgets.contains(&id) {
return true;
}
cursor = self.widgets.get(&id).and_then(|spec| spec.parent);
}
false
}
fn transient_popups(&self, owner: WidgetId) -> Vec<WidgetId> {
let mut popups: Vec<_> = self
.window_options
.iter()
.filter_map(|(widget_id, options)| {
(options.transient_for == Some(owner)).then_some(*widget_id)
})
.collect();
popups.sort_by_key(|widget_id| widget_id.0);
popups
}
pub fn capture_window_rgba(
&self,
window_id: WidgetId,
include_decorations: bool,
) -> GuiResult<(u32, u32, Vec<u8>)> {
let Some(spec) = self.widgets.get(&window_id) else {
return Err(GuiError::WidgetNotFound(window_id.0));
};
if !spec.kind.is_window_like() {
return Err(GuiError::UnsupportedWidget("capture_window"));
}
self.backend
.capture_window_rgba(window_id, include_decorations)
}
pub fn capture_widget_rgba(&self, widget_id: WidgetId) -> GuiResult<(u32, u32, Vec<u8>)> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.backend.capture_widget_rgba(widget_id)
}
pub fn native_read_text(&self, widget_id: WidgetId) -> GuiResult<Option<String>> {
let Some(spec) = self.widgets.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
match self.backend.native_read_text(widget_id)? {
Some(live) => Ok(Some(live)),
None => Ok(spec.text.clone()),
}
}
pub fn native_read_checked(&self, widget_id: WidgetId) -> GuiResult<Option<bool>> {
let Some(spec) = self.widgets.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
match self.backend.native_read_checked(widget_id)? {
Some(live) => Ok(Some(live)),
None => Ok(spec.checked),
}
}
pub fn native_click(&self, widget_id: WidgetId) -> GuiResult<bool> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.backend.native_click(widget_id)
}
pub fn native_type_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<bool> {
let Some(spec) = self.widgets.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let handled = self.backend.native_type_text(widget_id, text)?;
if handled {
spec.text = Some(text.to_owned());
let _ = self.backend.set_text(widget_id, text);
}
Ok(handled)
}
pub fn remove(&mut self, widget_id: WidgetId) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
let children = self.children_index.remove(&widget_id).unwrap_or_default();
let mut all_children = children;
for popup in self.transient_popups(widget_id) {
if !all_children.contains(&popup) {
all_children.push(popup);
}
}
if let Some(&p_node) = self.layout_nodes.get(&widget_id) {
let _ = self.layout_tree.detach_all_children(p_node);
}
for (idx, &child_id) in all_children.iter().enumerate() {
if let Err(err) = self.remove(child_id) {
let surviving: Vec<WidgetId> = all_children[idx..].to_vec();
self.children_index.insert(widget_id, surviving);
return Err(err);
}
}
self.backend.remove(widget_id)?;
self.remove_widget_motions(widget_id);
if let Some(parent) = self.widgets.get(&widget_id).and_then(|spec| spec.parent) {
self.detach_child_edge(parent, widget_id);
}
self.children_index.remove(&widget_id);
self.widgets.remove(&widget_id);
self.gpu_degraded.remove(&widget_id);
if let Some(node) = self.layout_nodes.remove(&widget_id) {
let _ = self.layout_tree.remove_node(node);
}
self.layout_dirty.remove(&widget_id);
self.keyed_rows.remove(&widget_id);
self.keyed_selection.remove(&widget_id);
self.layout_roots.remove(&widget_id);
self.hidden_widgets.remove(&widget_id);
self.min_sizes.remove(&widget_id);
self.preferred_widths.remove(&widget_id);
self.window_min_sizes.remove(&widget_id);
self.data_grid_columns.remove(&widget_id);
self.data_grid_data.remove(&widget_id);
self.window_resizable.remove(&widget_id);
self.window_options.remove(&widget_id);
self.drag_sources.remove(&widget_id);
self.drag_targets.remove(&widget_id);
self.layout_root_sizes.remove(&widget_id);
self.on_window_close.remove(&widget_id);
self.on_window_resize.remove(&widget_id);
self.theme_overrides.remove(&widget_id);
#[cfg(feature = "property-grid")]
self.property_grids.forget(widget_id);
#[cfg(feature = "styled-text")]
self.styled_texts.forget(widget_id);
#[cfg(feature = "webview")]
self.webviews.forget(widget_id);
if self.focused == Some(widget_id) {
self.focused = None;
}
Ok(())
}
pub fn set_enabled(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
let Some(spec) = self.widgets.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let previous = spec.enabled;
spec.enabled = Some(enabled);
if let Err(error) = self.backend.set_enabled(widget_id, enabled) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.enabled = previous;
}
return Err(error);
}
Ok(())
}
pub fn activate(&mut self, widget_id: WidgetId) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.backend.activate(widget_id)
}
pub fn app_data_dir(&self) -> GuiResult<PathBuf> {
self.backend.data_dir()
}
pub fn set_tooltip(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
Self::reject_embedded_nul(text)?;
let Some(spec) = self.widgets.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let previous = spec.tooltip.clone();
spec.tooltip = Some(text.to_owned());
if let Err(error) = self.backend.set_tooltip(widget_id, text) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.tooltip = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_accessible_name(&mut self, widget_id: WidgetId, name: &str) -> GuiResult<()> {
Self::reject_embedded_nul(name)?;
let Some(spec) = self.widgets.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let previous = spec.accessibility.name.clone();
spec.accessibility.name = Some(name.to_owned());
if let Err(error) = self.backend.set_accessible_name(widget_id, name) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.accessibility.name = previous;
}
return Err(error);
}
Ok(())
}
pub fn set_accessible_description(
&mut self,
widget_id: WidgetId,
description: &str,
) -> GuiResult<()> {
Self::reject_embedded_nul(description)?;
let Some(spec) = self.widgets.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let previous = spec.accessibility.description.clone();
spec.accessibility.description = Some(description.to_owned());
if let Err(error) = self
.backend
.set_accessible_description(widget_id, description)
{
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.accessibility.description = previous;
}
return Err(error);
}
Ok(())
}
pub fn accessibility(&self, widget_id: WidgetId) -> Option<&AccessibilitySpec> {
self.widget(widget_id).map(|spec| &spec.accessibility)
}
pub fn set_focusable(&mut self, widget_id: WidgetId, focusable: bool) -> GuiResult<()> {
let Some(spec) = self.widgets.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let previous = spec.focusable;
spec.focusable = Some(focusable);
if let Err(error) = self.backend.set_focusable(widget_id, focusable) {
if let Some(spec) = self.widgets.get_mut(&widget_id) {
spec.focusable = previous;
}
return Err(error);
}
Ok(())
}
pub fn is_focusable(&self, widget_id: WidgetId) -> Option<bool> {
self.widget(widget_id).map(crate::focus::is_focusable)
}
pub fn focus(&mut self, widget_id: WidgetId) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.backend.set_focus(widget_id)?;
self.focused = Some(widget_id);
self.backend
.post_accessible_notification(widget_id, AccessibleNotification::FocusChanged)
}
pub fn focused(&self) -> Option<WidgetId> {
self.focused
}
pub fn focus_order(&self) -> Vec<WidgetId> {
let mut ids: Vec<WidgetId> = self.widgets.keys().copied().collect();
ids.sort_by_key(|id| id.0);
ids.retain(|id| {
let popup_takes_focus = self.window_options.get(id).is_some_and(|options| {
options.role == WindowRole::Popup && options.focus == WindowFocusPolicy::Take
});
self.widgets.get(id).is_some_and(|spec| {
(crate::focus::is_focusable(spec) || popup_takes_focus)
&& self.focus_chain_enabled(*id)
})
});
ids
}
pub fn spatial_focus_order(&self) -> Vec<WidgetId> {
let candidates = self.focus_order();
if candidates.len() <= 1 {
return candidates;
}
let mut with_pos: Vec<(WidgetId, f32, f32)> = candidates
.into_iter()
.map(|id| {
if let Some(spec) = self.widgets.get(&id) {
if let Some((x, y)) = spec.position {
return (id, x as f32, y as f32);
}
}
if let Ok(rect) = self.layout_rect(id) {
(id, rect.x, rect.y)
} else {
(id, 0.0, 0.0)
}
})
.collect();
const ROW_TOLERANCE: f32 = 12.0;
with_pos.sort_by(|a, b| {
let row_a = (a.2 / ROW_TOLERANCE).floor() as i32;
let row_b = (b.2 / ROW_TOLERANCE).floor() as i32;
if row_a != row_b {
row_a.cmp(&row_b)
} else {
a.1.total_cmp(&b.1).then_with(|| a.0 .0.cmp(&b.0 .0))
}
});
with_pos.into_iter().map(|(id, _, _)| id).collect()
}
fn focus_chain_enabled(&self, widget_id: WidgetId) -> bool {
let mut cursor = Some(widget_id);
while let Some(id) = cursor {
let Some(spec) = self.widgets.get(&id) else {
return false;
};
if spec.enabled == Some(false) {
return false;
}
cursor = spec.parent;
}
true
}
pub fn focus_next(&mut self) -> GuiResult<Option<WidgetId>> {
self.focus_step(1)
}
pub fn focus_previous(&mut self) -> GuiResult<Option<WidgetId>> {
self.focus_step(-1)
}
fn focus_step(&mut self, direction: isize) -> GuiResult<Option<WidgetId>> {
let order = self.focus_order();
if order.is_empty() {
self.focused = None;
return Ok(None);
}
let next = match self
.focused
.and_then(|current| order.iter().position(|id| *id == current))
{
Some(position) => {
let len = order.len() as isize;
let target = (position as isize + direction).rem_euclid(len) as usize;
order[target]
}
None if direction >= 0 => order[0],
None => *order.last().expect("order is not empty"),
};
self.focus(next)?;
Ok(Some(next))
}
pub fn set_theme(&mut self, theme: Theme) -> GuiResult<()> {
self.backend.set_theme(&theme)?;
self.theme = theme;
Ok(())
}
pub fn set_theme_mode(&mut self, mode: ThemeMode) -> GuiResult<()> {
self.set_theme(Theme::for_mode(mode))
}
pub fn theme(&self) -> &Theme {
&self.theme
}
pub fn theme_mode(&self) -> ThemeMode {
self.theme.mode
}
pub fn theme_capabilities(&self) -> ThemeCapabilities {
self.backend.theme_capabilities()
}
pub fn gpu_surface_capabilities(&self) -> GpuSurfaceCapabilities {
self.backend.gpu_surface_capabilities()
}
pub fn supports_capability(&self, capability: &str) -> bool {
self.gpu_surface_capabilities().supports(capability)
}
pub fn set_gpu_degradation_policy(&mut self, policy: GpuDegradationPolicy) {
self.gpu_degradation_policy = policy;
}
pub fn is_gpu_degraded(&self, widget_id: WidgetId) -> bool {
self.gpu_degraded.contains_key(&widget_id)
}
pub fn display_capabilities(&self) -> DisplayCapabilities {
self.backend.display_capabilities()
}
#[cfg(feature = "displays")]
pub fn displays(&self) -> GuiResult<Vec<DisplayInfo>> {
self.backend.displays()
}
#[cfg(feature = "displays")]
pub fn primary_display(&self) -> GuiResult<Option<DisplayInfo>> {
self.backend.primary_display()
}
pub fn logical_pointer_projection(&self, widget_id: WidgetId, x: f32, y: f32) -> (f32, f32) {
let scale = self.backend.widget_scale_factor(widget_id);
crate::logical_pointer_projection(x, y, scale)
}
pub fn system_theme_mode(&self) -> Option<ThemeMode> {
self.backend.system_theme_mode()
}
pub fn system_high_contrast(&self) -> bool {
self.backend.system_high_contrast()
}
pub fn stock_icon(&self, role: IconRole, size: IconSize) -> StockIcon {
self.stock_icon_at_scale(role, size, 1)
}
pub fn stock_icon_at_scale(&self, role: IconRole, size: IconSize, scale: u32) -> StockIcon {
crate::artprov::render_stock_icon(role, size, self.theme.mode, scale)
}
pub fn native_stock_icon(&self, role: IconRole, size: IconSize) -> GuiResult<StockIcon> {
self.backend.native_stock_icon(role, size)
}
pub fn art_capabilities(&self) -> ArtCapabilities {
self.backend.art_capabilities()
}
pub fn set_theme_override(
&mut self,
widget_id: WidgetId,
theme_override: ThemeOverride,
) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.backend.set_theme_override(widget_id, theme_override)?;
self.theme_overrides
.entry(widget_id)
.or_default()
.push(theme_override);
Ok(())
}
pub fn theme_overrides(&self, widget_id: WidgetId) -> &[ThemeOverride] {
self.theme_overrides
.get(&widget_id)
.map(Vec::as_slice)
.unwrap_or(&[])
}
pub fn clear_theme_overrides(&mut self, widget_id: WidgetId) -> GuiResult<()> {
if !self.widgets.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.backend.clear_theme_overrides(widget_id)?;
self.theme_overrides.remove(&widget_id);
Ok(())
}
#[cfg(feature = "async")]
pub fn task_proxy(&mut self) -> UiProxy {
if self.task_channel.is_none() {
let (proxy, receiver) =
UiProxy::new(self.backend.wake_handle(), DEFAULT_TASK_QUEUE_CAPACITY);
self.task_channel = Some((proxy, receiver));
}
self.task_channel
.as_ref()
.map(|(proxy, _)| proxy.clone())
.expect("task channel initialized above")
}
#[cfg(feature = "async")]
pub fn shutdown(mut self) -> usize {
self.discard_pending_tasks()
}
#[cfg(feature = "async")]
fn discard_pending_tasks(&mut self) -> usize {
let mut discarded = 0;
if let Some((_, receiver)) = self.task_channel.take() {
while receiver.try_recv().is_ok() {
discarded += 1;
}
}
self.task_callbacks.clear();
self.task_handles.clear();
self.task_completions = None;
discarded
}
#[cfg(feature = "async")]
pub fn drain_task_commands(&mut self) -> TaskDrainReport {
let mut report = TaskDrainReport::default();
let mut queued = Vec::new();
if let Some((_, receiver)) = &self.task_channel {
while let Ok(command) = receiver.try_recv() {
queued.push(command);
}
}
for command in queued {
match &command {
TaskCommand::SetText { widget_id, text } => {
let result = self.set_text(*widget_id, text);
self.note_task_outcome(&command, result, &mut report);
}
TaskCommand::SetValue { widget_id, value } => {
let result = self.set_value(*widget_id, *value);
self.note_task_outcome(&command, result, &mut report);
}
TaskCommand::SetChecked { widget_id, checked } => {
let result = self.set_checked(*widget_id, *checked);
self.note_task_outcome(&command, result, &mut report);
}
TaskCommand::SetEnabled { widget_id, enabled } => {
let result = self.set_enabled(*widget_id, *enabled);
self.note_task_outcome(&command, result, &mut report);
}
TaskCommand::SetVisible { widget_id, visible } => {
let result = self.set_visible(*widget_id, *visible);
self.note_task_outcome(&command, result, &mut report);
}
TaskCommand::SetDataListItems { widget_id, items } => {
let result = self.set_data_list_items(*widget_id, items);
self.note_task_outcome(&command, result, &mut report);
}
TaskCommand::SetDataGridRows { widget_id, rows } => {
let result = self.set_data_grid_rows(*widget_id, rows);
self.note_task_outcome(&command, result, &mut report);
}
TaskCommand::Progress { task, value } => {
self.pending_events
.push_back(UiEvent::Task(TaskEvent::Progress {
task: *task,
value: *value,
}));
report.applied += 1;
}
TaskCommand::Finished { task } => {
self.pending_events
.push_back(UiEvent::Task(TaskEvent::Finished { task: *task }));
report.applied += 1;
}
TaskCommand::Failed { task, message } => {
self.pending_events
.push_back(UiEvent::Task(TaskEvent::Failed {
task: *task,
message: message.clone(),
}));
report.applied += 1;
}
}
}
self.drain_task_callbacks();
report
}
#[cfg(feature = "async")]
pub fn drain_task_callbacks(&mut self) {
let mut completed = Vec::new();
if let Some((_, rx)) = &self.task_completions {
while let Ok(item) = rx.try_recv() {
completed.push(item);
}
}
for (task_id, payload) in completed {
if let Some(handle) = self.task_handles.remove(&task_id) {
handle.mark_finished();
}
if let Some(callback) = self.task_callbacks.remove(&task_id) {
let _ = callback(self, payload);
}
}
}
#[cfg(feature = "async")]
pub fn try_spawn_task_with_callback<T, W, C>(
&mut self,
worker: W,
callback: C,
) -> GuiResult<crate::async_ui::TaskHandle>
where
T: Send + 'static,
W: FnOnce(crate::async_ui::TaskToken) -> T + Send + 'static,
C: FnOnce(&mut Ui<B>, T) -> GuiResult<()> + 'static,
{
let token = self.task_proxy().start_task();
let task_id = token.id();
if self.task_completions.is_none() {
self.task_completions = Some(std::sync::mpsc::channel());
}
let sender = self.task_completions.as_ref().unwrap().0.clone();
let wake = self.backend.wake_handle();
let token_for_worker = token.clone();
let token_for_check = token.clone();
self.task_callbacks.insert(
task_id,
Box::new(
move |ui: &mut Ui<B>, boxed: Box<dyn std::any::Any + Send>| {
if token_for_check.is_cancelled() {
return Ok(());
}
if let Ok(res) = boxed.downcast::<Result<T, String>>() {
match *res {
Ok(val) => callback(ui, val),
Err(panic_msg) => {
ui.pending_events.push_back(UiEvent::Task(
crate::async_ui::TaskEvent::Failed {
task: task_id,
message: format!("worker panicked: {panic_msg}"),
},
));
Ok(())
}
}
} else {
Ok(())
}
},
),
);
let handle = crate::async_ui::TaskHandle::new(token);
self.task_handles.insert(task_id, handle.clone());
let spawn_res = std::thread::Builder::new()
.name(format!("task-{}", task_id.0))
.spawn(move || {
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
worker(token_for_worker)
}));
let payload: Box<dyn std::any::Any + Send> = match outcome {
Ok(val) => Box::new(Ok::<T, String>(val)),
Err(panic_err) => {
let msg = if let Some(s) = panic_err.downcast_ref::<&str>() {
s.to_string()
} else if let Some(s) = panic_err.downcast_ref::<String>() {
s.clone()
} else {
"worker panicked with unknown payload".to_string()
};
Box::new(Err::<T, String>(msg))
}
};
let _ = sender.send((task_id, payload));
if let Some(wake) = wake {
wake();
}
});
if let Err(_err) = spawn_res {
self.task_callbacks.remove(&task_id);
self.task_handles.remove(&task_id);
return Err(GuiError::ResourceExhausted {
operation: "spawn_task_with_callback thread creation",
code: None,
});
}
Ok(handle)
}
#[cfg(feature = "async")]
pub fn spawn_task_with_callback<T, W, C>(
&mut self,
worker: W,
callback: C,
) -> crate::async_ui::TaskHandle
where
T: Send + 'static,
W: FnOnce(crate::async_ui::TaskToken) -> T + Send + 'static,
C: FnOnce(&mut Ui<B>, T) -> GuiResult<()> + 'static,
{
self.try_spawn_task_with_callback(worker, callback)
.expect("spawn_task_with_callback failed to spawn thread")
}
#[cfg(feature = "async")]
fn note_task_outcome(
&mut self,
command: &TaskCommand,
result: GuiResult<()>,
report: &mut TaskDrainReport,
) {
match result {
Ok(()) => report.applied += 1,
Err(error) => {
report.rejected += 1;
if let Some((widget_id, kind)) = command.widget_target() {
let reason = if self.widgets.contains_key(&widget_id) {
TaskAbortReason::Refused(error)
} else {
TaskAbortReason::WidgetRemoved
};
self.pending_events
.push_back(UiEvent::Task(TaskEvent::Aborted {
widget_id,
command: kind,
reason,
}));
}
}
}
}
pub fn wait_event(&mut self) -> GuiResult<UiEvent> {
loop {
#[cfg(feature = "async")]
self.drain_task_commands();
self.flush_layout_roots();
if let Some(event) = self.pending_events.pop_front() {
if let Some(event) = self.translate_motion_event(event)? {
let event = self.project_pointer(event);
self.pre_dispatch(&event);
return Ok(event);
}
continue;
}
let event = self.backend.wait_event()?;
if matches!(event, UiEvent::TasksPending) {
continue;
}
#[cfg(feature = "async")]
self.drain_task_commands();
if let Some(task_event) = self.pending_events.pop_front() {
self.pending_events.push_back(event);
let task_event = self.project_pointer(task_event);
self.pre_dispatch(&task_event);
return Ok(task_event);
}
if let Some(event) = self.translate_motion_event(event)? {
let event = self.project_pointer(event);
self.pre_dispatch(&event);
return Ok(event);
}
}
}
pub fn poll_event(&mut self) -> GuiResult<Option<UiEvent>> {
loop {
#[cfg(feature = "async")]
self.drain_task_commands();
self.flush_layout_roots();
if let Some(event) = self.pending_events.pop_front() {
if let Some(event) = self.translate_motion_event(event)? {
let event = self.project_pointer(event);
self.pre_dispatch(&event);
return Ok(Some(event));
}
continue;
}
match self.backend.poll_event()? {
Some(UiEvent::TasksPending) => continue,
Some(event) => {
if let Some(event) = self.translate_motion_event(event)? {
let event = self.project_pointer(event);
self.pre_dispatch(&event);
return Ok(Some(event));
}
}
None => return Ok(None),
}
}
}
fn translate_motion_event(&mut self, event: UiEvent) -> GuiResult<Option<UiEvent>> {
let UiEvent::TimerFired {
timer,
elapsed,
missed,
} = event
else {
return Ok(Some(event));
};
let Some(motion) = self.motion_timers.get(&timer).copied() else {
return Ok(Some(UiEvent::TimerFired {
timer,
elapsed,
missed,
}));
};
let Some(active) = self.motions.get(&motion).copied() else {
self.motion_timers.remove(&timer);
return Ok(None);
};
let finished = elapsed >= active.spec.duration;
let progress = if finished {
1.0
} else {
let ratio = elapsed.as_secs_f64() / active.spec.duration.as_secs_f64();
(ratio as f32).min(f32::from_bits(1.0_f32.to_bits() - 1))
};
if finished {
self.backend.cancel_timer(timer)?;
self.motions.remove(&motion);
self.motion_timers.remove(&timer);
self.pending_events.push_front(UiEvent::MotionFinished {
motion,
widget_id: active.widget_id,
});
}
Ok(Some(UiEvent::MotionTicked {
motion,
widget_id: active.widget_id,
progress,
}))
}
fn purge_motion_events(&mut self, motion: MotionId, timer: TimerId) {
self.pending_events.retain(|event| match event {
UiEvent::TimerFired { timer: queued, .. } => *queued != timer,
UiEvent::MotionTicked { motion: queued, .. }
| UiEvent::MotionFinished { motion: queued, .. } => *queued != motion,
_ => true,
});
}
fn remove_widget_motions(&mut self, widget_id: WidgetId) {
let removed: Vec<_> = self
.motions
.iter()
.filter_map(|(motion, active)| {
(active.widget_id == widget_id).then_some((*motion, active.timer))
})
.collect();
for (motion, timer) in &removed {
self.motions.remove(motion);
self.motion_timers.remove(timer);
}
self.pending_events.retain(|event| match event {
UiEvent::TimerFired { timer, .. } => !removed.iter().any(|(_, queued)| queued == timer),
UiEvent::MotionTicked {
widget_id: queued, ..
}
| UiEvent::MotionFinished {
widget_id: queued, ..
} => *queued != widget_id,
_ => true,
});
}
fn project_pointer(&mut self, mut event: UiEvent) -> UiEvent {
if let UiEvent::PopupDismissed { widget_id, .. } = &event {
self.hidden_widgets.insert(*widget_id);
}
match &mut event {
UiEvent::PointerDown {
widget_id, x, y, ..
}
| UiEvent::PointerMove { widget_id, x, y }
| UiEvent::PointerUp {
widget_id, x, y, ..
} => self.project_axes(*widget_id, x, y),
_ => {}
}
event
}
fn project_axes(&self, widget_id: WidgetId, x: &mut f32, y: &mut f32) {
let (logical_x, logical_y) = self.logical_pointer_projection(widget_id, *x, *y);
*x = logical_x;
*y = logical_y;
}
pub fn dispatch_events<F>(&mut self, mut handler: F) -> GuiResult<usize>
where
F: FnMut(UiEvent),
{
let mut dispatched = 0;
while let Some(event) = self.poll_event()? {
self.dispatch_event(event, &mut handler);
dispatched += 1;
}
Ok(dispatched)
}
pub fn dispatch_events_with<F>(&mut self, mut handler: F) -> GuiResult<usize>
where
F: FnMut(&mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
let mut dispatched = 0;
while let Some(event) = self.poll_event()? {
dispatched += 1;
if handler(self, event)? == LoopFlow::Exit {
break;
}
}
Ok(dispatched)
}
pub fn run_until_closed<F>(&mut self, mut handler: F) -> GuiResult<()>
where
F: FnMut(UiEvent),
{
loop {
let event = self.wait_event()?;
let closed = matches!(event, UiEvent::WindowClosed { .. });
self.dispatch_event(event, &mut handler);
if closed {
return Ok(());
}
}
}
pub fn run_until_closed_with<F>(&mut self, mut handler: F) -> GuiResult<()>
where
F: FnMut(&mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
loop {
let event = self.wait_event()?;
let closed = matches!(event, UiEvent::WindowClosed { .. });
let flow = handler(self, event)?;
if closed || flow == LoopFlow::Exit {
return Ok(());
}
}
}
pub fn run_bounded<F>(&mut self, budget: Option<Duration>, mut handler: F) -> GuiResult<RunStop>
where
F: FnMut(UiEvent),
{
self.run_bounded_with(budget, |_ui, event| {
handler(event);
Ok(LoopFlow::Continue)
})
}
pub fn run_bounded_with<F>(
&mut self,
budget: Option<Duration>,
mut handler: F,
) -> GuiResult<RunStop>
where
F: FnMut(&mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
let Some(budget) = budget else {
self.run_until_closed_with(handler)?;
return Ok(RunStop::WindowClosed);
};
let started = Instant::now();
loop {
let mut stop = None;
self.dispatch_events_with(|ui, event| {
let closed = matches!(event, UiEvent::WindowClosed { .. });
let flow = handler(ui, event)?;
if closed {
stop = Some(RunStop::WindowClosed);
} else if flow == LoopFlow::Exit {
stop = Some(RunStop::Exit);
}
if stop.is_some() {
return Ok(LoopFlow::Exit);
}
Ok(LoopFlow::Continue)
})?;
if let Some(stop) = stop {
return Ok(stop);
}
if started.elapsed() >= budget {
return Ok(RunStop::TimedOut);
}
std::thread::sleep(crate::autoclose::BOUNDED_POLL_INTERVAL);
}
}
#[cfg(feature = "routes")]
pub fn run_routed<M, F>(&mut self, routes: &Routes<M>, mut handler: F) -> GuiResult<()>
where
M: Clone + 'static,
F: FnMut(&mut Ui<B>, M) -> GuiResult<LoopFlow>,
{
self.run_until_closed_with(|ui, event| match routes.translate(&event) {
Some(message) => handler(ui, message),
None => Ok(LoopFlow::Continue),
})
}
#[cfg(feature = "routes")]
pub fn dispatch_routed<M, F>(&mut self, routes: &Routes<M>, mut handler: F) -> GuiResult<usize>
where
M: Clone + 'static,
F: FnMut(&mut Ui<B>, M) -> GuiResult<LoopFlow>,
{
self.dispatch_events_with(|ui, event| match routes.translate(&event) {
Some(message) => handler(ui, message),
None => Ok(LoopFlow::Continue),
})
}
fn dispatch_event<F>(&mut self, event: UiEvent, handler: &mut F)
where
F: FnMut(UiEvent),
{
handler(event);
}
pub fn pre_dispatch(&mut self, event: &UiEvent) {
if let UiEvent::WindowResized {
widget_id,
width,
height,
} = event
{
if self.layout_roots.contains(widget_id) {
if let Some(compute) = self.auto_layout_fn {
let _ = compute(self, *widget_id, *width as f32, *height as f32);
}
}
}
if let UiEvent::FocusChanged { widget_id, focused } = event {
if *focused {
self.focused = Some(*widget_id);
} else if self.focused == Some(*widget_id) {
self.focused = None;
}
}
#[cfg(feature = "widgets-pickers")]
if let UiEvent::ColorSelected {
widget_id,
color: Some(color),
} = event
{
if let Some(spec) = self.widgets.get_mut(widget_id) {
if spec.kind == WidgetKind::ColorDialog {
spec.color_dialog_data
.get_or_insert_with(|| ColorDialogData::new(*color))
.remember_accepted(*color);
}
}
}
#[cfg(feature = "widgets-pickers")]
if let UiEvent::FontSelected {
widget_id,
selection: Some((descriptor, effects)),
} = event
{
if let Some(spec) = self.widgets.get_mut(widget_id) {
if spec.kind == WidgetKind::FontDialog {
let data = spec
.font_dialog_data
.get_or_insert_with(|| FontDialogData::new(descriptor.clone()));
data.effects = *effects;
let size = data.clamp_size(descriptor.size_pt);
data.initial = FontDescriptor {
size_pt: size,
..descriptor.clone()
};
}
}
}
self.mirror_user_value(event);
if let UiEvent::ToolToggled {
widget_id,
tool_id,
checked,
} = event
{
if let Some(spec) = self.widgets.get_mut(widget_id) {
if spec.kind == WidgetKind::Toolbar {
if let Some(tool) = toolbar::find_tool_mut(&mut spec.toolbar_items, *tool_id) {
tool.checked = *checked;
}
}
}
}
#[cfg(feature = "property-grid")]
self.observe_property_grid_event(event);
#[cfg(feature = "styled-text")]
self.observe_styled_text_event(event);
#[cfg(feature = "webview")]
self.observe_webview_event(event);
self.dispatch_registered_callbacks(event);
}
#[cfg(any(feature = "property-grid", feature = "styled-text"))]
pub(crate) fn queue_event(&mut self, event: UiEvent) {
self.pending_events.push_back(event);
}
pub fn observe_event(&mut self, event: &UiEvent) {
self.pre_dispatch(event);
}
fn mirror_user_value(&mut self, event: &UiEvent) {
match event {
UiEvent::TextChanged { widget_id, text }
| UiEvent::TextSubmitted { widget_id, text } => {
if let Some(spec) = self.widgets.get_mut(widget_id) {
#[cfg(feature = "widgets-text")]
let is_text_input = matches!(
spec.kind,
WidgetKind::TextInput | WidgetKind::TextArea | WidgetKind::RichText
);
#[cfg(not(feature = "widgets-text"))]
let is_text_input = false;
if is_text_input {
spec.text = Some(text.clone());
}
}
}
UiEvent::Toggled { widget_id, checked } => {
if let Some(spec) = self.widgets.get_mut(widget_id) {
if spec.ensure_property(WidgetProperty::Checked).is_ok() {
spec.checked = Some(*checked);
}
}
}
UiEvent::SelectionChanged {
widget_id, index, ..
} => {
let mirrored = match self.widgets.get_mut(widget_id) {
Some(spec) if spec.ensure_property(WidgetProperty::SelectedIndex).is_ok() => {
spec.selected_index = *index;
true
}
_ => false,
};
if mirrored {
if let Some(index) = index {
self.record_keyed_selection(*widget_id, &[*index]);
}
}
}
UiEvent::MultiSelectionChanged { widget_id, indices } => {
if let Some(spec) = self.widgets.get_mut(widget_id) {
if spec
.ensure_property(WidgetProperty::SelectedIndices)
.is_ok()
{
spec.selected_indices = indices.clone();
}
}
}
UiEvent::ValueChanged { widget_id, value } => {
if let Some(spec) = self.widgets.get_mut(widget_id) {
if spec.ensure_property(WidgetProperty::Value).is_ok() {
spec.value = Some(*value);
}
}
}
UiEvent::DateChanged {
widget_id,
iso_date,
} => {
if let Some(spec) = self.widgets.get_mut(widget_id) {
spec.date_value = Some(iso_date.clone());
}
}
_ => {}
}
}
pub fn text(&self, widget_id: WidgetId) -> GuiResult<&str> {
let spec = self
.widgets
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
Ok(spec.text.as_deref().unwrap_or(""))
}
pub fn is_checked(&self, widget_id: WidgetId) -> GuiResult<bool> {
let spec = self.widget_spec(widget_id)?;
spec.ensure_property(WidgetProperty::Checked)?;
Ok(spec.checked.unwrap_or(false))
}
pub fn selected_index(&self, widget_id: WidgetId) -> GuiResult<Option<usize>> {
let spec = self.widget_spec(widget_id)?;
spec.ensure_property(WidgetProperty::SelectedIndex)?;
Ok(spec.selected_index)
}
pub fn selected_indices(&self, widget_id: WidgetId) -> GuiResult<&[usize]> {
let spec = self.widget_spec(widget_id)?;
spec.ensure_property(WidgetProperty::SelectedIndices)?;
Ok(&spec.selected_indices)
}
pub fn value(&self, widget_id: WidgetId) -> GuiResult<Option<i32>> {
let spec = self.widget_spec(widget_id)?;
spec.ensure_property(WidgetProperty::Value)?;
Ok(spec.value)
}
pub fn date_value(&self, widget_id: WidgetId) -> GuiResult<Option<&str>> {
let spec = self.widget_spec(widget_id)?;
Ok(spec.date_value.as_deref())
}
pub fn on_window_close<F>(&mut self, window_id: WidgetId, callback: F) -> GuiResult<()>
where
F: FnMut() + 'static,
{
self.ensure_window(window_id, WidgetProperty::WindowCallback)?;
self.on_window_close
.entry(window_id)
.or_default()
.push(Box::new(callback));
Ok(())
}
pub fn on_window_resize<F>(&mut self, window_id: WidgetId, callback: F) -> GuiResult<()>
where
F: FnMut(i32, i32) + 'static,
{
self.ensure_window(window_id, WidgetProperty::WindowCallback)?;
self.on_window_resize
.entry(window_id)
.or_default()
.push(Box::new(callback));
Ok(())
}
pub fn set_layout_root(&mut self, window_id: WidgetId) -> GuiResult<()> {
self.add_layout_root(window_id)
}
pub fn add_layout_root(&mut self, window_id: WidgetId) -> GuiResult<()> {
self.ensure_window(window_id, WidgetProperty::LayoutRoot)?;
self.enable_auto_layout();
self.layout_roots.insert(window_id);
if let Some((w, h)) = self.widgets.get(&window_id).and_then(|spec| spec.size) {
self.layout_root_sizes
.insert(window_id, (w as f32, h as f32));
self.invalidate_layout(window_id);
}
Ok(())
}
pub fn has_dirty_layout(&self) -> bool {
!self.layout_dirty.is_empty()
}
pub fn is_layout_dirty(&self, widget_id: WidgetId) -> bool {
self.layout_dirty.contains(&widget_id)
}
pub fn flush_layout_roots(&mut self) {
let Some(compute) = self.auto_layout_fn else {
return;
};
if self.layout_dirty.is_empty() {
return;
}
let pending: Vec<(WidgetId, (f32, f32))> = self
.layout_root_sizes
.iter()
.filter(|(root, _)| self.layout_roots.contains(root))
.filter(|(root, _)| {
self.layout_dirty
.iter()
.any(|widget_id| self.chain_reaches_root(*widget_id, **root))
})
.map(|(root, size)| (*root, *size))
.collect();
for (root, (width, height)) in pending {
let _ = compute(self, root, width, height);
}
}
pub fn compute_layout_if_dirty(&mut self) {
self.flush_layout_roots();
}
pub fn remove_layout_root(&mut self, window_id: WidgetId) -> bool {
self.layout_roots.remove(&window_id)
}
pub fn is_layout_root(&self, window_id: WidgetId) -> bool {
self.layout_roots.contains(&window_id)
}
pub fn layout_roots(&self) -> &HashSet<WidgetId> {
&self.layout_roots
}
pub fn on_menu_item_selected<F>(&mut self, item_id: MenuItemId, callback: F) -> GuiResult<()>
where
F: FnMut() + 'static,
{
if !self.menu_item_to_menu.contains_key(&item_id) {
return Err(GuiError::Backend(format!(
"Menu item not found: {}",
item_id.0
)));
}
self.on_menu_item_selected
.entry(item_id)
.or_default()
.push(Box::new(callback));
Ok(())
}
fn reject_embedded_nul(text: &str) -> GuiResult<()> {
if text.contains('\0') {
Err(GuiError::Backend(
"text cannot contain an embedded NUL".to_owned(),
))
} else {
Ok(())
}
}
pub(crate) fn widget_spec(&self, widget_id: WidgetId) -> GuiResult<&WidgetSpec> {
self.widgets
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))
}
fn require_property(
&mut self,
widget_id: WidgetId,
property: WidgetProperty,
) -> GuiResult<&mut WidgetSpec> {
let spec = self
.widgets
.get_mut(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
spec.ensure_property(property)?;
Ok(spec)
}
fn ensure_window(&self, widget_id: WidgetId, property: WidgetProperty) -> GuiResult<()> {
self.widget_spec(widget_id)?.ensure_property(property)
}
fn dispatch_registered_callbacks(&mut self, event: &UiEvent) {
match event {
UiEvent::WindowClosed { widget_id } => {
if let Some(callbacks) = self.on_window_close.get_mut(widget_id) {
for callback in callbacks.iter_mut() {
callback();
}
}
}
UiEvent::WindowResized {
widget_id,
width,
height,
} => {
if let Some(callbacks) = self.on_window_resize.get_mut(widget_id) {
for callback in callbacks.iter_mut() {
callback(*width, *height);
}
}
}
UiEvent::MenuItemSelected { item_id, .. } => {
if let Some(callbacks) = self.on_menu_item_selected.get_mut(item_id) {
for callback in callbacks.iter_mut() {
callback();
}
}
}
_ => {}
}
}
pub fn widget(&self, widget_id: WidgetId) -> Option<&WidgetSpec> {
self.widgets.get(&widget_id)
}
#[doc(hidden)]
pub fn e2e_widget_specs(&self) -> impl Iterator<Item = &WidgetSpec> {
self.widgets.values()
}
#[doc(hidden)]
pub fn e2e_dispatch_one<F>(&mut self, handler: &mut F) -> GuiResult<Option<LoopFlow>>
where
F: FnMut(&mut Self, UiEvent) -> GuiResult<LoopFlow>,
{
#[cfg(feature = "async")]
self.drain_task_commands();
let event = match self.pending_events.pop_front() {
Some(event) => Some(event),
None => self.backend.e2e_poll_event()?,
};
let Some(event) = event else {
return Ok(None);
};
let Some(event) = self.translate_motion_event(event)? else {
return Ok(Some(LoopFlow::Continue));
};
let event = self.project_pointer(event);
if matches!(event, UiEvent::TasksPending) {
return Ok(Some(LoopFlow::Continue));
}
match &event {
UiEvent::TextChanged { widget_id, text } => {
if let Some(spec) = self.widgets.get_mut(widget_id) {
spec.text = Some(text.clone());
}
}
UiEvent::Toggled { widget_id, checked } => {
if let Some(spec) = self.widgets.get_mut(widget_id) {
spec.checked = Some(*checked);
}
}
_ => {}
}
self.pre_dispatch(&event);
handler(self, event).map(Some)
}
pub fn widget_count(&self) -> usize {
self.widgets.len()
}
}
#[cfg(feature = "widgets-data")]
fn serialize_data_grid_rows(rows: &[Vec<String>]) -> String {
rows.iter()
.map(|row| row.join("\t"))
.collect::<Vec<String>>()
.join("\n")
}
#[cfg(feature = "widgets-data")]
fn parse_data_list_items(content: &str) -> Vec<String> {
content
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.map(ToOwned::to_owned)
.collect()
}
#[cfg(feature = "widgets-data")]
fn parse_data_grid_rows(content: &str) -> Vec<Vec<String>> {
content
.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| line.split('\t').map(ToOwned::to_owned).collect())
.collect()
}
#[cfg(test)]
mod tests {
use crate::access::AccessibleRole;
use crate::events::{AccessibleNotification, UiEvent};
use crate::pickers::Rgba;
use crate::test_support::MockBackend;
use crate::theme::{Theme, ThemeMode, ThemeOverride};
use super::*;
#[test]
fn backend_inventory_matches_declarations_and_group_totals() {
let raw_source = include_str!("ui.rs");
let source = raw_source.replace("\r\n", "\n");
let body = |declaration| {
source
.split_once(declaration)
.unwrap()
.1
.split_once("\n}\n")
.unwrap()
.0
};
let backend = body("\npub trait Backend: TextMeasure {");
let methods = |body: &str| {
body.lines()
.filter(|line| line.starts_with(" fn ") || line.starts_with(" unsafe fn "))
.count()
};
let declared = methods(backend);
let associated = backend
.lines()
.filter(|line| line.starts_with(" type "))
.count();
let inherited = methods(body("\npub trait TextMeasure {"));
let total = declared + associated + inherited;
assert!(source.contains(&format!(
"/// The trait carries {total} items: {declared} methods declared here"
)));
assert!(source.contains(&format!(
"/// It must print `Backend {declared} fns + {associated} assoc type + {inherited} supertrait fn = {total}"
)));
let table = source
.split_once("/// | Group | Items | Covers |")
.unwrap()
.1
.split_once("/// # Maintenance")
.unwrap()
.0;
let grouped: usize = table
.lines()
.filter_map(|line| line.split('|').nth(2)?.trim().parse::<usize>().ok())
.sum();
assert_eq!(grouped, total);
}
#[test]
fn create_attach_show_happy_path() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Main"))
.expect("window should be created");
let button = ui
.create(WidgetKind::Button, Some("Run"))
.expect("button should be created");
ui.attach(window, button).expect("attach should succeed");
ui.show(window).expect("window should show");
assert_eq!(ui.widget_count(), 2);
assert_eq!(ui.widget(button).and_then(|s| s.parent), Some(window));
assert_eq!(ui.backend().shown, vec![window]);
}
#[test]
fn set_text_for_unknown_widget_fails() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let err = ui
.set_text(WidgetId(999), "Nope")
.expect_err("unknown widget should return error");
assert_eq!(err, GuiError::WidgetNotFound(999));
}
#[test]
#[cfg(feature = "widgets-text")]
fn set_text_updates_text_area() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let text_area = ui
.create(WidgetKind::TextArea, Some("line 1"))
.expect("text area should be created");
ui.set_text(text_area, "line 1\nline 2")
.expect("set_text should update text area");
assert_eq!(
ui.widget(text_area).and_then(|spec| spec.text.as_deref()),
Some("line 1\nline 2")
);
}
#[test]
#[cfg(feature = "widgets-text")]
fn set_text_and_placeholder_reject_embedded_nul_without_mutating_spec() {
let mut ui = Ui::new(MockBackend::default());
let input = ui
.create(WidgetKind::TextInput, Some("visible"))
.expect("text input should be created");
ui.set_placeholder_text(input, "hint")
.expect("placeholder should be accepted");
let err = ui
.set_text(input, "visible\0hidden")
.expect_err("embedded NUL must be rejected");
assert!(
matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")),
"unexpected error: {err:?}"
);
assert_eq!(
ui.widget(input).and_then(|spec| spec.text.as_deref()),
Some("visible"),
"a rejected set_text must not store the truncated suffix"
);
let err = ui
.set_placeholder_text(input, "hint\0hidden")
.expect_err("embedded NUL must be rejected");
assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
assert_eq!(
ui.widget(input)
.and_then(|spec| spec.placeholder_text.as_deref()),
Some("hint")
);
}
#[test]
fn comprehensive_embedded_nul_rejection_and_transactional_rollback() {
let mut ui = Ui::new(MockBackend::default());
let err = ui
.create(WidgetKind::Label, Some("visible\0hidden"))
.expect_err("embedded NUL in creation text must be rejected");
assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
let label = ui
.create(WidgetKind::Label, Some("status"))
.expect("clean label");
#[cfg(feature = "widgets-media")]
let img = ui.create(WidgetKind::Image, None).expect("clean image");
let tabs = ui.create(WidgetKind::Tabs, None).expect("clean tabs");
let err = ui
.set_tooltip(label, "info\0hidden")
.expect_err("embedded NUL in tooltip must be rejected");
assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
assert_eq!(ui.widget(label).and_then(|s| s.tooltip.as_deref()), None);
#[cfg(feature = "widgets-media")]
{
let err = ui
.set_image_source(img, "art\0hidden.png")
.expect_err("embedded NUL in image source must be rejected");
assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
assert_eq!(ui.widget(img).and_then(|s| s.image_source.as_deref()), None);
}
let err = ui
.set_tab_items(tabs, &["Tab 1".to_owned(), "Tab 2\0hidden".to_owned()])
.expect_err("embedded NUL in tab items must be rejected");
assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
assert!(ui.widget(tabs).unwrap().tab_items.is_empty());
let err = ui
.show_confirm_dialog("Delete?\0hidden", "Are you sure?")
.expect_err("embedded NUL in dialog title must be rejected");
assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
let menu = ui.create_menu().expect("menu");
let err = ui
.add_submenu(menu, "Sub\0hidden")
.expect_err("embedded NUL in submenu must be rejected");
assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
let err = ui
.add_menu_item(menu, "Item\0hidden")
.expect_err("embedded NUL in menu item must be rejected");
assert!(matches!(err, GuiError::Backend(ref msg) if msg.contains("NUL")));
}
#[test]
fn unsupported_label_presentation_setters_are_transactional() {
let mut ui = Ui::new(CustomMeasuringBackend::default());
let label = ui
.create(WidgetKind::Label, Some("status"))
.expect("label should be created");
let before = ui.widget(label).cloned().expect("label spec");
assert_eq!(
ui.set_label_alignment(label, LabelAlignment::Center),
Err(GuiError::UnsupportedCapability(
"label_alignment".to_owned()
))
);
assert_eq!(
ui.set_label_wrap(label, LabelWrap::Word),
Err(GuiError::UnsupportedCapability("label_wrap".to_owned()))
);
assert_eq!(ui.widget(label), Some(&before));
assert_eq!(ui.backend().created.get(&label), Some(&before));
}
#[test]
#[cfg(feature = "widgets-canvas")]
fn canvas_surface_round_trips_and_rejects_other_kinds() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let canvas = ui
.create(WidgetKind::Canvas, None)
.expect("canvas should be created");
let button = ui
.create(WidgetKind::Button, Some("button"))
.expect("button should be created");
let mut pixels = vec![0u8; 4 * 4 * 4];
for pixel in pixels.as_chunks_mut::<4>().0 {
pixel[3] = 255;
}
let surface = crate::CanvasSurface::from_rgba(4, 4, pixels).expect("valid surface");
assert_eq!(surface.width(), 4);
assert_eq!(surface.height(), 4);
assert_eq!(surface.pixels().len(), 64);
ui.set_canvas_surface(canvas, &surface)
.expect("canvas accepts a surface");
assert_eq!(
ui.widget(canvas)
.and_then(|spec| spec.canvas_surface.as_ref()),
Some(&surface)
);
assert_eq!(ui.backend().last_canvas_surface(), Some(&surface));
let err = ui
.set_canvas_surface(button, &surface)
.expect_err("only canvases accept surfaces");
assert_eq!(err, GuiError::UnsupportedWidget("set_canvas_surface"));
assert!(crate::CanvasSurface::from_rgba(4, 4, vec![0; 63]).is_err());
assert!(crate::CanvasSurface::from_rgba(0, 4, Vec::new()).is_err());
}
#[test]
#[cfg(feature = "widgets-canvas")]
fn canvas_scene_rejects_invalid_logical_size() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let canvas = ui
.create(WidgetKind::Canvas, None)
.expect("canvas should be created");
let invalid = crate::CanvasScene {
logical_width: 0.0,
logical_height: 10.0,
primitives: vec![],
};
let err = ui
.set_canvas_scene(canvas, &invalid)
.expect_err("canvas scenes must have positive finite logical dimensions");
assert_eq!(
err,
GuiError::Backend("Canvas scene logical size must be finite and positive".to_owned())
);
}
#[test]
fn vulkan_canvas_handle_requires_vulkan_canvas_widget() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui
.create(WidgetKind::Button, Some("button"))
.expect("button should be created");
let err = ui
.native_handle(button)
.expect_err("non-vulkan widget should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("native_handle"));
}
#[test]
fn gpu_capabilities_are_queryable_and_unknown_names_are_false() {
let ui = Ui::new(MockBackend::default());
let capabilities = ui.gpu_surface_capabilities();
assert_eq!(capabilities, GpuSurfaceCapabilities::all());
assert!(ui.supports_capability("vulkan_surface"));
assert!(ui.supports_capability("gpu_surface"));
assert!(ui.supports_capability("gpu_degradation_fallback"));
assert!(!ui.supports_capability("unknown_gpu_capability"));
}
#[test]
#[cfg(feature = "widgets-canvas")]
fn unavailable_vulkan_canvas_strictly_fails_with_typed_capability_error() {
let mut backend = MockBackend::default();
let mut capabilities = GpuSurfaceCapabilities::all();
capabilities.vulkan_surface = false;
backend.set_gpu_surface_capabilities(capabilities);
let mut ui = Ui::new(backend);
assert_eq!(
ui.create(WidgetKind::VulkanCanvas, None),
Err(GuiError::UnsupportedCapability("vulkan_surface".to_owned()))
);
assert_eq!(ui.widget_count(), 0);
assert!(!ui.is_gpu_degraded(WidgetId(1)));
}
#[test]
#[cfg(feature = "widgets-canvas")]
fn gpu_diagnostic_placeholder_policy_is_deterministic_in_mock() {
let mut backend = MockBackend::default();
let mut capabilities = GpuSurfaceCapabilities::all();
capabilities.vulkan_surface = false;
backend.set_gpu_surface_capabilities(capabilities);
let mut ui = Ui::new(backend);
ui.set_gpu_degradation_policy(GpuDegradationPolicy::DiagnosticPlaceholder);
let canvas = ui
.create(WidgetKind::VulkanCanvas, None)
.expect("Mock should simulate a diagnostic placeholder");
assert!(ui.is_gpu_degraded(canvas));
assert_eq!(
ui.backend().gpu_fallbacks.get(&canvas),
Some(&GpuDegradationPolicy::DiagnosticPlaceholder)
);
assert_eq!(
ui.vulkan_canvas_handle(canvas),
Err(GuiError::UnsupportedCapability("vulkan_surface".to_owned()))
);
assert_eq!(
ui.draw_demo_cube(canvas),
Err(GuiError::UnsupportedCapability("vulkan_surface".to_owned()))
);
ui.remove(canvas).expect("remove degraded widget");
assert!(!ui.is_gpu_degraded(canvas));
}
#[test]
#[cfg(feature = "widgets-canvas")]
fn gpu_canvas_fallback_accepts_canvas_scenes_and_refuses_without_support() {
let mut backend = MockBackend::default();
let mut capabilities = GpuSurfaceCapabilities::all();
capabilities.vulkan_surface = false;
backend.set_gpu_surface_capabilities(capabilities);
let mut ui = Ui::new(backend);
ui.set_gpu_degradation_policy(GpuDegradationPolicy::Canvas2DFallback);
let canvas = ui
.create(WidgetKind::VulkanCanvas, None)
.expect("Mock should simulate the 2D fallback");
let scene = crate::CanvasScene {
logical_width: 80.0,
logical_height: 60.0,
primitives: Vec::new(),
};
ui.set_canvas_scene(canvas, &scene)
.expect("the 2D fallback accepts a canvas scene");
assert_eq!(ui.backend().last_canvas_scene(), Some(&scene));
let mut no_fallback = GpuSurfaceCapabilities::all();
no_fallback.vulkan_surface = false;
no_fallback.diagnostic_placeholder = false;
no_fallback.headless_emulation = false;
let mut backend = MockBackend::default();
backend.set_gpu_surface_capabilities(no_fallback);
let mut ui = Ui::new(backend);
ui.set_gpu_degradation_policy(GpuDegradationPolicy::Canvas2DFallback);
assert_eq!(
ui.create(WidgetKind::VulkanCanvas, None),
Err(GuiError::UnsupportedCapability(
"gpu_degradation_fallback".to_owned()
))
);
assert_eq!(ui.widget_count(), 0);
}
#[test]
#[cfg(feature = "widgets-canvas")]
fn vulkan_canvas_handle_returns_backend_handle() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let canvas = ui
.create(WidgetKind::VulkanCanvas, None)
.expect("vulkan canvas should be created");
let handle = ui
.native_handle(canvas)
.expect("native handle should be returned");
assert_eq!(handle, canvas.0 as usize);
}
#[test]
#[cfg(feature = "widgets-canvas")]
fn draw_demo_cube_requires_vulkan_canvas_widget() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
let err = ui
.draw_demo_cube(label)
.expect_err("non-vulkan widget should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("draw_demo_cube"));
}
#[test]
#[cfg(feature = "widgets-canvas")]
fn draw_demo_cube_accepts_vulkan_canvas_widget() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let canvas = ui
.create(WidgetKind::VulkanCanvas, None)
.expect("vulkan canvas should be created");
ui.draw_demo_cube(canvas)
.expect("draw demo cube should succeed for canvas");
}
#[test]
fn dispatch_events_processes_backend_queue() {
let mut backend = MockBackend::default();
backend.push_event(UiEvent::Clicked {
widget_id: WidgetId(1),
});
backend.push_event(UiEvent::WindowClosed {
widget_id: WidgetId(1),
});
let mut ui = Ui::new(backend);
let mut seen = Vec::new();
let count = ui
.dispatch_events(|event| seen.push(event))
.expect("dispatch should succeed");
assert_eq!(count, 2);
assert_eq!(
seen,
vec![
UiEvent::Clicked {
widget_id: WidgetId(1),
},
UiEvent::WindowClosed {
widget_id: WidgetId(1),
},
]
);
}
#[test]
fn dispatch_events_with_hands_ui_to_handler_and_preserves_order() {
use std::cell::RefCell;
use std::rc::Rc;
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Runner"))
.expect("window should be created");
let label = ui
.create(WidgetKind::Label, Some("before"))
.expect("label should be created");
ui.attach(window, label).expect("attach label");
ui.show(window).expect("show window");
let order = Rc::new(RefCell::new(Vec::new()));
let callback_order = Rc::clone(&order);
ui.on_window_close(window, move || {
callback_order.borrow_mut().push("callback");
})
.expect("register close callback");
ui.backend_mut()
.push_event(UiEvent::Clicked { widget_id: label });
ui.backend_mut()
.push_event(UiEvent::WindowClosed { widget_id: window });
let handler_order = Rc::clone(&order);
let dispatched = ui
.dispatch_events_with(|ui, event| {
handler_order.borrow_mut().push(match &event {
UiEvent::Clicked { .. } => "click",
UiEvent::WindowClosed { .. } => "close",
_ => "other",
});
if matches!(event, UiEvent::Clicked { .. }) {
ui.set_text(label, "mutated")?;
}
Ok(LoopFlow::Continue)
})
.expect("dispatch should succeed");
assert_eq!(dispatched, 2);
assert_eq!(
ui.widget(label).and_then(|spec| spec.text.as_deref()),
Some("mutated"),
"the handler mutates widgets inline"
);
assert_eq!(&*order.borrow(), &["click", "callback", "close"]);
}
#[test]
fn run_until_closed_with_can_mutate_and_exit_early() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Runner"))
.expect("window should be created");
let label = ui
.create(WidgetKind::Label, Some("idle"))
.expect("label should be created");
ui.attach(window, label).expect("attach label");
ui.show(window).expect("show window");
ui.backend_mut()
.push_event(UiEvent::Clicked { widget_id: label });
let mut seen = 0;
ui.run_until_closed_with(|ui, event| {
if matches!(event, UiEvent::Clicked { .. }) {
seen += 1;
ui.set_text(label, "clicked")?;
return Ok(LoopFlow::Exit);
}
Ok(LoopFlow::Continue)
})
.expect("runner should stop on Exit");
assert_eq!(seen, 1);
assert_eq!(
ui.widget(label).and_then(|spec| spec.text.as_deref()),
Some("clicked")
);
}
#[test]
fn run_bounded_without_a_budget_matches_the_unbounded_runner() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Bounded"))
.expect("window should be created");
ui.show(window).expect("show window");
ui.backend_mut()
.push_event(UiEvent::WindowClosed { widget_id: window });
let stop = ui
.run_bounded_with(None, |_ui, _event| Ok(LoopFlow::Continue))
.expect("runner should stop on the queued close");
assert_eq!(stop, RunStop::WindowClosed);
}
#[test]
fn run_bounded_with_stops_on_exit_and_on_the_budget() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Bounded"))
.expect("window should be created");
ui.show(window).expect("show window");
ui.backend_mut()
.push_event(UiEvent::Clicked { widget_id: window });
let exit = ui
.run_bounded_with(Some(Duration::from_secs(5)), |_ui, event| {
Ok(if matches!(event, UiEvent::Clicked { .. }) {
LoopFlow::Exit
} else {
LoopFlow::Continue
})
})
.expect("runner should stop on Exit");
assert_eq!(exit, RunStop::Exit, "an explicit exit beats the budget");
let started = Instant::now();
let timed_out = ui
.run_bounded_with(Some(Duration::from_millis(20)), |_ui, _event| {
panic!("no event should arrive")
})
.expect("runner should return once the budget elapses");
assert_eq!(timed_out, RunStop::TimedOut);
assert!(
started.elapsed() >= Duration::from_millis(20),
"the budget, not an event, ended the run"
);
}
#[test]
fn run_bounded_with_returns_immediately_on_a_zero_budget() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Bounded"))
.expect("window should be created");
ui.show(window).expect("show window");
let started = Instant::now();
let stop = ui
.run_bounded_with(Some(Duration::ZERO), |_ui, _event| {
panic!("no event should arrive")
})
.expect("runner should return at once");
assert_eq!(stop, RunStop::TimedOut);
assert!(
started.elapsed() < Duration::from_secs(1),
"a zero budget never sleeps through a poll interval"
);
}
#[test]
fn run_bounded_dispatches_events_and_reports_the_timeout() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Bounded"))
.expect("window should be created");
ui.show(window).expect("show window");
ui.backend_mut()
.push_event(UiEvent::Clicked { widget_id: window });
let mut seen = 0;
let stop = ui
.run_bounded(Some(Duration::from_millis(20)), |_event| seen += 1)
.expect("runner should return once the budget elapses");
assert_eq!(stop, RunStop::TimedOut, "the queued click is not a close");
assert_eq!(seen, 1, "queued events are still dispatched");
}
#[test]
fn pointer_events_are_projected_onto_the_logical_space() {
use crate::displays::{DisplayInfo, DisplayRect};
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Pointer"))
.expect("window should be created");
let canvas = ui
.create(WidgetKind::Button, Some("target"))
.expect("target should be created");
ui.attach(window, canvas).expect("attach canvas");
ui.show(window).expect("show window");
ui.backend_mut().push_event(UiEvent::PointerMove {
widget_id: canvas,
x: 100.0,
y: 200.0,
});
assert_eq!(
ui.poll_event().expect("poll should succeed"),
Some(UiEvent::PointerMove {
widget_id: canvas,
x: 100.0,
y: 200.0,
})
);
ui.backend_mut().set_displays(vec![DisplayInfo::new(
1,
"mock-primary",
DisplayRect::new(0, 0, 1920, 1080),
DisplayRect::new(0, 0, 1920, 1040),
1.25,
true,
)]);
for (physical, logical) in [
(
UiEvent::PointerDown {
widget_id: canvas,
x: 125.0,
y: 250.0,
button: 0,
},
(100.0, 200.0),
),
(
UiEvent::PointerMove {
widget_id: canvas,
x: 250.0,
y: 375.0,
},
(200.0, 300.0),
),
(
UiEvent::PointerUp {
widget_id: canvas,
x: 62.5,
y: 0.0,
button: 0,
},
(50.0, 0.0),
),
] {
ui.backend_mut().push_event(physical);
let delivered = ui
.poll_event()
.expect("poll should succeed")
.expect("the pushed event should be delivered");
let (x, y) = match delivered {
UiEvent::PointerDown { x, y, .. }
| UiEvent::PointerMove { x, y, .. }
| UiEvent::PointerUp { x, y, .. } => (x, y),
other => panic!("unexpected event: {other:?}"),
};
assert_eq!(
(x, y),
logical,
"physical input maps onto the logical space"
);
}
ui.backend_mut().push_event(UiEvent::WindowResized {
widget_id: window,
width: 800,
height: 600,
});
assert_eq!(
ui.poll_event().expect("poll should succeed"),
Some(UiEvent::WindowResized {
widget_id: window,
width: 800,
height: 600,
})
);
}
#[test]
fn pointer_projection_applies_once_per_event_on_every_delivery_path() {
use crate::displays::{DisplayInfo, DisplayRect};
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Pointer"))
.expect("window should be created");
let canvas = ui
.create(WidgetKind::Button, Some("target"))
.expect("target should be created");
ui.attach(window, canvas).expect("attach canvas");
ui.show(window).expect("show window");
ui.backend_mut().set_displays(vec![DisplayInfo::new(
1,
"mock-primary",
DisplayRect::new(0, 0, 1920, 1080),
DisplayRect::new(0, 0, 1920, 1040),
2.0,
true,
)]);
ui.backend_mut().push_event(UiEvent::PointerMove {
widget_id: canvas,
x: 200.0,
y: 100.0,
});
let mut seen = Vec::new();
let dispatched = ui
.dispatch_events(|event| seen.push(event))
.expect("dispatch should succeed");
assert_eq!(dispatched, 1);
assert_eq!(
seen,
vec![UiEvent::PointerMove {
widget_id: canvas,
x: 100.0,
y: 50.0,
}],
"a 200 % display divides exactly once"
);
assert_eq!(
ui.logical_pointer_projection(canvas, 200.0, 100.0),
(100.0, 50.0),
"the event path and the explicit projection agree"
);
}
#[test]
fn handler_produced_events_are_delivered_not_dropped() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Runner"))
.expect("window should be created");
let button = ui
.create(WidgetKind::Button, Some("Go"))
.expect("button should be created");
ui.attach(window, button).expect("attach button");
ui.show(window).expect("show window");
ui.backend_mut()
.push_event(UiEvent::Clicked { widget_id: button });
let mut produced = false;
let mut clicks = 0;
let dispatched = ui
.dispatch_events_with(|ui, event| {
if matches!(event, UiEvent::Clicked { .. }) {
clicks += 1;
if !produced {
produced = true;
ui.activate(button)?;
}
}
Ok(LoopFlow::Continue)
})
.expect("dispatch should succeed");
assert_eq!(clicks, 2, "the handler-produced click is delivered");
assert_eq!(dispatched, 2);
}
#[test]
#[cfg(feature = "routes")]
fn dispatch_routed_translates_messages_and_keeps_callback_order() {
use std::cell::RefCell;
use std::rc::Rc;
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Routed"))
.expect("window should be created");
let button = ui
.create(WidgetKind::Button, Some("Go"))
.expect("button should be created");
let label = ui
.create(WidgetKind::Label, Some("idle"))
.expect("label should be created");
ui.attach(window, button).expect("attach button");
ui.attach(window, label).expect("attach label");
ui.show(window).expect("show window");
let order = Rc::new(RefCell::new(Vec::new()));
let callback_order = Rc::clone(&order);
ui.on_window_close(window, move || {
callback_order.borrow_mut().push("callback");
})
.expect("register close callback");
let mut routes = Routes::new();
routes.on(button, "go");
routes.on_event(window, |event| match event {
UiEvent::WindowClosed { .. } => Some("closed"),
_ => None,
});
ui.backend_mut()
.push_event(UiEvent::Clicked { widget_id: button });
ui.backend_mut().push_event(UiEvent::Toggled {
widget_id: label,
checked: true,
});
ui.backend_mut()
.push_event(UiEvent::WindowClosed { widget_id: window });
let handler_order = Rc::clone(&order);
let dispatched = ui
.dispatch_routed(&routes, |ui, message| {
handler_order.borrow_mut().push(message);
if message == "go" {
ui.set_text(label, "clicked")?;
}
Ok(LoopFlow::Continue)
})
.expect("routed dispatch should succeed");
assert_eq!(dispatched, 3, "every event is drained");
assert_eq!(
ui.widget(label).and_then(|spec| spec.text.as_deref()),
Some("clicked"),
"the routed handler updates widgets inline"
);
assert_eq!(&*order.borrow(), &["go", "callback", "closed"]);
}
#[test]
#[cfg(feature = "routes")]
fn run_routed_hands_typed_messages_and_stops_on_exit() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Routed"))
.expect("window should be created");
let button = ui
.create(WidgetKind::Button, Some("Quit"))
.expect("button should be created");
ui.attach(window, button).expect("attach button");
ui.show(window).expect("show window");
let mut routes = Routes::new();
routes.on(button, "quit");
ui.backend_mut()
.push_event(UiEvent::Clicked { widget_id: button });
let mut messages = Vec::new();
ui.run_routed(&routes, |_ui, message| {
messages.push(message);
Ok(LoopFlow::Exit)
})
.expect("routed runner should stop on Exit");
assert_eq!(messages, vec!["quit"]);
}
#[test]
fn register_window_callback_requires_window_widget() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui
.create(WidgetKind::Button, Some("not a window"))
.expect("button should be created");
let err = ui
.on_window_close(button, || {})
.expect_err("non-window should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("window_callback"));
}
#[test]
fn computed_layout_updates_apply_parent_frames_before_descendants() {
let mut ui = Ui::new(MockBackend::default());
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let root = ui.create(WidgetKind::Container, None).expect("root");
let keypad = ui.create(WidgetKind::Container, None).expect("keypad");
let row = ui.create(WidgetKind::Container, None).expect("row");
let button = ui.create(WidgetKind::Button, Some("7")).expect("button");
ui.attach(window, root).expect("attach root");
ui.attach(root, keypad).expect("attach keypad");
ui.attach(keypad, row).expect("attach row");
ui.attach(row, button).expect("attach button");
let mut updates = vec![
(button, Some((40, 30)), Some((0, 0))),
(row, Some((200, 40)), Some((0, 0))),
(keypad, Some((200, 160)), Some((0, 0))),
(root, Some((300, 300)), Some((0, 0))),
];
ui.sort_layout_updates_parent_first(&mut updates);
assert_eq!(
updates.iter().map(|(id, _, _)| *id).collect::<Vec<_>>(),
vec![root, keypad, row, button]
);
ui.set_container_direction(root, ContainerDirection::Vertical)
.expect("root direction");
ui.set_container_padding(root, 16).expect("root padding");
ui.set_container_direction(keypad, ContainerDirection::Vertical)
.expect("keypad direction");
ui.set_flex_grow(keypad, 1.0).expect("keypad grows");
ui.set_container_direction(row, ContainerDirection::Horizontal)
.expect("row direction");
ui.set_flex_grow(row, 1.0).expect("row grows");
ui.set_min_size(button, 28, 28).expect("button minimum");
ui.set_flex_grow(button, 1.0).expect("button grows");
ui.compute_layout(window, 318.0, 322.0)
.expect("compute nested layout");
assert_eq!(ui.layout_rect(keypad).unwrap().x, 16.0);
assert_eq!(ui.layout_rect(keypad).unwrap().y, 16.0);
assert_eq!(ui.layout_rect(row).unwrap().x, 0.0);
assert_eq!(ui.layout_rect(row).unwrap().y, 0.0);
assert_eq!(ui.layout_rect(button).unwrap().x, 0.0);
assert_eq!(ui.layout_rect(button).unwrap().y, 0.0);
}
#[test]
fn set_layout_root_recomputes_layout_on_window_resize() {
use crate::layout::{Dimension, Size, Style};
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("w"))
.expect("window created");
let button = ui
.create(WidgetKind::Button, Some("b"))
.expect("button created");
ui.attach(window, button).expect("attached");
if let Some(&node) = ui.layout_nodes.get(&button) {
let style = Style {
size: Size {
width: Dimension::length(40.0),
height: Dimension::length(20.0),
},
..Default::default()
};
let _ = ui.layout_tree.set_style(node, style);
}
ui.set_layout_root(window).expect("layout root set");
ui.backend_mut().push_event(UiEvent::WindowResized {
widget_id: window,
width: 640,
height: 480,
});
let count = ui.dispatch_events(|_| {}).expect("dispatch");
assert_eq!(count, 1);
assert_eq!(ui.widget(button).and_then(|spec| spec.size), Some((40, 20)));
}
#[test]
#[cfg(feature = "widgets-text")]
fn computed_layout_expansion_tracks_percent_flex_and_stretch() {
use crate::layout::{Dimension, Size};
let mut ui = Ui::new(MockBackend::default());
let window = ui
.create(WidgetKind::Window, Some("Notepad layout"))
.expect("window created");
let root = ui
.create(WidgetKind::Container, None)
.expect("root container created");
let editor = ui
.create(WidgetKind::TextArea, None)
.expect("editor created");
let status = ui.create(WidgetKind::Label, None).expect("status created");
ui.attach(window, root).expect("attach root");
ui.attach(root, editor).expect("attach editor");
ui.attach(root, status).expect("attach status");
ui.set_container_direction(root, ContainerDirection::Vertical)
.expect("set vertical flow");
let root_node = ui.layout_nodes[&root];
let mut root_style = ui.layout_tree.style(root_node).unwrap().clone();
root_style.size = Size {
width: Dimension::percent(1.0),
height: Dimension::percent(1.0),
};
ui.layout_tree.set_style(root_node, root_style).unwrap();
let editor_node = ui.layout_nodes[&editor];
let mut editor_style = ui.layout_tree.style(editor_node).unwrap().clone();
editor_style.flex_grow = 1.0;
ui.layout_tree.set_style(editor_node, editor_style).unwrap();
ui.compute_layout(window, 740.0, 850.0)
.expect("compute Notepad layout");
assert_eq!(ui.computed_layout_expansion(root), (true, true));
assert_eq!(
ui.computed_layout_expansion(editor),
(true, true),
"the editor stretches across the column and grows vertically"
);
assert_eq!(
ui.computed_layout_expansion(status),
(true, false),
"a status label stretches across the column without taking spare height"
);
assert_eq!(ui.widget(root).and_then(|spec| spec.size), Some((740, 850)));
}
#[test]
fn set_layout_root_rejects_non_window_widget() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui
.create(WidgetKind::Button, Some("b"))
.expect("button created");
let err = ui.set_layout_root(button).expect_err("non-window rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_layout_root"));
}
#[test]
fn set_flex_grow_lets_sized_panes_fill_a_resized_layout_root() {
let mut ui = Ui::new(MockBackend::default());
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let row = ui.create(WidgetKind::Container, None).expect("row");
ui.set_container_direction(row, ContainerDirection::Horizontal)
.expect("row direction");
let sidebar = ui.create(WidgetKind::Container, None).expect("sidebar");
let content = ui.create(WidgetKind::Container, None).expect("content");
ui.attach(window, row).expect("attach row");
ui.attach(row, sidebar).expect("attach sidebar");
ui.attach(row, content).expect("attach content");
ui.set_size(sidebar, 200, 100).expect("sidebar size");
ui.set_size(content, 400, 100).expect("content size");
ui.set_layout_root(window).expect("layout root");
ui.compute_layout(window, 600.0, 400.0)
.expect("initial layout");
assert_eq!(
ui.widget(content).and_then(|spec| spec.size),
Some((400, 100))
);
ui.backend_mut().push_event(UiEvent::WindowResized {
widget_id: window,
width: 1000,
height: 400,
});
ui.dispatch_events(|_| {}).expect("dispatch");
assert_eq!(
ui.widget(content).and_then(|spec| spec.size),
Some((400, 100))
);
ui.set_flex_grow(content, 1.0).expect("grow");
assert_eq!(ui.flex_grow(content), Ok(1.0));
ui.backend_mut().push_event(UiEvent::WindowResized {
widget_id: window,
width: 1200,
height: 400,
});
ui.dispatch_events(|_| {}).expect("dispatch");
assert_eq!(
ui.widget(sidebar).and_then(|spec| spec.size),
Some((200, 100))
);
assert_eq!(
ui.widget(content).and_then(|spec| spec.size),
Some((1000, 100))
);
assert_eq!(
ui.widget(content).and_then(|spec| spec.position),
Some((200, 0))
);
assert!(ui.set_flex_grow(content, -1.0).is_err());
assert!(ui.set_flex_grow(content, f32::NAN).is_err());
assert_eq!(
ui.set_flex_grow(WidgetId(9_999), 1.0),
Err(GuiError::WidgetNotFound(9_999))
);
}
#[test]
fn set_min_size_keeps_a_floor_while_panes_stretch_with_the_window() {
let mut ui = Ui::new(MockBackend::default());
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let column = ui.create(WidgetKind::Container, None).expect("column");
let row = ui.create(WidgetKind::Container, None).expect("row");
ui.set_container_direction(row, ContainerDirection::Horizontal)
.expect("row direction");
let sidebar = ui.create(WidgetKind::Container, None).expect("sidebar");
let content = ui.create(WidgetKind::Container, None).expect("content");
ui.attach(window, column).expect("attach column");
ui.attach(column, row).expect("attach row");
ui.attach(row, sidebar).expect("attach sidebar");
ui.attach(row, content).expect("attach content");
ui.set_min_size(sidebar, 180, 0).expect("sidebar min");
ui.set_min_size(content, 300, 200).expect("content min");
ui.set_flex_grow(row, 1.0).expect("row grows");
ui.set_flex_grow(content, 1.0).expect("content grows");
assert_eq!(ui.min_size(content), Ok((300, 200)));
ui.set_layout_root(window).expect("layout root");
ui.compute_layout(window, 900.0, 500.0).expect("layout");
assert_eq!(
ui.widget(sidebar).and_then(|spec| spec.size),
Some((180, 500))
);
assert_eq!(
ui.widget(content).and_then(|spec| spec.size),
Some((720, 500))
);
ui.backend_mut().push_event(UiEvent::WindowResized {
widget_id: window,
width: 1400,
height: 800,
});
ui.dispatch_events(|_| {}).expect("dispatch");
assert_eq!(
ui.widget(content).and_then(|spec| spec.size),
Some((1220, 800))
);
ui.compute_layout(window, 300.0, 100.0).expect("shrunk");
assert_eq!(
ui.widget(sidebar).and_then(|spec| spec.size.map(|s| s.0)),
Some(180)
);
assert_eq!(
ui.widget(content).and_then(|spec| spec.size),
Some((300, 200))
);
ui.set_min_size(sidebar, 0, 0).expect("clear");
assert_eq!(ui.min_size(sidebar), Ok((0, 0)));
assert!(ui.set_min_size(sidebar, -1, 0).is_err());
assert_eq!(
ui.set_min_size(WidgetId(9_999), 1, 1),
Err(GuiError::WidgetNotFound(9_999))
);
}
#[test]
fn layout_roots_flush_pending_invalidations_before_the_next_event_wait() {
let mut ui = Ui::new(MockBackend::default());
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let column = ui.create(WidgetKind::Container, None).expect("column");
let panel = ui.create(WidgetKind::Container, None).expect("panel");
ui.attach(window, column).expect("attach column");
ui.attach(column, panel).expect("attach panel");
ui.set_flex_grow(panel, 1.0).expect("panel grows");
ui.hide(panel).expect("hide panel");
ui.set_layout_root(window).expect("layout root");
ui.backend_mut().push_event(UiEvent::WindowResized {
widget_id: window,
width: 500,
height: 300,
});
ui.dispatch_events(|_| {}).expect("dispatch");
assert_eq!(ui.widget(panel).and_then(|spec| spec.size), Some((0, 0)));
ui.show(panel).expect("show panel");
ui.dispatch_events(|_| {}).expect("dispatch");
assert_eq!(
ui.widget(panel).and_then(|spec| spec.size),
Some((500, 300))
);
ui.remove_layout_root(window);
ui.hide(panel).expect("hide again");
ui.dispatch_events(|_| {}).expect("dispatch");
assert_eq!(
ui.widget(panel).and_then(|spec| spec.size),
Some((500, 300))
);
}
#[test]
fn show_hide_schedules_layout_pass() {
let mut ui = Ui::new(MockBackend::default());
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let panel = ui.create(WidgetKind::Container, None).expect("panel");
ui.attach(window, panel).expect("attach panel");
ui.set_layout_root(window).expect("layout root");
ui.compute_layout(window, 500.0, 300.0)
.expect("initial layout");
assert!(!ui.has_dirty_layout(), "layout clean after compute");
ui.hide(panel).expect("hide panel");
assert!(ui.is_layout_dirty(panel));
assert!(ui.has_dirty_layout());
ui.compute_layout_if_dirty();
assert!(!ui.has_dirty_layout(), "layout clean after flush");
ui.show(panel).expect("show panel");
assert!(ui.is_layout_dirty(panel));
assert!(ui.has_dirty_layout());
ui.compute_layout_if_dirty();
assert!(!ui.has_dirty_layout(), "layout clean after second flush");
}
#[test]
fn set_preferred_width_constrains_width_only() {
let mut ui = Ui::new(MockBackend::default());
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let root = ui.create(WidgetKind::Container, None).expect("root");
ui.set_container_direction(root, ContainerDirection::Horizontal)
.expect("row");
let inspector = ui.create(WidgetKind::Container, None).expect("inspector");
let content = ui.create(WidgetKind::Container, None).expect("content");
ui.attach(window, root).expect("attach root");
ui.attach(root, inspector).expect("attach inspector");
ui.attach(root, content).expect("attach content");
ui.set_flex_grow(content, 1.0).expect("content grows");
ui.set_preferred_width(inspector, 240)
.expect("set preferred width");
assert_eq!(ui.preferred_width(inspector), Ok(Some(240)));
ui.set_layout_root(window).expect("layout root");
ui.compute_layout(window, 800.0, 600.0)
.expect("compute layout");
let (inspector_w, inspector_h) = ui.widget(inspector).unwrap().size.unwrap();
assert_eq!(inspector_w, 240);
assert_eq!(inspector_h, 600);
ui.compute_layout(window, 1000.0, 700.0)
.expect("recompute layout");
let (inspector_w2, inspector_h2) = ui.widget(inspector).unwrap().size.unwrap();
assert_eq!(inspector_w2, 240);
assert_eq!(inspector_h2, 700);
ui.set_preferred_width(inspector, 0)
.expect("clear preferred width");
assert_eq!(ui.preferred_width(inspector), Ok(None));
}
#[test]
fn window_min_size_and_resizable_api() {
let mut ui = Ui::new(MockBackend::default());
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let button = ui.create(WidgetKind::Button, Some("b")).expect("button");
let err = ui
.set_window_min_size(button, 400, 300)
.expect_err("non-window rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_window_min_size"));
let err = ui.window_min_size(button).expect_err("non-window rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_window_min_size"));
let err = ui
.set_resizable(button, false)
.expect_err("non-window rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_resizable"));
let err = ui.is_resizable(button).expect_err("non-window rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_resizable"));
assert_eq!(ui.is_resizable(window), Ok(true));
assert_eq!(ui.resizable(window), Ok(true));
let res = ui.set_window_min_size(window, 400, 300);
assert_eq!(
res,
Err(GuiError::UnsupportedCapability(
"set_window_min_size".to_owned()
))
);
assert_eq!(ui.explicit_window_min_size(window), Ok(Some((400, 300))));
assert_eq!(ui.window_min_size(window), Ok(Some((400, 300))));
let res = ui.set_resizable(window, false);
assert_eq!(
res,
Err(GuiError::UnsupportedCapability("set_resizable".to_owned()))
);
assert_eq!(ui.is_resizable(window), Ok(false));
let window2 = ui.create(WidgetKind::Window, Some("w2")).expect("window 2");
let child = ui.create(WidgetKind::Container, None).expect("child");
ui.attach(window2, child).expect("attach child");
ui.set_min_size(child, 320, 240).expect("child min");
ui.set_layout_root(window2).expect("layout root");
assert_eq!(ui.window_min_size(window2), Ok(Some((320, 240))));
}
#[test]
fn multiple_layout_roots_recompute_layout_independently_on_window_resize() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window1 = ui
.create(WidgetKind::Window, Some("w1"))
.expect("window1 created");
let btn1 = ui
.create(WidgetKind::Button, Some("b1"))
.expect("btn1 created");
ui.attach(window1, btn1).expect("attached");
let window2 = ui
.create(WidgetKind::Window, Some("w2"))
.expect("window2 created");
let btn2 = ui
.create(WidgetKind::Button, Some("b2"))
.expect("btn2 created");
ui.attach(window2, btn2).expect("attached");
if let Some(&node) = ui.layout_nodes.get(&btn1) {
let style = crate::layout::Style {
size: crate::layout::Size {
width: crate::layout::Dimension::length(50.0),
height: crate::layout::Dimension::length(25.0),
},
..Default::default()
};
let _ = ui.layout_tree.set_style(node, style);
}
if let Some(&node) = ui.layout_nodes.get(&btn2) {
let style = crate::layout::Style {
size: crate::layout::Size {
width: crate::layout::Dimension::length(70.0),
height: crate::layout::Dimension::length(35.0),
},
..Default::default()
};
let _ = ui.layout_tree.set_style(node, style);
}
ui.set_layout_root(window1)
.expect("window1 layout root set");
ui.add_layout_root(window2)
.expect("window2 layout root added");
assert!(ui.is_layout_root(window1));
assert!(ui.is_layout_root(window2));
assert_eq!(ui.layout_roots().len(), 2);
ui.backend_mut().push_event(UiEvent::WindowResized {
widget_id: window1,
width: 800,
height: 600,
});
let count = ui.dispatch_events(|_| {}).expect("dispatch");
assert_eq!(count, 1);
assert_eq!(ui.widget(btn1).and_then(|spec| spec.size), Some((50, 25)));
assert_eq!(ui.widget(btn2).and_then(|spec| spec.size), None);
ui.backend_mut().push_event(UiEvent::WindowResized {
widget_id: window2,
width: 400,
height: 300,
});
let count = ui.dispatch_events(|_| {}).expect("dispatch");
assert_eq!(count, 1);
assert_eq!(ui.widget(btn2).and_then(|spec| spec.size), Some((70, 35)));
assert!(ui.remove_layout_root(window2));
assert!(!ui.is_layout_root(window2));
assert!(ui.is_layout_root(window1));
assert_eq!(ui.layout_roots().len(), 1);
assert!(!ui.remove_layout_root(window2));
ui.remove(window1).expect("removed");
assert!(!ui.is_layout_root(window1));
assert!(ui.layout_roots().is_empty());
}
#[test]
fn add_layout_root_rejects_non_window_widget() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui
.create(WidgetKind::Button, Some("b"))
.expect("button created");
let err = ui.add_layout_root(button).expect_err("non-window rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_layout_root"));
}
fn widget_write_counts(backend: &MockBackend, id: WidgetId) -> (usize, usize) {
(
backend.size_writes.get(&id).copied().unwrap_or(0),
backend.position_writes.get(&id).copied().unwrap_or(0),
)
}
#[test]
fn layout_pass_is_bounded_to_the_invalidated_branch() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let left = ui
.create(WidgetKind::Container, Some("left"))
.expect("left");
let right = ui
.create(WidgetKind::Container, Some("right"))
.expect("right");
let l1 = ui.create(WidgetKind::Label, Some("l1")).expect("l1");
let r1 = ui.create(WidgetKind::Label, Some("r1")).expect("r1");
ui.attach(window, left).expect("attach left");
ui.attach(window, right).expect("attach right");
ui.attach(left, l1).expect("attach l1");
ui.attach(right, r1).expect("attach r1");
ui.compute_layout(window, 400.0, 300.0).expect("first pass");
assert!(ui.layout_dirty.is_empty(), "the pass consumes the schedule");
let probes = ui
.backend()
.natural_size_probes
.load(std::sync::atomic::Ordering::Relaxed);
let r1_writes = widget_write_counts(ui.backend(), r1);
ui.compute_layout(window, 400.0, 300.0)
.expect("steady pass");
assert_eq!(
ui.backend()
.natural_size_probes
.load(std::sync::atomic::Ordering::Relaxed),
probes,
"an unchanged pass performs no backend measurements"
);
assert_eq!(widget_write_counts(ui.backend(), r1), r1_writes);
assert!(ui.layout_dirty.is_empty());
let l2 = ui.create(WidgetKind::Label, Some("l2")).expect("l2");
ui.attach(left, l2).expect("attach l2");
ui.compute_layout(window, 400.0, 300.0)
.expect("branch pass");
assert_eq!(
ui.backend()
.natural_size_probes
.load(std::sync::atomic::Ordering::Relaxed),
probes + 1,
"only the invalidated leaf is measured"
);
assert_eq!(
widget_write_counts(ui.backend(), r1),
r1_writes,
"the untouched branch is not rewritten"
);
let (l2_sizes, l2_positions) = widget_write_counts(ui.backend(), l2);
assert!(
l2_sizes + l2_positions > 0,
"the new leaf receives its geometry"
);
assert!(ui.layout_dirty.is_empty());
}
#[test]
fn layout_schedule_is_topological_and_ancestor_free() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let left = ui
.create(WidgetKind::Container, Some("left"))
.expect("left");
let inner = ui
.create(WidgetKind::Container, Some("inner"))
.expect("inner");
let l1 = ui.create(WidgetKind::Label, Some("l1")).expect("l1");
let right = ui
.create(WidgetKind::Container, Some("right"))
.expect("right");
let r1 = ui.create(WidgetKind::Label, Some("r1")).expect("r1");
ui.attach(window, left).expect("attach left");
ui.attach(window, right).expect("attach right");
ui.attach(left, inner).expect("attach inner");
ui.attach(inner, l1).expect("attach l1");
ui.attach(right, r1).expect("attach r1");
ui.compute_layout(window, 400.0, 300.0).expect("first pass");
assert!(ui.layout_dirty.is_empty());
ui.set_container_direction(left, ContainerDirection::Horizontal)
.expect("direction");
assert!(ui.layout_dirty.contains(&left));
ui.set_container_direction(inner, ContainerDirection::Horizontal)
.expect("inner direction");
assert_eq!(
ui.layout_dirty.len(),
1,
"descendant invalidations are subsumed by the scheduled branch"
);
let dirty_nodes = |ui: &Ui<MockBackend>| -> usize {
ui.layout_nodes
.values()
.filter(|node| ui.layout_tree.is_dirty(**node).unwrap_or(false))
.count()
};
assert!(
dirty_nodes(&ui) > 0,
"the direction change dirtied layout nodes"
);
ui.compute_layout(window, 400.0, 300.0).expect("pass");
assert!(ui.layout_dirty.is_empty(), "the pass consumes the schedule");
assert_eq!(
dirty_nodes(&ui),
0,
"layout recomputes and clears every dirty node"
);
}
#[test]
fn layout_passes_still_apply_resizes_and_write_only_changes() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let left = ui
.create(WidgetKind::Container, Some("left"))
.expect("left");
let right = ui
.create(WidgetKind::Container, Some("right"))
.expect("right");
ui.attach(window, left).expect("attach left");
ui.attach(window, right).expect("attach right");
ui.compute_layout(window, 400.0, 300.0).expect("first pass");
let write_total = |ui: &Ui<MockBackend>| -> usize {
ui.backend()
.size_writes
.values()
.chain(ui.backend().position_writes.values())
.sum()
};
let before = write_total(&ui);
ui.compute_layout(window, 800.0, 300.0)
.expect("resize pass");
let after_resize = write_total(&ui);
assert!(
after_resize > before,
"a resize still recomputes and applies changed geometry"
);
ui.compute_layout(window, 800.0, 300.0)
.expect("repeat pass");
assert_eq!(
write_total(&ui),
after_resize,
"repeating the same pass writes nothing"
);
}
#[test]
fn layout_schedule_drops_removed_widgets() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
ui.compute_layout(window, 100.0, 100.0).expect("pass");
assert!(ui.layout_dirty.is_empty());
let label = ui.create(WidgetKind::Label, Some("l")).expect("label");
ui.attach(window, label).expect("attach");
assert!(ui.layout_dirty.contains(&label));
ui.remove(label).expect("remove");
assert!(
ui.layout_dirty.is_empty(),
"a removed widget leaves no schedule entry"
);
}
#[test]
fn keyed_rows_preserve_selection_and_reanchor_by_key() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let list = ui.create(WidgetKind::DataList, Some("rows")).expect("list");
let first = [
RowSet::new(1, &["Backlog"]),
RowSet::new(2, &["Doing"]),
RowSet::new(3, &["Done"]),
];
let delta = ui.set_rows_keyed(list, &first).expect("first apply");
assert_eq!(
delta,
RowDelta {
inserted: 3,
updated: 0,
removed: 0,
moved: 0,
unchanged: 0,
}
);
assert_eq!(
ui.widget(list).expect("spec").data_list_items,
vec!["Backlog".to_owned(), "Doing".to_owned(), "Done".to_owned()]
);
let writes = ui.backend().row_writes.get(&list).copied().unwrap_or(0);
let delta = ui.set_rows_keyed(list, &first).expect("no-op apply");
assert!(delta.is_noop());
assert_eq!(
ui.backend().row_writes.get(&list).copied().unwrap_or(0),
writes,
"a no-op keyed apply performs no backend write"
);
ui.set_selected_index(list, 1).expect("select");
assert_eq!(ui.selected_row_key(list), Some(RowKey(2)));
ui.backend_mut().scroll_anchors.insert(list, 0);
let reordered = [
RowSet::new(3, &["Done"]),
RowSet::new(1, &["Backlog"]),
RowSet::new(2, &["Doing"]),
];
let delta = ui.set_rows_keyed(list, &reordered).expect("reorder");
assert_eq!(
delta,
RowDelta {
inserted: 0,
updated: 0,
removed: 0,
moved: 3,
unchanged: 0,
}
);
assert_eq!(
ui.widget(list).expect("spec").selected_index,
Some(2),
"the selection follows its key to the new index"
);
assert_eq!(ui.selected_row_key(list), Some(RowKey(2)));
assert_eq!(
ui.backend().scroll_requests,
vec![(list, 1)],
"the anchor key re-anchors at its new index"
);
let event = ui.poll_event().expect("poll").expect("selection event");
assert_eq!(
event,
UiEvent::SelectionChanged {
widget_id: list,
selected: Some("Doing".to_owned()),
index: Some(2),
}
);
assert_eq!(ui.visible_anchor(list).expect("anchor"), Some(RowKey(1)));
let without_doing = [RowSet::new(3, &["Done"]), RowSet::new(1, &["Backlog"])];
let delta = ui
.set_rows_keyed(list, &without_doing)
.expect("remove selected");
assert_eq!(delta.removed, 1);
assert_eq!(ui.widget(list).expect("spec").selected_index, None);
assert_eq!(ui.selected_row_key(list), None);
assert_eq!(ui.backend().selection_clears, vec![list]);
let event = ui.poll_event().expect("poll").expect("clear event");
assert_eq!(
event,
UiEvent::SelectionChanged {
widget_id: list,
selected: None,
index: None,
}
);
let before = ui.widget(list).cloned();
assert_eq!(
ui.set_rows_keyed(list, &[RowSet::new(5, &["x"]), RowSet::new(5, &["y"])]),
Err(GuiError::Backend("duplicate row key".to_owned()))
);
assert_eq!(ui.widget(list), before.as_ref());
}
#[test]
fn keyed_rows_filter_multi_selection_by_key() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let list = ui.create(WidgetKind::ListView, Some("rows")).expect("list");
let rows = [
RowSet::new(1, &["a"]),
RowSet::new(2, &["b"]),
RowSet::new(3, &["c"]),
];
ui.set_rows_keyed(list, &rows).expect("apply");
ui.set_selected_indices(list, &[0, 2])
.expect("multi select");
let delta = ui
.set_rows_keyed(list, &[RowSet::new(1, &["a"]), RowSet::new(2, &["b"])])
.expect("apply");
assert_eq!(delta.removed, 1);
assert_eq!(ui.widget(list).expect("spec").selected_indices, vec![0]);
let event = ui.poll_event().expect("poll").expect("multi event");
assert_eq!(
event,
UiEvent::MultiSelectionChanged {
widget_id: list,
indices: vec![0],
}
);
ui.set_selected_index(list, 0).expect("select");
ui.clear_selection(list).expect("clear");
assert_eq!(ui.widget(list).expect("spec").selected_index, None);
assert_eq!(
ui.widget(list).expect("spec").selected_indices,
Vec::<usize>::new()
);
assert_eq!(ui.selected_row_key(list), None);
let event = ui.poll_event().expect("poll").expect("clear event");
assert_eq!(
event,
UiEvent::SelectionChanged {
widget_id: list,
selected: None,
index: None,
}
);
}
#[test]
fn keyed_rows_cover_grids_and_reject_other_kinds() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let grid = ui.create(WidgetKind::DataGrid, Some("grid")).expect("grid");
let delta = ui
.set_rows_keyed(grid, &[RowSet::new(1, &["r1c1", "r1c2"])])
.expect("apply");
assert_eq!(delta.inserted, 1);
assert_eq!(
ui.widget(grid)
.expect("spec")
.data_grid_rows
.as_ref()
.clone(),
vec![vec!["r1c1".to_owned(), "r1c2".to_owned()]]
);
assert_eq!(ui.visible_anchor(grid).expect("anchor"), None);
assert!(ui.backend().scroll_requests.is_empty());
let button = ui.create(WidgetKind::Button, Some("b")).expect("button");
assert_eq!(
ui.set_rows_keyed(button, &[RowSet::new(1, &["x"])])
.expect_err("button rejected"),
GuiError::UnsupportedWidget("set_rows_keyed")
);
assert_eq!(
ui.clear_selection(button).expect_err("button rejected"),
GuiError::UnsupportedWidget("clear_selection")
);
assert_eq!(
ui.visible_anchor(button).expect_err("button rejected"),
GuiError::UnsupportedWidget("visible_anchor")
);
assert_eq!(
ui.scroll_to_row(button, 0).expect_err("button rejected"),
GuiError::UnsupportedWidget("visible_anchor")
);
}
#[test]
fn scroll_to_row_moves_the_mock_anchor() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let list = ui.create(WidgetKind::DataList, None).expect("list");
ui.set_data_list_items(list, &["a".into(), "b".into(), "c".into()])
.expect("items");
ui.scroll_to_row(list, 2).expect("scroll");
assert_eq!(
ui.backend().scroll_requests,
vec![(list, 2)],
"Ui::scroll_to_row is recorded on the mock"
);
assert_eq!(
ui.backend().visible_anchor_index(list).expect("anchor"),
Some(2)
);
}
#[test]
fn keyed_rows_feed_a_columned_list_view_through_list_rows() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let list = ui
.create(WidgetKind::ListView, Some("Files"))
.expect("list");
ui.set_list_columns(list, &[ColumnSpec::new("Name"), ColumnSpec::new("Size")])
.expect("columns");
let delta = ui
.set_rows_keyed(
list,
&[
RowSet::new(1, &["a.txt", "12 KB"]),
RowSet::new(2, &["b.txt", "8 KB"]),
],
)
.expect("keyed rows");
assert_eq!(delta.inserted, 2);
let spec = ui.widget(list).expect("spec");
assert_eq!(
spec.list_rows,
vec![
vec!["a.txt".to_owned(), "12 KB".to_owned()],
vec!["b.txt".to_owned(), "8 KB".to_owned()],
]
);
assert!(spec.data_list_items.is_empty());
ui.set_selected_index(list, 1).expect("select");
assert_eq!(ui.selected_row_key(list), Some(RowKey(2)));
let plain = ui
.create(WidgetKind::ListView, Some("Plain"))
.expect("plain list");
ui.set_rows_keyed(plain, &[RowSet::new(7, &["only"])])
.expect("plain keyed rows");
assert_eq!(
ui.widget(plain).expect("spec").data_list_items,
vec!["only".to_owned()]
);
assert!(ui.widget(plain).expect("spec").list_rows.is_empty());
}
#[test]
fn list_columns_and_rows_update_spec_and_mock_record() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let list = ui
.create(WidgetKind::ListView, Some("Files"))
.expect("list");
let columns = [
ColumnSpec::new("Name"),
ColumnSpec::new("Size").with_width(80),
];
ui.set_list_columns(list, &columns).expect("columns");
ui.set_list_rows(list, &[vec!["a.txt".to_owned(), "12 KB".to_owned()]])
.expect("rows");
let spec = ui.widget(list).expect("spec");
assert_eq!(spec.list_columns, columns);
assert_eq!(
spec.list_rows,
vec![vec!["a.txt".to_owned(), "12 KB".to_owned()]]
);
let native = ui.backend().created.get(&list).expect("native record");
assert_eq!(native.list_columns, columns);
let button = ui.create(WidgetKind::Button, Some("b")).expect("button");
assert_eq!(
ui.set_list_columns(button, &columns)
.expect_err("button rejected"),
GuiError::UnsupportedWidget("set_list_columns")
);
assert_eq!(
ui.set_list_rows(button, &[]).expect_err("button rejected"),
GuiError::UnsupportedWidget("set_list_rows")
);
assert!(ui.widget(button).expect("spec").list_columns.is_empty());
}
#[test]
fn menu_item_callback_requires_existing_item() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let err = ui
.on_menu_item_selected(MenuItemId(999), || {})
.expect_err("unknown menu item should be rejected");
assert_eq!(
err,
GuiError::Backend("Menu item not found: 999".to_owned())
);
}
#[test]
fn add_menu_item_with_shortcut_registers_backend_shortcut() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let menu = ui.create_menu().expect("menu should be created");
let item = ui
.add_menu_item_with_shortcut(menu, "Quit", Some("Ctrl+Q"))
.expect("menu item should be created");
assert_eq!(
ui.backend().menu_shortcuts.get(&item).cloned(),
Some("Ctrl+Q".to_owned())
);
}
#[test]
fn set_selected_indices_supports_multi_select_lists() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let list = ui.create(WidgetKind::ListView, None).expect("list created");
ui.set_selected_indices(list, &[0, 2])
.expect("multi select set");
assert_eq!(ui.widget(list).unwrap().selected_indices, vec![0, 2]);
let button = ui
.create(WidgetKind::Button, Some("b"))
.expect("button created");
let err = ui
.set_selected_indices(button, &[0])
.expect_err("button rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_selected_indices"));
}
#[test]
fn set_tree_items_populates_tree_view_and_rejects_others() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let tree = ui.create(WidgetKind::TreeView, None).expect("tree created");
let items = vec![
TreeItem::new("Documents").with_child(TreeItem::new("Archive")),
TreeItem::new("Downloads"),
];
ui.set_tree_items(tree, &items).expect("tree items set");
assert_eq!(ui.widget(tree).unwrap().tree_items, items);
assert_eq!(
items[0].indented_rows(),
vec!["Documents".to_owned(), " Archive".to_owned()]
);
let button = ui
.create(WidgetKind::Button, Some("b"))
.expect("button created");
let err = ui
.set_tree_items(button, &items)
.expect_err("button rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_tree_items"));
}
#[test]
fn set_container_direction_rejects_non_container() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui
.create(WidgetKind::Button, Some("button"))
.expect("button should be created");
let err = ui
.set_container_direction(button, ContainerDirection::Horizontal)
.expect_err("non-container should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_container_direction"));
}
#[test]
fn set_container_scroll_rejects_non_container() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui
.create(WidgetKind::Button, Some("button"))
.expect("button should be created");
let err = ui
.set_container_scroll(button, true, false)
.expect_err("non-container should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_container_scroll"));
}
#[test]
fn set_container_gap_and_padding_update_spec_and_layout() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let container = ui
.create(WidgetKind::Container, None)
.expect("container should be created");
ui.set_container_gap(container, 6).expect("set gap");
ui.set_container_padding(container, 10)
.expect("set padding");
assert_eq!(
ui.widget(container).and_then(|spec| spec.container_gap),
Some(6)
);
assert_eq!(
ui.widget(container).and_then(|spec| spec.container_padding),
Some(10)
);
let node = ui
.layout_nodes
.get(&container)
.copied()
.expect("layout node");
let style = ui.layout_tree.style(node).expect("layout style").clone();
assert_eq!(
style.gap.width,
crate::layout::LengthPercentage::length(6.0)
);
assert_eq!(
style.gap.height,
crate::layout::LengthPercentage::length(6.0)
);
assert_eq!(
style.padding.left,
crate::layout::LengthPercentage::length(10.0)
);
assert_eq!(
style.padding.bottom,
crate::layout::LengthPercentage::length(10.0)
);
ui.set_container_gap(container, -4).expect("clamped gap");
ui.set_container_padding(container, -9)
.expect("clamped padding");
assert_eq!(
ui.widget(container).and_then(|spec| spec.container_gap),
Some(0)
);
assert_eq!(
ui.widget(container).and_then(|spec| spec.container_padding),
Some(0)
);
let style = ui.layout_tree.style(node).expect("layout style").clone();
assert_eq!(
style.gap.width,
crate::layout::LengthPercentage::length(0.0)
);
assert_eq!(
style.padding.top,
crate::layout::LengthPercentage::length(0.0)
);
}
#[test]
fn set_container_gap_and_padding_reject_non_container() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui
.create(WidgetKind::Button, Some("button"))
.expect("button should be created");
assert!(matches!(
ui.set_container_gap(button, 4),
Err(GuiError::UnsupportedWidget("set_container_gap"))
));
assert!(matches!(
ui.set_container_padding(button, 4),
Err(GuiError::UnsupportedWidget("set_container_padding"))
));
#[cfg(feature = "widgets-containers")]
{
let split = ui
.create(WidgetKind::SplitPane, None)
.expect("split pane should be created");
assert!(matches!(
ui.set_container_gap(split, 4),
Err(GuiError::UnsupportedWidget("set_container_gap"))
));
}
}
#[test]
fn set_container_scroll_updates_widget_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let container = ui
.create(WidgetKind::Container, None)
.expect("container should be created");
ui.set_container_scroll(container, true, true)
.expect("set container scroll should succeed");
let Some(spec) = ui.widget(container) else {
panic!("container spec should exist");
};
assert!(spec.container_scroll_vertical);
assert!(spec.container_scroll_horizontal);
}
#[test]
fn set_size_accepts_non_button_widget() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
ui.set_size(label, 120, 40)
.expect("set size should support non-button widgets");
assert_eq!(ui.widget(label).and_then(|spec| spec.size), Some((120, 40)));
}
#[test]
fn set_size_updates_widget_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui
.create(WidgetKind::Button, Some("Run"))
.expect("button should be created");
ui.set_size(button, 140, 44)
.expect("set size should succeed");
assert_eq!(
ui.widget(button).and_then(|spec| spec.size),
Some((140, 44))
);
assert_eq!(
ui.backend().created.get(&button).and_then(|spec| spec.size),
Some((140, 44))
);
}
#[test]
fn set_size_rejects_non_positive_dimensions() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui
.create(WidgetKind::Button, Some("Run"))
.expect("button should be created");
let err = ui
.set_size(button, 0, 44)
.expect_err("non-positive size should be rejected");
assert_eq!(
err,
GuiError::Backend("Widget size must be positive".to_owned())
);
}
#[test]
fn set_size_survives_a_compute_layout_pass() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let column = ui
.create(WidgetKind::Container, Some("column"))
.expect("column");
ui.set_container_direction(column, ContainerDirection::Vertical)
.expect("column direction");
let tile = ui.create(WidgetKind::Label, Some("tile")).expect("tile");
ui.attach(window, column).expect("attach column");
ui.attach(column, tile).expect("attach tile");
ui.set_size(tile, 160, 120).expect("tile size");
ui.compute_layout(window, 800.0, 600.0).expect("pass");
assert_eq!(
ui.widget(tile).and_then(|spec| spec.size),
Some((160, 120)),
"the spec keeps the requested size through the pass"
);
assert_eq!(
ui.backend().created.get(&tile).and_then(|spec| spec.size),
Some((160, 120)),
"the backend receives the requested size, not a rewrite"
);
let node = *ui.layout_nodes.get(&tile).expect("layout node");
let layout = ui.layout_tree.layout(node).expect("layout");
assert_eq!(
(layout.width, layout.height),
(160.0, 120.0),
"layout computes the requested size, so later passes agree"
);
}
#[test]
#[cfg(all(feature = "declarative", feature = "widgets-media"))]
fn size_authoring_paths_lay_out_alike() {
use crate::declarative::{DeclarativeUi, Image as NodeImage, Window as NodeWindow};
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let column = ui
.create(WidgetKind::Container, Some("column"))
.expect("column");
ui.set_container_direction(column, ContainerDirection::Vertical)
.expect("column direction");
ui.attach(window, column).expect("attach column");
let imperative = ui.create(WidgetKind::Image, None).expect("imperative");
ui.attach(column, imperative).expect("attach imperative");
ui.set_size(imperative, 160, 120).expect("imperative size");
let spec_based = ui
.create_with(WidgetKind::Image, |spec| spec.size = Some((160, 120)))
.expect("spec-based");
ui.attach(column, spec_based).expect("attach spec-based");
let mut node_ui = Ui::new(MockBackend::default());
let mut declarative = WidgetId(0);
let mut tree = NodeWindow::new("w").child(
crate::declarative::Container::vertical().child(
NodeImage::new()
.size(160.0, 120.0)
.bind_id(&mut declarative),
),
);
let node_root = node_ui.render(&mut tree).expect("render");
drop(tree);
ui.compute_layout(window, 800.0, 600.0)
.expect("imperative pass");
node_ui
.compute_layout(node_root, 800.0, 600.0)
.expect("declarative pass");
let layout_size = |ui: &Ui<MockBackend>, id: WidgetId| {
let node = *ui.layout_nodes.get(&id).expect("layout node");
let layout = ui.layout_tree.layout(node).expect("layout");
(layout.width, layout.height)
};
for id in [imperative, spec_based] {
assert_eq!(
ui.widget(id).and_then(|spec| spec.size),
Some((160, 120)),
"imperative and spec-based requests keep their size"
);
assert_eq!(layout_size(&ui, id), (160.0, 120.0));
}
assert_eq!(
node_ui.widget(declarative).and_then(|spec| spec.size),
Some((160, 120)),
"the declarative leaf lands on the same spec size"
);
assert_eq!(
layout_size(&node_ui, declarative),
(160.0, 120.0),
"the declarative leaf lands on the same layout geometry"
);
}
#[test]
fn computed_sizes_do_not_pin_auto_axes_into_layout() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let label = ui
.create(WidgetKind::Label, Some("stretch"))
.expect("label");
ui.attach(window, label).expect("attach");
ui.compute_layout(window, 800.0, 600.0).expect("first pass");
let node = *ui.layout_nodes.get(&label).expect("layout node");
let first = ui.layout_tree.layout(node).expect("layout");
assert_eq!((first.width, first.height), (800.0, 600.0));
ui.compute_layout(window, 800.0, 300.0)
.expect("shorter pass");
let second = ui.layout_tree.layout(node).expect("layout");
assert_eq!(
second.height, 300.0,
"the auto leaf follows the window on the next pass"
);
}
#[test]
fn set_position_updates_widget_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui
.create(WidgetKind::Button, Some("Move"))
.expect("button should be created");
ui.set_position(button, 18, 26)
.expect("set position should succeed");
assert_eq!(
ui.widget(button).and_then(|spec| spec.position),
Some((18, 26))
);
assert_eq!(
ui.backend()
.created
.get(&button)
.and_then(|spec| spec.position),
Some((18, 26))
);
}
#[test]
fn set_background_color_updates_widget_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
let color = Color::rgb(12, 34, 56);
ui.set_background_color(label, color)
.expect("set background color should succeed");
assert_eq!(
ui.widget(label).and_then(|spec| spec.background_color),
Some(color)
);
assert_eq!(
ui.backend()
.created
.get(&label)
.and_then(|spec| spec.background_color),
Some(color)
);
}
#[test]
#[cfg(feature = "widgets-containers")]
fn set_alert_level_rejects_non_alert_dialog() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
let err = ui
.set_alert_level(label, AlertLevel::Warning)
.expect_err("non-alert widget should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_alert_level"));
}
#[test]
#[cfg(feature = "widgets-containers")]
fn set_alert_level_updates_widget_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let alert = ui
.create(WidgetKind::AlertDialog, Some("Something happened"))
.expect("alert should be created");
ui.set_alert_level(alert, AlertLevel::Error)
.expect("set alert level should succeed");
assert_eq!(
ui.widget(alert).and_then(|spec| spec.alert_level),
Some(AlertLevel::Error)
);
assert_eq!(
ui.backend()
.created
.get(&alert)
.and_then(|spec| spec.alert_level),
Some(AlertLevel::Error)
);
}
#[test]
#[cfg(feature = "widgets-data")]
fn set_data_list_items_updates_widget_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let data_list = ui
.create(WidgetKind::DataList, None)
.expect("data list should be created");
let items = vec!["Alpha".to_owned(), "Beta".to_owned()];
ui.set_data_list_items(data_list, &items)
.expect("set data list items should succeed");
assert_eq!(
ui.widget(data_list)
.map(|spec| spec.data_list_items.clone())
.unwrap_or_default(),
items
);
}
#[test]
#[cfg(feature = "widgets-containers")]
fn set_tab_items_updates_widget_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let tabs = ui
.create(WidgetKind::Tabs, None)
.expect("tabs should be created");
let labels = vec!["General".to_owned(), "Editor".to_owned()];
ui.set_tab_items(tabs, &labels)
.expect("set tab items should succeed");
assert_eq!(
ui.widget(tabs)
.map(|spec| spec.tab_items.clone())
.unwrap_or_default(),
labels
);
assert_eq!(
ui.backend()
.created
.get(&tabs)
.map(|spec| spec.tab_items.clone())
.unwrap_or_default(),
labels
);
}
#[test]
fn set_tab_items_rejects_unsupported_kind() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("Not tabs"))
.expect("label should be created");
assert!(matches!(
ui.set_tab_items(label, &["Nope".to_owned()]),
Err(GuiError::UnsupportedWidget("set_tab_items"))
));
}
#[test]
#[cfg(feature = "widgets-containers")]
fn test_containers_widgets_and_setters_contract() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let sep = ui.create(WidgetKind::Separator, None).expect("separator");
assert_eq!(ui.widget(sep).map(|s| s.kind), Some(WidgetKind::Separator));
let group = ui
.create(WidgetKind::GroupBox, Some("Options"))
.expect("group");
assert_eq!(ui.widget(group).map(|s| s.kind), Some(WidgetKind::GroupBox));
let tabs = ui.create(WidgetKind::Tabs, None).expect("tabs");
assert_eq!(ui.widget(tabs).map(|s| s.kind), Some(WidgetKind::Tabs));
ui.set_tab_items(tabs, &["Tab A".to_string(), "Tab B".to_string()])
.expect("tab items");
assert_eq!(
ui.widget(tabs).unwrap().tab_items,
vec!["Tab A".to_string(), "Tab B".to_string()]
);
ui.set_selected_index(tabs, 1).expect("selected index");
assert_eq!(ui.widget(tabs).unwrap().selected_index, Some(1));
let split = ui
.create_with(WidgetKind::SplitPane, |s| {
s.split_ratio = Some(70);
s.container_direction = Some(ContainerDirection::Horizontal);
})
.expect("split pane");
assert_eq!(
ui.widget(split).map(|s| s.kind),
Some(WidgetKind::SplitPane)
);
assert_eq!(ui.widget(split).and_then(|s| s.split_ratio), Some(70));
let alert = ui
.create(WidgetKind::AlertDialog, Some("Caution"))
.expect("alert");
assert_eq!(
ui.widget(alert).map(|s| s.kind),
Some(WidgetKind::AlertDialog)
);
ui.set_alert_level(alert, AlertLevel::Warning)
.expect("alert level");
assert_eq!(
ui.widget(alert).and_then(|s| s.alert_level),
Some(AlertLevel::Warning)
);
}
#[test]
#[cfg(feature = "widgets-data")]
fn data_grid_clipboard_round_trip() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let source = ui
.create(WidgetKind::DataGrid, None)
.expect("source grid should be created");
let target = ui
.create(WidgetKind::DataGrid, None)
.expect("target grid should be created");
let rows = vec![
vec!["A1".to_owned(), "B1".to_owned()],
vec!["A2".to_owned(), "B2".to_owned()],
];
ui.set_data_grid_rows(source, &rows)
.expect("source rows should be set");
ui.copy_to_clipboard(source).expect("copy should succeed");
ui.paste_from_clipboard(target)
.expect("paste should succeed");
assert_eq!(
ui.widget(target)
.map(|spec| spec.data_grid_rows.as_ref().clone())
.unwrap_or_default(),
rows
);
}
#[test]
fn clipboard_rejects_unsupported_widgets() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui
.create(WidgetKind::Button, Some("nope"))
.expect("button should be created");
let err = ui
.copy_to_clipboard(button)
.expect_err("non-clipboard widget should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("copy_to_clipboard"));
}
#[test]
#[cfg(feature = "widgets-text")]
fn clipboard_round_trips_text_widgets_and_labels() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("0"))
.expect("label should be created");
let input = ui
.create(WidgetKind::TextInput, None)
.expect("input should be created");
ui.set_text(label, "42 + 7").expect("label text");
ui.copy_to_clipboard(label).expect("copy should succeed");
ui.paste_from_clipboard(input)
.expect("paste should succeed");
assert_eq!(
ui.widget(input).and_then(|spec| spec.text.clone()),
Some("42 + 7".to_owned())
);
ui.set_text(input, "clear").expect("input text");
ui.copy_to_clipboard(input).expect("copy from input");
ui.paste_from_clipboard(label).expect("paste into label");
assert_eq!(
ui.widget(label).and_then(|spec| spec.text.clone()),
Some("clear".to_owned())
);
}
#[test]
fn create_all_tier_widget_kinds_on_mock_backend() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let kinds = [
#[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-containers")]
WidgetKind::AlertDialog,
];
for kind in kinds {
let id = ui
.create(kind, Some("demo"))
.expect("new widget kind should be creatable");
assert_eq!(ui.widget(id).map(|spec| spec.kind), Some(kind));
}
}
#[test]
fn create_with_applies_creation_time_spec_and_keeps_the_allocated_id() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let id = ui
.create_with(WidgetKind::Toolbar, |spec| {
spec.id = WidgetId(9_999);
spec.text = Some("Strip".to_owned());
spec.toolbar_orientation = ToolbarOrientation::Vertical;
spec.toolbar_items = vec![ToolbarItem::tool(ToolId(1), "New")];
spec.background_color = Some(Color::rgb(10, 20, 30));
spec.selected_index = Some(2);
})
.expect("spec-based creation succeeds on Mock");
assert_ne!(id, WidgetId(9_999), "the Ui allocates the id");
let spec = ui.widget(id).expect("the spec is stored");
assert_eq!(spec.text.as_deref(), Some("Strip"));
assert_eq!(spec.toolbar_orientation, ToolbarOrientation::Vertical);
assert_eq!(spec.toolbar_items.len(), 1);
assert_eq!(spec.background_color, Some(Color::rgb(10, 20, 30)));
assert_eq!(spec.selected_index, Some(2));
let recorded = ui
.backend()
.created
.get(&id)
.expect("the Mock backend records the created spec");
assert_eq!(recorded.toolbar_orientation, ToolbarOrientation::Vertical);
assert_eq!(recorded.toolbar_items.len(), 1);
assert_eq!(recorded.background_color, Some(Color::rgb(10, 20, 30)));
}
#[test]
#[cfg(feature = "widgets-text")]
fn set_text_selection_records_on_text_controls_only() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let input = ui
.create(WidgetKind::TextInput, Some("report.txt"))
.expect("input");
let area = ui.create(WidgetKind::TextArea, None).expect("area");
let button = ui.create(WidgetKind::Button, Some("OK")).expect("button");
let rich = ui
.create(WidgetKind::RichText, Some("🦀 alpha"))
.expect("rich");
ui.set_text_selection(rich, 2, 7)
.expect("RichText supports selection jumps");
assert_eq!(ui.widget(rich).unwrap().text_selection, Some((2, 7)));
assert!(matches!(
ui.text_selection(rich),
Err(GuiError::UnsupportedCapability(_))
));
assert!(matches!(
ui.text_selection(button),
Err(GuiError::UnsupportedWidget(_))
));
assert_eq!(
ui.text_selection(WidgetId(u64::MAX)),
Err(GuiError::WidgetNotFound(u64::MAX))
);
ui.set_spell_check(rich, true)
.expect("native checking flag forwarded");
assert_eq!(ui.backend().spell_check.get(&rich), Some(&true));
assert!(matches!(
ui.set_spell_check(button, true),
Err(GuiError::UnsupportedWidget(_))
));
ui.set_text_selection(input, 0, 6)
.expect("selection applies to text inputs");
ui.set_text_selection(area, 2, 4)
.expect("selection applies to text areas");
assert_eq!(
ui.widget(input).and_then(|spec| spec.text_selection),
Some((0, 6))
);
assert_eq!(
ui.widget(area).and_then(|spec| spec.text_selection),
Some((2, 4))
);
assert_eq!(
ui.backend()
.created
.get(&input)
.and_then(|spec| spec.text_selection),
Some((0, 6))
);
let err = ui
.set_text_selection(button, 0, 1)
.expect_err("buttons have no text selection");
assert_eq!(err, GuiError::UnsupportedWidget("set_text_selection"));
let err = ui
.set_text_selection(input, 4, 2)
.expect_err("reversed ranges are rejected");
assert_eq!(
err,
GuiError::Backend("Text selection start must be <= end".to_owned())
);
}
#[test]
fn set_font_validates_and_records_on_supported_widgets() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("Preview"))
.expect("label");
let window = ui.create(WidgetKind::Window, Some("Win")).expect("window");
let font = FontDescriptor::new("Helvetica", 16.0);
ui.set_font(label, Some(&font)).expect("set font");
assert_eq!(ui.widget(label).unwrap().font.as_ref(), Some(&font));
ui.set_font(label, None).expect("clear font");
assert_eq!(ui.widget(label).unwrap().font, None);
let invalid = FontDescriptor::new("", 12.0);
assert!(ui.set_font(label, Some(&invalid)).is_err());
assert_eq!(
ui.set_font(window, Some(&font)),
Err(GuiError::UnsupportedWidget("set_font"))
);
}
#[cfg(feature = "widgets-data")]
#[test]
fn set_row_icons_records_on_list_widgets_only() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let list = ui.create(WidgetKind::DataList, None).expect("list");
let view = ui.create(WidgetKind::ListView, None).expect("view");
let label = ui.create(WidgetKind::Label, Some("Text")).expect("label");
let icons = vec![Some(IconRole::Folder), Some(IconRole::File), None];
ui.set_row_icons(list, &icons).expect("datalist icons");
ui.set_row_icons(view, &icons).expect("listview icons");
assert_eq!(ui.widget(list).unwrap().row_icons, icons);
assert_eq!(ui.widget(view).unwrap().row_icons, icons);
assert_eq!(
ui.set_row_icons(label, &icons),
Err(GuiError::UnsupportedWidget("set_row_icons"))
);
}
#[test]
fn set_icon_records_on_button_capable_widgets_only() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui.create(WidgetKind::Button, Some("Save")).expect("button");
#[cfg(feature = "widgets-pickers")]
let chooser = ui
.create(WidgetKind::FileChooserDialog, Some("Open File..."))
.expect("chooser");
let label = ui.create(WidgetKind::Label, Some("status")).expect("label");
ui.set_icon(button, Some(IconRole::Save))
.expect("buttons accept a role");
#[cfg(feature = "widgets-pickers")]
ui.set_icon(chooser, Some(IconRole::Open))
.expect("file chooser buttons accept a role");
assert_eq!(
ui.widget(button).and_then(|spec| spec.icon),
Some(IconRole::Save)
);
#[cfg(feature = "widgets-pickers")]
assert_eq!(
ui.widget(chooser).and_then(|spec| spec.icon),
Some(IconRole::Open)
);
assert_eq!(
ui.backend().created.get(&button).and_then(|spec| spec.icon),
Some(IconRole::Save)
);
ui.set_icon(button, None).expect("None clears the role");
assert_eq!(ui.widget(button).and_then(|spec| spec.icon), None);
assert_eq!(
ui.backend().created.get(&button).and_then(|spec| spec.icon),
None
);
let err = ui
.set_icon(label, Some(IconRole::Save))
.expect_err("labels have no button art");
assert_eq!(err, GuiError::UnsupportedWidget("set_icon"));
}
#[test]
fn data_grid_metric_overrides_record_and_reject_non_grids() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, None).expect("window");
let grid = ui.create(WidgetKind::DataGrid, None).expect("grid");
ui.set_data_grid_col_width(grid, 0, 220)
.expect("width records");
ui.set_data_grid_row_height(grid, 1, 40)
.expect("height records");
assert_eq!(
ui.backend().data_grid_col_widths.get(&(grid, 0)),
Some(&220)
);
assert_eq!(
ui.backend().data_grid_row_heights.get(&(grid, 1)),
Some(&40)
);
ui.set_data_grid_col_width(grid, 0, 0)
.expect("width clears");
assert_eq!(ui.backend().data_grid_col_widths.get(&(grid, 0)), None);
assert!(matches!(
ui.set_data_grid_col_width(window, 0, 100),
Err(GuiError::UnsupportedWidget("set_data_grid_col_width"))
));
assert!(matches!(
ui.set_data_grid_row_height(window, 0, 30),
Err(GuiError::UnsupportedWidget("set_data_grid_row_height"))
));
}
#[test]
fn display_metrics_fixture_records_capabilities_and_change_events() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
assert_eq!(ui.display_capabilities(), DisplayCapabilities::none());
assert!(matches!(
ui.displays(),
Err(GuiError::UnsupportedCapability(ref capability)) if capability == "display_metrics"
));
let primary = DisplayInfo::new(
1,
"mock-primary",
crate::DisplayRect::new(0, 0, 1920, 1080),
crate::DisplayRect::new(0, 0, 1920, 1040),
1.0,
true,
);
let secondary = DisplayInfo::new(
2,
"mock-secondary",
crate::DisplayRect::new(1920, 0, 1280, 1024),
crate::DisplayRect::new(1920, 0, 1280, 984),
1.25,
false,
);
ui.backend_mut()
.set_displays(vec![primary.clone(), secondary.clone()]);
assert!(ui.display_capabilities().enumeration);
assert_eq!(
ui.displays().expect("fixture enumerates"),
vec![primary.clone(), secondary.clone()]
);
assert_eq!(
ui.primary_display().expect("primary query"),
Some(primary.clone())
);
ui.backend_mut().inject_display_change(secondary.clone());
assert!(ui.display_capabilities().dpi_change_events);
assert_eq!(
ui.poll_event().expect("poll"),
Some(UiEvent::DisplayChanged {
display: secondary.clone()
})
);
ui.backend_mut()
.set_display_capabilities(DisplayCapabilities::none());
assert_eq!(ui.display_capabilities(), DisplayCapabilities::none());
assert_eq!(
ui.displays().expect("fixture still enumerates"),
vec![primary, secondary]
);
}
#[test]
fn numeric_and_metadata_setters_update_widget_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
#[cfg(feature = "widgets-range")]
let slider = {
let s = ui
.create(WidgetKind::Slider, Some("slider"))
.expect("slider should be created");
ui.set_range(s, 0, 200).expect("range set");
ui.set_step(s, 5).expect("step set");
ui.set_value(s, 55).expect("value set");
s
};
#[cfg(feature = "widgets-containers")]
let tabs = {
let tabs = ui
.create(WidgetKind::Tabs, Some("tabs"))
.expect("tabs should be created");
ui.set_selected_index(tabs, 0).expect("selected index set");
tabs
};
#[cfg(feature = "widgets-media")]
let image = {
let img = ui
.create(WidgetKind::Image, None)
.expect("image should be created");
ui.set_image_source(img, "./assets/icon.png")
.expect("image source set");
img
};
#[cfg(feature = "widgets-pickers")]
let date = ui
.create(WidgetKind::DatePicker, None)
.expect("date picker should be created");
#[cfg(feature = "widgets-pickers")]
ui.set_date_value(date, "2026-03-06")
.expect("date value set");
#[cfg(feature = "widgets-text")]
let link = ui
.create(WidgetKind::LinkLabel, Some("Open docs"))
.expect("link label should be created");
#[cfg(feature = "widgets-text")]
ui.set_link_url(link, "https://example.com")
.expect("link url set");
#[cfg(feature = "widgets-range")]
{
assert_eq!(
ui.widget(slider).and_then(|spec| spec.range),
Some((0, 200))
);
assert_eq!(ui.widget(slider).and_then(|spec| spec.step), Some(5));
assert_eq!(ui.widget(slider).and_then(|spec| spec.value), Some(55));
}
#[cfg(feature = "widgets-containers")]
assert_eq!(
ui.widget(tabs).and_then(|spec| spec.selected_index),
Some(0)
);
#[cfg(feature = "widgets-media")]
assert_eq!(
ui.widget(image)
.and_then(|spec| spec.image_source.as_deref()),
Some("./assets/icon.png")
);
#[cfg(feature = "widgets-pickers")]
assert_eq!(
ui.widget(date).and_then(|spec| spec.date_value.as_deref()),
Some("2026-03-06")
);
#[cfg(feature = "widgets-text")]
assert_eq!(
ui.widget(link).and_then(|spec| spec.link_url.as_deref()),
Some("https://example.com")
);
}
#[test]
#[cfg(feature = "widgets-choice")]
fn set_checked_updates_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let checkbox = ui
.create(WidgetKind::Checkbox, Some("I agree"))
.expect("checkbox should be created");
ui.set_checked(checkbox, true)
.expect("set_checked should succeed");
assert_eq!(
ui.widget(checkbox).and_then(|spec| spec.checked),
Some(true)
);
}
#[test]
fn set_value_rejects_unsupported_kind() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
let err = ui
.set_value(label, 5)
.expect_err("non-value widget should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_value"));
}
#[test]
#[cfg(feature = "widgets-range")]
fn set_value_updates_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let progress = ui
.create(WidgetKind::ProgressBar, None)
.expect("progress bar should be created");
ui.set_value(progress, 42)
.expect("set_value should succeed");
assert_eq!(ui.widget(progress).and_then(|spec| spec.value), Some(42));
}
#[test]
#[cfg(feature = "widgets-range")]
fn set_range_rejects_inverted_bounds() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let slider = ui
.create(WidgetKind::Slider, None)
.expect("slider should be created");
let err = ui
.set_range(slider, 10, 5)
.expect_err("inverted range should be rejected");
assert_eq!(
err,
GuiError::Backend("Widget range min must be <= max".to_owned())
);
}
#[test]
#[cfg(feature = "widgets-range")]
fn set_step_rejects_non_positive_value() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let slider = ui
.create(WidgetKind::Slider, None)
.expect("slider should be created");
let err = ui
.set_step(slider, 0)
.expect_err("non-positive step should be rejected");
assert_eq!(
err,
GuiError::Backend("Widget step must be positive".to_owned())
);
}
#[test]
fn set_selected_index_rejects_unsupported_kind() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
let err = ui
.set_selected_index(label, 0)
.expect_err("non-selection widget should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_selected_index"));
}
#[test]
fn set_data_grid_rows_rejects_non_grid() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
let err = ui
.set_data_grid_rows(label, &[vec!["x".to_owned()]])
.expect_err("non-grid widget should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_data_grid_rows"));
}
#[test]
fn set_data_grid_rows_updates_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let grid = ui
.create(WidgetKind::DataGrid, None)
.expect("grid should be created");
let rows = vec![vec!["A".to_owned(), "B".to_owned()]];
ui.set_data_grid_rows(grid, &rows)
.expect("set_data_grid_rows should succeed");
assert_eq!(
ui.widget(grid)
.map(|spec| spec.data_grid_rows.as_ref().clone())
.unwrap_or_default(),
rows
);
}
#[test]
#[cfg(feature = "widgets-media")]
fn set_image_source_rejects_non_image() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
let err = ui
.set_image_source(label, "./icon.png")
.expect_err("non-image widget should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_image_source"));
}
#[test]
#[cfg(not(feature = "widgets-media"))]
fn image_setters_return_unsupported_when_media_is_compiled_out() {
let mut ui = Ui::new(MockBackend::default());
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
assert_eq!(
ui.set_image_source(label, "./icon.png"),
Err(GuiError::UnsupportedWidget("set_image_source"))
);
assert_eq!(
ui.set_image_fit(label, ImageFit::Contain),
Err(GuiError::UnsupportedWidget("set_image_fit"))
);
}
#[test]
#[cfg(feature = "widgets-media")]
fn set_image_fit_round_trips_and_rejects_non_image() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let image = ui
.create(WidgetKind::Image, None)
.expect("image should be created");
assert_eq!(
ui.widget(image).map(|spec| spec.image_fit),
Some(ImageFit::Contain),
"the default preserves the existing letterbox behavior"
);
ui.set_image_fit(image, ImageFit::Cover)
.expect("set_image_fit should succeed");
assert_eq!(
ui.widget(image).map(|spec| spec.image_fit),
Some(ImageFit::Cover)
);
assert_eq!(
ui.backend().created.get(&image).map(|spec| spec.image_fit),
Some(ImageFit::Cover),
"the backend records the mode too"
);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
let err = ui
.set_image_fit(label, ImageFit::Fill)
.expect_err("non-image widget should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_image_fit"));
}
#[test]
#[cfg(feature = "widgets-pickers")]
fn set_file_chooser_mode_round_trips_and_rejects_non_chooser() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let chooser = ui
.create(WidgetKind::FileChooserDialog, Some("Open Folder…"))
.expect("chooser should be created");
assert_eq!(
ui.widget(chooser).map(|spec| spec.file_chooser_mode),
Some(FileChooserMode::OpenFile),
"the default keeps the open-file dialog"
);
ui.set_file_chooser_mode(chooser, FileChooserMode::PickFolder)
.expect("set_file_chooser_mode should succeed");
assert_eq!(
ui.widget(chooser).map(|spec| spec.file_chooser_mode),
Some(FileChooserMode::PickFolder)
);
assert_eq!(
ui.backend()
.created
.get(&chooser)
.map(|spec| spec.file_chooser_mode),
Some(FileChooserMode::PickFolder),
"the backend records the mode too"
);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
assert_eq!(
ui.set_file_chooser_mode(label, FileChooserMode::PickFolder)
.unwrap_err(),
GuiError::UnsupportedWidget("set_file_chooser_mode")
);
}
#[test]
#[cfg(feature = "widgets-pickers")]
fn set_color_dialog_data_round_trips_and_rejects_non_dialogs() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let dialog = ui
.create(WidgetKind::ColorDialog, Some("Pick colour…"))
.expect("colour dialog should be created");
assert_eq!(
ui.widget(dialog)
.and_then(|spec| spec.color_dialog_data.as_ref()),
None,
"a fresh dialog carries no preferences"
);
let mut data = ColorDialogData::new(Rgba::new(4, 5, 6, 255));
data.push_custom(Rgba::new(7, 8, 9, 255)).unwrap();
ui.set_color_dialog_data(dialog, data.clone())
.expect("set_color_dialog_data should succeed");
assert_eq!(
ui.widget(dialog)
.and_then(|spec| spec.color_dialog_data.as_ref()),
Some(&data)
);
assert_eq!(
ui.backend()
.created
.get(&dialog)
.and_then(|spec| spec.color_dialog_data.as_ref()),
Some(&data),
"the backend records the preferences too"
);
let mut oversized = data.clone();
for index in 0..=crate::MAX_CUSTOM_COLORS {
oversized.custom.push(Rgba::new(index as u8, 0, 0, 255));
}
let error = ui.set_color_dialog_data(dialog, oversized).unwrap_err();
assert!(
matches!(error, GuiError::Backend(ref message) if message.contains("at most 16 are supported")),
"unexpected error: {error:?}"
);
assert_eq!(
ui.widget(dialog)
.and_then(|spec| spec.color_dialog_data.as_ref()),
Some(&data),
"a rejected update leaves the stored preferences untouched"
);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
assert_eq!(
ui.set_color_dialog_data(label, ColorDialogData::default())
.unwrap_err(),
GuiError::UnsupportedWidget("set_color_dialog_data")
);
}
#[test]
#[cfg(feature = "widgets-pickers")]
fn set_font_dialog_data_round_trips_and_rejects_non_dialogs() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let dialog = ui
.create(WidgetKind::FontDialog, Some("Pick font…"))
.expect("font dialog should be created");
assert_eq!(
ui.widget(dialog)
.and_then(|spec| spec.font_dialog_data.as_ref()),
None,
"a fresh dialog carries no preferences"
);
let mut data = FontDialogData::new(FontDescriptor::new("Inter", 12.0));
data.min_size_pt = Some(9.0);
data.max_size_pt = Some(24.0);
ui.set_font_dialog_data(dialog, data.clone())
.expect("set_font_dialog_data should succeed");
assert_eq!(
ui.widget(dialog)
.and_then(|spec| spec.font_dialog_data.as_ref()),
Some(&data)
);
assert_eq!(
ui.backend()
.created
.get(&dialog)
.and_then(|spec| spec.font_dialog_data.as_ref()),
Some(&data),
"the backend records the preferences too"
);
let mut inverted = data.clone();
inverted.min_size_pt = Some(30.0);
inverted.max_size_pt = Some(20.0);
let error = ui.set_font_dialog_data(dialog, inverted).unwrap_err();
assert!(
matches!(error, GuiError::Backend(ref message) if message.contains("inverted")),
"unexpected error: {error:?}"
);
assert_eq!(
ui.widget(dialog)
.and_then(|spec| spec.font_dialog_data.as_ref()),
Some(&data),
"a rejected update leaves the stored preferences untouched"
);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
assert_eq!(
ui.set_font_dialog_data(
label,
FontDialogData::new(FontDescriptor::new("Inter", 12.0))
)
.unwrap_err(),
GuiError::UnsupportedWidget("set_font_dialog_data")
);
}
#[test]
fn toolbar_setters_round_trip_and_reject_other_kinds() {
use crate::toolbar::ToolSpec;
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let toolbar = ui
.create(WidgetKind::Toolbar, Some("Main"))
.expect("toolbar should be created");
assert!(ui.widget(toolbar).unwrap().toolbar_items.is_empty());
assert_eq!(
ui.widget(toolbar).unwrap().toolbar_orientation,
ToolbarOrientation::Horizontal
);
let items = vec![
ToolbarItem::Tool(ToolSpec::new(ToolId(1), "New")),
ToolbarItem::Separator,
ToolbarItem::Tool(ToolSpec::new(ToolId(2), "Bold").with_checkable()),
];
ui.set_toolbar_items(toolbar, items.clone())
.expect("set_toolbar_items should succeed");
assert_eq!(ui.widget(toolbar).unwrap().toolbar_items, items);
assert_eq!(
ui.backend()
.created
.get(&toolbar)
.map(|spec| spec.toolbar_items.clone()),
Some(items.clone()),
"the backend records the rows too"
);
ui.set_toolbar_orientation(toolbar, ToolbarOrientation::Vertical)
.expect("set_toolbar_orientation should succeed");
assert_eq!(
ui.widget(toolbar).unwrap().toolbar_orientation,
ToolbarOrientation::Vertical
);
let dangling = vec![ToolbarItem::Tool(
ToolSpec::new(ToolId(3), "Center").with_radio_group(ToolId(9)),
)];
let error = ui.set_toolbar_items(toolbar, dangling).unwrap_err();
assert!(
matches!(error, GuiError::Backend(ref message) if message.contains("radio group")),
"unexpected error: {error:?}"
);
assert_eq!(ui.widget(toolbar).unwrap().toolbar_items, items);
assert_eq!(
ui.set_tool_state(toolbar, ToolId(1), true).unwrap_err(),
GuiError::Backend(crate::toolbar::ToolbarError::NotCheckable(ToolId(1)).to_string())
);
assert_eq!(
ui.set_tool_state(toolbar, ToolId(2), true).unwrap(),
vec![(ToolId(2), true)]
);
ui.update_tool(toolbar, ToolId(1), ToolUpdate::new().with_label("New file"))
.unwrap();
assert_eq!(
crate::toolbar::find_tool(&ui.widget(toolbar).unwrap().toolbar_items, ToolId(1))
.map(|tool| tool.label.clone()),
Some("New file".to_owned())
);
assert!(
ui.poll_event().expect("poll_event").is_none(),
"no events were emitted"
);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
assert_eq!(
ui.set_toolbar_items(label, items.clone()).unwrap_err(),
GuiError::UnsupportedWidget("set_toolbar_items")
);
assert_eq!(
ui.set_toolbar_orientation(label, ToolbarOrientation::Horizontal)
.unwrap_err(),
GuiError::UnsupportedWidget("set_toolbar_orientation")
);
assert_eq!(
ui.update_tool(label, ToolId(1), ToolUpdate::new()),
Err(GuiError::UnsupportedWidget("set_toolbar_items"))
);
}
#[test]
fn set_date_value_rejects_non_date_picker() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
let err = ui
.set_date_value(label, "2026-09-07")
.expect_err("non-date widget should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_date_value"));
}
#[test]
fn set_link_url_rejects_non_link_label() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("label"))
.expect("label should be created");
let err = ui
.set_link_url(label, "https://example.com")
.expect_err("non-link widget should be rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_link_url"));
}
#[test]
fn set_container_direction_updates_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let container = ui
.create(WidgetKind::Container, None)
.expect("container should be created");
ui.set_container_direction(container, ContainerDirection::Horizontal)
.expect("set_container_direction should succeed");
assert_eq!(
ui.widget(container)
.and_then(|spec| spec.container_direction),
Some(ContainerDirection::Horizontal)
);
let node = *ui.layout_nodes.get(&container).expect("layout node");
let style = ui.layout_tree.style(node).expect("style");
assert_eq!(style.flex_direction, crate::layout::FlexDirection::Row);
ui.set_container_direction(container, ContainerDirection::Vertical)
.expect("set_container_direction should succeed");
let style = ui.layout_tree.style(node).expect("style");
assert_eq!(style.flex_direction, crate::layout::FlexDirection::Column);
}
#[test]
fn unset_container_direction_stacks_vertically_like_native_backends() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let container = ui.create(WidgetKind::Container, None).expect("container");
let first = ui.create(WidgetKind::Button, Some("first")).expect("first");
let second = ui
.create(WidgetKind::Button, Some("second"))
.expect("second");
ui.attach(window, container).expect("attach container");
ui.attach(container, first).expect("attach first");
ui.attach(container, second).expect("attach second");
for widget in [
container,
ui.create(WidgetKind::GroupBox, Some("g")).expect("group"),
] {
let node = *ui.layout_nodes.get(&widget).expect("layout node");
let style = ui.layout_tree.style(node).expect("style");
assert_eq!(style.flex_direction, crate::layout::FlexDirection::Column);
}
let split = ui.create(WidgetKind::SplitPane, None).expect("split");
let node = *ui.layout_nodes.get(&split).expect("layout node");
let style = ui.layout_tree.style(node).expect("style");
assert_eq!(style.flex_direction, crate::layout::FlexDirection::Row);
ui.compute_layout(window, 420.0, 380.0).expect("layout");
let a = ui.layout_rect(first).expect("first rect");
let b = ui.layout_rect(second).expect("second rect");
assert!(
b.y >= a.y + a.height,
"children of an unset-direction container overlap or share a row: {a:?} vs {b:?}"
);
}
#[test]
fn set_tooltip_updates_spec_and_backend() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui
.create(WidgetKind::Button, Some("Run"))
.expect("button should be created");
ui.set_tooltip(button, "Run the build")
.expect("set_tooltip should succeed");
assert_eq!(
ui.widget(button).and_then(|spec| spec.tooltip.as_deref()),
Some("Run the build")
);
assert_eq!(
ui.backend()
.created
.get(&button)
.and_then(|spec| spec.tooltip.as_deref()),
Some("Run the build")
);
}
#[test]
#[cfg(feature = "widgets-canvas")]
fn set_accessible_metadata_updates_spec_and_backend() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let canvas = ui
.create(WidgetKind::Canvas, None)
.expect("canvas should be created");
assert_eq!(
ui.accessibility(canvas).map(|spec| spec.role),
Some(AccessibleRole::Canvas)
);
ui.set_accessible_name(canvas, "Live chart")
.expect("set_accessible_name should succeed");
ui.set_accessible_description(canvas, "Renders throughput over time")
.expect("set_accessible_description should succeed");
let spec = ui.widget(canvas).expect("widget spec");
assert_eq!(spec.accessibility.name.as_deref(), Some("Live chart"));
assert_eq!(
spec.accessibility.description.as_deref(),
Some("Renders throughput over time")
);
let mock_spec = ui.backend().created.get(&canvas).expect("mock spec");
assert_eq!(mock_spec.accessibility.name.as_deref(), Some("Live chart"));
assert_eq!(
mock_spec.accessibility.description.as_deref(),
Some("Renders throughput over time")
);
let err = ui
.set_accessible_name(WidgetId(9999), "missing")
.expect_err("missing widget should fail");
assert_eq!(err, GuiError::WidgetNotFound(9999));
}
#[test]
#[cfg(all(feature = "widgets-containers", feature = "widgets-text"))]
fn dynamic_accessible_updates_are_forwarded_to_the_backend() {
let mut ui = Ui::new(MockBackend::default());
let window = ui
.create(WidgetKind::Window, Some("Notifications"))
.expect("window");
let input = ui
.create(WidgetKind::TextInput, Some("Initial"))
.expect("text input");
#[cfg(feature = "widgets-range")]
let slider = ui.create(WidgetKind::Slider, None).expect("slider");
let alert = ui
.create(WidgetKind::AlertDialog, Some("Saved"))
.expect("alert dialog");
ui.attach(window, input).expect("attach input");
#[cfg(feature = "widgets-range")]
ui.attach(window, slider).expect("attach slider");
ui.attach(window, alert).expect("attach alert");
ui.set_text(input, "Updated").expect("update text");
#[cfg(feature = "widgets-range")]
ui.set_value(slider, 42).expect("update value");
ui.focus(input).expect("move focus");
ui.show(alert).expect("show alert widget");
ui.show_confirm_dialog("Continue?", "Save first?")
.expect("show confirm dialog");
#[cfg(feature = "widgets-range")]
let expected_notifications = vec![
(input, AccessibleNotification::TextChanged),
(slider, AccessibleNotification::ValueChanged),
(input, AccessibleNotification::FocusChanged),
(
alert,
AccessibleNotification::Announcement("Saved".to_owned()),
),
(
input,
AccessibleNotification::Announcement("Continue?. Save first?".to_owned()),
),
];
#[cfg(not(feature = "widgets-range"))]
let expected_notifications = vec![
(input, AccessibleNotification::TextChanged),
(input, AccessibleNotification::FocusChanged),
(
alert,
AccessibleNotification::Announcement("Saved".to_owned()),
),
(
input,
AccessibleNotification::Announcement("Continue?. Save first?".to_owned()),
),
];
assert_eq!(
ui.backend().posted_accessible_notifications,
expected_notifications,
);
let err = ui
.set_text(WidgetId(9999), "missing")
.expect_err("unknown widget is rejected");
assert_eq!(err, GuiError::WidgetNotFound(9999));
#[cfg(feature = "widgets-range")]
assert_eq!(ui.backend().posted_accessible_notifications.len(), 5);
#[cfg(not(feature = "widgets-range"))]
assert_eq!(ui.backend().posted_accessible_notifications.len(), 4);
}
#[test]
#[cfg(feature = "widgets-text")]
fn focus_traversal_visits_focusable_widgets_in_creation_order() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("Form")).expect("window");
let container = ui.create(WidgetKind::Container, None).expect("container");
let label = ui.create(WidgetKind::Label, Some("Name")).expect("label");
let name = ui.create(WidgetKind::TextInput, None).expect("text input");
let save = ui.create(WidgetKind::Button, Some("Save")).expect("button");
ui.attach(window, container).expect("attach container");
ui.attach(container, label).expect("attach label");
ui.attach(container, name).expect("attach input");
ui.attach(container, save).expect("attach button");
assert_eq!(ui.focused(), None);
assert_eq!(ui.focus_next().expect("focus"), Some(name));
assert_eq!(ui.focused(), Some(name));
assert_eq!(ui.focus_next().expect("focus"), Some(save));
assert_eq!(
ui.focus_next().expect("focus"),
Some(name),
"traversal wraps to the start"
);
assert_eq!(
ui.focus_previous().expect("focus"),
Some(save),
"backwards traversal wraps too"
);
}
#[test]
#[cfg(feature = "widgets-text")]
fn focus_traversal_skips_disabled_widgets_and_their_children() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, None).expect("window");
let first = ui
.create(WidgetKind::Button, Some("First"))
.expect("button");
let group = ui.create(WidgetKind::Container, None).expect("container");
let nested = ui
.create(WidgetKind::TextInput, Some("Nested"))
.expect("text_input");
let last = ui.create(WidgetKind::Button, Some("Last")).expect("button");
ui.attach(window, first).expect("attach first");
ui.attach(window, group).expect("attach group");
ui.attach(group, nested).expect("attach nested");
ui.attach(window, last).expect("attach last");
assert_eq!(ui.focus_next().expect("focus"), Some(first));
assert_eq!(ui.focus_next().expect("focus"), Some(nested));
assert_eq!(ui.focus_next().expect("focus"), Some(last));
ui.set_enabled(group, false).expect("disable group");
ui.focus(first).expect("focus first");
assert_eq!(
ui.focus_next().expect("focus"),
Some(last),
"disabled subtree is skipped"
);
ui.set_enabled(group, true).expect("enable group");
ui.focus(first).expect("focus first");
assert_eq!(ui.focus_next().expect("focus"), Some(nested));
}
#[test]
fn set_focusable_updates_spec_and_backend_and_validates() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, None).expect("window");
let label = ui.create(WidgetKind::Label, Some("Static")).expect("label");
assert_eq!(ui.is_focusable(label), Some(false));
ui.set_focusable(label, true)
.expect("label becomes focusable");
assert_eq!(ui.is_focusable(label), Some(true));
assert_eq!(ui.widget(label).and_then(|spec| spec.focusable), Some(true));
assert_eq!(
ui.backend()
.created
.get(&label)
.and_then(|spec| spec.focusable),
Some(true)
);
let order = ui.focus_order();
assert!(order.contains(&label), "override joins the traversal order");
assert!(!order.contains(&window), "window stays out of the order");
let err = ui
.set_focusable(WidgetId(9999), true)
.expect_err("unknown widget rejected");
assert_eq!(err, GuiError::WidgetNotFound(9999));
}
#[test]
fn focus_reports_changes_and_clears_on_remove() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, None).expect("window");
let first = ui
.create(WidgetKind::Button, Some("First"))
.expect("button");
let second = ui
.create(WidgetKind::Button, Some("Second"))
.expect("button");
ui.attach(window, first).expect("attach first");
ui.attach(window, second).expect("attach second");
ui.focus(first).expect("focus first");
assert_eq!(ui.backend().focused, Some(first));
ui.focus(second).expect("focus second");
assert_eq!(ui.backend().focused, Some(second));
let mut events = Vec::new();
ui.dispatch_events(|event| events.push(event))
.expect("dispatch");
let reported: Vec<(WidgetId, bool)> = events
.iter()
.filter_map(|event| match event {
UiEvent::FocusChanged { widget_id, focused } => Some((*widget_id, *focused)),
_ => None,
})
.collect();
assert_eq!(
reported,
vec![(first, true), (first, false), (second, true)]
);
assert_eq!(
ui.focused(),
Some(second),
"dispatch keeps the Ui record in sync"
);
ui.remove(second).expect("remove focused widget");
assert_eq!(
ui.focused(),
None,
"removing the focused widget clears focus"
);
let err = ui
.focus(WidgetId(4242))
.expect_err("unknown widget rejected");
assert_eq!(err, GuiError::WidgetNotFound(4242));
}
#[test]
fn focus_next_without_candidates_reports_none() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
ui.create(WidgetKind::Window, None).expect("window");
assert_eq!(ui.focus_next().expect("focus"), None);
assert_eq!(ui.focused(), None);
}
#[test]
fn set_theme_and_mode_update_record_and_backend() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
assert_eq!(ui.theme_mode(), ThemeMode::Light);
assert_eq!(ui.backend().theme, None);
ui.set_theme_mode(ThemeMode::Dark)
.expect("theme mode should apply");
assert_eq!(ui.theme_mode(), ThemeMode::Dark);
assert_eq!(
ui.backend().theme.as_ref().map(|theme| theme.mode),
Some(ThemeMode::Dark)
);
let custom = Theme::light();
ui.set_theme(custom.clone()).expect("theme should apply");
assert_eq!(ui.theme(), &custom);
assert_eq!(ui.backend().theme.as_ref(), Some(&custom));
}
#[test]
fn theme_overrides_round_trip_and_clear() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let button = ui.create(WidgetKind::Button, Some("Go")).expect("button");
assert!(ui.theme_overrides(button).is_empty());
ui.set_theme_override(button, ThemeOverride::Padding(12))
.expect("padding override should apply");
ui.set_theme_override(button, ThemeOverride::FontSize(15.0))
.expect("font override should apply");
assert_eq!(
ui.theme_overrides(button),
[ThemeOverride::Padding(12), ThemeOverride::FontSize(15.0)]
);
assert_eq!(
ui.backend().theme_overrides.get(&button).map(Vec::len),
Some(2)
);
ui.clear_theme_overrides(button).expect("clear should work");
assert!(ui.theme_overrides(button).is_empty());
assert!(!ui.backend().theme_overrides.contains_key(&button));
let err = ui
.set_theme_override(WidgetId(9999), ThemeOverride::Padding(1))
.expect_err("unknown widget rejected");
assert_eq!(err, GuiError::WidgetNotFound(9999));
}
#[test]
fn stock_icon_resolution_follows_theme_mode_and_dpi_scale() {
use crate::artprov::IconSource;
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let light_small = ui.stock_icon(IconRole::Warning, IconSize::Small);
assert_eq!(light_small.mode, ThemeMode::Light);
assert_eq!(light_small.size, IconSize::Small);
assert_eq!((light_small.width, light_small.height), (16, 16));
assert_eq!(light_small.source, IconSource::Portable);
assert!(light_small.has_visible_pixels());
let light_large_2x = ui.stock_icon_at_scale(IconRole::Warning, IconSize::Large, 2);
assert_eq!((light_large_2x.width, light_large_2x.height), (64, 64));
assert_eq!(light_large_2x.scale, 2);
ui.set_theme_mode(ThemeMode::Dark)
.expect("theme mode should apply");
let dark_small = ui.stock_icon(IconRole::Warning, IconSize::Small);
assert_eq!(dark_small.mode, ThemeMode::Dark);
assert_ne!(
dark_small.pixels, light_small.pixels,
"theme mode must change the resolved pixels"
);
}
#[test]
fn native_stock_icon_is_a_typed_capability_error_on_mock() {
let backend = MockBackend::default();
let ui = Ui::new(backend);
assert_eq!(ui.art_capabilities(), ArtCapabilities::none());
let err = ui
.native_stock_icon(IconRole::Information, IconSize::Large)
.expect_err("mock has no native stock art");
match err {
GuiError::UnsupportedCapability(message) => {
assert!(message.contains("information"), "message: {message}");
assert!(message.contains("large"), "message: {message}");
}
other => panic!("expected UnsupportedCapability, got {other:?}"),
}
}
#[test]
fn attach_context_menu_binds_menu_to_widget_and_validates() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let list = ui
.create(WidgetKind::DataList, Some("Files"))
.expect("list should be created");
let menu = ui.create_menu().expect("menu should be created");
let item = ui
.add_menu_item(menu, "Open")
.expect("item should be created");
ui.attach_context_menu(list, menu)
.expect("attach should succeed");
assert_eq!(ui.backend().context_menus.get(&list), Some(&menu));
assert_eq!(ui.backend().menus.get(&menu), Some(&vec![item]));
assert_eq!(
ui.attach_context_menu(WidgetId(9999), menu).unwrap_err(),
GuiError::WidgetNotFound(9999)
);
assert!(matches!(
ui.attach_context_menu(list, MenuId(9999)),
Err(GuiError::Backend(_))
));
}
#[test]
fn set_row_drag_updates_spec_and_backend_and_validates() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let list = ui
.create(WidgetKind::ListView, Some("Files"))
.expect("list should be created");
ui.set_row_drag(list, true, true)
.expect("set_row_drag should succeed");
assert!(ui.widget(list).unwrap().row_drag_source);
assert!(ui.widget(list).unwrap().row_drop_target);
assert!(ui.backend().created.get(&list).unwrap().row_drag_source);
assert!(ui.backend().created.get(&list).unwrap().row_drop_target);
ui.set_row_drag(list, false, false)
.expect("disable should succeed");
assert!(!ui.widget(list).unwrap().row_drag_source);
assert!(!ui.widget(list).unwrap().row_drop_target);
let button = ui
.create(WidgetKind::Button, Some("nope"))
.expect("button should be created");
let err = ui
.set_row_drag(button, true, false)
.expect_err("button rejected");
assert_eq!(err, GuiError::UnsupportedWidget("set_row_drag"));
}
#[test]
fn show_confirm_dialog_returns_token_and_records_request() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let token1 = ui
.show_confirm_dialog("Delete?", "Move to trash?")
.expect("first dialog");
let token2 = ui
.show_confirm_dialog("Exit?", "Really quit?")
.expect("second dialog");
assert!(token2 > token1);
assert_eq!(
ui.backend().confirm_requests,
vec![
(token1, "Delete?".to_owned(), "Move to trash?".to_owned()),
(token2, "Exit?".to_owned(), "Really quit?".to_owned()),
]
);
ui.backend_mut().push_event(UiEvent::DialogResponse {
token: token1,
confirmed: true,
});
assert_eq!(
ui.poll_event().unwrap(),
Some(UiEvent::DialogResponse {
token: token1,
confirmed: true
})
);
}
#[test]
fn close_guard_records_per_window_and_rejects_other_kinds() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Guard"))
.expect("window should be created");
ui.set_close_guard(window, true).expect("guard on");
assert_eq!(ui.backend().close_guards.get(&window), Some(&true));
ui.set_close_guard(window, false).expect("guard off");
assert_eq!(ui.backend().close_guards.get(&window), Some(&false));
let label = ui
.create(WidgetKind::Label, Some("not a window"))
.expect("label should be created");
let err = ui
.set_close_guard(label, true)
.expect_err("labels cannot be guarded");
assert_eq!(err, GuiError::UnsupportedWidget("set_close_guard"));
}
#[test]
fn menu_item_enable_state_records_on_mock_and_validates_the_item() {
let mut ui = Ui::new(MockBackend::default());
let menu = ui.create_menu().expect("menu should be created");
let item = ui.add_menu_item(menu, "Undo").expect("menu item");
ui.set_menu_item_enabled(item, false).expect("disable");
assert_eq!(ui.backend().menu_item_enabled.get(&item), Some(&false));
ui.set_menu_item_enabled(item, true).expect("enable");
assert_eq!(ui.backend().menu_item_enabled.get(&item), Some(&true));
let err = ui
.set_menu_item_enabled(MenuItemId(9_999), true)
.expect_err("unknown items are rejected");
assert!(
matches!(&err, GuiError::Backend(message) if message.contains("Menu item not found")),
"{err:?}"
);
}
#[test]
fn dynamic_menu_items_relabel_insert_remove_and_detach_submenus() {
let mut ui = Ui::new(MockBackend::default());
let menu = ui.create_menu().expect("menu should be created");
let recent = ui.add_submenu(menu, "Open Recent").expect("submenu");
let recent_slot = *ui
.submenu_slots
.get(&recent)
.expect("the submenu row slot is recorded");
assert_eq!(
ui.backend().menus.get(&menu).cloned(),
Some(vec![recent_slot]),
"a submenu holds its slot in the parent's ordered list"
);
let first = ui
.insert_menu_item(menu, 0, "New")
.expect("insert at a valid position should succeed");
assert_eq!(
ui.backend().menus.get(&menu).cloned(),
Some(vec![first, recent_slot])
);
ui.set_menu_item_text(first, "New Document")
.expect("relabel should succeed");
assert_eq!(
ui.backend().menu_item_text.get(&first).map(String::as_str),
Some("New Document")
);
let second = ui
.insert_menu_item_with_shortcut(menu, 1, "Open", Some("Ctrl+O"))
.expect("insert with shortcut");
let tail = ui
.insert_menu_item(menu, 99, "Quit")
.expect("an index past the end appends");
assert_eq!(
ui.backend().menus.get(&menu).cloned(),
Some(vec![first, second, recent_slot, tail]),
"bookkeeping and the recorded lane order agree"
);
assert_eq!(
ui.backend().menu_shortcuts.get(&second).map(String::as_str),
Some("Ctrl+O")
);
ui.on_menu_item_selected(second, || {}).expect("callback");
assert!(ui.on_menu_item_selected.contains_key(&second));
ui.remove_menu_item(second).expect("remove should succeed");
assert_eq!(
ui.backend().menus.get(&menu).cloned(),
Some(vec![first, recent_slot, tail])
);
assert!(!ui.backend().menu_item_text.contains_key(&second));
assert!(!ui.on_menu_item_selected.contains_key(&second));
let recent_item = ui
.add_menu_item(MenuId(recent.0), "notes.txt")
.expect("submenu item");
ui.remove_submenu(recent).expect("remove submenu");
assert_eq!(
ui.backend().menus.get(&menu).cloned(),
Some(vec![first, tail]),
"the parent loses the submenu slot"
);
assert!(!ui.backend().menus.contains_key(&MenuId(recent.0)));
assert!(!ui.backend().menu_item_text.contains_key(&recent_item));
assert!(!ui.menu_parents.contains_key(&recent));
assert!(ui.set_menu_item_text(MenuItemId(9_999), "x").is_err());
assert!(ui.remove_menu_item(MenuItemId(9_999)).is_err());
assert!(ui.insert_menu_item(MenuId(9_999), 0, "x").is_err());
let err = ui
.remove_submenu(menu)
.expect_err("a root menu has no parent to detach from");
assert!(
matches!(&err, GuiError::Backend(message) if message.contains("Submenu not found")),
"{err:?}"
);
}
#[test]
fn wait_event_returns_pushed_events_in_order() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Main"))
.expect("window should be created");
ui.backend_mut()
.push_event(UiEvent::Clicked { widget_id: window });
assert_eq!(
ui.wait_event().expect("wait should succeed"),
UiEvent::Clicked { widget_id: window }
);
ui.backend_mut()
.push_event(UiEvent::WindowClosed { widget_id: window });
assert_eq!(
ui.wait_event().expect("wait should succeed"),
UiEvent::WindowClosed { widget_id: window }
);
}
#[test]
fn activated_event_dispatches_to_handler_with_index() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Main"))
.expect("window should be created");
let mut seen: Vec<UiEvent> = Vec::new();
ui.backend_mut().push_event(UiEvent::Activated {
widget_id: window,
index: Some(2),
});
ui.dispatch_events(|event| seen.push(event))
.expect("event dispatch should succeed");
assert_eq!(
seen,
vec![UiEvent::Activated {
widget_id: window,
index: Some(2),
}]
);
}
#[test]
#[cfg(all(feature = "async", feature = "widgets-range"))]
fn task_proxy_applies_queued_mutations_in_fifo_order() {
use crate::async_ui::TaskDrainReport;
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("start"))
.expect("label should be created");
let progress = ui
.create(WidgetKind::ProgressBar, None)
.expect("progress bar should be created");
let data_list = ui
.create(WidgetKind::DataList, None)
.expect("data list should be created");
let grid = ui
.create(WidgetKind::DataGrid, None)
.expect("data grid should be created");
let proxy = ui.task_proxy();
let token = proxy.start_task();
proxy.set_text(label, "first").expect("post");
proxy.set_value(progress, 25).expect("post");
proxy
.set_data_list_items(data_list, ["Alpha".to_owned(), "Beta".to_owned()])
.expect("post");
proxy
.set_data_grid_rows(grid, [vec!["A1".to_owned(), "A2".to_owned()]])
.expect("post");
proxy.set_text(label, "second").expect("post");
proxy.progress(&token, 25.0).expect("post");
assert_eq!(
ui.widget(label).and_then(|spec| spec.text.as_deref()),
Some("start")
);
assert_eq!(ui.widget(progress).and_then(|spec| spec.value), None);
assert!(ui
.widget(data_list)
.map(|spec| spec.data_list_items.clone())
.unwrap_or_default()
.is_empty());
assert!(ui
.widget(grid)
.map(|spec| spec.data_grid_rows.clone())
.unwrap_or_default()
.is_empty());
let report = ui.drain_task_commands();
assert_eq!(
report,
TaskDrainReport {
applied: 6,
rejected: 0,
}
);
assert_eq!(
ui.widget(label).and_then(|spec| spec.text.as_deref()),
Some("second")
);
assert_eq!(ui.widget(progress).and_then(|spec| spec.value), Some(25));
assert_eq!(
ui.widget(data_list)
.map(|spec| spec.data_list_items.clone())
.unwrap_or_default(),
vec!["Alpha".to_owned(), "Beta".to_owned()]
);
assert_eq!(
ui.widget(grid)
.map(|spec| spec.data_grid_rows.as_ref().clone())
.unwrap_or_default(),
vec![vec!["A1".to_owned(), "A2".to_owned()]]
);
let event = ui.poll_event().expect("poll").expect("task event");
assert_eq!(
event,
UiEvent::Task(TaskEvent::Progress {
task: token.id(),
value: 25.0,
})
);
assert!(ui.poll_event().expect("poll").is_none());
}
#[test]
#[cfg(feature = "async")]
fn wait_event_applies_commands_and_wakes_on_a_worker_post() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("idle"))
.expect("label should be created");
let proxy = ui.task_proxy();
let token = proxy.start_task();
let worker_proxy = proxy.clone();
let worker_token = token.clone();
let worker = std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(30));
worker_proxy.set_text(label, "from worker").expect("post");
worker_proxy.finish(&worker_token).expect("post");
});
let event = ui.wait_event().expect("wait");
assert_eq!(
event,
UiEvent::Task(TaskEvent::Finished { task: token.id() })
);
assert_eq!(
ui.widget(label).and_then(|spec| spec.text.as_deref()),
Some("from worker")
);
worker.join().expect("worker should join");
}
#[test]
#[cfg(feature = "async")]
fn wake_marker_never_reaches_dispatch_handlers() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Main"))
.expect("window should be created");
let proxy = ui.task_proxy();
let token = proxy.start_task();
proxy.finish(&token).expect("post");
ui.backend_mut()
.push_event(UiEvent::Clicked { widget_id: window });
let mut seen = Vec::new();
let count = ui
.dispatch_events(|event| seen.push(event))
.expect("dispatch should succeed");
assert_eq!(count, 2);
assert_eq!(
seen,
vec![
UiEvent::Task(TaskEvent::Finished { task: token.id() }),
UiEvent::Clicked { widget_id: window },
]
);
}
#[test]
#[cfg(feature = "async")]
fn drain_rejects_commands_for_removed_widgets() {
use crate::async_ui::{TaskAbortReason, TaskCommandKind, TaskDrainReport};
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("alive"))
.expect("label should be created");
let doomed = ui
.create(WidgetKind::Label, Some("doomed"))
.expect("label should be created");
let proxy = ui.task_proxy();
ui.remove(doomed).expect("remove should succeed");
proxy.set_text(doomed, "ghost").expect("post");
proxy.set_text(label, "kept").expect("post");
let report = ui.drain_task_commands();
assert_eq!(
report,
TaskDrainReport {
applied: 1,
rejected: 1,
}
);
assert_eq!(
ui.widget(label).and_then(|spec| spec.text.as_deref()),
Some("kept")
);
assert!(ui.widget(doomed).is_none());
let event = ui.poll_event().expect("poll").expect("abort event");
assert_eq!(
event,
UiEvent::Task(TaskEvent::Aborted {
widget_id: doomed,
command: TaskCommandKind::SetText,
reason: TaskAbortReason::WidgetRemoved,
})
);
assert!(
ui.poll_event().expect("poll").is_none(),
"exactly one dead-letter event per aborted command"
);
}
#[test]
#[cfg(feature = "async")]
fn drain_reports_live_refusals_and_keeps_aborts_in_post_order() {
use crate::async_ui::{TaskAbortReason, TaskCommandKind, TaskDrainReport};
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("plain"))
.expect("label should be created");
let doomed = ui
.create(WidgetKind::Label, Some("doomed"))
.expect("label should be created");
let proxy = ui.task_proxy();
let token = proxy.start_task();
proxy.set_checked(label, true).expect("post");
ui.remove(doomed).expect("remove should succeed");
proxy.set_text(doomed, "final").expect("post");
proxy
.finish_lossless(&token, std::time::Duration::from_secs(1))
.expect("post");
let report = ui.drain_task_commands();
assert_eq!(
report,
TaskDrainReport {
applied: 1,
rejected: 2,
}
);
assert_eq!(ui.widget(label).and_then(|spec| spec.checked), None);
let events: Vec<UiEvent> = std::iter::from_fn(|| ui.poll_event().expect("poll")).collect();
assert_eq!(
events,
vec![
UiEvent::Task(TaskEvent::Aborted {
widget_id: label,
command: TaskCommandKind::SetChecked,
reason: TaskAbortReason::Refused(GuiError::UnsupportedWidget("set_checked")),
}),
UiEvent::Task(TaskEvent::Aborted {
widget_id: doomed,
command: TaskCommandKind::SetText,
reason: TaskAbortReason::WidgetRemoved,
}),
UiEvent::Task(TaskEvent::Finished { task: token.id() }),
]
);
}
#[test]
#[cfg(feature = "async")]
fn overflowing_task_queue_is_reported_and_recovers() {
use crate::async_ui::TaskSendError;
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui
.create(WidgetKind::Label, Some("x"))
.expect("label should be created");
let proxy = ui.task_proxy();
assert_eq!(proxy.capacity(), DEFAULT_TASK_QUEUE_CAPACITY);
for _ in 0..DEFAULT_TASK_QUEUE_CAPACITY {
proxy.set_text(label, "queued").expect("post within bound");
}
assert_eq!(proxy.set_text(label, "overflow"), Err(TaskSendError::Full));
let report = ui.drain_task_commands();
assert_eq!(report.applied, DEFAULT_TASK_QUEUE_CAPACITY);
assert_eq!(report.rejected, 0);
proxy
.set_text(label, "after drain")
.expect("post after drain");
assert_eq!(ui.drain_task_commands().applied, 1);
}
#[test]
#[cfg(feature = "async")]
fn posts_fail_closed_after_the_ui_is_dropped() {
use crate::async_ui::TaskSendError;
let proxy = {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
ui.create(WidgetKind::Label, None).expect("label");
ui.task_proxy()
};
assert_eq!(
proxy.set_text(WidgetId(1), "late"),
Err(TaskSendError::Closed)
);
}
#[test]
fn set_file_drop_target_updates_spec_and_backend() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("DropWindow")).unwrap();
assert!(!ui.widget(window).unwrap().file_drop_target);
assert!(!ui.backend().created.get(&window).unwrap().file_drop_target);
ui.set_file_drop_target(window, true).unwrap();
assert!(ui.widget(window).unwrap().file_drop_target);
assert!(ui.backend().created.get(&window).unwrap().file_drop_target);
ui.set_file_drop_target(window, false).unwrap();
assert!(!ui.widget(window).unwrap().file_drop_target);
assert!(!ui.backend().created.get(&window).unwrap().file_drop_target);
let err = ui.set_file_drop_target(WidgetId(9999), true).unwrap_err();
assert_eq!(err, GuiError::WidgetNotFound(9999));
}
#[test]
fn set_file_drop_target_refusal_preserves_spec_and_backend_state() {
let backend = CustomMeasuringBackend {
reject_file_drop: true,
..CustomMeasuringBackend::default()
};
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("DropWindow")).unwrap();
assert_eq!(
ui.set_file_drop_target(window, true),
Err(GuiError::UnsupportedCapability("drag_file_drop".to_owned()))
);
assert!(!ui.widget(window).unwrap().file_drop_target);
assert!(!ui.backend().created.get(&window).unwrap().file_drop_target);
ui.backend_mut().reject_file_drop = false;
ui.set_file_drop_target(window, true).unwrap();
assert!(ui.widget(window).unwrap().file_drop_target);
assert!(ui.backend().created.get(&window).unwrap().file_drop_target);
}
#[test]
fn files_dropped_event_dispatches_paths() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("Main")).unwrap();
let mut seen = Vec::new();
let paths = vec![
"/home/user/doc.txt".to_string(),
"/home/user/img.png".to_string(),
];
ui.backend_mut().push_event(UiEvent::FilesDropped {
widget_id: window,
paths: paths.clone(),
});
ui.dispatch_events(|event| seen.push(event)).unwrap();
assert_eq!(
seen,
vec![UiEvent::FilesDropped {
widget_id: window,
paths,
}]
);
}
fn assert_acyclic_parentage(ui: &Ui<MockBackend>) {
for (id, spec) in &ui.widgets {
let Some(parent) = spec.parent else {
continue;
};
assert_ne!(parent, *id, "widget {id:?} is its own parent");
assert!(
ui.widgets.contains_key(&parent),
"widget {id:?} points at removed parent {parent:?}"
);
let mut hops = 0usize;
let mut cursor = Some(parent);
while let Some(current) = cursor {
hops += 1;
assert!(
hops <= ui.widgets.len(),
"parent chain from {id:?} does not terminate (cycle)"
);
cursor = ui.widgets.get(¤t).and_then(|spec| spec.parent);
}
}
}
fn assert_children_index_matches_links(ui: &Ui<MockBackend>) {
use std::collections::BTreeMap;
let total: usize = ui.children_index.values().map(Vec::len).sum();
let parented = ui
.widgets
.values()
.filter(|spec| spec.parent.is_some())
.count();
assert_eq!(
total, parented,
"the index must hold exactly one entry per parented widget"
);
let mut from_links: BTreeMap<u64, Vec<u64>> = BTreeMap::new();
for (id, spec) in &ui.widgets {
if let Some(parent) = spec.parent {
from_links.entry(parent.0).or_default().push(id.0);
}
}
for children in from_links.values_mut() {
children.sort_unstable();
}
let mut from_index: BTreeMap<u64, Vec<u64>> = BTreeMap::new();
for (parent, children) in &ui.children_index {
assert!(
!children.is_empty(),
"parent key {parent:?} left in the index with no children"
);
let mut ids = Vec::with_capacity(children.len());
for child in children {
assert!(
ui.widgets.contains_key(child),
"stale {child:?} under {parent:?} in the index"
);
assert_eq!(
ui.widgets.get(child).and_then(|spec| spec.parent),
Some(*parent),
"index edge {parent:?} -> {child:?} contradicts the parent link"
);
ids.push(child.0);
}
ids.sort_unstable();
ids.dedup();
assert_eq!(
ids.len(),
children.len(),
"duplicate child entries under {parent:?}"
);
from_index.insert(parent.0, ids);
}
assert_eq!(
from_index, from_links,
"children_index disagrees with the parent-link view"
);
}
fn assert_mock_mirror_is_exact(ui: &Ui<MockBackend>) {
assert_eq!(
ui.widgets.len(),
ui.backend().created.len(),
"shared and native widget sets diverged"
);
for (id, spec) in &ui.widgets {
let native = ui
.backend()
.created
.get(id)
.unwrap_or_else(|| panic!("no native record for {id:?}"));
assert_eq!(
spec, native,
"shared spec and native record differ for {id:?}"
);
}
}
#[test]
fn attach_and_reparent_reject_self_and_cycles_without_mutation() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("Root")).unwrap();
let container = ui.create(WidgetKind::Container, None).unwrap();
let label = ui.create(WidgetKind::Label, Some("Leaf")).unwrap();
ui.attach(window, container).unwrap();
ui.attach(container, label).unwrap();
assert_mock_mirror_is_exact(&ui);
assert!(ui.attach(window, window).is_err(), "self-attach refused");
assert!(
ui.reparent(window, window).is_err(),
"self-reparent refused"
);
assert!(
ui.attach(label, container).is_err(),
"upward attach refused"
);
assert!(
ui.attach(container, window).is_err(),
"upward attach refused"
);
assert!(
ui.reparent(window, label).is_err(),
"cycle reparent refused"
);
assert_eq!(ui.widget(window).unwrap().parent, None);
assert_eq!(ui.widget(container).unwrap().parent, Some(window));
assert_eq!(ui.widget(label).unwrap().parent, Some(container));
assert_eq!(
ui.attach(WidgetId(9001), label),
Err(GuiError::WidgetNotFound(9001))
);
assert_eq!(
ui.attach(window, WidgetId(9001)),
Err(GuiError::WidgetNotFound(9001))
);
let other = ui.create(WidgetKind::Container, None).unwrap();
ui.attach(window, other).unwrap();
ui.reparent(label, other).expect("legal reparent");
assert_eq!(ui.widget(label).unwrap().parent, Some(other));
assert_acyclic_parentage(&ui);
assert_mock_mirror_is_exact(&ui);
}
#[test]
fn remove_cascades_the_subtree_and_never_reuses_ids() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("Root")).unwrap();
let left = ui.create(WidgetKind::Container, None).unwrap();
let right = ui.create(WidgetKind::Container, None).unwrap();
let leaf_a = ui.create(WidgetKind::Label, Some("A")).unwrap();
let leaf_b = ui.create(WidgetKind::Label, Some("B")).unwrap();
let leaf_c = ui.create(WidgetKind::Label, Some("C")).unwrap();
ui.attach(window, left).unwrap();
ui.attach(window, right).unwrap();
ui.attach(left, leaf_a).unwrap();
ui.attach(left, leaf_b).unwrap();
ui.attach(right, leaf_c).unwrap();
ui.show(left).unwrap();
ui.remove(left).expect("cascade removal");
for gone in [left, leaf_a, leaf_b] {
assert!(ui.widget(gone).is_none(), "{gone:?} must be removed");
assert!(
!ui.backend().created.contains_key(&gone),
"{gone:?} must leave the native record"
);
assert_eq!(ui.remove(gone), Err(GuiError::WidgetNotFound(gone.0)));
}
for survivor in [window, right, leaf_c] {
assert!(ui.widget(survivor).is_some(), "{survivor:?} must survive");
}
assert_eq!(ui.widget_count(), 3);
assert!(!ui.backend().shown.contains(&left), "show record cleaned");
let next = ui.create(WidgetKind::Label, Some("D")).unwrap();
assert!(
next.0 > leaf_c.0,
"new ids must be monotonic ({next:?} after {leaf_c:?})"
);
for old in [left, leaf_a, leaf_b] {
assert_ne!(next, old, "removed id {old:?} was reused");
}
assert_acyclic_parentage(&ui);
assert_mock_mirror_is_exact(&ui);
assert_children_index_matches_links(&ui);
}
#[test]
fn children_index_tracks_attach_reparent_and_remove() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("Root")).unwrap();
let left = ui.create(WidgetKind::Container, None).unwrap();
let right = ui.create(WidgetKind::Container, None).unwrap();
let branch = ui.create(WidgetKind::Container, None).unwrap();
let leaf = ui.create(WidgetKind::Label, Some("Leaf")).unwrap();
ui.attach(window, left).unwrap();
ui.attach(window, right).unwrap();
ui.attach(left, branch).unwrap();
ui.attach(branch, leaf).unwrap();
assert_children_index_matches_links(&ui);
ui.attach(left, branch).unwrap();
assert_children_index_matches_links(&ui);
assert_eq!(ui.children_index.get(&left), Some(&vec![branch]));
ui.reparent(branch, right).unwrap();
assert_children_index_matches_links(&ui);
assert_eq!(
ui.children_index.get(&left),
None,
"the old parent's empty key must be dropped"
);
ui.remove(left).expect("left has no children left");
assert!(ui.widget(branch).is_some(), "moved branch survives");
assert!(ui.widget(leaf).is_some(), "moved leaf survives");
assert_children_index_matches_links(&ui);
ui.remove(right).expect("cascade through the new parent");
for gone in [branch, leaf, right] {
assert!(ui.widget(gone).is_none(), "{gone:?} must be removed");
assert!(
!ui.backend().created.contains_key(&gone),
"{gone:?} must leave the native record"
);
}
assert!(ui.widget(window).is_some(), "the window survives");
assert_children_index_matches_links(&ui);
assert_acyclic_parentage(&ui);
assert_mock_mirror_is_exact(&ui);
}
#[test]
fn create_with_a_configured_parent_joins_the_children_index() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("Root")).unwrap();
let declarative = ui
.create_with(WidgetKind::Label, |spec| {
spec.text = Some("configured".to_owned());
spec.parent = Some(window);
})
.expect("create with a configured parent");
assert_children_index_matches_links(&ui);
assert_eq!(ui.children_index.get(&window), Some(&vec![declarative]));
ui.remove(window)
.expect("cascade through the configured edge");
assert!(ui.widget(declarative).is_none());
assert_eq!(ui.widget_count(), 0);
assert_children_index_matches_links(&ui);
assert_mock_mirror_is_exact(&ui);
}
#[test]
fn teardown_walks_each_node_once_even_at_scale() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let root = ui.create(WidgetKind::Window, Some("Root")).unwrap();
let stem = ui.create(WidgetKind::Container, None).unwrap();
ui.attach(root, stem).unwrap();
let mut cursor = stem;
for _ in 0..100 {
let next = ui.create(WidgetKind::Container, None).unwrap();
ui.attach(cursor, next).unwrap();
cursor = next;
}
for _ in 0..2000 {
let leaf = ui.create(WidgetKind::Label, Some("leaf")).unwrap();
ui.attach(root, leaf).unwrap();
}
assert_children_index_matches_links(&ui);
ui.remove(root).expect("single-pass teardown");
assert_eq!(ui.widget_count(), 0);
assert!(ui.backend().created.is_empty());
assert!(ui.children_index.is_empty(), "index fully drained");
}
#[test]
#[cfg(feature = "widgets-range")]
fn refused_setters_leave_the_spec_and_the_native_record_untouched() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui.create(WidgetKind::Label, Some("text")).unwrap();
let slider = ui.create(WidgetKind::Slider, None).unwrap();
type Refusal = Box<dyn Fn(&mut Ui<MockBackend>) -> GuiResult<()>>;
let cases: Vec<(&str, GuiError, Refusal)> = vec![
(
"set_checked on a Label",
GuiError::UnsupportedWidget("set_checked"),
Box::new(move |ui| ui.set_checked(label, true)),
),
(
"set_value on a Label",
GuiError::UnsupportedWidget("set_value"),
Box::new(move |ui| ui.set_value(label, 7)),
),
(
"set_range with inverted bounds",
GuiError::Backend("Widget range min must be <= max".to_owned()),
Box::new(move |ui| ui.set_range(slider, 10, 0)),
),
(
"set_step with a non-positive step",
GuiError::Backend("Widget step must be positive".to_owned()),
Box::new(move |ui| ui.set_step(slider, 0)),
),
(
"set_size with a zero dimension",
GuiError::Backend("Widget size must be positive".to_owned()),
Box::new(move |ui| ui.set_size(label, 0, 0)),
),
(
"set_text_selection with start > end",
GuiError::Backend("Text selection start must be <= end".to_owned()),
Box::new(move |ui| ui.set_text_selection(label, 3, 1)),
),
(
"set_text on an unknown id",
GuiError::WidgetNotFound(4242),
Box::new(move |ui| ui.set_text(WidgetId(4242), "nope")),
),
(
"set_checked on an unknown id",
GuiError::WidgetNotFound(4242),
Box::new(move |ui| ui.set_checked(WidgetId(4242), true)),
),
(
"focus on an unknown id",
GuiError::WidgetNotFound(4242),
Box::new(move |ui| ui.focus(WidgetId(4242))),
),
(
"remove on an unknown id",
GuiError::WidgetNotFound(4242),
Box::new(move |ui| ui.remove(WidgetId(4242))),
),
(
"attach with an unknown parent",
GuiError::WidgetNotFound(4242),
Box::new(move |ui| ui.attach(WidgetId(4242), label)),
),
];
for (name, expected, call) in cases {
let before_count = ui.widget_count();
let before_label = ui.widget(label).cloned();
let before_slider = ui.widget(slider).cloned();
let before_native_label = ui.backend().created.get(&label).cloned();
let before_native_slider = ui.backend().created.get(&slider).cloned();
let error = call(&mut ui).expect_err(name);
assert_eq!(error, expected, "{name}: typed error");
assert_eq!(ui.widget_count(), before_count, "{name}: widget count");
assert_eq!(
ui.widget(label).cloned(),
before_label,
"{name}: label spec"
);
assert_eq!(
ui.widget(slider).cloned(),
before_slider,
"{name}: slider spec"
);
assert_eq!(
ui.backend().created.get(&label).cloned(),
before_native_label,
"{name}: label native record"
);
assert_eq!(
ui.backend().created.get(&slider).cloned(),
before_native_slider,
"{name}: slider native record"
);
}
assert_acyclic_parentage(&ui);
assert_mock_mirror_is_exact(&ui);
}
#[test]
#[cfg(not(feature = "widgets-range"))]
fn range_setters_return_unsupported_when_range_is_compiled_out() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui.create(WidgetKind::Label, Some("test")).unwrap();
assert_eq!(
ui.set_value(label, 10).unwrap_err(),
GuiError::UnsupportedWidget("set_value")
);
assert_eq!(
ui.set_range(label, 0, 10).unwrap_err(),
GuiError::UnsupportedWidget("set_range")
);
assert_eq!(
ui.set_step(label, 1).unwrap_err(),
GuiError::UnsupportedWidget("set_step")
);
}
#[test]
#[cfg(not(feature = "widgets-choice"))]
fn choice_setters_return_unsupported_when_choice_is_compiled_out() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui.create(WidgetKind::Label, Some("test")).unwrap();
assert_eq!(
ui.set_checked(label, true).unwrap_err(),
GuiError::UnsupportedWidget("set_checked")
);
}
#[test]
#[cfg(not(feature = "widgets-containers"))]
fn containers_setters_return_unsupported_when_containers_is_compiled_out() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui.create(WidgetKind::Label, Some("test")).unwrap();
assert_eq!(
ui.set_tab_items(label, &["Tab 1".to_string()]).unwrap_err(),
GuiError::UnsupportedWidget("set_tab_items")
);
assert_eq!(
ui.set_alert_level(label, AlertLevel::Info).unwrap_err(),
GuiError::UnsupportedWidget("set_alert_level")
);
}
#[test]
#[cfg(not(feature = "widgets-pickers"))]
fn pickers_setters_return_unsupported_when_pickers_is_compiled_out() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui.create(WidgetKind::Label, Some("test")).unwrap();
assert_eq!(
ui.set_date_value(label, "2026-09-07").unwrap_err(),
GuiError::UnsupportedWidget("set_date_value")
);
assert_eq!(
ui.set_file_chooser_mode(label, FileChooserMode::PickFolder)
.unwrap_err(),
GuiError::UnsupportedWidget("set_file_chooser_mode")
);
assert_eq!(
ui.set_color_dialog_data(label, ColorDialogData::default())
.unwrap_err(),
GuiError::UnsupportedWidget("set_color_dialog_data")
);
assert_eq!(
ui.set_font_dialog_data(
label,
FontDialogData::new(FontDescriptor::new("Inter", 12.0))
)
.unwrap_err(),
GuiError::UnsupportedWidget("set_font_dialog_data")
);
assert_eq!(
ui.set_calendar_selected_dates(label, &[]).unwrap_err(),
GuiError::UnsupportedWidget("set_calendar_selected_dates")
);
assert_eq!(
ui.set_calendar_bounds(label, None, None).unwrap_err(),
GuiError::UnsupportedWidget("set_calendar_bounds")
);
assert_eq!(
ui.set_calendar_first_day_of_week(label, CalendarFirstDayOfWeek::Monday)
.unwrap_err(),
GuiError::UnsupportedWidget("set_calendar_first_day_of_week")
);
assert_eq!(
ui.set_calendar_selection_mode(label, CalendarSelectionMode::Single)
.unwrap_err(),
GuiError::UnsupportedWidget("set_calendar_selection_mode")
);
}
#[test]
#[cfg(not(feature = "widgets-text"))]
fn text_setters_return_unsupported_when_text_is_compiled_out() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui.create(WidgetKind::Label, Some("test")).unwrap();
assert_eq!(
ui.set_link_url(label, "https://example.com").unwrap_err(),
GuiError::UnsupportedWidget("set_link_url")
);
assert_eq!(
ui.set_placeholder_text(label, "placeholder").unwrap_err(),
GuiError::UnsupportedWidget("set_placeholder_text")
);
assert_eq!(
ui.set_text_selection(label, 0, 5).unwrap_err(),
GuiError::UnsupportedWidget("set_text_selection")
);
assert_eq!(
ui.set_text_completion_items(label, &["one".to_string()])
.unwrap_err(),
GuiError::UnsupportedWidget("set_text_completion_items")
);
assert_eq!(
ui.set_spell_check(label, true).unwrap_err(),
GuiError::UnsupportedWidget("set_spell_check")
);
assert_eq!(
ui.set_rich_text_runs(label, &[]).unwrap_err(),
GuiError::UnsupportedWidget("set_rich_text_runs")
);
assert_eq!(
ui.set_rich_text_images(label, &[]).unwrap_err(),
GuiError::UnsupportedWidget("set_rich_text_images")
);
}
#[test]
#[cfg(feature = "async")]
fn concurrent_task_posts_are_applied_exactly_once_and_in_order() {
use crate::async_ui::TaskSendError;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let label = ui.create(WidgetKind::Label, Some("idle")).unwrap();
let proxy = ui.task_proxy();
const TOTAL: usize = 512;
let posted = Arc::new(AtomicUsize::new(0));
let worker_proxy = proxy.clone();
let worker_posted = Arc::clone(&posted);
let worker = thread::spawn(move || {
for index in 0..TOTAL {
let text = format!("tick-{index}");
loop {
match worker_proxy.set_text(label, text.clone()) {
Ok(()) => break,
Err(TaskSendError::Full) => thread::yield_now(),
Err(TaskSendError::Closed) => panic!("channel closed early"),
}
}
worker_posted.fetch_add(1, Ordering::SeqCst);
}
});
let mut applied = 0usize;
while applied < TOTAL {
let report = ui.drain_task_commands();
assert_eq!(report.rejected, 0, "every command targets a live label");
applied += report.applied;
thread::yield_now();
}
worker.join().expect("worker thread");
assert_eq!(posted.load(Ordering::SeqCst), TOTAL);
assert_eq!(applied, TOTAL, "exactly-once delivery");
assert_eq!(ui.drain_task_commands().total(), 0, "queue drained");
assert_eq!(
ui.widget(label).and_then(|spec| spec.text.clone()),
Some(format!("tick-{}", TOTAL - 1)),
"single producer is FIFO, so the last post wins"
);
assert_acyclic_parentage(&ui);
assert_mock_mirror_is_exact(&ui);
}
#[test]
#[cfg(feature = "async")]
fn lifecycle_tokens_survive_a_saturated_task_queue() {
use crate::async_ui::{TaskId, TaskSendError};
use std::sync::mpsc::channel;
use std::time::{Duration, Instant};
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let proxy = ui.task_proxy();
let capacity = proxy.capacity();
const TASKS: usize = 500;
const SAMPLES_PER_TASK: usize = 3;
let (saturated_tx, saturated_rx) = channel();
let worker_proxy = proxy.clone();
let worker = std::thread::spawn(move || {
let filler = worker_proxy.start_task();
for index in 0..capacity {
worker_proxy
.progress(&filler, index as f64)
.expect("filling within capacity");
}
assert_eq!(
worker_proxy.progress(&filler, f64::MAX),
Err(TaskSendError::Full),
"the queue must be saturated here"
);
saturated_tx.send(()).expect("signal saturation");
worker_proxy
.finish_lossless(&filler, Duration::from_secs(10))
.expect("the filler task completes losslessly too");
let mut dropped_samples = 0usize;
for _ in 0..TASKS {
let token = worker_proxy.start_task();
for _ in 0..SAMPLES_PER_TASK {
if worker_proxy.progress(&token, 1.0).is_err() {
dropped_samples += 1;
}
}
worker_proxy
.finish_lossless(&token, Duration::from_secs(10))
.expect("lifecycle token must survive queue saturation");
}
dropped_samples
});
saturated_rx.recv().expect("worker saturated the queue");
let deadline = Instant::now() + Duration::from_secs(20);
let mut finished = Vec::new();
while finished.len() < TASKS + 1 {
while let Some(event) = ui.poll_event().expect("poll") {
if let UiEvent::Task(TaskEvent::Finished { task }) = event {
finished.push(task);
}
}
assert!(
Instant::now() < deadline,
"only {} of {} completion tokens arrived before the deadline",
finished.len(),
TASKS + 1
);
std::thread::yield_now();
}
let _dropped_samples = worker.join().expect("worker thread");
let expected: Vec<TaskId> = (1..=TASKS as u64 + 1).map(TaskId).collect();
assert_eq!(
finished, expected,
"completion tokens must arrive exactly once, in order"
);
assert_eq!(ui.drain_task_commands().total(), 0, "queue drained");
}
#[test]
#[cfg(feature = "widgets-text")]
fn set_text_completion_items_records_on_text_inputs_only() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let input = ui.create(WidgetKind::TextInput, Some("alp")).unwrap();
let area = ui.create(WidgetKind::TextArea, Some("alp")).unwrap();
let label = ui.create(WidgetKind::Label, Some("plain")).unwrap();
ui.set_text_completion_items(input, &["alpha".to_owned()])
.expect("TextInput accepts completion items");
assert_eq!(
ui.widget(input).unwrap().completion_items,
vec!["alpha".to_owned()]
);
assert_eq!(
ui.backend().created.get(&input).unwrap().completion_items,
vec!["alpha".to_owned()],
"the shared spec and the Mock record agree"
);
for widget in [area, label] {
let before = ui.widget(widget).cloned();
let error = ui
.set_text_completion_items(widget, &["nope".to_owned()])
.expect_err("completion is TextInput-only");
assert_eq!(
error,
GuiError::UnsupportedWidget("set_text_completion_items")
);
assert_eq!(ui.widget(widget).cloned(), before);
assert!(ui.widget(widget).unwrap().completion_items.is_empty());
}
}
#[test]
fn hidden_widget_in_container_does_not_take_layout_space_and_has_zero_dimension() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let column = ui
.create(WidgetKind::Container, Some("col"))
.expect("column");
ui.set_container_direction(column, ContainerDirection::Vertical)
.expect("vertical");
let item1 = ui.create(WidgetKind::Label, Some("item1")).expect("item1");
ui.set_size(item1, 200, 30).expect("item1 size");
#[cfg(feature = "widgets-pickers")]
let chooser = ui
.create(WidgetKind::FileChooserDialog, Some("hidden_chooser"))
.expect("chooser");
#[cfg(not(feature = "widgets-pickers"))]
let chooser = ui
.create(WidgetKind::Button, Some("hidden_chooser"))
.expect("chooser");
ui.set_size(chooser, 200, 40).expect("chooser size");
let item2 = ui.create(WidgetKind::Label, Some("item2")).expect("item2");
ui.set_size(item2, 200, 30).expect("item2 size");
ui.attach(window, column).expect("attach column");
ui.attach(column, item1).expect("attach item1");
ui.attach(column, chooser).expect("attach chooser");
ui.attach(column, item2).expect("attach item2");
ui.hide(chooser).expect("hide chooser");
assert!(!ui.is_visible(chooser));
assert!(ui.is_visible(item1));
assert!(ui.is_visible(item2));
ui.compute_layout(window, 400.0, 300.0)
.expect("layout pass");
assert_eq!(
ui.widget(chooser).and_then(|spec| spec.size),
Some((0, 0)),
"hidden widget must report zero dimension in computed size"
);
let chooser_node = *ui.layout_nodes.get(&chooser).expect("layout node");
let chooser_layout = ui.layout_tree.layout(chooser_node).expect("layout");
assert_eq!(chooser_layout.width, 0.0);
assert_eq!(chooser_layout.height, 0.0);
let item1_y = ui
.widget(item1)
.and_then(|spec| spec.position)
.map(|pos| pos.1)
.unwrap_or(0);
let item2_y = ui
.widget(item2)
.and_then(|spec| spec.position)
.map(|pos| pos.1)
.unwrap_or(0);
assert_eq!(item1_y, 0);
assert_eq!(
item2_y, 30,
"item2 must follow immediately after item1 without space taken by hidden chooser"
);
ui.show(chooser).expect("show chooser");
assert!(ui.is_visible(chooser));
ui.compute_layout(window, 400.0, 300.0)
.expect("layout pass");
assert_eq!(
ui.widget(chooser).and_then(|spec| spec.size),
Some((200, 40)),
"visible chooser restores its size"
);
let item2_y_after = ui
.widget(item2)
.and_then(|spec| spec.position)
.map(|pos| pos.1)
.unwrap_or(0);
assert_eq!(
item2_y_after, 70,
"item2 must now be placed after item1 (30) + chooser (40)"
);
}
#[test]
fn warm_layout_pass_restores_flow_geometry_after_set_position() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let column = ui.create(WidgetKind::Container, None).expect("column");
ui.set_container_direction(column, ContainerDirection::Vertical)
.expect("vertical");
ui.attach(window, column).expect("column");
let label = ui.create(WidgetKind::Label, Some("row")).expect("label");
ui.attach(column, label).expect("label");
ui.compute_layout(window, 640.0, 480.0).expect("cold pass");
let computed = ui.widget(label).and_then(|spec| spec.position);
ui.set_position(label, 123, 45)
.expect("imperative position");
assert_eq!(
ui.widget(label).and_then(|spec| spec.position),
Some((123, 45))
);
ui.compute_layout(window, 640.0, 480.0).expect("warm pass");
assert_eq!(
ui.widget(label).and_then(|spec| spec.position),
computed,
"a layout pass restores computed flow geometry"
);
}
type ColumnRects = (Vec<(i32, i32)>, Vec<(i32, i32)>);
fn compressed_column(floor: Option<(i32, i32)>) -> ColumnRects {
let mut ui = Ui::new(CustomMeasuringBackend {
inner: MockBackend::with_natural_sizes(),
compressed_floor: floor,
..CustomMeasuringBackend::default()
});
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let column = ui.create(WidgetKind::Container, None).expect("column");
ui.set_container_direction(column, ContainerDirection::Vertical)
.expect("column direction");
ui.attach(window, column).expect("attach column");
let mut labels = Vec::new();
for index in 0..8 {
let label = ui
.create(WidgetKind::Label, Some(&format!("Row {index}")))
.expect("label");
ui.attach(column, label).expect("attach label");
labels.push(label);
}
let row = ui.create(WidgetKind::Container, None).expect("row");
ui.set_container_direction(row, ContainerDirection::Horizontal)
.expect("row direction");
ui.attach(column, row).expect("attach row");
let mut buttons = Vec::new();
for text in ["New", "Save", "Undo", "Redo", "Clear"] {
let button = ui.create(WidgetKind::Button, Some(text)).expect("button");
ui.attach(row, button).expect("attach button");
buttons.push(button);
}
ui.compute_layout(window, 120.0, 64.0).expect("layout");
let rows = labels
.iter()
.map(|id| {
let spec = ui.widget(*id).expect("label spec");
(
spec.position.unwrap_or((0, 0)).1,
spec.size.unwrap_or((0, 0)).1,
)
})
.collect();
let cols = buttons
.iter()
.map(|id| {
let spec = ui.widget(*id).expect("button spec");
(
spec.position.unwrap_or((0, 0)).0,
spec.size.unwrap_or((0, 0)).0,
)
})
.collect();
(rows, cols)
}
#[test]
fn compression_floor_keeps_quantized_leaves_from_overlapping() {
let (rows, _) = compressed_column(None);
assert!(
rows.iter().any(|(_, h)| *h < 16),
"default lanes still compress: {rows:?}"
);
let (rows, cols) = compressed_column(Some((40, 16)));
let mut bottom = i32::MIN;
for (y, h) in &rows {
assert!(*h >= 16, "leaf compressed below the floor: {rows:?}");
assert!(*y >= bottom, "siblings overlap: {rows:?}");
bottom = y + h;
}
let mut right = i32::MIN;
for (x, w) in &cols {
assert!(*w >= 40, "row leaf compressed below the floor: {cols:?}");
assert!(*x >= right, "row siblings overlap: {cols:?}");
right = x + w;
}
}
#[test]
fn creation_time_parent_attaches_through_the_backend() {
let mut ui = Ui::new(CustomMeasuringBackend::default());
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let child = ui
.create_with(WidgetKind::Label, |spec| {
spec.text = Some("child".to_owned());
spec.parent = Some(window);
})
.expect("create with parent");
assert_eq!(ui.backend().add_child_calls, 1);
assert_eq!(ui.widget(child).and_then(|spec| spec.parent), Some(window));
assert_eq!(
ui.children_index.get(&window),
Some(&vec![child]),
"exactly one edge is recorded"
);
assert_eq!(ui.layout_nodes.len(), ui.widget_count());
}
#[test]
fn creation_time_parent_must_exist_before_any_widget_is_created() {
let mut ui = Ui::new(CustomMeasuringBackend::default());
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let before = ui.widget_count();
let error = ui
.create_with(WidgetKind::Label, |spec| {
spec.parent = Some(WidgetId(999));
})
.expect_err("a missing parent is refused like attach does");
assert_eq!(error, GuiError::WidgetNotFound(999));
assert_eq!(ui.widget_count(), before, "no orphan widget is created");
assert_eq!(ui.layout_nodes.len(), before, "no orphan layout node");
assert!(
!ui.children_index.contains_key(&WidgetId(999)),
"a refused creation records no edge"
);
assert_eq!(
ui.backend().created.len(),
before,
"nothing reached the lane"
);
let child = ui
.create_with(WidgetKind::Label, |spec| spec.parent = Some(window))
.expect("valid creation-time parent");
assert_eq!(ui.widget(child).and_then(|spec| spec.parent), Some(window));
}
#[test]
fn refused_creation_time_attachment_rolls_the_widget_back() {
let backend = CustomMeasuringBackend {
reject_add_child: true,
..CustomMeasuringBackend::default()
};
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let before = ui.widget_count();
let error = ui
.create_with(WidgetKind::Label, |spec| spec.parent = Some(window))
.expect_err("the lane refuses the attachment");
assert!(matches!(error, GuiError::Backend(_)));
assert_eq!(ui.widget_count(), before, "the widget is rolled back");
assert_eq!(ui.layout_nodes.len(), before);
assert_eq!(
ui.backend().created.len(),
before,
"the refused native widget is removed"
);
assert!(!ui.children_index.contains_key(&window) || ui.children_index[&window].is_empty());
}
#[test]
fn refused_attach_and_reparent_leave_the_previous_edge_in_place() {
let backend = CustomMeasuringBackend {
reject_add_child: true,
..CustomMeasuringBackend::default()
};
let mut ui = Ui::new(backend);
ui.backend_mut().reject_add_child = false;
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let first = ui
.create(WidgetKind::Container, Some("first"))
.expect("first");
let second = ui
.create(WidgetKind::Container, Some("second"))
.expect("second");
let child = ui.create(WidgetKind::Label, Some("child")).expect("child");
ui.attach(window, first).expect("window -> first");
ui.attach(window, second).expect("window -> second");
ui.backend_mut().reject_add_child = true;
let error = ui.attach(first, child).expect_err("attach is refused");
assert!(matches!(error, GuiError::Backend(_)));
assert_eq!(
ui.widget(child).and_then(|spec| spec.parent),
None,
"a refused attach must not claim a parent"
);
assert!(
!ui.children_index
.get(&first)
.is_some_and(|children| children.contains(&child)),
"a refused attach must not record an index edge"
);
ui.backend_mut().reject_add_child = false;
ui.attach(second, child).expect("seed the old edge");
ui.backend_mut().reject_add_child = true;
let error = ui.reparent(child, first).expect_err("reparent is refused");
assert!(matches!(error, GuiError::Backend(_)));
assert_eq!(
ui.widget(child).and_then(|spec| spec.parent),
Some(second),
"the previous parent edge survives a refused reparent"
);
assert!(ui.children_index[&second].contains(&child));
assert!(!ui
.children_index
.get(&first)
.is_some_and(|children| children.contains(&child)));
}
#[test]
fn refused_row_writes_leave_the_spec_rows_untouched() {
let backend = CustomMeasuringBackend {
reject_row_writes: true,
..CustomMeasuringBackend::default()
};
let mut ui = Ui::new(backend);
let list = ui.create(WidgetKind::DataList, Some("list")).expect("list");
ui.set_data_list_items(list, &["seed".to_owned()])
.expect_err("the lane refuses row writes");
assert!(
ui.widget(list).expect("spec").data_list_items.is_empty(),
"a refused list write stores nothing"
);
let grid = ui.create(WidgetKind::DataGrid, None).expect("grid");
let error = ui
.set_data_grid_rows(grid, &[vec!["a".to_owned()]])
.expect_err("the lane refuses grid rows");
assert!(matches!(error, GuiError::Backend(_)));
assert!(
ui.widget(grid).expect("spec").data_grid_rows.is_empty(),
"a refused grid write stores nothing"
);
ui.backend_mut().reject_row_writes = false;
ui.set_data_list_items(list, &["seed".to_owned()])
.expect("accepted");
assert_eq!(
ui.widget(list).expect("spec").data_list_items,
vec!["seed".to_owned()]
);
}
#[test]
fn refused_keyed_row_writes_leave_spec_selection_and_baseline_untouched() {
let backend = CustomMeasuringBackend {
reject_row_writes: false,
..CustomMeasuringBackend::default()
};
let mut ui = Ui::new(backend);
let list = ui.create(WidgetKind::DataList, Some("list")).expect("list");
let initial_rows = vec![RowSet::new(1, &["row1"]), RowSet::new(2, &["row2"])];
ui.set_rows_keyed(list, &initial_rows).expect("initial set");
ui.set_selected_index(list, 0).expect("select first");
assert_eq!(ui.widget(list).expect("spec").selected_index, Some(0));
assert_eq!(ui.selected_row_key(list), Some(RowKey(1)));
ui.backend_mut().reject_row_writes = true;
let new_rows = vec![RowSet::new(2, &["row2_updated"]), RowSet::new(3, &["row3"])];
let err = ui
.set_rows_keyed(list, &new_rows)
.expect_err("refused row write");
assert!(matches!(err, GuiError::Backend(_)));
assert_eq!(
ui.widget(list).expect("spec").selected_index,
Some(0),
"selection index remains intact"
);
assert_eq!(
ui.selected_row_key(list),
Some(RowKey(1)),
"selected row key remains intact"
);
assert_eq!(
ui.widget(list).expect("spec").data_list_items,
vec!["row1".to_string(), "row2".to_string()],
"data_list_items remains untouched"
);
}
#[test]
fn remove_drops_window_callbacks_and_theme_overrides() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
ui.on_window_close(window, || {}).expect("close callback");
ui.on_window_resize(window, |_, _| {})
.expect("resize callback");
let _ = ui.set_theme_override(window, ThemeOverride::Padding(4));
ui.remove(window).expect("remove");
assert!(!ui.on_window_close.contains_key(&window));
assert!(!ui.on_window_resize.contains_key(&window));
assert!(!ui.theme_overrides.contains_key(&window));
assert!(ui.widgets.is_empty());
}
#[test]
fn unchanged_window_layout_pass_reuses_the_cached_root() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let column = ui.create(WidgetKind::Container, None).expect("column");
ui.set_container_direction(column, ContainerDirection::Vertical)
.expect("vertical");
ui.attach(window, column).expect("attach column");
for _ in 0..8 {
let label = ui.create(WidgetKind::Label, Some("row")).expect("label");
ui.attach(column, label).expect("attach label");
}
ui.compute_layout(window, 640.0, 480.0)
.expect("initial pass");
let hits = ui.layout_tree.metrics().cache_hits;
let misses = ui.layout_tree.metrics().cache_misses;
let solves = ui.layout_tree.metrics().solves;
let style_updates = ui.layout_tree.metrics().style_updates;
let geometry: Vec<Option<(i32, i32)>> =
ui.widgets.values().map(|spec| spec.position).collect();
ui.compute_layout(window, 640.0, 480.0)
.expect("second pass");
let metrics = ui.layout_tree.metrics();
assert_eq!(metrics.cache_hits, hits + 1, "the second pass is a hit");
assert_eq!(metrics.cache_misses, misses, "no solve on the second pass");
assert_eq!(metrics.solves, solves + 1);
assert_eq!(
metrics.style_updates, style_updates,
"an unchanged pass must not rewrite layout styles"
);
let geometry_after: Vec<Option<(i32, i32)>> =
ui.widgets.values().map(|spec| spec.position).collect();
assert_eq!(geometry_after, geometry, "cached geometry is unchanged");
ui.compute_layout(window, 641.0, 480.0)
.expect("resize pass");
assert_eq!(
ui.layout_tree.metrics().cache_misses,
misses + 1,
"a size change is a cache miss"
);
}
#[test]
#[cfg(feature = "widgets-containers")]
fn empty_or_childless_tabs_preserves_minimum_height_in_compute_layout() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let column = ui
.create(WidgetKind::Container, Some("col"))
.expect("column");
ui.set_container_direction(column, ContainerDirection::Vertical)
.expect("vertical");
let tabs = ui.create(WidgetKind::Tabs, None).expect("tabs");
let following = ui.create(WidgetKind::Label, Some("below")).expect("label");
ui.set_size(following, 200, 20).expect("following size");
ui.attach(window, column).expect("attach column");
ui.attach(column, tabs).expect("attach tabs");
ui.attach(column, following).expect("attach following");
ui.compute_layout(window, 500.0, 400.0)
.expect("layout pass");
let tabs_size = ui
.widget(tabs)
.and_then(|spec| spec.size)
.expect("tabs size");
assert!(
tabs_size.1 >= MIN_TABS_HEIGHT as i32,
"childless tabs must preserve minimum height ({}), got {}",
MIN_TABS_HEIGHT,
tabs_size.1
);
let tabs_node = *ui.layout_nodes.get(&tabs).expect("layout node");
let tabs_layout = ui.layout_tree.layout(tabs_node).expect("layout");
assert!(
tabs_layout.height >= MIN_TABS_HEIGHT,
"childless tabs layout height must be >= {}, got {}",
MIN_TABS_HEIGHT,
tabs_layout.height
);
let following_y = ui
.widget(following)
.and_then(|spec| spec.position)
.map(|p| p.1)
.unwrap_or(0);
assert!(
following_y >= MIN_TABS_HEIGHT as i32,
"following widget y offset must be >= tabs minimum height, got {}",
following_y
);
let page1 = ui.create(WidgetKind::Container, None).expect("page1");
let page2 = ui.create(WidgetKind::Container, None).expect("page2");
ui.attach(tabs, page1).expect("attach page1");
ui.attach(tabs, page2).expect("attach page2");
ui.compute_layout(window, 500.0, 400.0)
.expect("layout pass with empty pages");
let tabs_size_pages = ui
.widget(tabs)
.and_then(|spec| spec.size)
.expect("tabs size with pages");
assert!(
tabs_size_pages.1 >= MIN_TABS_HEIGHT as i32,
"tabs with empty container pages must preserve minimum height ({}), got {}",
MIN_TABS_HEIGHT,
tabs_size_pages.1
);
let following_y_pages = ui
.widget(following)
.and_then(|spec| spec.position)
.map(|p| p.1)
.unwrap_or(0);
assert!(
following_y_pages >= MIN_TABS_HEIGHT as i32,
"following widget y offset must remain >= tabs minimum height with empty pages, got {}",
following_y_pages
);
}
#[test]
#[cfg(all(feature = "widgets-containers", feature = "widgets-choice"))]
fn tabs_pages_fill_the_tabs_box_and_keep_their_rows_apart() {
for with_min in [true, false] {
let mut ui = Ui::new(MockBackend::with_natural_sizes());
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let root = ui.create(WidgetKind::Container, None).expect("root");
ui.set_container_direction(root, ContainerDirection::Vertical)
.expect("vertical");
ui.attach(window, root).expect("attach root");
let tabs = ui.create(WidgetKind::Tabs, None).expect("tabs");
ui.attach(root, tabs).expect("attach tabs");
if with_min {
ui.set_min_size(tabs, 600, 300).expect("tabs min");
}
let mut pages = Vec::new();
let mut rows = Vec::new();
for _ in 0..3 {
let page = ui.create(WidgetKind::Container, None).expect("page");
ui.set_container_direction(page, ContainerDirection::Vertical)
.expect("page vertical");
ui.set_container_gap(page, 10).expect("page gap");
ui.attach(tabs, page).expect("attach page");
for text in ["Restore last session", "Check for updates", "Theme"] {
let check = ui
.create(WidgetKind::Checkbox, Some(text))
.expect("checkbox");
ui.attach(page, check).expect("attach checkbox");
rows.push((page, check));
}
pages.push(page);
}
ui.compute_layout(window, 640.0, 480.0).expect("layout");
let (tabs_w, tabs_h) = ui
.widget(tabs)
.and_then(|spec| spec.size)
.expect("tabs size");
let first = ui
.widget(pages[0])
.and_then(|spec| spec.size)
.expect("page size");
for &page in &pages {
let (w, h) = ui
.widget(page)
.and_then(|spec| spec.size)
.expect("page size");
assert_eq!(
(w, h),
first,
"every page gets the same box (min={with_min})"
);
assert_eq!(h, tabs_h, "page fills the Tabs height (min={with_min})");
assert!(
w * 2 > tabs_w && w <= tabs_w,
"page width {w} vs Tabs {tabs_w} (min={with_min})"
);
}
for page in pages {
let mut bottom = 0;
for &(_, check) in rows.iter().filter(|(owner, _)| *owner == page) {
let spec = ui.widget(check).expect("checkbox spec");
let (_, y) = spec.position.expect("checkbox position");
let (_, h) = spec.size.expect("checkbox size");
assert!(h >= 24, "checkbox keeps its natural height, got {h}");
assert!(
y >= bottom,
"checkbox rows overlap: y={y} < previous bottom {bottom}"
);
bottom = y + h;
}
}
}
}
#[derive(Debug, Default)]
struct CustomMeasuringBackend {
inner: MockBackend,
tabs_natural_height: Option<i32>,
compressed_floor: Option<(i32, i32)>,
reject_file_drop: bool,
reject_add_child: bool,
reject_row_writes: bool,
reject_theme: bool,
reject_theme_override: bool,
add_child_calls: usize,
}
impl std::ops::Deref for CustomMeasuringBackend {
type Target = MockBackend;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl std::ops::DerefMut for CustomMeasuringBackend {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl TextMeasure for CustomMeasuringBackend {
fn measure_text(
&self,
widget_id: crate::widgets::WidgetId,
known_dimensions: crate::layout::Size<Option<f32>>,
available_space: crate::layout::Size<crate::layout::AvailableSpace>,
) -> Option<crate::layout::Size<f32>> {
self.inner
.measure_text(widget_id, known_dimensions, available_space)
}
}
impl Backend for CustomMeasuringBackend {
type NativeHandle = <MockBackend as Backend>::NativeHandle;
fn natural_size(&self, widget_id: WidgetId) -> Option<(i32, i32)> {
#[cfg(feature = "widgets-containers")]
if let Some(h) = self.tabs_natural_height {
if self.inner.created.get(&widget_id).map(|s| s.kind) == Some(WidgetKind::Tabs) {
return Some((200, h));
}
}
self.inner.natural_size(widget_id)
}
fn min_compressed_size(&self, _widget_id: WidgetId) -> Option<(i32, i32)> {
self.compressed_floor
}
fn create_widget(&mut self, spec: &WidgetSpec) -> GuiResult<()> {
self.inner.create_widget(spec)
}
fn create_menu(&mut self, menu_id: MenuId) -> GuiResult<()> {
self.inner.create_menu(menu_id)
}
fn add_submenu(
&mut self,
parent_id: MenuId,
submenu_id: MenuId,
slot_id: MenuItemId,
text: &str,
) -> GuiResult<()> {
self.inner.add_submenu(parent_id, submenu_id, slot_id, text)
}
fn create_menu_item(
&mut self,
menu_id: MenuId,
item_id: MenuItemId,
text: &str,
shortcut: Option<&str>,
) -> GuiResult<()> {
self.inner
.create_menu_item(menu_id, item_id, text, shortcut)
}
fn attach_menu_to_window(&mut self, window_id: WidgetId, menu_id: MenuId) -> GuiResult<()> {
self.inner.attach_menu_to_window(window_id, menu_id)
}
fn attach_context_menu(&mut self, widget_id: WidgetId, menu_id: MenuId) -> GuiResult<()> {
self.inner.attach_context_menu(widget_id, menu_id)
}
fn set_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
self.inner.set_text(widget_id, text)
}
fn set_checked(&mut self, widget_id: WidgetId, checked: bool) -> GuiResult<()> {
self.inner.set_checked(widget_id, checked)
}
fn set_value(&mut self, widget_id: WidgetId, value: i32) -> GuiResult<()> {
self.inner.set_value(widget_id, value)
}
fn set_range(&mut self, widget_id: WidgetId, min: i32, max: i32) -> GuiResult<()> {
self.inner.set_range(widget_id, min, max)
}
fn set_step(&mut self, widget_id: WidgetId, step: i32) -> GuiResult<()> {
self.inner.set_step(widget_id, step)
}
fn set_selected_index(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
self.inner.set_selected_index(widget_id, index)
}
fn set_tab_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
self.inner.set_tab_items(widget_id, items)
}
fn set_selected_indices(
&mut self,
widget_id: WidgetId,
indices: &[usize],
) -> GuiResult<()> {
self.inner.set_selected_indices(widget_id, indices)
}
fn set_row_drag(
&mut self,
widget_id: WidgetId,
source: bool,
target: bool,
) -> GuiResult<()> {
self.inner.set_row_drag(widget_id, source, target)
}
fn set_file_drop_target(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
if self.reject_file_drop && enabled {
return Err(GuiError::UnsupportedCapability("drag_file_drop".to_owned()));
}
self.inner.set_file_drop_target(widget_id, enabled)
}
fn set_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
self.inner.set_size(widget_id, width, height)
}
fn set_min_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
self.inner.set_min_size(widget_id, width, height)
}
fn set_data_list_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
if self.reject_row_writes {
return Err(GuiError::Backend("row write refused".to_owned()));
}
self.inner.set_data_list_items(widget_id, items)
}
fn apply_row_delta(
&mut self,
widget_id: WidgetId,
ops: &[crate::widgets::RowOp],
) -> GuiResult<()> {
if self.reject_row_writes {
return Err(GuiError::Backend("row write refused".to_owned()));
}
self.inner.apply_row_delta(widget_id, ops)
}
fn set_data_grid_rows(
&mut self,
widget_id: WidgetId,
rows: Arc<Vec<Vec<String>>>,
) -> GuiResult<()> {
if self.reject_row_writes {
return Err(GuiError::Backend("row write refused".to_owned()));
}
self.inner.set_data_grid_rows(widget_id, rows)
}
fn set_data_grid_model(
&mut self,
widget_id: WidgetId,
model: Box<dyn crate::widgets::DataGridModel>,
) -> GuiResult<()> {
self.inner.set_data_grid_model(widget_id, model)
}
fn set_data_grid_row_height(
&mut self,
widget_id: WidgetId,
row: usize,
height: i32,
) -> GuiResult<()> {
self.inner.set_data_grid_row_height(widget_id, row, height)
}
fn set_data_grid_col_width(
&mut self,
widget_id: WidgetId,
col: usize,
width: i32,
) -> GuiResult<()> {
self.inner.set_data_grid_col_width(widget_id, col, width)
}
fn set_data_grid_frozen_panes(
&mut self,
widget_id: WidgetId,
rows: usize,
cols: usize,
) -> GuiResult<()> {
self.inner.set_data_grid_frozen_panes(widget_id, rows, cols)
}
fn set_data_grid_selection(
&mut self,
widget_id: WidgetId,
selection: &[(usize, usize)],
) -> GuiResult<()> {
self.inner.set_data_grid_selection(widget_id, selection)
}
fn set_tree_items(&mut self, widget_id: WidgetId, items: &[TreeItem]) -> GuiResult<()> {
self.inner.set_tree_items(widget_id, items)
}
fn set_position(&mut self, widget_id: WidgetId, x: i32, y: i32) -> GuiResult<()> {
self.inner.set_position(widget_id, x, y)
}
fn set_background_color(&mut self, widget_id: WidgetId, color: Color) -> GuiResult<()> {
self.inner.set_background_color(widget_id, color)
}
fn set_alert_level(&mut self, widget_id: WidgetId, level: AlertLevel) -> GuiResult<()> {
self.inner.set_alert_level(widget_id, level)
}
fn set_image_source(&mut self, widget_id: WidgetId, source: &str) -> GuiResult<()> {
self.inner.set_image_source(widget_id, source)
}
fn set_date_value(&mut self, widget_id: WidgetId, iso_date: &str) -> GuiResult<()> {
self.inner.set_date_value(widget_id, iso_date)
}
fn set_link_url(&mut self, widget_id: WidgetId, url: &str) -> GuiResult<()> {
self.inner.set_link_url(widget_id, url)
}
fn set_container_direction(
&mut self,
widget_id: WidgetId,
direction: ContainerDirection,
) -> GuiResult<()> {
self.inner.set_container_direction(widget_id, direction)
}
fn set_container_scroll(
&mut self,
widget_id: WidgetId,
vertical: bool,
horizontal: bool,
) -> GuiResult<()> {
self.inner
.set_container_scroll(widget_id, vertical, horizontal)
}
fn set_container_gap(&mut self, widget_id: WidgetId, gap: i32) -> GuiResult<()> {
self.inner.set_container_gap(widget_id, gap)
}
fn set_container_padding(&mut self, widget_id: WidgetId, padding: i32) -> GuiResult<()> {
self.inner.set_container_padding(widget_id, padding)
}
fn draw_demo_cube(&mut self, widget_id: WidgetId) -> GuiResult<()> {
self.inner.draw_demo_cube(widget_id)
}
fn create_gpu_fallback(
&mut self,
spec: &WidgetSpec,
policy: GpuDegradationPolicy,
) -> GuiResult<()> {
self.inner.create_gpu_fallback(spec, policy)
}
fn gpu_surface_capabilities(&self) -> GpuSurfaceCapabilities {
self.inner.gpu_surface_capabilities()
}
fn set_canvas_scene(
&mut self,
widget_id: WidgetId,
scene: &crate::CanvasScene,
) -> GuiResult<()> {
self.inner.set_canvas_scene(widget_id, scene)
}
fn native_handle(&self, widget_id: WidgetId) -> GuiResult<Self::NativeHandle> {
self.inner.native_handle(widget_id)
}
fn metal_canvas_handle(&self, widget_id: WidgetId) -> GuiResult<MetalCanvasHandle> {
self.inner.metal_canvas_handle(widget_id)
}
fn add_child(&mut self, parent: WidgetId, child: WidgetId) -> GuiResult<()> {
self.add_child_calls += 1;
if self.reject_add_child {
return Err(GuiError::Backend("attach refused".to_owned()));
}
self.inner.add_child(parent, child)
}
fn show(&mut self, widget_id: WidgetId) -> GuiResult<()> {
self.inner.show(widget_id)
}
fn hide(&mut self, widget_id: WidgetId) -> GuiResult<()> {
self.inner.hide(widget_id)
}
fn remove(&mut self, widget_id: WidgetId) -> GuiResult<()> {
self.inner.remove(widget_id)
}
fn set_enabled(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
self.inner.set_enabled(widget_id, enabled)
}
fn activate(&mut self, widget_id: WidgetId) -> GuiResult<()> {
self.inner.activate(widget_id)
}
fn data_dir(&self) -> GuiResult<PathBuf> {
self.inner.data_dir()
}
fn set_tooltip(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
self.inner.set_tooltip(widget_id, text)
}
fn poll_event(&mut self) -> GuiResult<Option<UiEvent>> {
self.inner.poll_event()
}
fn wait_event(&mut self) -> GuiResult<UiEvent> {
self.inner.wait_event()
}
fn show_confirm_dialog(&mut self, token: u64, title: &str, message: &str) -> GuiResult<()> {
self.inner.show_confirm_dialog(token, title, message)
}
fn set_theme(&mut self, theme: &Theme) -> GuiResult<()> {
if self.reject_theme {
return Err(GuiError::Backend("theme rejected".to_owned()));
}
self.inner.set_theme(theme)
}
fn set_theme_override(
&mut self,
widget_id: WidgetId,
theme_override: ThemeOverride,
) -> GuiResult<()> {
if self.reject_theme_override {
return Err(GuiError::Backend("theme override rejected".to_owned()));
}
self.inner.set_theme_override(widget_id, theme_override)
}
fn clear_theme_overrides(&mut self, widget_id: WidgetId) -> GuiResult<()> {
if self.reject_theme_override {
return Err(GuiError::Backend(
"clear theme override rejected".to_owned(),
));
}
self.inner.clear_theme_overrides(widget_id)
}
}
#[test]
fn tray_default_stubs_return_unsupported_capability() {
let mut ui = Ui::new(CustomMeasuringBackend::default());
assert_eq!(
ui.create_tray_icon("Test"),
Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
);
assert_eq!(
ui.destroy_tray_icon(TrayIconId(1)),
Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
);
assert_eq!(
ui.set_tray_icon_tooltip(TrayIconId(1), "Tip"),
Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
);
assert_eq!(
ui.set_tray_icon_menu(TrayIconId(1), None),
Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
);
assert_eq!(
ui.set_tray_icon_visible(TrayIconId(1), true),
Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
);
assert_eq!(
ui.create_tray_icon_with_icon("Test", vec![1, 2, 3, 4]),
Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
);
assert_eq!(
ui.set_tray_icon_icon(TrayIconId(1), Some(vec![1, 2, 3, 4])),
Err(GuiError::UnsupportedCapability("tray_icon".to_string()))
);
}
#[test]
#[cfg(feature = "widgets-containers")]
fn tabs_strip_respects_dynamic_natural_height_from_backend() {
let backend = CustomMeasuringBackend {
inner: MockBackend::default(),
tabs_natural_height: Some(44),
reject_file_drop: false,
..CustomMeasuringBackend::default()
};
let mut ui = Ui::new(backend);
let window = ui.create(WidgetKind::Window, Some("w")).expect("window");
let column = ui
.create(WidgetKind::Container, Some("col"))
.expect("column");
ui.set_container_direction(column, ContainerDirection::Vertical)
.expect("vertical");
let tabs = ui.create(WidgetKind::Tabs, None).expect("tabs");
let following = ui.create(WidgetKind::Label, Some("below")).expect("label");
ui.set_size(following, 200, 20).expect("following size");
ui.attach(window, column).expect("attach column");
ui.attach(column, tabs).expect("attach tabs");
ui.attach(column, following).expect("attach following");
assert_eq!(ui.min_tabs_height(tabs), 44.0);
assert_eq!(ui.tabs_min_height(tabs), 44.0);
ui.compute_layout(window, 500.0, 400.0)
.expect("layout pass");
let tabs_size = ui
.widget(tabs)
.and_then(|spec| spec.size)
.expect("tabs size");
assert!(
tabs_size.1 >= 44,
"tabs with natural height 44px must preserve dynamic floor (got {})",
tabs_size.1
);
let tabs_node = *ui.layout_nodes.get(&tabs).expect("layout node");
let tabs_layout = ui.layout_tree.layout(tabs_node).expect("layout");
assert!(
tabs_layout.height >= 44.0,
"layout height must respect 44.0 floor instead of clamping to 30.0 (got {})",
tabs_layout.height
);
let following_y = ui
.widget(following)
.and_then(|spec| spec.position)
.map(|p| p.1)
.unwrap_or(0);
assert!(
following_y >= 44,
"following widget y offset must be >= 44 (got {})",
following_y
);
let backend36 = CustomMeasuringBackend {
inner: MockBackend::default(),
tabs_natural_height: Some(36),
reject_file_drop: false,
..CustomMeasuringBackend::default()
};
let mut ui36 = Ui::new(backend36);
let window36 = ui36.create(WidgetKind::Window, Some("w")).expect("window");
let column36 = ui36
.create(WidgetKind::Container, Some("col"))
.expect("column");
ui36.set_container_direction(column36, ContainerDirection::Vertical)
.expect("vertical");
let tabs36 = ui36.create(WidgetKind::Tabs, None).expect("tabs");
let page1 = ui36.create(WidgetKind::Container, None).expect("page1");
let page2 = ui36.create(WidgetKind::Container, None).expect("page2");
ui36.attach(tabs36, page1).expect("attach page1");
ui36.attach(tabs36, page2).expect("attach page2");
let following36 = ui36
.create(WidgetKind::Label, Some("below"))
.expect("label");
ui36.set_size(following36, 200, 20).expect("following size");
ui36.attach(window36, column36).expect("attach column");
ui36.attach(column36, tabs36).expect("attach tabs");
ui36.attach(column36, following36)
.expect("attach following");
assert_eq!(ui36.min_tabs_height(tabs36), 36.0);
ui36.compute_layout(window36, 500.0, 400.0)
.expect("layout pass 36");
let tabs36_size = ui36
.widget(tabs36)
.and_then(|spec| spec.size)
.expect("tabs size");
assert!(
tabs36_size.1 >= 36,
"tabs with empty pages and 36px natural height must preserve 36px floor (got {})",
tabs36_size.1
);
let following36_y = ui36
.widget(following36)
.and_then(|spec| spec.position)
.map(|p| p.1)
.unwrap_or(0);
assert!(
following36_y >= 36,
"following widget y offset must be >= 36 (got {})",
following36_y
);
let backend_none = CustomMeasuringBackend {
inner: MockBackend::default(),
tabs_natural_height: None,
reject_file_drop: false,
..CustomMeasuringBackend::default()
};
let ui_none = Ui::new(backend_none);
let tabs_none = WidgetId(42);
assert_eq!(ui_none.min_tabs_height(tabs_none), MIN_TABS_HEIGHT);
let backend_zero = CustomMeasuringBackend {
inner: MockBackend::default(),
tabs_natural_height: Some(0),
reject_file_drop: false,
..CustomMeasuringBackend::default()
};
let ui_zero = Ui::new(backend_zero);
assert_eq!(ui_zero.min_tabs_height(tabs_none), MIN_TABS_HEIGHT);
}
#[test]
fn perf_010_subtree_teardown_scales_linearly_below_3x_ratio() {
let n1 = 1500;
let n2 = 3000;
let mut ui1 = Ui::new(MockBackend::default());
let parent1 = ui1.create(WidgetKind::Container, None).expect("container");
for i in 0..n1 {
let child = ui1
.create_with(WidgetKind::Label, |spec| {
spec.text = Some(format!("c{}", i));
spec.parent = Some(parent1);
})
.expect("child");
let _ = child;
}
let mut ui2 = Ui::new(MockBackend::default());
let parent2 = ui2.create(WidgetKind::Container, None).expect("container");
for i in 0..n2 {
let child = ui2
.create_with(WidgetKind::Label, |spec| {
spec.text = Some(format!("c{}", i));
spec.parent = Some(parent2);
})
.expect("child");
let _ = child;
}
let start1 = std::time::Instant::now();
ui1.remove(parent1).expect("remove parent1");
let dur1 = start1.elapsed().as_nanos().max(1);
let start2 = std::time::Instant::now();
ui2.remove(parent2).expect("remove parent2");
let dur2 = start2.elapsed().as_nanos().max(1);
let ratio = (dur2 as f64) / (dur1 as f64);
let limit = crate::test_budget::teardown_ratio_limit();
assert!(
ratio < limit,
"Teardown ratio for 2N vs N must scale linearly (< {limit}x vs 4x+ quadratic), got {ratio:.2}x (dur1={dur1}ns, dur2={dur2}ns)"
);
assert!(ui1.widgets.is_empty());
assert!(ui2.widgets.is_empty());
}
#[test]
fn perf_014_leaf_attachment_short_circuits_cycle_check_and_detects_genuine_cycle() {
let mut ui = Ui::new(MockBackend::default());
let root = ui.create(WidgetKind::Window, None).expect("window");
let mut current_parent = root;
for _ in 0..100 {
let next = ui.create(WidgetKind::Container, None).expect("container");
ui.attach(current_parent, next)
.expect("attach next to parent");
current_parent = next;
}
let leaf = ui.create(WidgetKind::Label, None).expect("label");
let start = std::time::Instant::now();
ui.attach(current_parent, leaf).expect("attach leaf");
let elapsed = start.elapsed();
let limit = crate::test_budget::duration_budget(std::time::Duration::from_micros(500));
assert!(
elapsed < limit,
"Leaf attach took too long: {elapsed:?} (limit {limit:?})"
);
let cycle_err = ui.attach(current_parent, root);
assert!(cycle_err.is_err(), "Cycle attachment must be rejected");
}
#[test]
fn perf_015_set_text_replaces_without_cloning_and_rolls_back_on_error() {
let mut ui = Ui::new(MockBackend::default());
let label = ui
.create_with(WidgetKind::Label, |spec| {
spec.text = Some("Initial".to_string());
})
.expect("label");
ui.set_text(label, "Updated").expect("set_text");
assert_eq!(ui.widget(label).unwrap().text.as_deref(), Some("Updated"));
let err = ui.set_text(label, "Bad\0String");
assert!(err.is_err());
assert_eq!(ui.widget(label).unwrap().text.as_deref(), Some("Updated"));
}
#[test]
fn bug_007_refusing_backend_preserves_theme_and_overrides() {
let backend = CustomMeasuringBackend {
reject_theme: true,
reject_theme_override: true,
..CustomMeasuringBackend::default()
};
let mut ui = Ui::new(backend);
let button = ui.create(WidgetKind::Button, Some("Test")).expect("button");
assert_eq!(ui.theme_mode(), ThemeMode::Light);
let err = ui.set_theme_mode(ThemeMode::Dark);
assert!(err.is_err(), "refusing backend must error");
assert_eq!(
ui.theme_mode(),
ThemeMode::Light,
"theme must remain Light on error"
);
let override_spec = ThemeOverride::Background(crate::Color::rgb(255, 0, 0));
let err = ui.set_theme_override(button, override_spec);
assert!(
err.is_err(),
"refusing backend must error on theme override"
);
assert!(
ui.theme_overrides(button).is_empty(),
"theme overrides must remain empty when backend rejects"
);
}
#[test]
fn bug_005_max_layout_depth_boundary_test() {
let mut ui = Ui::new(MockBackend::default());
let root = ui.create(WidgetKind::Window, None).unwrap();
let mut current = root;
for _ in 1..crate::layout::box_sizing::MAX_LAYOUT_DEPTH {
let next = ui.create(WidgetKind::Container, None).unwrap();
ui.attach(current, next).expect("depth <= 128 accepted");
current = next;
}
let extra = ui.create(WidgetKind::Container, None).unwrap();
let err = ui.attach(current, extra);
assert!(
err.is_err(),
"attaching beyond MAX_LAYOUT_DEPTH (128) must be refused"
);
match err {
Err(GuiError::Backend(msg)) => {
assert!(msg.contains("maximum layout recursion depth exceeded"));
}
other => panic!("expected GuiError::Backend, got {:?}", other),
}
let extra_create = ui.create_with(WidgetKind::Container, |spec| {
spec.parent = Some(current);
});
assert!(
extra_create.is_err(),
"create_with beyond MAX_LAYOUT_DEPTH must be refused"
);
}
#[test]
#[cfg(feature = "widgets-text")]
fn test_b1453_poll_and_wait_event_mirror_user_text_into_spec() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let input = ui
.create(WidgetKind::TextInput, Some("initial"))
.expect("create input");
assert_eq!(ui.text(input).unwrap(), "initial");
ui.backend_mut().push_event(UiEvent::TextChanged {
widget_id: input,
text: "edited_via_poll".to_string(),
});
let event = ui.poll_event().expect("poll event").expect("event exists");
assert!(matches!(event, UiEvent::TextChanged { .. }));
assert_eq!(
ui.text(input).unwrap(),
"edited_via_poll",
"poll_event must run pre_dispatch to mirror text"
);
assert_eq!(
ui.widget(input).unwrap().text.as_deref(),
Some("edited_via_poll")
);
ui.backend_mut().push_event(UiEvent::TextChanged {
widget_id: input,
text: "edited_via_wait".to_string(),
});
let event = ui.wait_event().expect("wait event");
assert!(matches!(event, UiEvent::TextChanged { .. }));
assert_eq!(
ui.text(input).unwrap(),
"edited_via_wait",
"wait_event must run pre_dispatch to mirror text"
);
}
#[test]
fn test_b1453_poll_event_recomputes_layout_on_window_resized() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, Some("Root"))
.expect("create window");
let btn = ui
.create(WidgetKind::Button, Some("Action"))
.expect("create btn");
ui.attach(window, btn).expect("attach");
if let Some(&node) = ui.layout_nodes.get(&btn) {
let style = crate::layout::Style {
size: crate::layout::Size {
width: crate::layout::Dimension::length(50.0),
height: crate::layout::Dimension::length(25.0),
},
..Default::default()
};
let _ = ui.layout_tree.set_style(node, style);
}
ui.add_layout_root(window).expect("add layout root");
assert_eq!(ui.widget(btn).and_then(|spec| spec.size), None);
ui.backend_mut().push_event(UiEvent::WindowResized {
widget_id: window,
width: 1024,
height: 768,
});
let event = ui.poll_event().expect("poll event").expect("event exists");
assert!(matches!(event, UiEvent::WindowResized { .. }));
assert_eq!(
ui.widget(btn).and_then(|spec| spec.size),
Some((50, 25)),
"poll_event must run pre_dispatch to recompute layout root"
);
}
#[test]
fn test_b1460_secondary_window_show_registers_layout_root_and_preserves_primary() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window1 = ui.create(WidgetKind::Window, Some("Primary")).unwrap();
let btn1 = ui.create(WidgetKind::Button, Some("Btn1")).unwrap();
ui.attach(window1, btn1).unwrap();
ui.set_size(window1, 800, 600).unwrap();
ui.show(window1).unwrap();
assert!(ui.is_layout_root(window1));
let window2 = ui.create(WidgetKind::Window, Some("Secondary")).unwrap();
let btn2 = ui.create(WidgetKind::Button, Some("Btn2")).unwrap();
ui.attach(window2, btn2).unwrap();
ui.set_size(window2, 400, 300).unwrap();
ui.show(window2).unwrap();
assert!(ui.is_layout_root(window2));
assert!(ui.is_layout_root(window1));
assert!(ui.layout_root_sizes.contains_key(&window1));
assert!(ui.layout_root_sizes.contains_key(&window2));
}
#[test]
fn text_changed_updates_spec_text() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let input = ui
.create(WidgetKind::TextInput, None)
.expect("input should be created");
ui.backend_mut().push_event(UiEvent::TextChanged {
widget_id: input,
text: "new text".to_string(),
});
ui.poll_event().expect("poll should succeed");
assert_eq!(
ui.widgets.get(&input).expect("input spec exists").text,
Some("new text".to_string())
);
}
#[test]
fn window_resized_recomputes_layout_on_poll() {
let backend = MockBackend::default();
let mut ui = Ui::new(backend);
let window = ui
.create(WidgetKind::Window, None)
.expect("window should be created");
ui.add_layout_root(window).expect("add layout root");
ui.backend_mut().push_event(UiEvent::WindowResized {
widget_id: window,
width: 800,
height: 600,
});
ui.poll_event().expect("poll should succeed");
assert!(ui.layout_root_sizes.contains_key(&window));
}
}