#![deny(rustdoc::broken_intra_doc_links)]
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration;
#[cfg(feature = "e2e")]
pub mod e2e;
#[cfg(feature = "webview")]
pub mod webview;
use native_gui_core::artprov::IconRole;
use native_gui_core::error::{GuiError, GuiResult};
use native_gui_core::events::AccessibleNotification;
use native_gui_core::pickers::{ColorDialogData, FontDescriptor, FontDialogData, FontEffects};
use native_gui_core::toolbar::{self, ToolId, ToolInteraction, ToolbarItem, ToolbarOrientation};
use native_gui_core::widgets::{DataGridModel, RichTextImage};
use native_gui_core::{
AlertLevel, Backend, CalendarDate, CalendarFirstDayOfWeek, CalendarSelectionMode, Color,
ColumnSpec, ContainerDirection, ContainerWrap, DragCapabilities, DragPayload, DragPayloadKind,
DragSessionId, DragSourceOptions, DragTargetOptions, DropCancelReason, FileChooserMode,
GpuDegradationPolicy, GpuSurfaceCapabilities, ImageData, ImageFit, ImageResourceCapabilities,
ImageResourceId, LabelAlignment, LabelWrap, LoopFlow, MenuId, MenuItemId, MotionCapabilities,
PopupDismissReason, ShowEffect, TextRun, TimerCapabilities, TimerFire, TimerId, TimerSpec,
TimerStopPolicy, TrayIconId, TrayIconSpec, Ui, UiEvent, WidgetId, WidgetKind, WidgetProperty,
WidgetSpec, WindowCapabilities, WindowOptions, WindowRole,
};
pub use native_gui_core::image_resource::{
AnimationData, AnimationFrame, AnimationResourceId, LoopCount,
};
#[derive(Debug, Default, Clone)]
pub struct MockModalFrame {
pub script: VecDeque<UiEvent>,
pub delivered: usize,
}
pub struct RetainedDataGridModel(Box<dyn DataGridModel>);
impl std::fmt::Debug for RetainedDataGridModel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RetainedDataGridModel")
.field("row_count", &self.0.row_count())
.field("col_count", &self.0.col_count())
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MockWindowEffect {
Show {
widget_id: WidgetId,
effect: ShowEffect,
},
Hide {
widget_id: WidgetId,
effect: ShowEffect,
},
}
#[derive(Debug, Clone)]
struct MockDragSession {
id: DragSessionId,
source: WidgetId,
kinds: Vec<DragPayloadKind>,
target: Option<WidgetId>,
}
#[derive(Debug, Clone, Copy)]
struct MockTimer {
spec: TimerSpec,
started_at: Duration,
deadline: Duration,
widget_scope: Option<(WidgetId, TimerStopPolicy)>,
}
#[derive(Debug, Clone, Copy)]
struct TimerDelivery {
deadline: Duration,
fire: TimerFire,
widget_scope: Option<(WidgetId, TimerStopPolicy)>,
}
fn duration_from_nanos(nanos: u128) -> Option<Duration> {
const NANOS_PER_SECOND: u128 = 1_000_000_000;
let seconds = u64::try_from(nanos / NANOS_PER_SECOND).ok()?;
let subsecond_nanos = u32::try_from(nanos % NANOS_PER_SECOND).ok()?;
Some(Duration::new(seconds, subsecond_nanos))
}
#[doc(hidden)]
pub mod windowed_fixture {
use native_gui_core::widgets::{WindowedDataGridHandle, WindowedDelivery};
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, TryRecvError};
use std::sync::Arc;
#[derive(Debug, Default, Clone)]
pub struct RepaintCounter {
count: Arc<AtomicUsize>,
}
impl RepaintCounter {
pub fn new() -> Self {
Self::default()
}
pub fn hook(&self) -> impl Fn() + 'static {
let count = Arc::clone(&self.count);
move || {
count.fetch_add(1, Ordering::SeqCst);
}
}
pub fn count(&self) -> usize {
self.count.load(Ordering::SeqCst)
}
}
pub struct MockRowProducer {
requests: Receiver<usize>,
observed: Vec<usize>,
scripted: HashMap<usize, Vec<String>>,
default_cells: Option<Box<dyn Fn(usize) -> Vec<String>>>,
}
impl MockRowProducer {
pub fn new() -> (Self, impl Fn(usize) + 'static) {
let (sender, requests) = mpsc::channel();
let producer = Self {
requests,
observed: Vec::new(),
scripted: HashMap::new(),
default_cells: None,
};
let hook = move |row: usize| {
let _ = sender.send(row);
};
(producer, hook)
}
pub fn script_row(&mut self, row: usize, cells: Vec<String>) {
self.scripted.insert(row, cells);
}
pub fn set_default_cells(&mut self, generator: impl Fn(usize) -> Vec<String> + 'static) {
self.default_cells = Some(Box::new(generator));
}
pub fn observed_requests(&self) -> &[usize] {
&self.observed
}
pub fn next_request(&mut self) -> Option<usize> {
match self.requests.try_recv() {
Ok(row) => {
self.observed.push(row);
Some(row)
}
Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => None,
}
}
pub fn serve_next(
&mut self,
handle: &WindowedDataGridHandle,
) -> Option<(usize, WindowedDelivery)> {
let row = self.next_request()?;
let cells = self.cells_for(row);
let delivery = handle.deliver_row(row, cells);
Some((row, delivery))
}
pub fn serve_pending(
&mut self,
handle: &WindowedDataGridHandle,
) -> Vec<(usize, WindowedDelivery)> {
let mut served = Vec::new();
while let Some(outcome) = self.serve_next(handle) {
served.push(outcome);
}
served
}
pub fn sender_dropped(&mut self) -> bool {
loop {
match self.requests.try_recv() {
Ok(row) => self.observed.push(row),
Err(TryRecvError::Empty) => return false,
Err(TryRecvError::Disconnected) => return true,
}
}
}
fn cells_for(&self, row: usize) -> Vec<String> {
if let Some(cells) = self.scripted.get(&row) {
return cells.clone();
}
if let Some(generator) = &self.default_cells {
return generator(row);
}
vec![format!("row {row}")]
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MockTrayIconState {
pub id: TrayIconId,
pub tooltip: String,
pub menu: Option<MenuId>,
pub visible: bool,
pub icon_bytes: Option<Vec<u8>>,
}
impl From<&TrayIconSpec> for MockTrayIconState {
fn from(spec: &TrayIconSpec) -> Self {
Self {
id: spec.id,
tooltip: spec.tooltip.clone(),
menu: spec.menu,
visible: spec.visible,
icon_bytes: spec.icon_bytes.clone(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MockAnimationState {
pub resource_id: AnimationResourceId,
pub current_frame: usize,
pub completed_loops: u32,
pub playing: bool,
pub paused: bool,
pub next_deadline: Option<Duration>,
pub remaining_in_frame: Option<Duration>,
pub finished: bool,
}
#[derive(Debug, Default)]
pub struct MockBackend {
pub created: HashMap<WidgetId, WidgetSpec>,
pub size_writes: HashMap<WidgetId, usize>,
pub position_writes: HashMap<WidgetId, usize>,
pub min_sizes: HashMap<WidgetId, (i32, i32)>,
pub natural_size_probes: AtomicUsize,
pub natural_sizes: bool,
pub scroll_anchors: HashMap<WidgetId, usize>,
pub visible_row_counts: HashMap<WidgetId, usize>,
pub scroll_failures: HashMap<WidgetId, GuiError>,
pub scroll_requests: Vec<(WidgetId, usize)>,
pub selection_clears: Vec<WidgetId>,
pub row_writes: HashMap<WidgetId, usize>,
pub applied_row_ops: Vec<(WidgetId, Vec<native_gui_core::widgets::RowOp>)>,
pub shown: Vec<WidgetId>,
pub focused: Option<WidgetId>,
pub theme: Option<native_gui_core::Theme>,
pub theme_overrides: HashMap<WidgetId, Vec<native_gui_core::ThemeOverride>>,
pub spell_check: HashMap<WidgetId, bool>,
pub user_text_selections: HashMap<WidgetId, (usize, usize)>,
pub monospace: HashMap<WidgetId, bool>,
pub color_dialog_results: HashMap<WidgetId, Option<native_gui_core::Rgba>>,
pub font_dialog_results: HashMap<WidgetId, Option<(FontDescriptor, FontEffects)>>,
pub system_theme: Option<native_gui_core::ThemeMode>,
pub theme_capabilities: native_gui_core::ThemeCapabilities,
pub displays: Vec<native_gui_core::DisplayInfo>,
pub display_capabilities: native_gui_core::DisplayCapabilities,
pub gpu_surface_capabilities_override: Option<GpuSurfaceCapabilities>,
pub gpu_fallbacks: HashMap<WidgetId, GpuDegradationPolicy>,
pub events: VecDeque<UiEvent>,
pub posted_accessible_notifications: Vec<(WidgetId, AccessibleNotification)>,
pub modal_loops: Vec<MockModalFrame>,
pub menus: HashMap<MenuId, Vec<MenuItemId>>,
pub menu_shortcuts: HashMap<MenuItemId, String>,
pub clipboard: Option<String>,
pub clipboard_image: Option<native_gui_core::widgets::ClipboardImage>,
pub context_menus: HashMap<WidgetId, MenuId>,
pub tray_icons: HashMap<TrayIconId, MockTrayIconState>,
pub confirm_requests: Vec<(u64, String, String)>,
pub file_dialog_requests: Vec<(u64, native_gui_core::file_dialog::FileDialog)>,
pub close_guards: HashMap<WidgetId, bool>,
pub window_options: HashMap<WidgetId, WindowOptions>,
pub window_capabilities_override: Option<WindowCapabilities>,
active_popup_sessions: HashSet<WidgetId>,
pub window_effects: Vec<MockWindowEffect>,
pub drag_source_options: HashMap<WidgetId, DragSourceOptions>,
pub drag_target_options: HashMap<WidgetId, DragTargetOptions>,
pub image_resources: HashMap<ImageResourceId, ImageData>,
pub image_resource_capabilities_override: Option<ImageResourceCapabilities>,
pub animation_resources: HashMap<AnimationResourceId, AnimationData>,
next_animation_resource_id: u64,
pub active_animations: HashMap<WidgetId, MockAnimationState>,
pub widget_image_resources: HashMap<WidgetId, ImageResourceId>,
pub animation_finished_events: Vec<WidgetId>,
pub drag_capabilities_override: Option<DragCapabilities>,
active_drag: Option<MockDragSession>,
next_drag_session: u64,
virtual_now: Duration,
timers: HashMap<TimerId, MockTimer>,
pending_timer_events: HashMap<TimerId, (Option<(WidgetId, TimerStopPolicy)>, usize)>,
pub timer_capabilities_override: Option<TimerCapabilities>,
pub motion_capabilities_override: Option<MotionCapabilities>,
pub menu_item_enabled: HashMap<MenuItemId, bool>,
pub menu_item_text: HashMap<MenuItemId, String>,
pub menu_submenu_slots: HashMap<MenuId, MenuItemId>,
pub rich_text_images: HashMap<WidgetId, Vec<RichTextImage>>,
pub last_canvas_scene: Option<native_gui_core::CanvasScene>,
pub last_canvas_surface: Option<native_gui_core::CanvasSurface>,
pub data_grid_row_heights: HashMap<(WidgetId, usize), i32>,
pub data_grid_col_widths: HashMap<(WidgetId, usize), i32>,
pub data_grid_models: HashMap<WidgetId, RetainedDataGridModel>,
pub data_grid_selections: HashMap<WidgetId, Vec<(usize, usize)>>,
#[cfg(feature = "webview")]
pub webviews: HashMap<WidgetId, webview::MockWebView>,
#[cfg(feature = "webview")]
pub webview_runtime_missing: bool,
#[cfg(feature = "property-grid")]
pub advanced_hosts: std::collections::HashSet<WidgetId>,
#[cfg(feature = "property-grid")]
pub advanced_engine: Option<native_gui_core::advanced::EngineInfo>,
#[cfg(feature = "property-grid")]
pub property_grid_models: HashMap<WidgetId, native_gui_core::PropertyModel>,
#[cfg(feature = "property-grid")]
pub property_grid_applied: Vec<(WidgetId, native_gui_core::PropertyId)>,
#[cfg(feature = "property-grid")]
pub property_grid_refreshes: HashMap<WidgetId, usize>,
natural_size_overrides: HashMap<WidgetId, (i32, i32)>,
pub app_data_dir: Option<PathBuf>,
wake_flag: Arc<AtomicBool>,
wake_signal: Arc<(Mutex<()>, Condvar)>,
}
impl MockBackend {
pub fn with_natural_sizes() -> Self {
Self {
natural_sizes: true,
..Self::default()
}
}
pub fn with_data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.app_data_dir = Some(dir.into());
self
}
pub fn mock_natural_size(spec: &WidgetSpec) -> Option<(i32, i32)> {
let chars = spec
.text
.as_deref()
.unwrap_or("")
.lines()
.map(|line| line.chars().count())
.max()
.unwrap_or(0) as i32;
let text_w = chars * 8;
Some(match spec.kind {
WidgetKind::Window | WidgetKind::Container => return None,
#[cfg(feature = "widgets-containers")]
WidgetKind::SplitPane => return None,
WidgetKind::Label => (text_w.max(8), 20),
WidgetKind::Button => ((text_w + 24).max(64), 32),
#[cfg(feature = "widgets-choice")]
WidgetKind::Checkbox | WidgetKind::RadioButton => (text_w + 24, 24),
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput => (160, 32),
#[cfg(feature = "widgets-text")]
WidgetKind::TextArea | WidgetKind::RichText => (240, 96),
#[cfg(feature = "widgets-choice")]
WidgetKind::ComboBox => (120, 32),
#[cfg(feature = "widgets-range")]
WidgetKind::Slider | WidgetKind::ProgressBar => (160, 24),
#[cfg(feature = "widgets-range")]
WidgetKind::SpinBox => (96, 32),
#[cfg(feature = "widgets-data")]
WidgetKind::DataGrid
| WidgetKind::DataList
| WidgetKind::ListView
| WidgetKind::TreeView => (240, 160),
_ => (100, 32),
})
}
fn default_image_resource_capabilities() -> ImageResourceCapabilities {
ImageResourceCapabilities {
rgba: true,
image_animation: true,
animation_decode: false,
}
}
pub fn set_image_resource_capabilities(&mut self, capabilities: ImageResourceCapabilities) {
self.image_resource_capabilities_override = Some(capabilities);
}
pub fn set_natural_size_override(&mut self, widget_id: WidgetId, size: (i32, i32)) {
self.natural_size_overrides.insert(widget_id, size);
}
pub fn image_resource(&self, resource: ImageResourceId) -> Option<&ImageData> {
self.image_resources.get(&resource)
}
pub fn load_animation_resource(
&mut self,
data: &AnimationData,
) -> GuiResult<AnimationResourceId> {
if !self.image_resource_capabilities().image_animation {
return Err(GuiError::UnsupportedCapability(
"image_animation".to_owned(),
));
}
data.validate()?;
for frame in &data.frames {
if !self.image_resources.contains_key(&frame.image) {
return Err(GuiError::Backend(format!(
"Image resource not found: {}",
frame.image.0
)));
}
}
let next =
self.next_animation_resource_id
.checked_add(1)
.ok_or(GuiError::ResourceExhausted {
operation: "animation resource id allocation",
code: None,
})?;
let resource_id = AnimationResourceId(next);
self.next_animation_resource_id = next;
self.animation_resources.insert(resource_id, data.clone());
Ok(resource_id)
}
pub fn release_animation_resource(&mut self, id: AnimationResourceId) -> GuiResult<()> {
if !self.image_resource_capabilities().image_animation {
return Err(GuiError::UnsupportedCapability(
"image_animation".to_owned(),
));
}
if self.animation_resources.remove(&id).is_none() {
return Err(GuiError::Backend(format!(
"Animation resource not found: {}",
id.0
)));
}
let widgets_using: Vec<WidgetId> = self
.active_animations
.iter()
.filter_map(|(wid, state)| (state.resource_id == id).then_some(*wid))
.collect();
for wid in widgets_using {
self.active_animations.remove(&wid);
self.widget_image_resources.remove(&wid);
}
Ok(())
}
pub fn animation_resource(&self, id: AnimationResourceId) -> Option<&AnimationData> {
self.animation_resources.get(&id)
}
pub fn decode_animation_resource(&mut self, _bytes: &[u8]) -> GuiResult<AnimationResourceId> {
if !self.image_resource_capabilities().animation_decode {
return Err(GuiError::UnsupportedCapability(
"animation_decode".to_owned(),
));
}
Err(GuiError::UnsupportedCapability(
"animation_decode".to_owned(),
))
}
pub fn set_image_animation(
&mut self,
widget_id: WidgetId,
animation: Option<AnimationResourceId>,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ImageSource)?;
if !self.image_resource_capabilities().image_animation {
return Err(GuiError::UnsupportedCapability(
"image_animation".to_owned(),
));
}
let Some(anim_id) = animation else {
self.active_animations.remove(&widget_id);
self.widget_image_resources.remove(&widget_id);
return Ok(());
};
let data = self.animation_resources.get(&anim_id).ok_or_else(|| {
GuiError::Backend(format!("Animation resource not found: {}", anim_id.0))
})?;
let is_shown = self.shown.contains(&widget_id);
let first_frame_image = data.frames[0].image;
let first_frame_delay = data.frames[0].delay;
let state = MockAnimationState {
resource_id: anim_id,
current_frame: 0,
completed_loops: 0,
playing: true,
paused: !is_shown,
next_deadline: if is_shown {
Some(
self.virtual_now
.checked_add(first_frame_delay)
.ok_or_else(|| {
GuiError::Backend("Mock animation deadline overflow".to_owned())
})?,
)
} else {
None
},
remaining_in_frame: if !is_shown {
Some(first_frame_delay)
} else {
None
},
finished: false,
};
self.active_animations.insert(widget_id, state);
self.widget_image_resources
.insert(widget_id, first_frame_image);
Ok(())
}
pub fn start_image_animation(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ImageSource)?;
if !self.image_resource_capabilities().image_animation {
return Err(GuiError::UnsupportedCapability(
"image_animation".to_owned(),
));
}
let state = self.active_animations.get_mut(&widget_id).ok_or_else(|| {
GuiError::Backend(format!("No animation assigned to widget: {}", widget_id.0))
})?;
let data = self
.animation_resources
.get(&state.resource_id)
.ok_or_else(|| {
GuiError::Backend(format!(
"Animation resource not found: {}",
state.resource_id.0
))
})?;
let is_shown = self.shown.contains(&widget_id);
let first_frame_image = data.frames[0].image;
let first_frame_delay = data.frames[0].delay;
state.current_frame = 0;
state.completed_loops = 0;
state.playing = true;
state.paused = !is_shown;
state.finished = false;
state.next_deadline = if is_shown {
Some(
self.virtual_now
.checked_add(first_frame_delay)
.ok_or_else(|| {
GuiError::Backend("Mock animation deadline overflow".to_owned())
})?,
)
} else {
None
};
state.remaining_in_frame = if !is_shown {
Some(first_frame_delay)
} else {
None
};
self.widget_image_resources
.insert(widget_id, first_frame_image);
Ok(())
}
pub fn stop_image_animation(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ImageSource)?;
if !self.image_resource_capabilities().image_animation {
return Err(GuiError::UnsupportedCapability(
"image_animation".to_owned(),
));
}
let state = self.active_animations.get_mut(&widget_id).ok_or_else(|| {
GuiError::Backend(format!("No animation assigned to widget: {}", widget_id.0))
})?;
let data = self
.animation_resources
.get(&state.resource_id)
.ok_or_else(|| {
GuiError::Backend(format!(
"Animation resource not found: {}",
state.resource_id.0
))
})?;
state.playing = false;
state.paused = false;
state.finished = false;
state.current_frame = 0;
state.next_deadline = None;
state.remaining_in_frame = None;
self.widget_image_resources
.insert(widget_id, data.frames[0].image);
Ok(())
}
pub fn widget_current_image_resource(&self, widget_id: WidgetId) -> Option<ImageResourceId> {
self.widget_image_resources.get(&widget_id).copied()
}
pub fn widget_animation_state(&self, widget_id: WidgetId) -> Option<&MockAnimationState> {
self.active_animations.get(&widget_id)
}
pub fn animation_finished_events(&self) -> &[WidgetId] {
&self.animation_finished_events
}
pub fn take_animation_finished_events(&mut self) -> Vec<WidgetId> {
std::mem::take(&mut self.animation_finished_events)
}
fn pause_animation_on_hide(&mut self, widget_id: WidgetId) {
if let Some(state) = self.active_animations.get_mut(&widget_id) {
if state.playing && !state.paused && !state.finished {
let remaining = state
.next_deadline
.map(|dl| dl.saturating_sub(self.virtual_now))
.unwrap_or(Duration::ZERO);
state.remaining_in_frame = Some(remaining);
state.next_deadline = None;
state.paused = true;
}
}
}
fn resume_animation_on_show(&mut self, widget_id: WidgetId) -> GuiResult<()> {
if let Some(state) = self.active_animations.get_mut(&widget_id) {
if state.playing && state.paused && !state.finished {
let delay = state.remaining_in_frame.take().unwrap_or(Duration::ZERO);
state.next_deadline =
Some(self.virtual_now.checked_add(delay).ok_or_else(|| {
GuiError::Backend("Mock animation deadline overflow".to_owned())
})?);
state.paused = false;
}
}
Ok(())
}
fn cleanup_animation_on_remove(&mut self, widget_id: WidgetId) {
self.active_animations.remove(&widget_id);
self.widget_image_resources.remove(&widget_id);
}
fn next_animation_deadline(&self) -> Option<Duration> {
self.active_animations
.values()
.filter(|anim| anim.playing && !anim.paused && !anim.finished)
.filter_map(|anim| anim.next_deadline)
.min()
}
fn service_due_animations(&mut self) -> GuiResult<()> {
let active_widget_ids: Vec<WidgetId> = self.active_animations.keys().copied().collect();
let now = self.virtual_now;
for widget_id in active_widget_ids {
let Some(state) = self.active_animations.get_mut(&widget_id) else {
continue;
};
if !state.playing || state.paused || state.finished {
continue;
}
let Some(anim_data) = self.animation_resources.get(&state.resource_id) else {
continue;
};
let frames = &anim_data.frames;
if frames.is_empty() {
continue;
}
while let Some(deadline) = state.next_deadline {
if deadline > now {
break;
}
let next_frame = state.current_frame + 1;
if next_frame < frames.len() {
state.current_frame = next_frame;
let next_delay = frames[next_frame].delay;
let next_dl = deadline.checked_add(next_delay).ok_or_else(|| {
GuiError::Backend("Mock animation deadline overflow".to_owned())
})?;
state.next_deadline = Some(next_dl);
self.widget_image_resources
.insert(widget_id, frames[next_frame].image);
} else {
state.completed_loops += 1;
match anim_data.loop_count {
LoopCount::Count(max_loops) if state.completed_loops >= max_loops => {
state.finished = true;
state.playing = false;
state.next_deadline = None;
self.animation_finished_events.push(widget_id);
break;
}
_ => {
state.current_frame = 0;
let next_delay = frames[0].delay;
let next_dl = deadline.checked_add(next_delay).ok_or_else(|| {
GuiError::Backend("Mock animation deadline overflow".to_owned())
})?;
state.next_deadline = Some(next_dl);
self.widget_image_resources
.insert(widget_id, frames[0].image);
}
}
}
}
}
Ok(())
}
fn default_timer_capabilities() -> TimerCapabilities {
TimerCapabilities {
timers: true,
widget_timers: true,
}
}
pub fn set_motion_capabilities(&mut self, capabilities: MotionCapabilities) {
self.motion_capabilities_override = Some(capabilities);
}
fn start_mock_timer(
&mut self,
timer: TimerId,
spec: TimerSpec,
widget_scope: Option<(WidgetId, TimerStopPolicy)>,
) -> GuiResult<()> {
spec.validate()?;
let deadline = self
.virtual_now
.checked_add(spec.first_delay)
.ok_or_else(|| GuiError::Backend("Timer deadline overflow".to_owned()))?;
if self.timers.contains_key(&timer) {
return Err(GuiError::Backend(format!(
"Timer already exists: {}",
timer.0
)));
}
self.timers.insert(
timer,
MockTimer {
spec,
started_at: self.virtual_now,
deadline,
widget_scope,
},
);
Ok(())
}
pub fn set_timer_capabilities(&mut self, capabilities: TimerCapabilities) {
self.timer_capabilities_override = Some(capabilities);
}
pub fn now(&self) -> Duration {
self.virtual_now
}
pub fn advance_time(&mut self, amount: Duration) -> GuiResult<()> {
self.virtual_now = self
.virtual_now
.checked_add(amount)
.ok_or_else(|| GuiError::Backend("Mock virtual clock overflow".to_owned()))?;
self.service_due_timers()?;
self.service_due_animations()
}
fn service_due_timers(&mut self) -> GuiResult<()> {
const MAX_UNCOALESCED_FIRES: u128 = 1_000_000;
let now = self.virtual_now;
let due: Vec<_> = self
.timers
.iter()
.filter_map(|(id, timer)| (timer.deadline <= now).then_some((*id, *timer)))
.collect();
let mut deliveries = Vec::new();
let mut completed = Vec::new();
let mut rescheduled = Vec::new();
for (id, timer) in due {
let elapsed = now - timer.started_at;
let Some(interval) = timer.spec.interval else {
deliveries.push(TimerDelivery {
deadline: timer.deadline,
fire: TimerFire {
timer: id,
elapsed,
missed: 0,
},
widget_scope: timer.widget_scope,
});
completed.push(id);
continue;
};
let due_count = (now - timer.deadline).as_nanos() / interval.as_nanos() + 1;
if timer.spec.coalesce {
let missed =
u32::try_from(due_count - 1).map_err(|_| GuiError::ResourceExhausted {
operation: "timer missed-deadline count",
code: None,
})?;
deliveries.push(TimerDelivery {
deadline: timer.deadline,
fire: TimerFire {
timer: id,
elapsed,
missed,
},
widget_scope: timer.widget_scope,
});
} else {
if due_count > MAX_UNCOALESCED_FIRES {
return Err(GuiError::ResourceExhausted {
operation: "Mock timer catch-up events",
code: None,
});
}
for deadline_index in 0..due_count {
let deadline_nanos = timer
.deadline
.as_nanos()
.checked_add(interval.as_nanos().checked_mul(deadline_index).ok_or(
GuiError::ResourceExhausted {
operation: "Mock timer deadline",
code: None,
},
)?)
.ok_or(GuiError::ResourceExhausted {
operation: "Mock timer deadline",
code: None,
})?;
let deadline =
duration_from_nanos(deadline_nanos).ok_or(GuiError::ResourceExhausted {
operation: "Mock timer deadline",
code: None,
})?;
deliveries.push(TimerDelivery {
deadline,
fire: TimerFire {
timer: id,
elapsed,
missed: 0,
},
widget_scope: timer.widget_scope,
});
}
}
let next_deadline_nanos = timer
.deadline
.as_nanos()
.checked_add(interval.as_nanos().checked_mul(due_count).ok_or(
GuiError::ResourceExhausted {
operation: "Mock timer deadline",
code: None,
},
)?)
.ok_or(GuiError::ResourceExhausted {
operation: "Mock timer deadline",
code: None,
})?;
let next_deadline =
duration_from_nanos(next_deadline_nanos).ok_or(GuiError::ResourceExhausted {
operation: "Mock timer deadline",
code: None,
})?;
rescheduled.push((id, next_deadline));
}
deliveries.sort_by_key(|delivery| (delivery.deadline, delivery.fire.timer));
for timer in completed {
self.timers.remove(&timer);
}
for (timer, deadline) in rescheduled {
if let Some(active) = self.timers.get_mut(&timer) {
active.deadline = deadline;
}
}
for delivery in deliveries {
self.push_timer_event(
UiEvent::TimerFired {
timer: delivery.fire.timer,
elapsed: delivery.fire.elapsed,
missed: delivery.fire.missed,
},
delivery.widget_scope,
);
}
Ok(())
}
fn push_timer_event(
&mut self,
event: UiEvent,
widget_scope: Option<(WidgetId, TimerStopPolicy)>,
) {
if let UiEvent::TimerFired { timer, .. } = &event {
let pending = self
.pending_timer_events
.entry(*timer)
.or_insert((widget_scope, 0));
pending.1 += 1;
}
if let Some(frame) = self.modal_loops.last_mut() {
frame.script.push_back(event);
let (_, cvar) = &*self.wake_signal;
cvar.notify_all();
} else {
self.push_event(event);
}
}
fn cancel_mock_timer(&mut self, timer: TimerId) -> GuiResult<()> {
if self.timers.remove(&timer).is_none() {
return Err(GuiError::Backend(format!("Timer not found: {}", timer.0)));
}
self.remove_queued_timer_events(timer);
Ok(())
}
fn remove_queued_timer_events(&mut self, timer: TimerId) {
self.events.retain(
|event| !matches!(event, UiEvent::TimerFired { timer: id, .. } if *id == timer),
);
for frame in &mut self.modal_loops {
frame.script.retain(
|event| !matches!(event, UiEvent::TimerFired { timer: id, .. } if *id == timer),
);
}
self.pending_timer_events.remove(&timer);
}
fn cancel_widget_timers(&mut self, widget_id: WidgetId, hiding: bool) {
let timers: Vec<_> = self
.timers
.iter()
.filter_map(|(timer, state)| {
let (scope, policy) = state.widget_scope?;
let within_scope = self.source_is_owned_by(scope, widget_id);
(within_scope && (!hiding || policy == TimerStopPolicy::RemoveOrHide))
.then_some(*timer)
})
.collect();
for timer in timers {
self.cancel_mock_timer(timer)
.expect("timer selected from the active timer map");
}
let pending: Vec<_> = self
.pending_timer_events
.iter()
.filter_map(|(timer, (scope, _))| {
let (scope, policy) = (*scope)?;
let within_scope = self.source_is_owned_by(scope, widget_id);
(within_scope && (!hiding || policy == TimerStopPolicy::RemoveOrHide))
.then_some(*timer)
})
.collect();
for timer in pending {
self.remove_queued_timer_events(timer);
}
}
fn next_timer_deadline(&self) -> Option<Duration> {
self.timers.values().map(|timer| timer.deadline).min()
}
fn next_combined_deadline(&self) -> Option<Duration> {
match (self.next_timer_deadline(), self.next_animation_deadline()) {
(Some(t), Some(a)) => Some(t.min(a)),
(Some(t), None) => Some(t),
(None, Some(a)) => Some(a),
(None, None) => None,
}
}
fn advance_to_next_timer(&mut self) -> GuiResult<bool> {
let Some(deadline) = self.next_combined_deadline() else {
return Ok(false);
};
if deadline > self.virtual_now {
self.virtual_now = deadline;
}
self.service_due_timers()?;
self.service_due_animations()?;
Ok(true)
}
fn pop_pump_event(&mut self) -> Option<UiEvent> {
let event = match self.modal_loops.last_mut() {
Some(frame) => {
let event = frame.script.pop_front();
if event.is_some() {
frame.delivered += 1;
}
event
}
None => self.events.pop_front(),
};
if let Some(UiEvent::TimerFired { timer, .. }) = &event {
let remove_entry = if let Some((_, count)) = self.pending_timer_events.get_mut(timer) {
if *count <= 1 {
true
} else {
*count -= 1;
false
}
} else {
false
};
if remove_entry {
self.pending_timer_events.remove(timer);
}
}
event
}
fn default_window_capabilities() -> WindowCapabilities {
WindowCapabilities {
anchored_popups: true,
popup_focus_dismissal: true,
transient_ownership: true,
undecorated: true,
always_on_top: true,
uniform_translucency: true,
shape_rounded: true,
shape_region: false,
show_fade: true,
show_slide: true,
}
}
fn default_drag_capabilities() -> DragCapabilities {
DragCapabilities {
text: true,
custom_mime: true,
drop_feedback: true,
preview: false,
}
}
pub fn set_window_capabilities(&mut self, capabilities: WindowCapabilities) {
self.window_capabilities_override = Some(capabilities);
}
pub fn set_drag_capabilities(&mut self, capabilities: DragCapabilities) {
self.drag_capabilities_override = Some(capabilities);
}
pub fn mock_start_drag(&mut self, source: WidgetId) -> GuiResult<DragSessionId> {
if self.active_drag.is_some() {
return Err(GuiError::UnsupportedCapability("drag_busy".to_owned()));
}
if !self.created.contains_key(&source) {
return Err(GuiError::WidgetNotFound(source.0));
}
let options = self
.drag_source_options
.get(&source)
.cloned()
.ok_or(GuiError::UnsupportedWidget("set_drag_source"))?;
if options.kinds.is_empty() {
return Err(GuiError::Backend(
"Drag sources must offer at least one payload kind".to_owned(),
));
}
let next = self
.next_drag_session
.checked_add(1)
.ok_or(GuiError::ResourceExhausted {
operation: "drag session id allocation",
code: None,
})?;
let session = DragSessionId(next);
self.next_drag_session = next;
self.active_drag = Some(MockDragSession {
id: session,
source,
kinds: options.kinds.clone(),
target: None,
});
self.push_drag_event(UiEvent::DragSessionStarted {
widget_id: source,
session,
kinds: options.kinds,
});
Ok(session)
}
pub fn mock_drag_enter(
&mut self,
session: DragSessionId,
target: WidgetId,
position: (i32, i32),
) -> GuiResult<bool> {
let Some(active) = self
.active_drag
.as_ref()
.filter(|active| active.id == session)
.cloned()
else {
return Ok(false);
};
if !self.created.contains_key(&target) {
return Err(GuiError::WidgetNotFound(target.0));
}
let target_options = self
.drag_target_options
.get(&target)
.ok_or(GuiError::UnsupportedWidget("set_drag_target_options"))?;
let offered: Vec<_> = active
.kinds
.iter()
.filter(|kind| target_options.kinds.contains(kind))
.map(|kind| kind.mime_type().to_owned())
.collect();
if offered.is_empty() {
if let Some(previous) = active.target {
self.mock_drag_exit(session, previous);
}
return Ok(false);
}
if active.target == Some(target) {
return Ok(true);
}
if let Some(previous) = active.target {
self.mock_drag_exit(session, previous);
}
if let Some(active) = self.active_drag.as_mut() {
active.target = Some(target);
}
self.push_drag_event(UiEvent::DragEntered {
target,
session,
position,
offered,
});
Ok(true)
}
pub fn mock_drag_move(
&mut self,
session: DragSessionId,
target: WidgetId,
position: (i32, i32),
) -> bool {
if !self
.active_drag
.as_ref()
.is_some_and(|active| active.id == session && active.target == Some(target))
{
return false;
}
self.push_drag_event(UiEvent::DragMoved {
target,
session,
position,
});
true
}
pub fn mock_drag_exit(&mut self, session: DragSessionId, target: WidgetId) -> bool {
let Some(active) = self
.active_drag
.as_mut()
.filter(|active| active.id == session && active.target == Some(target))
else {
return false;
};
active.target = None;
self.push_drag_event(UiEvent::DragExited { target, session });
true
}
pub fn mock_drag_drop(
&mut self,
session: DragSessionId,
target: WidgetId,
position: (i32, i32),
payload: DragPayload,
) -> GuiResult<bool> {
let Some(active) = self
.active_drag
.as_ref()
.filter(|active| active.id == session && active.target == Some(target))
.cloned()
else {
return Ok(false);
};
let payload = payload.normalized()?;
let kind = payload.kind().ok_or_else(|| {
GuiError::Backend("Row and file payloads use their existing drag events".to_owned())
})?;
let target_options = self
.drag_target_options
.get(&target)
.ok_or(GuiError::UnsupportedWidget("set_drag_target_options"))?;
if !active.kinds.contains(&kind) || !target_options.kinds.contains(&kind) {
return Err(GuiError::Backend(
"Drop payload kind is not accepted by both source and target".to_owned(),
));
}
let effect = target_options.effect;
self.mock_drag_exit(session, target);
self.push_drag_event(UiEvent::DragDropped {
target,
session,
position,
payload,
effect,
});
self.active_drag = None;
Ok(true)
}
pub fn mock_cancel_drag(&mut self, session: DragSessionId, reason: DropCancelReason) -> bool {
self.finish_drag_cancel(session, reason)
}
fn cancel_drag_from_source(&mut self, source: WidgetId) {
if let Some(session) = self
.active_drag
.as_ref()
.filter(|active| active.source == source)
.map(|active| active.id)
{
self.finish_drag_cancel(session, DropCancelReason::SourceRemoved);
}
}
fn finish_drag_cancel(&mut self, session: DragSessionId, reason: DropCancelReason) -> bool {
let Some(active) = self
.active_drag
.as_ref()
.filter(|active| active.id == session)
.cloned()
else {
return false;
};
if let Some(target) = active.target {
self.mock_drag_exit(session, target);
}
self.push_drag_event(UiEvent::DragCancelled { session, reason });
self.active_drag = None;
true
}
fn source_is_owned_by(&self, source: WidgetId, owner: WidgetId) -> bool {
let mut cursor = Some(source);
while let Some(widget_id) = cursor {
if widget_id == owner {
return true;
}
cursor = self.created.get(&widget_id).and_then(|spec| spec.parent);
}
false
}
fn push_drag_event(&mut self, event: UiEvent) {
if let Some(frame) = self.modal_loops.last_mut() {
frame.script.push_back(event);
let (_, cvar) = &*self.wake_signal;
cvar.notify_all();
} else {
self.push_event(event);
}
}
pub fn inject_popup_dismissal(
&mut self,
widget_id: WidgetId,
reason: PopupDismissReason,
) -> bool {
self.end_popup_session(widget_id, Some(reason))
}
pub fn inject_window_closed(&mut self, widget_id: WidgetId) {
if let Some(session) = self
.active_drag
.as_ref()
.filter(|active| self.source_is_owned_by(active.source, widget_id))
.map(|active| active.id)
{
self.finish_drag_cancel(session, DropCancelReason::OwnerClosed);
}
let mut popups: Vec<_> = self
.active_popup_sessions
.iter()
.copied()
.filter(|popup| {
self.window_options
.get(popup)
.is_some_and(|options| options.transient_for == Some(widget_id))
})
.collect();
popups.sort_by_key(|popup| popup.0);
for popup in popups {
self.end_popup_session(popup, Some(PopupDismissReason::OwnerClosed));
}
self.push_event(UiEvent::WindowClosed { widget_id });
}
fn end_popup_session(
&mut self,
widget_id: WidgetId,
reason: Option<PopupDismissReason>,
) -> bool {
if !self.active_popup_sessions.remove(&widget_id) {
return false;
}
if reason.is_some() {
if let Some(effect) = self
.window_options
.get(&widget_id)
.map(|options| options.hide_effect)
.filter(|effect| *effect != ShowEffect::None)
{
self.window_effects
.push(MockWindowEffect::Hide { widget_id, effect });
}
}
self.shown.retain(|shown| *shown != widget_id);
if let Some(reason) = reason {
self.push_event(UiEvent::PopupDismissed { widget_id, reason });
}
true
}
pub fn set_gpu_surface_capabilities(&mut self, capabilities: GpuSurfaceCapabilities) {
self.gpu_surface_capabilities_override = Some(capabilities);
}
pub fn push_event(&mut self, event: UiEvent) {
self.events.push_back(event);
let (_, cvar) = &*self.wake_signal;
cvar.notify_all();
}
pub fn begin_modal_loop(&mut self) {
self.modal_loops.push(MockModalFrame::default());
}
pub fn script_modal_event(&mut self, event: UiEvent) -> bool {
match self.modal_loops.last_mut() {
Some(frame) => {
frame.script.push_back(event);
let (_, cvar) = &*self.wake_signal;
cvar.notify_all();
true
}
None => false,
}
}
pub fn end_modal_loop(&mut self) -> Vec<UiEvent> {
match self.modal_loops.pop() {
Some(frame) => frame.script.into_iter().collect(),
None => Vec::new(),
}
}
pub fn modal_loop_depth(&self) -> usize {
self.modal_loops.len()
}
pub fn modal_loop_open(&self) -> bool {
!self.modal_loops.is_empty()
}
pub fn last_canvas_scene(&self) -> Option<&native_gui_core::CanvasScene> {
self.last_canvas_scene.as_ref()
}
pub fn last_canvas_surface(&self) -> Option<&native_gui_core::CanvasSurface> {
self.last_canvas_surface.as_ref()
}
pub fn data_grid_model(&self, widget_id: WidgetId) -> Option<&dyn DataGridModel> {
self.data_grid_models
.get(&widget_id)
.map(|model| model.0.as_ref())
}
pub fn data_grid_model_row_count(&self, widget_id: WidgetId) -> Option<usize> {
self.data_grid_model(widget_id)
.map(DataGridModel::row_count)
}
pub fn data_grid_model_col_count(&self, widget_id: WidgetId) -> Option<usize> {
self.data_grid_model(widget_id)
.map(DataGridModel::col_count)
}
pub fn data_grid_model_is_row_resident(&self, widget_id: WidgetId, row: usize) -> Option<bool> {
self.data_grid_model(widget_id)
.map(|model| model.is_row_resident(row))
}
pub fn data_grid_selection(&self, widget_id: WidgetId) -> Option<&[(usize, usize)]> {
self.data_grid_selections
.get(&widget_id)
.map(|s| s.as_slice())
}
pub fn inject_system_theme_mode(&mut self, mode: native_gui_core::ThemeMode) {
self.system_theme = Some(mode);
self.theme_capabilities = native_gui_core::ThemeCapabilities::all();
self.push_event(UiEvent::ThemeChanged {
mode,
high_contrast: self.system_high_contrast(),
});
}
pub fn set_displays(&mut self, displays: Vec<native_gui_core::DisplayInfo>) {
self.displays = displays;
self.display_capabilities.enumeration = true;
}
pub fn set_display_capabilities(&mut self, capabilities: native_gui_core::DisplayCapabilities) {
self.display_capabilities = capabilities;
}
pub fn inject_display_change(&mut self, display: native_gui_core::DisplayInfo) {
self.display_capabilities.dpi_change_events = true;
self.push_event(UiEvent::DisplayChanged { display });
}
pub fn inject_close_request(&mut self, widget_id: WidgetId) {
self.push_event(UiEvent::CloseRequested { widget_id });
}
pub fn inject_color_dialog_result(
&mut self,
widget_id: WidgetId,
result: Option<native_gui_core::Rgba>,
) {
self.color_dialog_results.insert(widget_id, result);
}
pub fn inject_font_dialog_result(
&mut self,
widget_id: WidgetId,
result: Option<(FontDescriptor, FontEffects)>,
) {
self.font_dialog_results.insert(widget_id, result);
}
pub fn inject_suggestion_selected(
&mut self,
widget_id: WidgetId,
text: impl Into<String>,
) -> GuiResult<()> {
self.ensure_text_completion_target(widget_id)?;
self.push_event(UiEvent::SuggestionSelected {
widget_id,
text: text.into(),
});
Ok(())
}
pub fn inject_suggestion_dismissed(&mut self, widget_id: WidgetId) -> GuiResult<()> {
self.ensure_text_completion_target(widget_id)?;
self.push_event(UiEvent::SuggestionDismissed { widget_id });
Ok(())
}
fn ensure_text_completion_target(&self, widget_id: WidgetId) -> GuiResult<()> {
let spec = self
.created
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
spec.ensure_property(WidgetProperty::TextCompletion)
}
pub fn inject_file_dialog_result(
&mut self,
token: u64,
paths: Vec<std::path::PathBuf>,
) -> GuiResult<()> {
let Some(position) = self
.file_dialog_requests
.iter()
.position(|(pending, _)| *pending == token)
else {
return Err(GuiError::Backend(format!(
"no pending file dialog with token {token}"
)));
};
let (_, request) = self.file_dialog_requests.remove(position);
if !request.multiple && paths.len() > 1 {
return Err(GuiError::Backend(
"a single-selection file dialog answers with at most one path".to_owned(),
));
}
self.push_event(UiEvent::FileDialogResponse { token, paths });
Ok(())
}
#[cfg(feature = "widgets-containers")]
pub fn inject_split_pane_moved(
&mut self,
widget_id: WidgetId,
position: i32,
extent: i32,
) -> GuiResult<()> {
let spec = self
.created
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if spec.kind != WidgetKind::SplitPane {
return Err(GuiError::UnsupportedWidget("SplitPaneMoved"));
}
self.push_event(UiEvent::SplitPaneMoved {
widget_id,
position,
extent,
});
Ok(())
}
pub fn click_tool(&mut self, widget_id: WidgetId, tool_id: ToolId) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ToolbarItems)?;
let interaction = toolbar::click_tool(&mut spec.toolbar_items, tool_id)
.map_err(|error| GuiError::Backend(error.to_string()))?;
match interaction {
ToolInteraction::Activated(tool_id) => {
self.push_event(UiEvent::ToolActivated { widget_id, tool_id });
}
ToolInteraction::Dropdown(tool_id) => {
self.push_event(UiEvent::ToolDropdown { widget_id, tool_id });
}
ToolInteraction::Toggled(changes) => {
for (tool_id, checked) in changes {
self.push_event(UiEvent::ToolToggled {
widget_id,
tool_id,
checked,
});
}
}
ToolInteraction::Ignored(_) => {}
}
Ok(())
}
pub fn hover_tool(&mut self, widget_id: WidgetId, tool_id: Option<ToolId>) -> GuiResult<()> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ToolbarItems)?;
if let Some(tool_id) = tool_id {
if toolbar::find_tool(&spec.toolbar_items, tool_id).is_none() {
return Err(GuiError::Backend(
native_gui_core::toolbar::ToolbarError::UnknownTool(tool_id).to_string(),
));
}
}
self.push_event(UiEvent::ToolHovered { widget_id, tool_id });
Ok(())
}
pub fn context_tool(&mut self, widget_id: WidgetId, tool_id: ToolId) -> GuiResult<()> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ToolbarItems)?;
if toolbar::find_tool(&spec.toolbar_items, tool_id).is_none() {
return Err(GuiError::Backend(
native_gui_core::toolbar::ToolbarError::UnknownTool(tool_id).to_string(),
));
}
self.push_event(UiEvent::ToolContext { widget_id, tool_id });
Ok(())
}
pub fn click_calendar_date(
&mut self,
widget_id: WidgetId,
date: CalendarDate,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::CalendarDates)?;
if let Some(min) = spec.calendar_min_date {
if date < min {
return Ok(());
}
}
if let Some(max) = spec.calendar_max_date {
if date > max {
return Ok(());
}
}
match spec.calendar_selection_mode {
CalendarSelectionMode::Single => {
spec.calendar_selected_dates = vec![date];
}
CalendarSelectionMode::Multiple => {
if let Some(pos) = spec.calendar_selected_dates.iter().position(|d| *d == date) {
spec.calendar_selected_dates.remove(pos);
} else {
spec.calendar_selected_dates.push(date);
spec.calendar_selected_dates.sort();
}
}
CalendarSelectionMode::Range => {
if spec.calendar_selected_dates.len() == 1 {
let first = spec.calendar_selected_dates[0];
spec.calendar_selected_dates = vec![first.min(date), first.max(date)];
} else {
spec.calendar_selected_dates = vec![date];
}
}
}
let selected_dates = spec.calendar_selected_dates.clone();
self.push_event(UiEvent::CalendarDateSelected {
widget_id,
date,
selected_dates,
});
Ok(())
}
pub fn navigate_calendar_month(
&mut self,
widget_id: WidgetId,
year: i32,
month: u32,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::CalendarBounds)?;
self.push_event(UiEvent::CalendarMonthChanged {
widget_id,
year,
month,
});
Ok(())
}
}
impl native_gui_core::ui::TextMeasure for MockBackend {
fn measure_text(
&self,
widget_id: native_gui_core::widgets::WidgetId,
known_dimensions: native_gui_core::layout::Size<Option<f32>>,
available_space: native_gui_core::layout::Size<native_gui_core::layout::AvailableSpace>,
) -> Option<native_gui_core::layout::Size<f32>> {
let _ = (widget_id, known_dimensions, available_space);
None
}
}
impl Backend for MockBackend {
fn backend_name(&self) -> &'static str {
"mock"
}
fn image_resource_capabilities(&self) -> ImageResourceCapabilities {
self.image_resource_capabilities_override
.unwrap_or_else(Self::default_image_resource_capabilities)
}
fn load_image_resource(
&mut self,
resource: ImageResourceId,
data: &ImageData,
) -> GuiResult<()> {
if !self.image_resource_capabilities().rgba {
return Err(GuiError::UnsupportedCapability(
"image_resource_rgba".to_owned(),
));
}
data.validate()?;
if self.image_resources.contains_key(&resource) {
return Err(GuiError::Backend(format!(
"Image resource already exists: {}",
resource.0
)));
}
self.image_resources.insert(resource, data.clone());
Ok(())
}
fn release_image_resource(&mut self, resource: ImageResourceId) -> GuiResult<()> {
if !self.image_resource_capabilities().rgba {
return Err(GuiError::UnsupportedCapability(
"image_resource_rgba".to_owned(),
));
}
self.image_resources
.remove(&resource)
.map(|_| ())
.ok_or_else(|| GuiError::Backend(format!("Image resource not found: {}", resource.0)))
}
fn timer_capabilities(&self) -> TimerCapabilities {
self.timer_capabilities_override
.unwrap_or_else(Self::default_timer_capabilities)
}
fn motion_capabilities(&self) -> MotionCapabilities {
self.motion_capabilities_override.unwrap_or_else(|| {
let timers = self.timer_capabilities();
MotionCapabilities {
motions: timers.timers && timers.widget_timers,
}
})
}
fn start_timer(&mut self, timer: TimerId, spec: TimerSpec) -> GuiResult<()> {
if !self.timer_capabilities().timers {
return Err(GuiError::UnsupportedCapability("ui_timer".to_owned()));
}
self.start_mock_timer(timer, spec, None)
}
fn start_widget_timer(
&mut self,
timer: TimerId,
widget_id: WidgetId,
spec: TimerSpec,
stop_policy: TimerStopPolicy,
) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
let capabilities = self.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()));
}
self.start_mock_timer(timer, spec, Some((widget_id, stop_policy)))
}
fn cancel_timer(&mut self, timer: TimerId) -> GuiResult<()> {
self.cancel_mock_timer(timer)
}
fn drag_capabilities(&self) -> DragCapabilities {
self.drag_capabilities_override
.unwrap_or_else(Self::default_drag_capabilities)
}
fn set_drag_source_options(
&mut self,
widget_id: WidgetId,
options: &DragSourceOptions,
) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.drag_source_options.insert(widget_id, options.clone());
Ok(())
}
fn set_drag_target_options(
&mut self,
widget_id: WidgetId,
options: &DragTargetOptions,
) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.drag_target_options.insert(widget_id, options.clone());
Ok(())
}
fn window_capabilities(&self) -> WindowCapabilities {
self.window_capabilities_override
.unwrap_or_else(Self::default_window_capabilities)
}
fn set_window_options(
&mut self,
widget_id: WidgetId,
options: &WindowOptions,
) -> GuiResult<()> {
let spec = self
.created
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if spec.kind != WidgetKind::Window {
return Err(GuiError::UnsupportedWidget("set_window_options"));
}
self.window_options.insert(widget_id, *options);
Ok(())
}
fn dismiss_popup(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let spec = self
.created
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if spec.kind != WidgetKind::Window {
return Err(GuiError::UnsupportedWidget("dismiss_popup"));
}
self.hide(widget_id)
}
fn e2e_poll_event(&mut self) -> GuiResult<Option<UiEvent>> {
self.poll_event()
}
#[cfg(feature = "e2e")]
fn e2e_capability(
&self,
widget_id: WidgetId,
operation: crate::e2e::Operation,
) -> GuiResult<crate::e2e::Capability> {
use crate::e2e::{Capability, InputMode, Operation};
let spec = self
.created
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
let supported = match operation {
Operation::Click => {
#[cfg(feature = "widgets-text")]
let is_link = spec.kind == WidgetKind::LinkLabel;
#[cfg(not(feature = "widgets-text"))]
let is_link = false;
spec.kind == WidgetKind::Button || is_link
}
Operation::TypeText => {
#[cfg(feature = "widgets-text")]
let is_text = matches!(spec.kind, WidgetKind::TextInput | WidgetKind::TextArea);
#[cfg(not(feature = "widgets-text"))]
let is_text = false;
is_text
}
#[cfg(feature = "widgets-choice")]
Operation::Check | Operation::Checked => spec.kind == WidgetKind::Checkbox,
#[cfg(not(feature = "widgets-choice"))]
Operation::Check | Operation::Checked => false,
Operation::Text => true,
_ => false,
};
Ok(if supported {
Capability::Supported {
mode: InputMode::Simulated,
}
} else {
Capability::Unsupported {
reason: format!(
"{} is not implemented for {:?}",
operation.name(),
spec.kind
),
}
})
}
#[cfg(feature = "e2e")]
fn e2e_click(&mut self, widget_id: WidgetId) -> GuiResult<()> {
match self.e2e_capability(widget_id, crate::e2e::Operation::Click)? {
crate::e2e::Capability::Supported { .. } => {
#[cfg(feature = "widgets-text")]
let is_link = self.created[&widget_id].kind == WidgetKind::LinkLabel;
#[cfg(not(feature = "widgets-text"))]
let is_link = false;
if is_link {
let url = self.created[&widget_id]
.link_url
.clone()
.unwrap_or_default();
self.push_event(UiEvent::LinkActivated { widget_id, url });
Ok(())
} else {
self.activate(widget_id)
}
}
_ => Err(GuiError::UnsupportedWidget("e2e.click")),
}
}
#[cfg(feature = "e2e")]
fn e2e_type_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
self.e2e_mock_type_text(widget_id, text)
}
#[cfg(feature = "e2e")]
fn e2e_check(&mut self, widget_id: WidgetId, checked: bool) -> GuiResult<()> {
#[cfg(feature = "widgets-choice")]
let is_checkbox = self
.created
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?
.kind
== WidgetKind::Checkbox;
#[cfg(not(feature = "widgets-choice"))]
let is_checkbox = false;
if !is_checkbox {
return Err(GuiError::UnsupportedWidget("e2e.check"));
}
self.e2e_mock_check(widget_id, checked)
}
#[cfg(feature = "e2e")]
fn e2e_text(&self, widget_id: WidgetId) -> GuiResult<String> {
Ok(self
.created
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?
.text
.clone()
.unwrap_or_default())
}
#[cfg(feature = "e2e")]
fn e2e_checked(&self, widget_id: WidgetId) -> GuiResult<bool> {
let spec = self
.created
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
#[cfg(feature = "widgets-choice")]
let is_checkbox = spec.kind == WidgetKind::Checkbox;
#[cfg(not(feature = "widgets-choice"))]
let is_checkbox = false;
if !is_checkbox {
return Err(GuiError::UnsupportedWidget("e2e.checked"));
}
Ok(spec.checked.unwrap_or(false))
}
type NativeHandle = usize;
#[cfg(feature = "property-grid")]
fn host_advanced_control(
&mut self,
host: WidgetId,
family: native_gui_core::advanced::AdvancedFamily,
) -> GuiResult<native_gui_core::advanced::AdvancedHostCapabilities> {
if !self.created.contains_key(&host) {
return Err(GuiError::WidgetNotFound(host.0));
}
match family {
native_gui_core::advanced::AdvancedFamily::PropertyGrid => {
self.advanced_hosts.insert(host);
Ok(native_gui_core::advanced::AdvancedHostCapabilities {
supported: true,
portable: true,
engine: self.advanced_engine.clone(),
decisions: native_gui_core::advanced::DecisionCounters::new(),
})
}
other => Err(GuiError::UnsupportedCapability(format!(
"advanced_control_{}",
other.as_str()
))),
}
}
fn create_widget(&mut self, spec: &WidgetSpec) -> GuiResult<()> {
#[cfg(not(feature = "widgets-media"))]
if WidgetProperty::ImageSource.supports(spec.kind) {
return Err(GuiError::UnsupportedWidget("unsupported widget kind"));
}
self.created.insert(spec.id, spec.clone());
Ok(())
}
fn create_menu(&mut self, menu_id: MenuId) -> GuiResult<()> {
self.menus.entry(menu_id).or_default();
Ok(())
}
fn add_submenu(
&mut self,
parent_id: MenuId,
submenu_id: MenuId,
slot_id: MenuItemId,
_text: &str,
) -> GuiResult<()> {
self.menus.entry(submenu_id).or_default();
if let Some(items) = self.menus.get_mut(&parent_id) {
items.push(slot_id);
}
self.menu_submenu_slots.insert(submenu_id, slot_id);
Ok(())
}
fn create_menu_item(
&mut self,
menu_id: MenuId,
item_id: MenuItemId,
text: &str,
shortcut: Option<&str>,
) -> GuiResult<()> {
let Some(items) = self.menus.get_mut(&menu_id) else {
return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
};
items.push(item_id);
self.menu_item_text.insert(item_id, text.to_owned());
if let Some(value) = shortcut {
self.menu_shortcuts.insert(item_id, value.to_owned());
}
Ok(())
}
fn attach_menu_to_window(&mut self, window_id: WidgetId, menu_id: MenuId) -> GuiResult<()> {
if !self.created.contains_key(&window_id) {
return Err(GuiError::WidgetNotFound(window_id.0));
}
if !self.menus.contains_key(&menu_id) {
return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
}
Ok(())
}
fn attach_context_menu(&mut self, widget_id: WidgetId, menu_id: MenuId) -> GuiResult<()> {
if !self.created.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.context_menus.insert(widget_id, menu_id);
Ok(())
}
fn show_confirm_dialog(&mut self, token: u64, title: &str, message: &str) -> GuiResult<()> {
self.confirm_requests
.push((token, title.to_owned(), message.to_owned()));
Ok(())
}
fn show_file_dialog(
&mut self,
token: u64,
request: &native_gui_core::file_dialog::FileDialog,
) -> GuiResult<()> {
self.file_dialog_requests.push((token, request.clone()));
Ok(())
}
fn set_close_guard(&mut self, widget_id: WidgetId, guarded: bool) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.close_guards.insert(widget_id, guarded);
Ok(())
}
fn set_menu_item_enabled(&mut self, item_id: MenuItemId, enabled: bool) -> GuiResult<()> {
let known = self.menus.values().any(|items| items.contains(&item_id));
if !known {
return Err(GuiError::Backend(format!(
"Menu item not found: {}",
item_id.0
)));
}
self.menu_item_enabled.insert(item_id, enabled);
Ok(())
}
fn set_menu_item_text(&mut self, item_id: MenuItemId, text: &str) -> GuiResult<()> {
let known = self.menus.values().any(|items| items.contains(&item_id));
if !known {
return Err(GuiError::Backend(format!(
"Menu item not found: {}",
item_id.0
)));
}
self.menu_item_text.insert(item_id, text.to_owned());
Ok(())
}
fn insert_menu_item(
&mut self,
menu_id: MenuId,
item_id: MenuItemId,
index: usize,
text: &str,
shortcut: Option<&str>,
) -> GuiResult<()> {
let Some(items) = self.menus.get_mut(&menu_id) else {
return Err(GuiError::Backend(format!("Menu not found: {}", menu_id.0)));
};
let position = index.min(items.len());
items.insert(position, item_id);
self.menu_item_text.insert(item_id, text.to_owned());
if let Some(value) = shortcut {
self.menu_shortcuts.insert(item_id, value.to_owned());
}
Ok(())
}
fn remove_menu_item(&mut self, item_id: MenuItemId) -> GuiResult<()> {
let known = self.menus.values().any(|items| items.contains(&item_id));
if !known {
return Err(GuiError::Backend(format!(
"Menu item not found: {}",
item_id.0
)));
}
for items in self.menus.values_mut() {
items.retain(|item| *item != item_id);
}
self.menu_item_text.remove(&item_id);
self.menu_item_enabled.remove(&item_id);
self.menu_shortcuts.remove(&item_id);
Ok(())
}
fn remove_submenu(&mut self, submenu_id: MenuId) -> GuiResult<()> {
let Some(slot) = self.menu_submenu_slots.remove(&submenu_id) else {
return Err(GuiError::Backend(format!(
"Submenu not found: {}",
submenu_id.0
)));
};
let Some(items) = self.menus.get_mut(&submenu_id) else {
return Err(GuiError::Backend(format!(
"Submenu not found: {}",
submenu_id.0
)));
};
let orphaned = std::mem::take(items);
for owner in self.menus.values_mut() {
owner.retain(|item| *item != slot);
}
self.menus.remove(&submenu_id);
for item in orphaned {
self.menu_item_text.remove(&item);
self.menu_item_enabled.remove(&item);
self.menu_shortcuts.remove(&item);
}
Ok(())
}
fn set_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.text = Some(text.to_owned());
if let Some((start, end)) = spec.text_selection {
let len = text.chars().count();
spec.text_selection = Some((start.min(len), end.min(len)));
}
Ok(())
}
fn set_label_alignment(
&mut self,
widget_id: WidgetId,
alignment: LabelAlignment,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::LabelAlignment)?;
spec.label_alignment = alignment;
Ok(())
}
fn set_label_wrap(&mut self, widget_id: WidgetId, wrap: LabelWrap) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::LabelWrap)?;
spec.label_wrap = wrap;
Ok(())
}
fn text_selection(&self, widget_id: WidgetId) -> GuiResult<(usize, usize)> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.user_text_selections
.get(&widget_id)
.copied()
.ok_or_else(|| GuiError::UnsupportedCapability("text_selection".to_owned()))
}
fn set_text_selection(
&mut self,
widget_id: WidgetId,
start: usize,
end: usize,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::TextSelection)?;
spec.text_selection = Some((start, end));
Ok(())
}
fn set_text_completion_items(
&mut self,
widget_id: WidgetId,
items: &[String],
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::TextCompletion)?;
spec.completion_items = items.to_vec();
Ok(())
}
fn set_placeholder_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::PlaceholderText)?;
spec.placeholder_text = if text.is_empty() {
None
} else {
Some(text.to_owned())
};
Ok(())
}
fn set_monospace(&mut self, widget_id: WidgetId, monospace: bool) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::Monospace)?;
spec.monospace = monospace;
self.monospace.insert(widget_id, monospace);
Ok(())
}
fn set_font(
&mut self,
widget_id: WidgetId,
font: Option<&native_gui_core::FontDescriptor>,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::Font)?;
if let Some(descriptor) = font {
descriptor
.validate()
.map_err(|error| GuiError::Backend(error.to_string()))?;
}
spec.font = font.cloned();
Ok(())
}
fn set_row_icons(
&mut self,
widget_id: WidgetId,
icons: &[Option<native_gui_core::IconRole>],
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::RowIcons)?;
spec.row_icons = icons.to_vec();
Ok(())
}
fn set_spell_check(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.spell_check.insert(widget_id, enabled);
Ok(())
}
fn set_rich_text_runs(&mut self, widget_id: WidgetId, runs: &[TextRun]) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::RichTextRuns)?;
spec.rich_text_runs = runs.to_vec();
Ok(())
}
fn set_rich_text_images(
&mut self,
widget_id: WidgetId,
images: &[RichTextImage],
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::RichTextImages)?;
spec.rich_text_images = images.to_vec();
self.rich_text_images.insert(widget_id, images.to_vec());
Ok(())
}
fn set_checked(&mut self, widget_id: WidgetId, checked: bool) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::Checked)?;
spec.checked = Some(checked);
Ok(())
}
fn set_value(&mut self, widget_id: WidgetId, value: i32) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::Value)?;
spec.value = Some(value);
Ok(())
}
fn set_range(&mut self, widget_id: WidgetId, min: i32, max: i32) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::Range)?;
spec.range = Some((min, max));
Ok(())
}
fn set_step(&mut self, widget_id: WidgetId, step: i32) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::Step)?;
spec.step = Some(step);
Ok(())
}
fn set_selected_index(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::SelectedIndex)?;
spec.selected_index = Some(index);
Ok(())
}
fn set_selected_indices(&mut self, widget_id: WidgetId, indices: &[usize]) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::SelectedIndices)?;
spec.selected_indices = indices.to_vec();
Ok(())
}
fn set_row_drag(&mut self, widget_id: WidgetId, source: bool, target: bool) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::RowDrag)?;
spec.row_drag_source = source;
spec.row_drop_target = target;
Ok(())
}
fn set_file_drop_target(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.file_drop_target = enabled;
Ok(())
}
fn set_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.size = Some((width, height));
*self.size_writes.entry(widget_id).or_insert(0) += 1;
Ok(())
}
fn set_min_size(&mut self, widget_id: WidgetId, width: i32, height: i32) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
if width == 0 && height == 0 {
self.min_sizes.remove(&widget_id);
} else {
self.min_sizes
.insert(widget_id, (width.max(0), height.max(0)));
}
Ok(())
}
fn set_combo_box_items(&mut self, widget_id: WidgetId, _items: &[String]) -> GuiResult<()> {
let Some(_spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
#[cfg(feature = "widgets-choice")]
if _spec.kind != WidgetKind::ComboBox {
return Err(GuiError::UnsupportedWidget("set_combo_box_items"));
}
#[cfg(not(feature = "widgets-choice"))]
return Err(GuiError::UnsupportedWidget("set_combo_box_items"));
#[cfg(feature = "widgets-choice")]
{
_spec.text = Some(_items.join("|"));
_spec.selected_index = match _spec.selected_index {
Some(index) if index < _items.len() => Some(index),
_ if _items.is_empty() => None,
_ => Some(0),
};
Ok(())
}
}
fn set_data_list_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::DataListItems)?;
spec.data_list_items = items.to_vec();
*self.row_writes.entry(widget_id).or_insert(0) += 1;
Ok(())
}
fn set_list_columns(&mut self, widget_id: WidgetId, columns: &[ColumnSpec]) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ListViewColumns)?;
spec.list_columns = columns.to_vec();
Ok(())
}
fn set_list_rows(&mut self, widget_id: WidgetId, rows: &[Vec<String>]) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ListViewRows)?;
spec.list_rows = rows.to_vec();
Ok(())
}
fn clear_selection(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ClearSelection)?;
spec.selected_index = None;
spec.selected_indices.clear();
self.selection_clears.push(widget_id);
Ok(())
}
fn visible_anchor_index(&self, widget_id: WidgetId) -> GuiResult<Option<usize>> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
Ok(self.scroll_anchors.get(&widget_id).copied())
}
fn scroll_to_row(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
if let Some(error) = self.scroll_failures.get(&widget_id) {
return Err(error.clone());
}
self.scroll_anchors.insert(widget_id, index);
self.scroll_requests.push((widget_id, index));
Ok(())
}
#[cfg(feature = "widgets-data")]
fn rows_end_visible(&self, widget_id: WidgetId) -> GuiResult<bool> {
let spec = self
.created
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
let row_count = match spec.kind {
WidgetKind::DataList => spec.data_list_items.len(),
WidgetKind::ListView if spec.list_columns.is_empty() => spec.data_list_items.len(),
WidgetKind::ListView => spec.list_rows.len(),
WidgetKind::DataGrid => spec.data_grid_rows.len(),
_ => return Err(GuiError::UnsupportedCapability("scroll_anchor".to_owned())),
};
if row_count == 0 {
return Ok(false);
}
let top = self
.scroll_anchors
.get(&widget_id)
.copied()
.ok_or_else(|| GuiError::UnsupportedCapability("scroll_anchor".to_owned()))?;
let visible_rows = self
.visible_row_counts
.get(&widget_id)
.copied()
.unwrap_or(1);
Ok(top.saturating_add(visible_rows) >= row_count)
}
#[cfg(not(feature = "widgets-data"))]
fn rows_end_visible(&self, _widget_id: WidgetId) -> GuiResult<bool> {
Err(GuiError::UnsupportedCapability("scroll_anchor".to_owned()))
}
fn set_tab_items(&mut self, widget_id: WidgetId, items: &[String]) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::TabItems)?;
spec.tab_items = items.to_vec();
Ok(())
}
#[cfg(feature = "widgets-data")]
fn apply_row_delta(
&mut self,
widget_id: WidgetId,
ops: &[native_gui_core::widgets::RowOp],
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
match spec.kind {
WidgetKind::DataGrid => {
spec.ensure_property(WidgetProperty::DataGridRows)?;
let rows = Arc::make_mut(&mut spec.data_grid_rows);
native_gui_core::widgets::apply_row_ops_to_cells(rows, ops);
}
WidgetKind::DataList => {
spec.ensure_property(WidgetProperty::DataListItems)?;
native_gui_core::widgets::apply_row_ops_to_items(&mut spec.data_list_items, ops);
}
WidgetKind::ListView => {
if !spec.list_columns.is_empty() {
spec.ensure_property(WidgetProperty::ListViewRows)?;
native_gui_core::widgets::apply_row_ops_to_cells(&mut spec.list_rows, ops);
} else {
spec.ensure_property(WidgetProperty::DataListItems)?;
native_gui_core::widgets::apply_row_ops_to_items(
&mut spec.data_list_items,
ops,
);
}
}
_ => return Err(GuiError::UnsupportedWidget("apply_row_delta")),
}
*self.row_writes.entry(widget_id).or_insert(0) += 1;
self.applied_row_ops.push((widget_id, ops.to_vec()));
Ok(())
}
#[cfg(not(feature = "widgets-data"))]
fn apply_row_delta(
&mut self,
_widget_id: WidgetId,
_ops: &[native_gui_core::widgets::RowOp],
) -> GuiResult<()> {
Err(GuiError::UnsupportedWidget("apply_row_delta"))
}
fn set_data_grid_rows(
&mut self,
widget_id: WidgetId,
rows: Arc<Vec<Vec<String>>>,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::DataGridRows)?;
spec.data_grid_rows = rows;
*self.row_writes.entry(widget_id).or_insert(0) += 1;
Ok(())
}
fn set_data_grid_model(
&mut self,
widget_id: WidgetId,
model: Box<dyn native_gui_core::widgets::DataGridModel>,
) -> GuiResult<()> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::DataGridModel)?;
self.data_grid_models
.insert(widget_id, RetainedDataGridModel(model));
Ok(())
}
fn set_data_grid_row_height(
&mut self,
widget_id: WidgetId,
row: usize,
height: i32,
) -> GuiResult<()> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::DataGridRowHeight)?;
if height > 0 {
self.data_grid_row_heights.insert((widget_id, row), height);
} else {
self.data_grid_row_heights.remove(&(widget_id, row));
}
Ok(())
}
fn set_data_grid_col_width(
&mut self,
widget_id: WidgetId,
col: usize,
width: i32,
) -> GuiResult<()> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::DataGridColWidth)?;
if width > 0 {
self.data_grid_col_widths.insert((widget_id, col), width);
} else {
self.data_grid_col_widths.remove(&(widget_id, col));
}
Ok(())
}
fn set_data_grid_frozen_panes(
&mut self,
widget_id: WidgetId,
_rows: usize,
_cols: usize,
) -> GuiResult<()> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::DataGridFrozenPanes)?;
Ok(())
}
fn set_data_grid_selection(
&mut self,
widget_id: WidgetId,
selection: &[(usize, usize)],
) -> GuiResult<()> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::DataGridSelection)?;
self.data_grid_selections
.insert(widget_id, selection.to_vec());
Ok(())
}
fn set_tree_items(
&mut self,
widget_id: WidgetId,
items: &[native_gui_core::TreeItem],
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::TreeItems)?;
spec.tree_items = items.to_vec();
Ok(())
}
fn set_position(&mut self, widget_id: WidgetId, x: i32, y: i32) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.position = Some((x, y));
*self.position_writes.entry(widget_id).or_insert(0) += 1;
Ok(())
}
fn natural_size(&self, widget_id: WidgetId) -> Option<(i32, i32)> {
self.natural_size_probes.fetch_add(1, Ordering::Relaxed);
if let Some(&override_size) = self.natural_size_overrides.get(&widget_id) {
return Some(override_size);
}
if !self.natural_sizes {
return None;
}
self.created
.get(&widget_id)
.and_then(Self::mock_natural_size)
}
fn set_background_color(&mut self, widget_id: WidgetId, color: Color) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.background_color = Some(color);
Ok(())
}
fn set_alert_level(&mut self, widget_id: WidgetId, level: AlertLevel) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::AlertLevel)?;
spec.alert_level = Some(level);
Ok(())
}
fn set_image_source(&mut self, widget_id: WidgetId, source: &str) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ImageSource)?;
spec.image_source = Some(source.to_owned());
Ok(())
}
fn set_image_fit(&mut self, widget_id: WidgetId, fit: ImageFit) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ImageFit)?;
spec.image_fit = fit;
Ok(())
}
fn set_file_chooser_mode(
&mut self,
widget_id: WidgetId,
mode: FileChooserMode,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::FileChooserMode)?;
spec.file_chooser_mode = mode;
Ok(())
}
fn set_icon(&mut self, widget_id: WidgetId, icon: Option<IconRole>) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ButtonIcon)?;
spec.icon = icon;
Ok(())
}
fn set_date_value(&mut self, widget_id: WidgetId, iso_date: &str) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::DateValue)?;
spec.date_value = Some(iso_date.to_owned());
Ok(())
}
fn set_link_url(&mut self, widget_id: WidgetId, url: &str) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::LinkUrl)?;
spec.link_url = Some(url.to_owned());
Ok(())
}
fn set_container_direction(
&mut self,
widget_id: WidgetId,
direction: ContainerDirection,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ContainerDirection)?;
spec.container_direction = Some(direction);
Ok(())
}
fn set_container_wrap(&mut self, widget_id: WidgetId, wrap: ContainerWrap) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ContainerWrap)?;
spec.container_wrap = Some(wrap);
Ok(())
}
fn set_container_scroll(
&mut self,
widget_id: WidgetId,
vertical: bool,
horizontal: bool,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ContainerScroll)?;
spec.container_scroll_vertical = vertical;
spec.container_scroll_horizontal = horizontal;
Ok(())
}
fn set_container_gap(&mut self, widget_id: WidgetId, gap: i32) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ContainerGap)?;
spec.container_gap = Some(gap.max(0));
Ok(())
}
fn set_container_padding(&mut self, widget_id: WidgetId, padding: i32) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ContainerPadding)?;
spec.container_padding = Some(padding.max(0));
Ok(())
}
fn draw_demo_cube(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::DrawDemoCube)?;
if self.gpu_fallbacks.contains_key(&widget_id) {
#[cfg(feature = "widgets-canvas")]
let cap = if spec.kind == WidgetKind::MetalCanvas {
"metal_surface"
} else {
"vulkan_surface"
};
#[cfg(not(feature = "widgets-canvas"))]
let cap = "vulkan_surface";
return Err(GuiError::UnsupportedCapability(cap.to_owned()));
}
Ok(())
}
fn create_gpu_fallback(
&mut self,
spec: &WidgetSpec,
policy: GpuDegradationPolicy,
) -> GuiResult<()> {
let _ = spec;
let _ = policy;
#[cfg(feature = "widgets-canvas")]
if spec.kind != WidgetKind::VulkanCanvas && spec.kind != WidgetKind::MetalCanvas {
return Err(GuiError::UnsupportedWidget("vulkan_canvas"));
}
#[cfg(not(feature = "widgets-canvas"))]
return Err(GuiError::UnsupportedWidget("vulkan_canvas"));
#[allow(unreachable_code)]
let capabilities = self.gpu_surface_capabilities();
let supported = match policy {
GpuDegradationPolicy::StrictFail => false,
GpuDegradationPolicy::DiagnosticPlaceholder => capabilities.diagnostic_placeholder,
GpuDegradationPolicy::Canvas2DFallback => capabilities.headless_emulation,
};
if !supported {
return Err(GuiError::UnsupportedCapability(
"gpu_degradation_fallback".to_owned(),
));
}
self.created.insert(spec.id, spec.clone());
self.gpu_fallbacks.insert(spec.id, policy);
Ok(())
}
fn set_canvas_scene(
&mut self,
widget_id: WidgetId,
scene: &native_gui_core::CanvasScene,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
#[cfg(feature = "widgets-canvas")]
let skip_property = spec.kind == WidgetKind::VulkanCanvas
&& self.gpu_fallbacks.get(&widget_id) == Some(&GpuDegradationPolicy::Canvas2DFallback);
#[cfg(not(feature = "widgets-canvas"))]
let skip_property = false;
if !skip_property {
spec.ensure_property(WidgetProperty::CanvasScene)?;
}
spec.canvas_scene = Some(scene.clone());
self.last_canvas_scene = Some(scene.clone());
Ok(())
}
fn set_canvas_surface(
&mut self,
widget_id: WidgetId,
surface: &native_gui_core::CanvasSurface,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::CanvasSurface)?;
spec.canvas_surface = Some(surface.clone());
self.last_canvas_surface = Some(surface.clone());
Ok(())
}
fn native_handle(&self, widget_id: WidgetId) -> GuiResult<Self::NativeHandle> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::NativeHandle)?;
if self.gpu_fallbacks.contains_key(&widget_id) {
return Err(GuiError::UnsupportedCapability("vulkan_surface".to_owned()));
}
Ok(widget_id.0 as usize)
}
fn metal_canvas_handle(
&self,
widget_id: WidgetId,
) -> GuiResult<native_gui_core::ui::MetalCanvasHandle> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::MetalHandle)?;
if self.gpu_fallbacks.contains_key(&widget_id) {
return Err(GuiError::UnsupportedCapability("metal_surface".to_owned()));
}
Ok(native_gui_core::ui::MetalCanvasHandle {
ns_view: widget_id.0 as usize,
ca_metal_layer: widget_id.0 as usize,
mtl_device: widget_id.0 as usize,
})
}
fn add_child(&mut self, parent: WidgetId, child: WidgetId) -> GuiResult<()> {
if !self.created.contains_key(&parent) {
return Err(GuiError::WidgetNotFound(parent.0));
}
let Some(spec) = self.created.get_mut(&child) else {
return Err(GuiError::WidgetNotFound(child.0));
};
spec.parent = Some(parent);
Ok(())
}
fn show(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let spec = self
.created
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if spec.kind == WidgetKind::Window {
if let Some(options) = self.window_options.get(&widget_id).copied() {
if options.show_effect != ShowEffect::None {
self.window_effects.push(MockWindowEffect::Show {
widget_id,
effect: options.show_effect,
});
}
if options.role == WindowRole::Popup {
let mut replaced: Vec<_> = self
.active_popup_sessions
.iter()
.copied()
.filter(|popup| {
*popup != widget_id
&& self.window_options.get(popup).is_some_and(|active| {
active.transient_for == options.transient_for
})
})
.collect();
replaced.sort_by_key(|popup| popup.0);
for popup in replaced {
self.end_popup_session(popup, Some(PopupDismissReason::Replaced));
}
self.active_popup_sessions.insert(widget_id);
}
}
}
self.resume_animation_on_show(widget_id)?;
self.shown.push(widget_id);
Ok(())
}
fn hide(&mut self, widget_id: WidgetId) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.cancel_widget_timers(widget_id, true);
self.pause_animation_on_hide(widget_id);
if let Some(options) = self.window_options.get(&widget_id) {
if options.hide_effect != ShowEffect::None {
self.window_effects.push(MockWindowEffect::Hide {
widget_id,
effect: options.hide_effect,
});
}
}
self.end_popup_session(widget_id, None);
self.shown.retain(|&id| id != widget_id);
Ok(())
}
fn remove(&mut self, widget_id: WidgetId) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.cancel_widget_timers(widget_id, false);
self.cleanup_animation_on_remove(widget_id);
self.cancel_drag_from_source(widget_id);
if let Some((session, target)) = self
.active_drag
.as_ref()
.and_then(|active| active.target.map(|target| (active.id, target)))
.filter(|(_, target)| *target == widget_id)
{
self.mock_drag_exit(session, target);
}
self.created
.remove(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
#[cfg(feature = "webview")]
self.forget_webview(widget_id);
let mut owned_popups: Vec<_> = self
.active_popup_sessions
.iter()
.copied()
.filter(|popup| {
self.window_options
.get(popup)
.is_some_and(|options| options.transient_for == Some(widget_id))
})
.collect();
owned_popups.sort_by_key(|popup| popup.0);
for popup in owned_popups {
self.end_popup_session(popup, None);
}
self.end_popup_session(widget_id, None);
self.window_options.remove(&widget_id);
self.drag_source_options.remove(&widget_id);
self.drag_target_options.remove(&widget_id);
self.gpu_fallbacks.remove(&widget_id);
self.shown.retain(|&id| id != widget_id);
Ok(())
}
fn set_enabled(&mut self, widget_id: WidgetId, enabled: bool) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.enabled = Some(enabled);
Ok(())
}
fn activate(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let kind = spec.kind;
#[cfg(feature = "widgets-pickers")]
if kind == WidgetKind::ColorDialog {
let result = self.color_dialog_results.remove(&widget_id).unwrap_or(None);
if let Some(color) = result {
self.push_event(UiEvent::ColorChanged { widget_id, color });
}
self.push_event(UiEvent::ColorSelected {
widget_id,
color: result,
});
return Ok(());
}
#[cfg(feature = "widgets-pickers")]
if kind == WidgetKind::FontDialog {
let dialog_data = spec.font_dialog_data.clone();
let result = self.font_dialog_results.remove(&widget_id).unwrap_or(None);
if let Some((descriptor, effects)) = result {
let size = dialog_data
.as_ref()
.map(|data| data.clamp_size(descriptor.size_pt))
.unwrap_or(descriptor.size_pt);
let descriptor = FontDescriptor {
size_pt: size,
..descriptor
};
self.push_event(UiEvent::FontChanged {
widget_id,
descriptor: descriptor.clone(),
});
self.push_event(UiEvent::FontSelected {
widget_id,
selection: Some((descriptor, effects)),
});
} else {
self.push_event(UiEvent::FontSelected {
widget_id,
selection: None,
});
}
return Ok(());
}
if kind == WidgetKind::Toolbar {
let first = spec.toolbar_items.iter().find_map(|item| {
item.tool_spec()
.filter(|tool| tool.enabled && tool.visible)
.map(|tool| tool.id)
});
return match first {
Some(tool_id) => self.click_tool(widget_id, tool_id),
None => Ok(()),
};
}
self.events.push_back(UiEvent::Clicked { widget_id });
Ok(())
}
fn set_font_dialog_data(
&mut self,
widget_id: WidgetId,
data: &FontDialogData,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::FontDialogData)?;
spec.font_dialog_data = Some(data.clone());
Ok(())
}
fn set_color_dialog_data(
&mut self,
widget_id: WidgetId,
data: &ColorDialogData,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ColorDialogData)?;
spec.color_dialog_data = Some(data.clone());
Ok(())
}
fn set_toolbar_items(&mut self, widget_id: WidgetId, items: &[ToolbarItem]) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ToolbarItems)?;
spec.toolbar_items = items.to_vec();
Ok(())
}
fn set_toolbar_orientation(
&mut self,
widget_id: WidgetId,
orientation: ToolbarOrientation,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::ToolbarOrientation)?;
spec.toolbar_orientation = orientation;
Ok(())
}
fn set_calendar_selected_dates(
&mut self,
widget_id: WidgetId,
dates: &[CalendarDate],
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::CalendarDates)?;
spec.calendar_selected_dates = dates.to_vec();
Ok(())
}
fn set_calendar_bounds(
&mut self,
widget_id: WidgetId,
min_date: Option<CalendarDate>,
max_date: Option<CalendarDate>,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::CalendarBounds)?;
spec.calendar_min_date = min_date;
spec.calendar_max_date = max_date;
Ok(())
}
fn set_calendar_first_day_of_week(
&mut self,
widget_id: WidgetId,
first_day: CalendarFirstDayOfWeek,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::CalendarFirstDayOfWeek)?;
spec.calendar_first_day_of_week = first_day;
Ok(())
}
fn set_calendar_selection_mode(
&mut self,
widget_id: WidgetId,
mode: CalendarSelectionMode,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.ensure_property(WidgetProperty::CalendarDates)?;
spec.calendar_selection_mode = mode;
spec.calendar_selected_dates.clear();
Ok(())
}
fn data_dir(&self) -> GuiResult<PathBuf> {
Ok(self.app_data_dir.clone().unwrap_or_else(std::env::temp_dir))
}
fn set_clipboard_text(&mut self, text: &str) -> GuiResult<()> {
self.clipboard = Some(text.to_owned());
Ok(())
}
fn paste_image_from_clipboard(
&mut self,
) -> GuiResult<Option<native_gui_core::widgets::ClipboardImage>> {
Ok(self.clipboard_image.clone())
}
fn clipboard_text(&mut self) -> GuiResult<Option<String>> {
Ok(self.clipboard.clone())
}
fn set_tooltip(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.tooltip = Some(text.to_owned());
Ok(())
}
fn set_accessible_name(&mut self, widget_id: WidgetId, name: &str) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.accessibility.name = Some(name.to_owned());
Ok(())
}
fn set_accessible_description(
&mut self,
widget_id: WidgetId,
description: &str,
) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.accessibility.description = Some(description.to_owned());
Ok(())
}
fn post_accessible_notification(
&mut self,
widget_id: WidgetId,
notification: AccessibleNotification,
) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.posted_accessible_notifications
.push((widget_id, notification));
Ok(())
}
fn set_focus(&mut self, widget_id: WidgetId) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
let previous = self.focused.replace(widget_id);
if let Some(previous) = previous {
if previous != widget_id {
self.push_event(UiEvent::FocusChanged {
widget_id: previous,
focused: false,
});
}
}
self.push_event(UiEvent::FocusChanged {
widget_id,
focused: true,
});
Ok(())
}
fn set_focusable(&mut self, widget_id: WidgetId, focusable: bool) -> GuiResult<()> {
let Some(spec) = self.created.get_mut(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
spec.focusable = Some(focusable);
Ok(())
}
fn set_theme(&mut self, theme: &native_gui_core::Theme) -> GuiResult<()> {
self.theme = Some(theme.clone());
Ok(())
}
fn set_theme_override(
&mut self,
widget_id: WidgetId,
theme_override: native_gui_core::ThemeOverride,
) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.theme_overrides
.entry(widget_id)
.or_default()
.push(theme_override);
Ok(())
}
fn clear_theme_overrides(&mut self, widget_id: WidgetId) -> GuiResult<()> {
if !self.created.contains_key(&widget_id) {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
self.theme_overrides.remove(&widget_id);
Ok(())
}
fn theme_capabilities(&self) -> native_gui_core::ThemeCapabilities {
self.theme_capabilities
}
fn system_theme_mode(&self) -> Option<native_gui_core::ThemeMode> {
self.system_theme
}
fn display_capabilities(&self) -> native_gui_core::DisplayCapabilities {
self.display_capabilities
}
fn gpu_surface_capabilities(&self) -> GpuSurfaceCapabilities {
self.gpu_surface_capabilities_override
.unwrap_or_else(GpuSurfaceCapabilities::all)
}
fn displays(&self) -> GuiResult<Vec<native_gui_core::DisplayInfo>> {
if self.displays.is_empty() && !self.display_capabilities.enumeration {
return Err(GuiError::UnsupportedCapability(
"display_metrics".to_owned(),
));
}
Ok(self.displays.clone())
}
fn widget_scale_factor(&self, _widget_id: WidgetId) -> f64 {
self.displays
.iter()
.find(|display| display.primary)
.or_else(|| self.displays.first())
.map(|display| display.scale_factor)
.unwrap_or(1.0)
}
fn wake_handle(&self) -> Option<Arc<dyn Fn() + Send + Sync>> {
let flag = Arc::clone(&self.wake_flag);
let signal = Arc::clone(&self.wake_signal);
Some(Arc::new(move || {
flag.store(true, Ordering::SeqCst);
let (_, cvar) = &*signal;
cvar.notify_all();
}))
}
fn poll_event(&mut self) -> GuiResult<Option<UiEvent>> {
self.service_due_timers()?;
self.service_due_animations()?;
if self.wake_flag.swap(false, Ordering::SeqCst) {
return Ok(Some(UiEvent::TasksPending));
}
Ok(self.pop_pump_event())
}
fn wait_event(&mut self) -> GuiResult<UiEvent> {
loop {
self.service_due_timers()?;
self.service_due_animations()?;
if self.wake_flag.swap(false, Ordering::SeqCst) {
return Ok(UiEvent::TasksPending);
}
let next = self.pop_pump_event();
if let Some(event) = next {
return Ok(event);
}
if self.advance_to_next_timer()? {
continue;
}
let (lock, cvar) = &*self.wake_signal;
let guard = lock.lock().unwrap_or_else(|poison| poison.into_inner());
let _ = cvar.wait_timeout(guard, std::time::Duration::from_millis(5));
}
}
fn capture_window_rgba(
&self,
widget_id: WidgetId,
include_decorations: bool,
) -> GuiResult<(u32, u32, Vec<u8>)> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
if !spec.kind.is_window_like() {
return Err(GuiError::UnsupportedWidget("capture_window_rgba"));
}
let (base_w, base_h) = spec
.size
.map(|(w, h)| (w.max(1) as u32, h.max(1) as u32))
.unwrap_or_else(|| {
if spec.kind.is_dialog() {
(420, 260)
} else {
(800, 600)
}
});
let (w, h) = if include_decorations {
(base_w, base_h.saturating_add(30))
} else {
(base_w, base_h)
};
let mut pixels = Vec::with_capacity((w * h * 4) as usize);
let bg = spec.background_color.unwrap_or(Color {
r: 240,
g: 240,
b: 245,
});
for y in 0..h {
for x in 0..w {
if include_decorations && y < 30 {
pixels.extend_from_slice(&[210, 215, 225, 255]);
} else {
let check = ((x / 16) + (y / 16)) % 2 == 0;
if check {
pixels.extend_from_slice(&[bg.r, bg.g, bg.b, 255]);
} else {
pixels.extend_from_slice(&[
bg.r.saturating_sub(20),
bg.g.saturating_sub(20),
bg.b.saturating_sub(20),
255,
]);
}
}
}
}
Ok((w, h, pixels))
}
fn capture_widget_rgba(&self, widget_id: WidgetId) -> GuiResult<(u32, u32, Vec<u8>)> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
let (w, h) = spec
.size
.map(|(w, h)| (w.max(1) as u32, h.max(1) as u32))
.unwrap_or_else(|| match spec.kind {
WidgetKind::Window => (800, 600),
WidgetKind::Button => (100, 32),
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput => (160, 28),
#[cfg(feature = "widgets-text")]
WidgetKind::TextArea | WidgetKind::RichText => (240, 120),
WidgetKind::Label => (120, 24),
#[cfg(feature = "widgets-range")]
WidgetKind::Slider | WidgetKind::ProgressBar => (150, 24),
#[cfg(feature = "widgets-choice")]
WidgetKind::Checkbox | WidgetKind::RadioButton => (120, 24),
_ => (120, 32),
});
let mut pixels = Vec::with_capacity((w * h * 4) as usize);
let id_factor = (widget_id.0 as u8).wrapping_mul(41);
let bg = spec.background_color.unwrap_or(Color {
r: 220u8.wrapping_add(id_factor),
g: 225u8.wrapping_add(id_factor),
b: 235u8.wrapping_add(id_factor),
});
for y in 0..h {
for x in 0..w {
let border = x == 0 || y == 0 || x == w - 1 || y == h - 1;
if border {
pixels.extend_from_slice(&[100, 105, 115, 255]);
} else {
let check = ((x / 8) + (y / 8)) % 2 == 0;
if check {
pixels.extend_from_slice(&[bg.r, bg.g, bg.b, 255]);
} else {
pixels.extend_from_slice(&[
bg.r.saturating_sub(15),
bg.g.saturating_sub(15),
bg.b.saturating_sub(15),
255,
]);
}
}
}
}
Ok((w, h, pixels))
}
fn native_read_text(&self, widget_id: WidgetId) -> GuiResult<Option<String>> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
Ok(spec.text.clone())
}
fn native_read_checked(&self, widget_id: WidgetId) -> GuiResult<Option<bool>> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
Ok(spec.checked)
}
fn native_click(&self, widget_id: WidgetId) -> GuiResult<bool> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
#[cfg(feature = "widgets-choice")]
let is_clickable = matches!(
spec.kind,
WidgetKind::Button | WidgetKind::Checkbox | WidgetKind::RadioButton
);
#[cfg(not(feature = "widgets-choice"))]
let is_clickable = matches!(spec.kind, WidgetKind::Button);
Ok(is_clickable)
}
fn native_type_text(&self, widget_id: WidgetId, _text: &str) -> GuiResult<bool> {
let Some(spec) = self.created.get(&widget_id) else {
return Err(GuiError::WidgetNotFound(widget_id.0));
};
#[cfg(feature = "widgets-text")]
let is_text = matches!(
spec.kind,
WidgetKind::TextInput | WidgetKind::TextArea | WidgetKind::RichText
);
#[cfg(not(feature = "widgets-text"))]
let is_text = {
let _ = spec;
false
};
Ok(is_text)
}
fn create_tray_icon(&mut self, spec: &TrayIconSpec) -> GuiResult<TrayIconId> {
self.tray_icons
.insert(spec.id, MockTrayIconState::from(spec));
Ok(spec.id)
}
fn destroy_tray_icon(&mut self, id: TrayIconId) -> GuiResult<()> {
self.tray_icons.remove(&id);
Ok(())
}
fn set_tray_icon_tooltip(&mut self, id: TrayIconId, tooltip: &str) -> GuiResult<()> {
if let Some(state) = self.tray_icons.get_mut(&id) {
state.tooltip = tooltip.to_owned();
}
Ok(())
}
fn set_tray_icon_menu(&mut self, id: TrayIconId, menu: Option<MenuId>) -> GuiResult<()> {
if let Some(state) = self.tray_icons.get_mut(&id) {
state.menu = menu;
}
Ok(())
}
fn set_tray_icon_visible(&mut self, id: TrayIconId, visible: bool) -> GuiResult<()> {
if let Some(state) = self.tray_icons.get_mut(&id) {
state.visible = visible;
}
Ok(())
}
fn set_tray_icon_icon(&mut self, id: TrayIconId, icon_bytes: Option<Vec<u8>>) -> GuiResult<()> {
if let Some(state) = self.tray_icons.get_mut(&id) {
state.icon_bytes = icon_bytes;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModalLoopOutcome {
Completed {
dispatched: usize,
},
Deadlocked {
dispatched: usize,
},
}
pub trait MockUiExt {
fn run_modal_loop<F, T>(
&mut self,
script: Vec<UiEvent>,
terminator: T,
handler: F,
) -> GuiResult<ModalLoopOutcome>
where
F: FnMut(&mut Ui<MockBackend>, UiEvent) -> GuiResult<LoopFlow>,
T: Fn(&UiEvent) -> bool;
}
impl MockUiExt for Ui<MockBackend> {
fn run_modal_loop<F, T>(
&mut self,
script: Vec<UiEvent>,
terminator: T,
mut handler: F,
) -> GuiResult<ModalLoopOutcome>
where
F: FnMut(&mut Ui<MockBackend>, UiEvent) -> GuiResult<LoopFlow>,
T: Fn(&UiEvent) -> bool,
{
self.backend_mut().begin_modal_loop();
for event in script {
let scripted = self.backend_mut().script_modal_event(event);
debug_assert!(scripted, "the modal frame was opened just above");
}
let mut terminated = false;
let dispatched = self.dispatch_events_with(|ui, event| {
let closes = terminator(&event);
let flow = handler(ui, event)?;
if closes {
terminated = true;
return Ok(LoopFlow::Exit);
}
Ok(flow)
});
let _leftover = self.backend_mut().end_modal_loop();
let dispatched = dispatched?;
Ok(if terminated {
ModalLoopOutcome::Completed { dispatched }
} else {
ModalLoopOutcome::Deadlocked { dispatched }
})
}
}
#[cfg(feature = "property-grid")]
impl native_gui_core::advanced::PropertyGridBackend for MockBackend {
fn property_grid_capabilities(&self) -> native_gui_core::advanced::PropertyGridCapabilities {
native_gui_core::advanced::PropertyGridCapabilities {
supported: true,
portable: true,
engine: self.advanced_engine.clone(),
native_editors: false,
virtualization: false,
}
}
fn bind_property_model(
&mut self,
host: WidgetId,
model: &native_gui_core::properties::PropertyModel,
) -> GuiResult<()> {
self.property_grid_models.insert(host, model.clone());
Ok(())
}
fn set_property_value(
&mut self,
host: WidgetId,
id: native_gui_core::properties::PropertyId,
value: &native_gui_core::properties::PropertyValue,
) -> GuiResult<()> {
let Some(model) = self.property_grid_models.get_mut(&host) else {
return Err(GuiError::UnsupportedCapability(
"property_grid_unbound".to_owned(),
));
};
model
.set_value(id, value.clone())
.map_err(|error| GuiError::Backend(format!("property model: {error}")))?;
self.property_grid_applied.push((host, id));
Ok(())
}
fn refresh_property_grid(&mut self, host: WidgetId) -> GuiResult<()> {
*self.property_grid_refreshes.entry(host).or_insert(0) += 1;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(feature = "widgets-media"))]
#[test]
fn image_kind_is_refused_when_core_media_is_enabled_without_mock_media() {
let image_kinds = native_gui_core::widgets::ALL_KINDS
.iter()
.copied()
.filter(|kind| WidgetProperty::ImageSource.supports(*kind))
.collect::<Vec<_>>();
let mut backend = MockBackend::default();
if let Some(kind) = image_kinds.first().copied() {
let spec = WidgetSpec::new(WidgetId(1), kind);
assert_eq!(
backend.create_widget(&spec),
Err(GuiError::UnsupportedWidget("unsupported widget kind"))
);
assert!(backend.created.is_empty());
} else {
assert!(WidgetProperty::ImageSource.applicable_kinds().is_empty());
}
}
#[test]
fn test_programmatic_setters_are_silent() {
let mut backend = MockBackend::default();
let _ = &mut backend;
#[cfg(feature = "widgets-text")]
{
let text_input = WidgetId(101);
backend
.create_widget(&WidgetSpec::new(text_input, WidgetKind::TextInput))
.unwrap();
backend.set_text(text_input, "initial").unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
let text_area = WidgetId(102);
backend
.create_widget(&WidgetSpec::new(text_area, WidgetKind::TextArea))
.unwrap();
backend.set_text(text_area, "multiline content").unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
}
#[cfg(feature = "widgets-range")]
{
let slider = WidgetId(201);
backend
.create_widget(&WidgetSpec::new(slider, WidgetKind::Slider))
.unwrap();
backend.set_value(slider, 42).unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
let spin_box = WidgetId(202);
backend
.create_widget(&WidgetSpec::new(spin_box, WidgetKind::SpinBox))
.unwrap();
backend.set_value(spin_box, 99).unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
let progress = WidgetId(203);
backend
.create_widget(&WidgetSpec::new(progress, WidgetKind::ProgressBar))
.unwrap();
backend.set_value(progress, 75).unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
}
#[cfg(feature = "widgets-choice")]
{
let checkbox = WidgetId(301);
backend
.create_widget(&WidgetSpec::new(checkbox, WidgetKind::Checkbox))
.unwrap();
backend.set_checked(checkbox, true).unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
let radio = WidgetId(302);
backend
.create_widget(&WidgetSpec::new(radio, WidgetKind::RadioButton))
.unwrap();
backend.set_checked(radio, true).unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
}
#[cfg(feature = "widgets-choice")]
{
let combo = WidgetId(401);
backend
.create_widget(&WidgetSpec::new(combo, WidgetKind::ComboBox))
.unwrap();
backend.set_selected_index(combo, 2).unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
}
#[cfg(feature = "widgets-data")]
{
let datalist = WidgetId(402);
backend
.create_widget(&WidgetSpec::new(datalist, WidgetKind::DataList))
.unwrap();
backend.set_selected_index(datalist, 1).unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
backend.set_selected_indices(datalist, &[0, 2]).unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
}
#[cfg(feature = "widgets-range")]
{
let slider = WidgetId(201);
backend.set_range(slider, 0, 100).unwrap();
backend.set_step(slider, 5).unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
}
#[cfg(feature = "widgets-pickers")]
{
let date_picker = WidgetId(501);
backend
.create_widget(&WidgetSpec::new(date_picker, WidgetKind::DatePicker))
.unwrap();
backend.set_date_value(date_picker, "2026-10-08").unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
}
#[cfg(feature = "widgets-text")]
{
let link = WidgetId(502);
backend
.create_widget(&WidgetSpec::new(link, WidgetKind::LinkLabel))
.unwrap();
backend.set_link_url(link, "https://example.com").unwrap();
assert_eq!(backend.poll_event().unwrap(), None);
}
}
#[test]
fn test_interaction_and_focus_transitions_emit_events() {
let mut backend = MockBackend::default();
let button = WidgetId(601);
backend
.create_widget(&WidgetSpec::new(button, WidgetKind::Button))
.unwrap();
backend.activate(button).unwrap();
assert_eq!(
backend.poll_event().unwrap(),
Some(UiEvent::Clicked { widget_id: button })
);
let input1 = WidgetId(602);
let input2 = WidgetId(603);
backend
.create_widget(&WidgetSpec::new(input1, WidgetKind::Button))
.unwrap();
backend
.create_widget(&WidgetSpec::new(input2, WidgetKind::Button))
.unwrap();
backend.set_focus(input1).unwrap();
assert_eq!(
backend.poll_event().unwrap(),
Some(UiEvent::FocusChanged {
widget_id: input1,
focused: true
})
);
backend.set_focus(input2).unwrap();
assert_eq!(
backend.poll_event().unwrap(),
Some(UiEvent::FocusChanged {
widget_id: input1,
focused: false
})
);
assert_eq!(
backend.poll_event().unwrap(),
Some(UiEvent::FocusChanged {
widget_id: input2,
focused: true
})
);
}
#[test]
fn with_data_dir_overrides_default_temp_dir() {
let default_backend = MockBackend::default();
assert_eq!(default_backend.data_dir().unwrap(), std::env::temp_dir());
let isolated = PathBuf::from("isolated-mock-data-dir");
let custom_backend = MockBackend::default().with_data_dir(&isolated);
assert_eq!(custom_backend.data_dir().unwrap(), isolated);
}
}