pub mod dialog;
pub mod gallery;
pub mod harness;
pub mod remote;
pub mod visual;
pub use dialog::*;
pub use gallery::*;
pub use harness::*;
pub use remote::*;
pub use visual::*;
use std::collections::{HashMap, HashSet};
use std::marker::PhantomData;
use std::rc::{Rc, Weak};
use std::time::{Duration, Instant};
use crate::MockBackend;
use native_gui_core::access::AccessibleRole;
use native_gui_core::error::{GuiError, GuiResult};
use native_gui_core::events::UiEvent;
use native_gui_core::ui::{Backend, LoopFlow, Ui};
use native_gui_core::widgets::{WidgetId, WidgetKind, WidgetProperty, WidgetSpec};
#[doc(hidden)]
pub trait E2eBackend: Backend + 'static {}
impl<B: Backend + 'static> E2eBackend for B {}
fn parse_key_chord(chord: &str) -> GuiResult<(String, bool, bool, bool)> {
if chord.is_empty() {
return Err(GuiError::Backend(
"e2e.invalid_argument: key chord must not be empty".into(),
));
}
let parts: Vec<&str> = chord.split('+').map(str::trim).collect();
let mut ctrl = false;
let mut shift = false;
let mut alt = false;
let mut key = String::new();
for (i, part) in parts.iter().enumerate() {
if i == parts.len() - 1 && !part.is_empty() {
key = (*part).to_owned();
} else {
match part.to_ascii_lowercase().as_str() {
"ctrl" | "control" => ctrl = true,
"shift" => shift = true,
"alt" => alt = true,
_ => {
if i == parts.len() - 1 {
key = (*part).to_owned();
} else {
return Err(GuiError::Backend(format!(
"e2e.invalid_argument: unknown modifier in key chord: {part}"
)));
}
}
}
}
}
if key.is_empty() {
return Err(GuiError::Backend(
"e2e.invalid_argument: key chord has no main key".into(),
));
}
Ok((key, ctrl, shift, alt))
}
impl MockBackend {
pub(crate) fn e2e_mock_type_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
let new_text = {
let spec = self
.created
.get_mut(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
spec.ensure_property(WidgetProperty::TextSelection)?;
let current = spec.text.as_deref().unwrap_or_default();
let chars: Vec<char> = current.chars().collect();
let (start, end) = spec.text_selection.unwrap_or((chars.len(), chars.len()));
let (start, end) = (start.min(chars.len()), end.min(chars.len()));
if start > end {
return Err(GuiError::Backend(
"E2E text selection is outside the current text".to_owned(),
));
}
let inserted: Vec<char> = text.chars().collect();
let mut updated = Vec::with_capacity(chars.len() - (end - start) + inserted.len());
updated.extend_from_slice(&chars[..start]);
updated.extend(inserted.iter().copied());
updated.extend_from_slice(&chars[end..]);
let caret = start + inserted.len();
let new_text: String = updated.into_iter().collect();
spec.text = Some(new_text.clone());
spec.text_selection = Some((caret, caret));
new_text
};
self.events.push_back(UiEvent::TextChanged {
widget_id,
text: new_text.clone(),
});
Ok(())
}
pub(crate) fn e2e_mock_check(&mut self, widget_id: WidgetId, checked: bool) -> GuiResult<()> {
let changed = {
let spec = self
.created
.get_mut(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
spec.ensure_property(WidgetProperty::Checked)?;
let changed = spec.checked.unwrap_or(false) != checked;
spec.checked = Some(checked);
changed
};
if changed {
self.events
.push_back(UiEvent::Toggled { widget_id, checked });
}
Ok(())
}
pub(crate) fn e2e_mock_press(&mut self, widget_id: WidgetId, chord: &str) -> GuiResult<()> {
let (key, ctrl, shift, alt) = parse_key_chord(chord)?;
self.events.push_back(UiEvent::KeyDown {
widget_id,
key: key.clone(),
ctrl,
shift,
alt,
});
if !ctrl && !alt && key.chars().count() == 1 {
self.events.push_back(UiEvent::Char {
widget_id,
text: key.clone(),
});
}
self.events.push_back(UiEvent::KeyUp {
widget_id,
key,
ctrl,
shift,
alt,
});
Ok(())
}
pub(crate) fn e2e_mock_select(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
let (selected_text, changed) = {
let spec = self
.created
.get_mut(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
spec.ensure_property(WidgetProperty::SelectedIndex)?;
let old = spec.selected_index;
spec.selected_index = Some(index);
let item_text = if !spec.data_list_items.is_empty() {
spec.data_list_items.get(index).cloned()
} else if !spec.tab_items.is_empty() {
spec.tab_items.get(index).cloned()
} else {
None
};
(item_text, old != Some(index))
};
if changed {
self.events.push_back(UiEvent::SelectionChanged {
widget_id,
selected: selected_text,
index: Some(index),
});
}
Ok(())
}
pub(crate) fn e2e_mock_select_text(
&mut self,
widget_id: WidgetId,
start: usize,
end: usize,
) -> GuiResult<()> {
let spec = self
.created
.get_mut(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
spec.ensure_property(WidgetProperty::TextSelection)?;
let len = spec.text.as_deref().unwrap_or_default().chars().count();
if start > end || end > len {
return Err(GuiError::Backend(
"e2e.invalid_argument: text selection is out of bounds".into(),
));
}
spec.text_selection = Some((start, end));
Ok(())
}
pub(crate) fn e2e_mock_set_value(&mut self, widget_id: WidgetId, value: i32) -> GuiResult<()> {
let changed = {
let spec = self
.created
.get_mut(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
spec.ensure_property(WidgetProperty::Value)?;
if let Some((min, max)) = spec.range {
if value < min {
return Err(GuiError::Backend(format!(
"e2e.invalid_argument: value {value} is below min {min}"
)));
}
if value > max {
return Err(GuiError::Backend(format!(
"e2e.invalid_argument: value {value} is above max {max}"
)));
}
}
let changed = spec.value != Some(value);
spec.value = Some(value);
changed
};
if changed {
self.events
.push_back(UiEvent::ValueChanged { widget_id, value });
}
Ok(())
}
pub(crate) fn e2e_mock_scroll(
&mut self,
widget_id: WidgetId,
_delta_x: f64,
delta_y: f64,
) -> GuiResult<()> {
let spec = self
.created
.get_mut(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
let supported = match spec.kind {
WidgetKind::Container => true,
#[cfg(feature = "widgets-text")]
WidgetKind::TextArea => true,
#[cfg(feature = "widgets-data")]
WidgetKind::ListView | WidgetKind::TreeView | WidgetKind::DataGrid => true,
_ => false,
};
if supported {
let row_offset = (delta_y.round() as i32).max(0) as usize;
self.scroll_anchors.insert(widget_id, row_offset);
Ok(())
} else {
Err(GuiError::UnsupportedWidget("e2e.scroll"))
}
}
pub(crate) fn e2e_mock_drag_to(
&mut self,
source_id: WidgetId,
target_id: WidgetId,
) -> GuiResult<()> {
if !self.created.contains_key(&source_id) {
return Err(GuiError::WidgetNotFound(source_id.0));
}
if !self.created.contains_key(&target_id) {
return Err(GuiError::WidgetNotFound(target_id.0));
}
self.events.push_back(UiEvent::DragStarted {
widget_id: source_id,
indices: vec![0],
});
self.events.push_back(UiEvent::Dropped {
widget_id: target_id,
target_index: 0,
source_indices: vec![0],
});
Ok(())
}
pub(crate) fn e2e_mock_close(&mut self, widget_id: WidgetId) -> GuiResult<()> {
let spec = self
.created
.get_mut(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
if !spec.kind.is_window_like() {
return Err(GuiError::UnsupportedWidget("e2e.close"));
}
if self.close_guards.get(&widget_id).copied().unwrap_or(false) {
self.events.push_back(UiEvent::CloseRequested { widget_id });
} else {
self.events.push_back(UiEvent::WindowClosed { widget_id });
self.shown.retain(|id| id != &widget_id);
}
Ok(())
}
pub(crate) fn e2e_mock_value(&self, widget_id: WidgetId) -> GuiResult<i32> {
let spec = self
.created
.get(&widget_id)
.ok_or(GuiError::WidgetNotFound(widget_id.0))?;
spec.value
.ok_or_else(|| GuiError::Backend(format!("widget {} has no value", widget_id.0)))
}
}
pub use native_gui_core::{Capability, InputMode, Operation};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WaitOptions {
pub timeout: Duration,
pub poll_interval: Duration,
}
impl WaitOptions {
pub fn new(timeout: Duration) -> Self {
Self {
timeout,
poll_interval: Duration::from_millis(10),
}
}
pub fn poll_interval(mut self, interval: Duration) -> Self {
self.poll_interval = interval;
self
}
}
impl Default for WaitOptions {
fn default() -> Self {
Self::new(Duration::from_secs(5))
}
}
#[derive(Debug, Clone, Default)]
pub struct Locator {
selectors: Vec<Selector>,
relations: Vec<Relation>,
}
impl Locator {
pub fn id(widget_id: WidgetId) -> Self {
Self::with_selector(Selector::Id(widget_id))
}
pub fn name(name: impl Into<String>) -> Self {
Self::with_selector(Selector::Name(name.into()))
}
pub fn test_id(test_id: impl Into<String>) -> Self {
Self::with_selector(Selector::TestId(test_id.into()))
}
pub fn role(role: AccessibleRole, label: impl Into<String>) -> Self {
Self::with_selector(Selector::Role(role, label.into()))
}
pub fn kind(kind: WidgetKind) -> Self {
Self::with_selector(Selector::Kind(kind))
}
pub fn window() -> Self {
Self::kind(WidgetKind::Window)
}
pub fn dialog() -> Self {
Self::with_selector(Selector::Dialog)
}
pub fn top_level() -> Self {
Self::with_selector(Selector::TopLevel)
}
pub fn text(text: impl Into<String>) -> Self {
Self::with_selector(Selector::Text(text.into()))
}
pub fn child_of(mut self, parent: Locator) -> Self {
self.relations.push(Relation::ChildOf(Box::new(parent)));
self
}
pub fn descendant_of(mut self, ancestor: Locator) -> Self {
self.relations
.push(Relation::DescendantOf(Box::new(ancestor)));
self
}
pub fn in_window(mut self, window: Locator) -> Self {
self.relations.push(Relation::InWindow(Box::new(window)));
self
}
pub fn with_kind(mut self, kind: WidgetKind) -> Self {
self.selectors.push(Selector::Kind(kind));
self
}
pub fn with_text(mut self, text: impl Into<String>) -> Self {
self.selectors.push(Selector::Text(text.into()));
self
}
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.selectors.push(Selector::Name(name.into()));
self
}
pub fn with_test_id(mut self, test_id: impl Into<String>) -> Self {
self.selectors.push(Selector::TestId(test_id.into()));
self
}
pub fn with_role(mut self, role: AccessibleRole, label: impl Into<String>) -> Self {
self.selectors.push(Selector::Role(role, label.into()));
self
}
fn with_selector(selector: Selector) -> Self {
Self {
selectors: vec![selector],
relations: Vec::new(),
}
}
}
#[derive(Debug, Clone)]
enum Selector {
Id(WidgetId),
Name(String),
TestId(String),
Role(AccessibleRole, String),
Kind(WidgetKind),
Text(String),
Dialog,
TopLevel,
}
#[derive(Debug, Clone)]
enum Relation {
ChildOf(Box<Locator>),
DescendantOf(Box<Locator>),
InWindow(Box<Locator>),
}
#[derive(Debug, Clone)]
pub enum CaptureTarget {
Window(WidgetId),
Element(Locator),
Viewport,
Prompt(u64),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CaptureImage {
pub width: u32,
pub height: u32,
pub data: Vec<u8>,
}
pub type RgbaImage = CaptureImage;
impl CaptureImage {
pub fn new(width: u32, height: u32, data: Vec<u8>) -> Self {
Self {
width,
height,
data,
}
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
pub fn data(&self) -> &[u8] {
&self.data
}
pub fn pixels(&self) -> &[u8] {
&self.data
}
pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
if x < self.width && y < self.height {
let idx = ((y * self.width + x) * 4) as usize;
if idx + 4 <= self.data.len() {
return Some([
self.data[idx],
self.data[idx + 1],
self.data[idx + 2],
self.data[idx + 3],
]);
}
}
None
}
pub fn to_png(&self) -> GuiResult<Vec<u8>> {
encode_png_rgba(self.width, self.height, &self.data)
}
pub fn save_png(&self, path: impl AsRef<std::path::Path>) -> GuiResult<()> {
let bytes = self.to_png()?;
std::fs::write(path, bytes)
.map_err(|e| GuiError::Backend(format!("e2e.screenshot: failed to save PNG: {e}")))
}
pub fn from_png(bytes: &[u8]) -> GuiResult<Self> {
decode_png_rgba(bytes)
}
pub fn load_png(path: impl AsRef<std::path::Path>) -> GuiResult<Self> {
let bytes = std::fs::read(path.as_ref()).map_err(|e| {
GuiError::Backend(format!(
"e2e.screenshot: failed to read PNG '{}': {e}",
path.as_ref().display()
))
})?;
Self::from_png(&bytes)
}
pub fn diff(&self, expected: &Self, options: &ImageDiffOptions) -> GuiResult<ImageDiffResult> {
compare_images(self, expected, options, &[])
}
}
const CRC_TABLE: [u32; 256] = {
let mut table = [0u32; 256];
let mut i = 0;
while i < 256 {
let mut c = i as u32;
let mut k = 0;
while k < 8 {
if c & 1 != 0 {
c = 0xEDB8_8320 ^ (c >> 1);
} else {
c >>= 1;
}
k += 1;
}
table[i] = c;
i += 1;
}
table
};
fn crc32_update(mut crc: u32, data: &[u8]) -> u32 {
for &byte in data {
crc = CRC_TABLE[((crc ^ (byte as u32)) & 0xFF) as usize] ^ (crc >> 8);
}
crc
}
fn adler32(data: &[u8]) -> u32 {
let mut s1 = 1u32;
let mut s2 = 0u32;
for &byte in data {
s1 = (s1 + byte as u32) % 65521;
s2 = (s2 + s1) % 65521;
}
(s2 << 16) | s1
}
fn write_png_chunk(out: &mut Vec<u8>, chunk_type: &[u8; 4], data: &[u8]) {
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(chunk_type);
out.extend_from_slice(data);
let mut crc = 0xFFFF_FFFFu32;
crc = crc32_update(crc, chunk_type);
crc = crc32_update(crc, data);
out.extend_from_slice(&(!crc).to_be_bytes());
}
fn encode_png_rgba(width: u32, height: u32, rgba_data: &[u8]) -> GuiResult<Vec<u8>> {
let expected_len = (width as usize)
.checked_mul(height as usize)
.and_then(|px| px.checked_mul(4))
.ok_or_else(|| GuiError::Backend("e2e.png: dimensions overflow".to_owned()))?;
if rgba_data.len() != expected_len {
return Err(GuiError::Backend(format!(
"e2e.png: pixel buffer length {} does not match dimensions {}x{} (expected {})",
rgba_data.len(),
width,
height,
expected_len
)));
}
let mut out = Vec::new();
out.extend_from_slice(&[137, 80, 78, 71, 13, 10, 26, 10]);
let mut ihdr_data = Vec::with_capacity(13);
ihdr_data.extend_from_slice(&width.to_be_bytes());
ihdr_data.extend_from_slice(&height.to_be_bytes());
ihdr_data.push(8); ihdr_data.push(6); ihdr_data.push(0); ihdr_data.push(0); ihdr_data.push(0); write_png_chunk(&mut out, b"IHDR", &ihdr_data);
let stride = (width as usize) * 4;
let filtered_len = (height as usize) * (1 + stride);
let mut filtered = Vec::with_capacity(filtered_len);
for y in 0..(height as usize) {
filtered.push(0); let start = y * stride;
filtered.extend_from_slice(&rgba_data[start..start + stride]);
}
let mut zlib_stream = Vec::new();
zlib_stream.push(0x78); zlib_stream.push(0x01);
let mut offset = 0;
let total = filtered.len();
if total == 0 {
zlib_stream.push(0x01);
zlib_stream.extend_from_slice(&0u16.to_le_bytes());
zlib_stream.extend_from_slice(&0xFFFFu16.to_le_bytes());
} else {
while offset < total {
let chunk_len = (total - offset).min(65535);
let is_final = (offset + chunk_len) == total;
zlib_stream.push(if is_final { 0x01 } else { 0x00 });
let len_u16 = chunk_len as u16;
let nlen_u16 = !len_u16;
zlib_stream.extend_from_slice(&len_u16.to_le_bytes());
zlib_stream.extend_from_slice(&nlen_u16.to_le_bytes());
zlib_stream.extend_from_slice(&filtered[offset..offset + chunk_len]);
offset += chunk_len;
}
}
let checksum = adler32(&filtered);
zlib_stream.extend_from_slice(&checksum.to_be_bytes());
write_png_chunk(&mut out, b"IDAT", &zlib_stream);
write_png_chunk(&mut out, b"IEND", &[]);
Ok(out)
}
struct RasterCanvas<'a> {
buffer: &'a mut [u8],
width: u32,
height: u32,
}
impl RasterCanvas<'_> {
fn new(buffer: &mut [u8], width: u32, height: u32) -> RasterCanvas<'_> {
RasterCanvas {
buffer,
width,
height,
}
}
fn draw_rect(&mut self, x: i32, y: i32, w: u32, h: u32, color: [u8; 4]) {
let x_start = x.max(0) as u32;
let y_start = y.max(0) as u32;
let x_end = ((x + w as i32).max(0) as u32).min(self.width);
let y_end = ((y + h as i32).max(0) as u32).min(self.height);
for cy in y_start..y_end {
for cx in x_start..x_end {
let idx = ((cy * self.width + cx) * 4) as usize;
self.buffer[idx..idx + 4].copy_from_slice(&color);
}
}
}
fn draw_border(&mut self, x: i32, y: i32, w: u32, h: u32, color: [u8; 4]) {
if w == 0 || h == 0 {
return;
}
self.draw_rect(x, y, w, 1, color);
self.draw_rect(x, y + h as i32 - 1, w, 1, color);
self.draw_rect(x, y, 1, h, color);
self.draw_rect(x + w as i32 - 1, y, 1, h, color);
}
fn draw_text_indicator(&mut self, x: i32, y: i32, w: u32, h: u32, text: &str, color: [u8; 4]) {
if text.is_empty() || w < 8 || h < 4 {
return;
}
let text_len = text.chars().count();
let line_len = (text_len * 6).min((w as usize).saturating_sub(8)).max(4) as u32;
let cy = y + (h as i32) / 2;
let cx = x + 4;
self.draw_rect(cx, cy, line_len, 2.min(h), color);
}
fn blit(&mut self, x: i32, y: i32, src: &[u8], src_w: u32, src_h: u32) {
let x_start = x.max(0) as u32;
let y_start = y.max(0) as u32;
let x_end = ((x + src_w as i32).max(0) as u32).min(self.width);
let y_end = ((y + src_h as i32).max(0) as u32).min(self.height);
for dy in y_start..y_end {
let sy = (dy as i32 - y) as u32;
let dst_row_start = ((dy * self.width + x_start) * 4) as usize;
let src_row_start = ((sy * src_w + (x_start as i32 - x) as u32) * 4) as usize;
let copy_len = ((x_end - x_start) * 4) as usize;
if dst_row_start + copy_len <= self.buffer.len()
&& src_row_start + copy_len <= src.len()
{
self.buffer[dst_row_start..dst_row_start + copy_len]
.copy_from_slice(&src[src_row_start..src_row_start + copy_len]);
}
}
}
fn render_mock_widget_raster(&mut self, x: i32, y: i32, w: u32, h: u32, spec: &WidgetSpec) {
let bg_color = if let Some(c) = spec.background_color {
[c.r, c.g, c.b, 255]
} else {
match spec.kind {
WidgetKind::Button => [66, 133, 244, 255],
#[cfg(feature = "widgets-text")]
WidgetKind::LinkLabel => [240, 244, 255, 255],
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput | WidgetKind::TextArea => [255, 255, 255, 255],
#[cfg(feature = "widgets-choice")]
WidgetKind::Checkbox | WidgetKind::RadioButton => [245, 245, 245, 255],
#[cfg(feature = "widgets-range")]
WidgetKind::Slider | WidgetKind::ProgressBar => [52, 168, 83, 255],
WidgetKind::Label => [235, 235, 238, 255],
WidgetKind::Container => [240, 242, 245, 255],
#[cfg(feature = "widgets-containers")]
WidgetKind::GroupBox => [240, 242, 245, 255],
#[cfg(feature = "widgets-data")]
WidgetKind::ListView | WidgetKind::TreeView | WidgetKind::DataGrid => {
[250, 250, 250, 255]
}
_ => [220, 222, 226, 255],
}
};
let border_color = match spec.kind {
WidgetKind::Button => [40, 100, 200, 255],
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput | WidgetKind::TextArea => [180, 184, 192, 255],
_ => [170, 175, 185, 255],
};
self.draw_rect(x, y, w, h, bg_color);
self.draw_border(x, y, w, h, border_color);
#[cfg(feature = "widgets-choice")]
if spec.kind == WidgetKind::Checkbox {
let box_size = 14u32.min(h.saturating_sub(4));
let bx = x + 4;
let by = y + ((h as i32) - box_size as i32) / 2;
self.draw_rect(bx, by, box_size, box_size, [255, 255, 255, 255]);
self.draw_border(bx, by, box_size, box_size, [100, 100, 100, 255]);
if spec.checked == Some(true) {
let inner_size = box_size.saturating_sub(4);
self.draw_rect(bx + 2, by + 2, inner_size, inner_size, [30, 140, 30, 255]);
}
}
if let Some(text) = &spec.text {
let text_color = match spec.kind {
WidgetKind::Button => [255, 255, 255, 255],
#[cfg(feature = "widgets-text")]
WidgetKind::LinkLabel => [25, 103, 210, 255],
_ => [40, 44, 52, 255],
};
#[cfg(feature = "widgets-choice")]
let is_checkbox = spec.kind == WidgetKind::Checkbox;
#[cfg(not(feature = "widgets-choice"))]
let is_checkbox = false;
let text_x = if is_checkbox { x + 24 } else { x + 6 };
self.draw_text_indicator(text_x, y, w.saturating_sub(12), h, text, text_color);
}
}
}
pub struct Driver<B: E2eBackend, H> {
ui: Ui<B>,
handler: H,
names: HashMap<String, WidgetId>,
test_ids: HashMap<String, WidgetId>,
session: Rc<()>,
requested_mode: Option<InputMode>,
exited: bool,
action_timeout: Duration,
active_modal: Option<WidgetId>,
}
impl<B: E2eBackend, H> Driver<B, H> {
pub fn new(ui: Ui<B>, handler: H) -> Self
where
H: FnMut(&mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
Self {
ui,
handler,
names: HashMap::new(),
test_ids: HashMap::new(),
session: Rc::new(()),
requested_mode: None,
exited: false,
action_timeout: Duration::from_millis(100),
active_modal: None,
}
}
pub fn with_input_mode(mut self, mode: InputMode) -> Self {
self.requested_mode = Some(mode);
self
}
pub fn with_action_timeout(mut self, timeout: Duration) -> Self {
self.action_timeout = timeout;
self
}
pub fn action_timeout(&self) -> Duration {
self.action_timeout
}
pub fn set_active_modal(&mut self, modal_id: Option<WidgetId>) {
self.active_modal = modal_id;
}
pub fn active_modal(&self) -> Option<WidgetId> {
self.active_modal
}
pub fn is_modal_eligible(&self, widget_id: WidgetId) -> GuiResult<bool> {
if let Some(modal_id) = self.active_modal {
let mut cursor = Some(widget_id);
let mut visited = HashSet::new();
while let Some(id) = cursor {
if id == modal_id {
return Ok(true);
}
if !visited.insert(id) {
return Err(GuiError::Backend(
"E2E widget graph contains a parent cycle".to_owned(),
));
}
let spec = self.ui.widget(id).ok_or(GuiError::WidgetNotFound(id.0))?;
cursor = spec.parent;
}
return Ok(false);
}
Ok(true)
}
pub fn capability(&self, element: &Element, operation: Operation) -> GuiResult<Capability> {
let spec = self.validate_element(element)?;
let backend_cap = self
.ui
.backend()
.e2e_capability(element.widget_id, operation)?;
if matches!(backend_cap, Capability::Supported { .. }) {
return Ok(backend_cap);
}
self.extended_capability(element.widget_id, spec, operation)
}
fn extended_capability(
&self,
_widget_id: WidgetId,
spec: &WidgetSpec,
operation: Operation,
) -> GuiResult<Capability> {
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
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
}
Operation::Check | Operation::Checked => {
#[cfg(feature = "widgets-choice")]
{
spec.kind == WidgetKind::Checkbox
}
#[cfg(not(feature = "widgets-choice"))]
{
false
}
}
Operation::Text => true,
Operation::Press => {
#[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
}
Operation::Select => match spec.kind {
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput | WidgetKind::TextArea => true,
#[cfg(feature = "widgets-containers")]
WidgetKind::Tabs => true,
#[cfg(feature = "widgets-choice")]
WidgetKind::ComboBox | WidgetKind::MultiSelect => true,
#[cfg(feature = "widgets-data")]
WidgetKind::ListView
| WidgetKind::TreeView
| WidgetKind::DataList
| WidgetKind::DataGrid => true,
_ => false,
},
Operation::SetValue => {
#[cfg(feature = "widgets-range")]
{
matches!(
spec.kind,
WidgetKind::Slider | WidgetKind::SpinBox | WidgetKind::ProgressBar
)
}
#[cfg(not(feature = "widgets-range"))]
{
false
}
}
Operation::Scroll => match spec.kind {
WidgetKind::Container => true,
#[cfg(feature = "widgets-text")]
WidgetKind::TextArea => true,
#[cfg(feature = "widgets-data")]
WidgetKind::ListView | WidgetKind::TreeView | WidgetKind::DataGrid => true,
_ => false,
},
Operation::DragTo | Operation::Screenshot => true,
Operation::Close => spec.kind.is_window_like(),
};
return Ok(if supported {
Capability::Supported {
mode: InputMode::Simulated,
}
} else {
Capability::Unsupported {
reason: format!(
"{} is not implemented for {:?}",
operation.name(),
spec.kind
),
}
});
}
if self.backend_name() == "win32" {
let supported = match operation {
Operation::Click => spec.kind == WidgetKind::Button,
Operation::Text => {
#[cfg(feature = "widgets-text")]
let is_text = matches!(spec.kind, WidgetKind::TextInput | WidgetKind::TextArea);
#[cfg(not(feature = "widgets-text"))]
let is_text = false;
#[cfg(feature = "widgets-choice")]
let is_checkbox = spec.kind == WidgetKind::Checkbox;
#[cfg(not(feature = "widgets-choice"))]
let is_checkbox = false;
matches!(
spec.kind,
WidgetKind::Button | WidgetKind::Label | WidgetKind::Window
) || is_checkbox
|| is_text
}
Operation::Check | Operation::Checked => {
#[cfg(feature = "widgets-choice")]
{
spec.kind == WidgetKind::Checkbox
}
#[cfg(not(feature = "widgets-choice"))]
{
false
}
}
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
}
Operation::Close => spec.kind == WidgetKind::Window,
Operation::SetValue => {
#[cfg(feature = "widgets-range")]
{
matches!(spec.kind, WidgetKind::Slider | WidgetKind::SpinBox)
}
#[cfg(not(feature = "widgets-range"))]
{
false
}
}
_ => false,
};
return Ok(if supported {
Capability::Supported {
mode: InputMode::SemanticNative,
}
} else {
Capability::Unsupported {
reason: format!(
"{} has no Win32 E2E mapping for {:?}",
operation.name(),
spec.kind
),
}
});
}
if self.backend_name() == "gtk" {
let supported = match operation {
Operation::Close => spec.kind == WidgetKind::Window,
_ => false,
};
if supported {
return Ok(Capability::Supported {
mode: InputMode::SemanticNative,
});
}
}
Ok(Capability::Unsupported {
reason: format!(
"{} has no E2E mapping for {:?}",
operation.name(),
spec.kind
),
})
}
fn require_operation(&self, element: &Element, operation: Operation) -> GuiResult<()> {
self.ensure_running()?;
match self.capability(element, operation)? {
Capability::Supported { mode }
if self
.requested_mode
.is_none_or(|requested| requested == mode) =>
{
Ok(())
}
_ => Err(GuiError::UnsupportedWidget(operation.name())),
}
}
fn ensure_running(&self) -> GuiResult<()> {
if self.exited {
Err(GuiError::Backend(
"e2e.session: application handler exited".into(),
))
} else {
Ok(())
}
}
pub fn ui(&self) -> &Ui<B> {
&self.ui
}
pub fn ui_mut(&mut self) -> &mut Ui<B> {
&mut self.ui
}
pub fn bind_name(&mut self, widget_id: WidgetId, name: impl Into<String>) -> GuiResult<()> {
self.bind(widget_id, name.into(), false)
}
pub fn bind_test_id(
&mut self,
widget_id: WidgetId,
test_id: impl Into<String>,
) -> GuiResult<()> {
self.bind(widget_id, test_id.into(), true)
}
pub fn find_all(&self, locator: &Locator) -> GuiResult<Vec<Element>> {
let mut matches = Vec::new();
for spec in self.ui.e2e_widget_specs() {
if self.matches_locator(spec.id, locator)? {
matches.push(spec.id);
}
}
matches.sort_by_key(|id| id.0);
Ok(matches
.into_iter()
.map(|widget_id| self.element(widget_id))
.collect())
}
pub fn find(&self, locator: &Locator) -> GuiResult<Option<Element>> {
let mut matches = self.find_all(locator)?;
match matches.len() {
0 => Ok(None),
1 => Ok(matches.pop()),
count => Err(GuiError::Backend(format!(
"E2E locator matched {count} widgets; expected at most one"
))),
}
}
pub fn expect_one(&self, locator: &Locator) -> GuiResult<Element> {
self.find(locator)?.ok_or_else(|| {
GuiError::Backend("E2E locator matched no widgets; expected exactly one".to_owned())
})
}
pub fn wait_for(&mut self, locator: &Locator, options: WaitOptions) -> GuiResult<Element>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
self.ensure_running()?;
let deadline = self.deadline(options)?;
loop {
if let Some(element) = self.find(locator)? {
return Ok(element);
}
if Instant::now() >= deadline {
return Err(GuiError::Backend(
"e2e.timeout: locator wait timed out".to_owned(),
));
}
self.pump()?;
self.ensure_running()?;
self.pause_until(deadline, options)?;
}
}
pub fn wait_until<F>(&mut self, options: WaitOptions, mut predicate: F) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
F: FnMut(&mut Self) -> GuiResult<bool>,
{
self.ensure_running()?;
let deadline = self.deadline(options)?;
loop {
if predicate(self)? {
return Ok(());
}
if Instant::now() >= deadline {
return Err(GuiError::Backend(
"e2e.timeout: predicate wait timed out".to_owned(),
));
}
self.pump()?;
self.ensure_running()?;
self.pause_until(deadline, options)?;
}
}
pub fn screenshot(&mut self, target: CaptureTarget) -> GuiResult<CaptureImage> {
self.ensure_running()?;
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
return self.mock_screenshot(target);
}
let bname = self.backend_name();
if bname == "gtk" || bname == "win32" || bname == "cocoa" {
let (w, h, data) = match target {
CaptureTarget::Window(wid) => {
let include_decorations = bname == "win32";
self.ui
.backend()
.capture_window_rgba(wid, include_decorations)?
}
CaptureTarget::Element(loc) => {
let elem = self.expect_one(&loc)?;
self.ui.backend().capture_widget_rgba(elem.widget_id)?
}
CaptureTarget::Viewport => {
let window_id = self
.ui
.e2e_widget_specs()
.find(|s| s.kind == WidgetKind::Window && self.ui.is_visible(s.id))
.map(|s| s.id)
.ok_or_else(|| {
GuiError::Backend(format!(
"{bname} capture: no active window for Viewport target"
))
})?;
self.ui.backend().capture_window_rgba(window_id, true)?
}
CaptureTarget::Prompt(_) => {
return Err(GuiError::UnsupportedCapability(format!(
"e2e.screenshot.prompt: {bname} system prompts cannot be captured"
)));
}
};
return Ok(CaptureImage::new(w, h, data));
}
Err(GuiError::UnsupportedCapability("e2e.screenshot".to_owned()))
}
fn mock_screenshot(&mut self, target: CaptureTarget) -> GuiResult<CaptureImage> {
match target {
CaptureTarget::Prompt(token) => self.mock_prompt_screenshot(token),
CaptureTarget::Element(locator) => {
let element = self.expect_one(&locator)?;
let spec = self
.ui
.widget(element.widget_id)
.ok_or(GuiError::WidgetNotFound(element.widget_id.0))?
.clone();
if !self.ui.is_visible(element.widget_id) {
return Err(GuiError::Backend(format!(
"e2e.screenshot: widget {} is not visible",
element.widget_id.0
)));
}
let (w, h) = Self::mock_widget_dimensions(&spec);
let mut buffer = vec![0u8; (w * h * 4) as usize];
let mut canvas = RasterCanvas::new(&mut buffer, w, h);
canvas.render_mock_widget_raster(0, 0, w, h, &spec);
let children: Vec<WidgetSpec> = self
.ui
.e2e_widget_specs()
.filter(|s| s.parent == Some(element.widget_id) && self.ui.is_visible(s.id))
.cloned()
.collect();
for (idx, child_spec) in children.iter().enumerate() {
let (cw, ch) = Self::mock_widget_dimensions(child_spec);
let (cx, cy) = child_spec.position.unwrap_or((10, 10 + (idx as i32) * 36));
canvas.render_mock_widget_raster(cx, cy, cw, ch, child_spec);
}
Ok(CaptureImage::new(w, h, buffer))
}
CaptureTarget::Window(window_id) => {
let win_spec = self
.ui
.widget(window_id)
.ok_or(GuiError::WidgetNotFound(window_id.0))?
.clone();
if !win_spec.kind.is_window_like() {
return Err(GuiError::UnsupportedWidget("e2e.screenshot.window"));
}
if !self.ui.is_visible(window_id) {
return Err(GuiError::Backend(format!(
"e2e.screenshot: window {} is not visible",
window_id.0
)));
}
let (win_w, win_h) = Self::mock_widget_dimensions(&win_spec);
let mut buffer = vec![0u8; (win_w * win_h * 4) as usize];
let bg_color = win_spec
.background_color
.map(|c| [c.r, c.g, c.b, 255])
.unwrap_or([245, 245, 247, 255]);
let mut canvas = RasterCanvas::new(&mut buffer, win_w, win_h);
canvas.draw_rect(0, 0, win_w, win_h, bg_color);
if win_h >= 28 {
canvas.draw_rect(0, 0, win_w, 28, [225, 227, 232, 255]);
canvas.draw_border(0, 0, win_w, 28, [200, 202, 208, 255]);
if let Some(title) = &win_spec.text {
canvas.draw_text_indicator(
12,
4,
win_w.saturating_sub(24),
20,
title,
[50, 50, 50, 255],
);
}
}
canvas.draw_border(0, 0, win_w, win_h, [160, 164, 172, 255]);
let descendants = self.collect_visible_descendants(window_id)?;
for (idx, child_spec) in descendants.iter().enumerate() {
let (cw, ch) = Self::mock_widget_dimensions(child_spec);
let (rel_x, rel_y) = self
.relative_position(child_spec.id, window_id)?
.unwrap_or((16, 36 + (idx as i32) * 40));
canvas.render_mock_widget_raster(rel_x, rel_y, cw, ch, child_spec);
}
Ok(CaptureImage::new(win_w, win_h, buffer))
}
CaptureTarget::Viewport => {
let visible_windows: Vec<WidgetSpec> = self
.ui
.e2e_widget_specs()
.filter(|s| s.kind.is_window_like() && self.ui.is_visible(s.id))
.cloned()
.collect();
let mut vp_w = 800u32;
let mut vp_h = 600u32;
for win in &visible_windows {
let (ww, wh) = Self::mock_widget_dimensions(win);
let (wx, wy) = win.position.unwrap_or((0, 0));
let right = (wx.max(0) as u32) + ww;
let bottom = (wy.max(0) as u32) + wh;
vp_w = vp_w.max(right);
vp_h = vp_h.max(bottom);
}
let mut buffer = vec![0u8; (vp_w * vp_h * 4) as usize];
let mut canvas = RasterCanvas::new(&mut buffer, vp_w, vp_h);
canvas.draw_rect(0, 0, vp_w, vp_h, [38, 42, 51, 255]);
for win in &visible_windows {
let (wx, wy) = win.position.unwrap_or((10, 10));
let win_capture = self.mock_screenshot(CaptureTarget::Window(win.id))?;
canvas.blit(
wx,
wy,
&win_capture.data,
win_capture.width,
win_capture.height,
);
}
Ok(CaptureImage::new(vp_w, vp_h, buffer))
}
}
}
fn mock_prompt_screenshot(&self, token: u64) -> GuiResult<CaptureImage> {
let any_backend: &dyn std::any::Any = self.ui.backend();
let mock = any_backend
.downcast_ref::<MockBackend>()
.ok_or_else(|| GuiError::UnsupportedCapability("e2e.screenshot.prompt".to_owned()))?;
let (title, lines, buttons): (String, Vec<String>, [&str; 2]) =
if let Some((_, title, message)) = mock
.confirm_requests
.iter()
.find(|(pending, _, _)| *pending == token)
{
(
title.clone(),
message.lines().map(str::to_owned).collect(),
["Cancel", "OK"],
)
} else if let Some((_, request)) = mock
.file_dialog_requests
.iter()
.find(|(pending, _)| *pending == token)
{
let mut lines = vec![format!("{:?}", request.mode)];
if let Some(folder) = &request.folder {
lines.push(folder.display().to_string());
}
if let Some(name) = &request.suggested_name {
lines.push(name.clone());
}
for filter in &request.filters {
lines.push(format!("{} ({})", filter.name, filter.patterns.join(", ")));
}
(
request.title.clone().unwrap_or_else(|| "File".to_owned()),
lines,
["Cancel", "Open"],
)
} else {
return Err(GuiError::Backend(format!(
"e2e.screenshot: no pending prompt with token {token}"
)));
};
let (w, h) = (420u32, 240u32);
let mut buffer = vec![0u8; (w * h * 4) as usize];
let mut canvas = RasterCanvas::new(&mut buffer, w, h);
canvas.draw_rect(0, 0, w, h, [250, 250, 252, 255]);
canvas.draw_rect(0, 0, w, 28, [225, 227, 232, 255]);
canvas.draw_border(0, 0, w, 28, [200, 202, 208, 255]);
canvas.draw_text_indicator(12, 4, w - 24, 20, &title, [50, 50, 50, 255]);
for (idx, line) in lines.iter().take(6).enumerate() {
canvas.draw_text_indicator(
16,
40 + idx as i32 * 22,
w - 32,
20,
line,
[70, 70, 70, 255],
);
}
for (idx, label) in buttons.iter().enumerate() {
let x = w as i32 - 232 + idx as i32 * 112;
canvas.draw_rect(x, h as i32 - 48, 100, 32, [232, 234, 238, 255]);
canvas.draw_border(x, h as i32 - 48, 100, 32, [160, 164, 172, 255]);
canvas.draw_text_indicator(x, h as i32 - 48, 100, 32, label, [40, 40, 40, 255]);
}
canvas.draw_border(0, 0, w, h, [160, 164, 172, 255]);
Ok(CaptureImage::new(w, h, buffer))
}
fn mock_widget_dimensions(spec: &WidgetSpec) -> (u32, u32) {
if let Some((w, h)) = spec.size {
if w > 0 && h > 0 {
return (w as u32, h as u32);
}
}
match spec.kind {
WidgetKind::Window => (800, 600),
#[cfg(feature = "widgets-containers")]
WidgetKind::AlertDialog => (420, 240),
#[cfg(feature = "widgets-pickers")]
WidgetKind::FileChooserDialog | WidgetKind::ColorDialog | WidgetKind::FontDialog => {
(420, 240)
}
WidgetKind::Container => (320, 200),
#[cfg(feature = "widgets-containers")]
WidgetKind::GroupBox | WidgetKind::SplitPane | WidgetKind::Tabs => (320, 200),
WidgetKind::Button => (100, 32),
#[cfg(feature = "widgets-text")]
WidgetKind::LinkLabel => (100, 32),
#[cfg(feature = "widgets-text")]
WidgetKind::TextInput => (160, 28),
#[cfg(feature = "widgets-text")]
WidgetKind::TextArea => (240, 120),
#[cfg(feature = "widgets-choice")]
WidgetKind::Checkbox | WidgetKind::RadioButton => (120, 24),
#[cfg(feature = "widgets-range")]
WidgetKind::Slider | WidgetKind::ProgressBar => (160, 24),
#[cfg(feature = "widgets-range")]
WidgetKind::SpinBox => (80, 24),
#[cfg(all(feature = "widgets-choice", feature = "widgets-data"))]
WidgetKind::ComboBox | WidgetKind::DataList | WidgetKind::MultiSelect => (140, 28),
#[cfg(all(feature = "widgets-choice", not(feature = "widgets-data")))]
WidgetKind::ComboBox | WidgetKind::MultiSelect => (140, 28),
#[cfg(all(not(feature = "widgets-choice"), feature = "widgets-data"))]
WidgetKind::DataList => (140, 28),
WidgetKind::Label => (100, 20),
#[cfg(feature = "widgets-data")]
WidgetKind::ListView | WidgetKind::TreeView | WidgetKind::DataGrid => (220, 160),
#[cfg(feature = "widgets-canvas")]
WidgetKind::Canvas | WidgetKind::VulkanCanvas => (300, 200),
_ => (100, 30),
}
}
fn collect_visible_descendants(&self, root_id: WidgetId) -> GuiResult<Vec<WidgetSpec>> {
let mut result = Vec::new();
let all = self.ui.e2e_widget_specs();
for spec in all {
if spec.id == root_id || !self.ui.is_visible(spec.id) {
continue;
}
let mut cursor = spec.parent;
let mut visited = HashSet::new();
while let Some(parent_id) = cursor {
if parent_id == root_id {
result.push(spec.clone());
break;
}
if !visited.insert(parent_id) {
break;
}
cursor = self.ui.widget(parent_id).and_then(|p| p.parent);
}
}
result.sort_by_key(|s| s.id.0);
Ok(result)
}
fn relative_position(
&self,
widget_id: WidgetId,
root_id: WidgetId,
) -> GuiResult<Option<(i32, i32)>> {
let mut total_x = 0;
let mut total_y = 0;
let mut cursor = Some(widget_id);
let mut visited = HashSet::new();
let mut has_pos = false;
while let Some(id) = cursor {
if id == root_id {
return Ok(if has_pos {
Some((total_x, total_y))
} else {
None
});
}
if !visited.insert(id) {
return Ok(None);
}
if let Some(spec) = self.ui.widget(id) {
if let Some((x, y)) = spec.position {
total_x += x;
total_y += y;
has_pos = true;
}
cursor = spec.parent;
} else {
return Ok(None);
}
}
Ok(None)
}
fn bind(&mut self, widget_id: WidgetId, value: String, test_id: bool) -> GuiResult<()> {
if value.is_empty() {
return Err(GuiError::Backend(
"E2E names and test ids must not be empty".to_owned(),
));
}
if self.ui.widget(widget_id).is_none() {
return Err(GuiError::WidgetNotFound(widget_id.0));
}
let registry = if test_id {
&mut self.test_ids
} else {
&mut self.names
};
registry.retain(|_, existing_id| self.ui.widget(*existing_id).is_some());
if registry
.get(&value)
.is_some_and(|existing_id| *existing_id != widget_id)
{
return Err(GuiError::Backend(format!(
"E2E binding {value:?} is already registered"
)));
}
registry.insert(value, widget_id);
Ok(())
}
fn element(&self, widget_id: WidgetId) -> Element {
Element {
widget_id,
session: Rc::downgrade(&self.session),
_thread_affine: PhantomData,
}
}
fn validate_element(&self, element: &Element) -> GuiResult<&WidgetSpec> {
if !Weak::ptr_eq(&element.session, &Rc::downgrade(&self.session)) {
return Err(GuiError::Backend(
"E2E element belongs to a different or expired driver session".to_owned(),
));
}
self.ui
.widget(element.widget_id)
.ok_or(GuiError::WidgetNotFound(element.widget_id.0))
}
fn matches_locator(&self, widget_id: WidgetId, locator: &Locator) -> GuiResult<bool> {
let Some(spec) = self.ui.widget(widget_id) else {
return Ok(false);
};
for selector in &locator.selectors {
let matches = match selector {
Selector::Id(id) => *id == widget_id,
Selector::Name(name) => self.names.get(name) == Some(&widget_id),
Selector::TestId(test_id) => self.test_ids.get(test_id) == Some(&widget_id),
Selector::Role(role, label) => {
spec.accessibility.role == *role
&& spec
.accessibility
.name
.as_deref()
.or(spec.text.as_deref())
.unwrap_or_default()
== label
}
Selector::Kind(kind) => spec.kind == *kind,
Selector::Text(text) => spec.text.as_deref().unwrap_or_default() == text,
Selector::Dialog => {
is_dialog(spec.kind)
|| spec.accessibility.role == AccessibleRole::Dialog
|| spec.accessibility.role == AccessibleRole::Alert
}
Selector::TopLevel => is_window_or_dialog(spec.kind),
};
if !matches {
return Ok(false);
}
}
for relation in &locator.relations {
match relation {
Relation::ChildOf(parent_locator) => {
let Some(parent_id) = spec.parent else {
return Ok(false);
};
self.require_live_parent(parent_id)?;
if !self.matches_locator(parent_id, parent_locator)? {
return Ok(false);
}
}
Relation::DescendantOf(ancestor_locator) => {
if !self.has_matching_ancestor(widget_id, ancestor_locator, false)? {
return Ok(false);
}
}
Relation::InWindow(window_locator) => {
if !self.has_matching_ancestor(widget_id, window_locator, true)? {
return Ok(false);
}
}
}
}
Ok(true)
}
fn has_matching_ancestor(
&self,
widget_id: WidgetId,
locator: &Locator,
include_self: bool,
) -> GuiResult<bool> {
let mut cursor = if include_self {
Some(widget_id)
} else {
self.ui.widget(widget_id).and_then(|spec| spec.parent)
};
let mut visited = HashSet::new();
while let Some(ancestor_id) = cursor {
if !visited.insert(ancestor_id) {
return Err(GuiError::Backend(
"E2E widget graph contains a parent cycle".to_owned(),
));
}
let ancestor = self.require_live_parent(ancestor_id)?;
if include_self && is_window_or_dialog(ancestor.kind) {
if self.matches_locator(ancestor_id, locator)? {
return Ok(true);
}
} else if !include_self && self.matches_locator(ancestor_id, locator)? {
return Ok(true);
}
cursor = ancestor.parent;
}
Ok(false)
}
fn require_live_parent(&self, widget_id: WidgetId) -> GuiResult<&WidgetSpec> {
self.ui.widget(widget_id).ok_or_else(|| {
GuiError::Backend(format!(
"E2E widget graph references missing parent {}",
widget_id.0
))
})
}
fn deadline(&self, options: WaitOptions) -> GuiResult<Instant> {
if options.poll_interval.is_zero() {
return Err(GuiError::Backend(
"E2E poll interval must be greater than zero".to_owned(),
));
}
Instant::now()
.checked_add(options.timeout)
.ok_or_else(|| GuiError::Backend("E2E wait deadline overflow".to_owned()))
}
fn pause_until(&self, deadline: Instant, options: WaitOptions) -> GuiResult<()> {
let remaining = deadline.saturating_duration_since(Instant::now());
let slice = options
.poll_interval
.min(Duration::from_millis(25))
.min(remaining);
if !slice.is_zero() {
std::thread::sleep(slice);
}
Ok(())
}
pub fn pump(&mut self) -> GuiResult<usize>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
self.ensure_running()?;
let start = Instant::now();
let mut dispatched = 0;
while dispatched < 64 && start.elapsed() < Duration::from_millis(5) {
let Some(flow) = self.ui.e2e_dispatch_one(&mut self.handler)? else {
break;
};
dispatched += 1;
if flow == LoopFlow::Exit {
self.exited = true;
break;
}
}
Ok(dispatched)
}
fn is_enabled(&self, element: &Element) -> GuiResult<bool> {
let mut cursor = Some(element.widget_id);
let mut visited = HashSet::new();
while let Some(id) = cursor {
if !visited.insert(id) {
return Err(GuiError::Backend(
"E2E widget graph contains a parent cycle".to_owned(),
));
}
let spec = self.ui.widget(id).ok_or(GuiError::WidgetNotFound(id.0))?;
if spec.enabled == Some(false) {
return Ok(false);
}
cursor = spec.parent;
}
Ok(true)
}
fn is_visible(&self, element: &Element) -> GuiResult<bool> {
let mut cursor = Some(element.widget_id);
let mut visited = HashSet::new();
while let Some(id) = cursor {
if !visited.insert(id) {
return Err(GuiError::Backend(
"E2E widget graph contains a parent cycle".to_owned(),
));
}
if !self.ui.is_visible(id) {
return Ok(false);
}
cursor = self.ui.widget(id).and_then(|spec| spec.parent);
}
Ok(true)
}
fn value(&self, element: &Element) -> GuiResult<i32> {
let spec = self.validate_element(element)?;
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_backend: &dyn std::any::Any = self.ui.backend();
if let Some(mock) = any_backend.downcast_ref::<MockBackend>() {
return mock.e2e_mock_value(element.widget_id);
}
}
spec.value.ok_or_else(|| {
GuiError::Backend(format!(
"E2E widget {} has no numeric value",
element.widget_id.0
))
})
}
pub fn windows(&self) -> GuiResult<Vec<Element>> {
self.find_all(&Locator::kind(WidgetKind::Window))
}
pub fn dialogs(&self) -> GuiResult<Vec<DialogHandle>> {
let mut result = Vec::new();
for spec in self.ui.e2e_widget_specs() {
if is_dialog(spec.kind)
|| (spec.kind == WidgetKind::Window
&& (spec.accessibility.role == AccessibleRole::Dialog
|| spec.accessibility.role == AccessibleRole::Alert
|| self.active_modal == Some(spec.id)))
{
result.push(DialogHandle::new(spec.id, spec.kind));
}
}
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_backend: &dyn std::any::Any = self.ui.backend();
if let Some(mock) = any_backend.downcast_ref::<MockBackend>() {
for (token, _title, _msg) in &mock.confirm_requests {
let fake_id = self.active_modal.unwrap_or(WidgetId(999_000 + *token));
result.push(DialogHandle::for_token(fake_id, *token));
}
}
}
Ok(result)
}
pub fn find_dialog(&self, locator: &Locator) -> GuiResult<Option<DialogHandle>> {
let matching = self.find(locator)?;
if let Some(elem) = matching {
let spec = self
.ui
.widget(elem.id())
.ok_or(GuiError::WidgetNotFound(elem.id().0))?;
if is_window_or_dialog(spec.kind) {
return Ok(Some(DialogHandle::new(elem.id(), spec.kind)));
}
}
Ok(None)
}
pub fn expect_dialog(&self, locator: &Locator) -> GuiResult<DialogHandle> {
let elem = self.expect_one(locator)?;
let spec = self
.ui
.widget(elem.id())
.ok_or(GuiError::WidgetNotFound(elem.id().0))?;
if is_window_or_dialog(spec.kind) {
Ok(DialogHandle::new(elem.id(), spec.kind))
} else {
Err(GuiError::Backend(format!(
"e2e.dialog: widget {} is not a window or dialog (kind {:?})",
elem.id().0,
spec.kind
)))
}
}
pub fn find_in_window(
&self,
window_id: WidgetId,
locator: &Locator,
) -> GuiResult<Option<Element>> {
self.find(&locator.clone().in_window(Locator::id(window_id)))
}
pub fn find_all_in_window(
&self,
window_id: WidgetId,
locator: &Locator,
) -> GuiResult<Vec<Element>> {
self.find_all(&locator.clone().in_window(Locator::id(window_id)))
}
pub fn expect_one_in_window(
&self,
window_id: WidgetId,
locator: &Locator,
) -> GuiResult<Element> {
self.expect_one(&locator.clone().in_window(Locator::id(window_id)))
}
pub fn pending_confirm_requests(&self) -> Vec<(u64, String, String)> {
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_backend: &dyn std::any::Any = self.ui.backend();
if let Some(mock) = any_backend.downcast_ref::<MockBackend>() {
return mock.confirm_requests.clone();
}
}
Vec::new()
}
pub fn backend_name(&self) -> &'static str {
self.ui.backend().backend_name()
}
pub fn compare_screenshot(
&mut self,
target: CaptureTarget,
expected: &CaptureImage,
options: &ImageDiffOptions,
) -> GuiResult<ImageDiffResult> {
let actual = self.screenshot(target.clone())?;
let mask_rects = self.resolve_mask_rects(&target, options)?;
compare_images(&actual, expected, options, &mask_rects)
}
fn resolve_mask_rects(
&self,
target: &CaptureTarget,
options: &ImageDiffOptions,
) -> GuiResult<Vec<Rect>> {
let mut resolved = Vec::new();
for mask in &options.masks {
match mask {
MaskRegion::Rect(rect) => resolved.push(*rect),
MaskRegion::Element(locator) => {
if let Ok(Some(elem)) = self.find(locator) {
if let Some(spec) = self.ui.widget(elem.widget_id) {
let (cw, ch) = Self::mock_widget_dimensions(spec);
let pos = match target {
CaptureTarget::Window(win_id) => self
.relative_position(elem.widget_id, *win_id)?
.unwrap_or((0, 0)),
CaptureTarget::Element(_) => (0, 0),
CaptureTarget::Viewport => spec.position.unwrap_or((0, 0)),
CaptureTarget::Prompt(_) => continue,
};
let rx = pos.0.max(0) as u32;
let ry = pos.1.max(0) as u32;
resolved.push(Rect::new(rx, ry, cw, ch));
}
}
}
}
}
Ok(resolved)
}
}
impl<B: E2eBackend, H> Driver<B, H>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
fn complete_action(&mut self, started: Instant) -> GuiResult<()> {
let drain_timeout = self.action_timeout.max(Duration::from_secs(5));
loop {
if started.elapsed() >= drain_timeout {
return Err(GuiError::Backend(
"e2e.timeout: action dispatch did not finish; input will not be replayed"
.into(),
));
}
if self.pump()? == 0 || self.exited {
return Ok(());
}
}
}
fn check_readiness(&self, widget_id: WidgetId) -> GuiResult<&WidgetSpec> {
let mut cursor = Some(widget_id);
let mut visited = HashSet::new();
let mut target = None;
while let Some(id) = cursor {
if !visited.insert(id) {
return Err(GuiError::Backend(
"E2E widget graph contains a parent cycle".to_owned(),
));
}
let spec = self.ui.widget(id).ok_or(GuiError::WidgetNotFound(id.0))?;
if !self.ui.is_visible(id) || spec.enabled == Some(false) {
return Err(GuiError::Backend(format!(
"E2E widget {} is hidden or disabled",
id.0
)));
}
if id == widget_id {
target = Some(spec);
}
cursor = spec.parent;
}
if !self.is_modal_eligible(widget_id)? {
let modal_desc = self.active_modal.map(|m| m.0).unwrap_or(0);
return Err(GuiError::Backend(format!(
"e2e.readiness: widget {} is blocked by active modal {}",
widget_id.0, modal_desc
)));
}
target.ok_or(GuiError::WidgetNotFound(widget_id.0))
}
#[allow(dead_code)]
fn ensure_actionable(&self, widget_id: WidgetId) -> GuiResult<&WidgetSpec> {
self.check_readiness(widget_id)
}
fn wait_for_readiness(&mut self, widget_id: WidgetId, started: Instant) -> GuiResult<()> {
let deadline = started + self.action_timeout;
let poll_interval = Duration::from_millis(10);
loop {
match self.check_readiness(widget_id) {
Ok(_) => return Ok(()),
Err(err) => {
if matches!(err, GuiError::WidgetNotFound(_)) {
return Err(err);
}
if Instant::now() >= deadline {
return Err(GuiError::Backend(format!(
"e2e.timeout: readiness auto-wait timed out: {err}"
)));
}
}
}
self.pump()?;
self.ensure_running()?;
let remaining = deadline.saturating_duration_since(Instant::now());
let slice = poll_interval.min(Duration::from_millis(25)).min(remaining);
if !slice.is_zero() {
std::thread::sleep(slice);
}
}
}
fn click(&mut self, element: &Element) -> GuiResult<()> {
let started = Instant::now();
self.require_operation(element, Operation::Click)?;
self.wait_for_readiness(element.widget_id, started)?;
let deadline = started + self.action_timeout;
let poll_interval = Duration::from_millis(10);
loop {
match self.ui.backend_mut().e2e_click(element.widget_id) {
Ok(()) => break,
Err(GuiError::Backend(msg)) if msg.starts_with("e2e.readiness:") => {
if Instant::now() >= deadline {
return Err(GuiError::Backend(format!(
"e2e.timeout: readiness auto-wait timed out: {msg}"
)));
}
self.pump()?;
self.ensure_running()?;
let remaining = deadline.saturating_duration_since(Instant::now());
let slice = poll_interval.min(Duration::from_millis(25)).min(remaining);
if !slice.is_zero() {
std::thread::sleep(slice);
}
}
Err(err) => return Err(err),
}
}
self.complete_action(started)
}
fn type_text(&mut self, element: &Element, text: &str) -> GuiResult<()> {
let started = Instant::now();
self.require_operation(element, Operation::TypeText)?;
self.wait_for_readiness(element.widget_id, started)?;
let deadline = started + self.action_timeout;
let poll_interval = Duration::from_millis(10);
loop {
let res = self.ui.backend_mut().e2e_type_text(element.widget_id, text);
match res {
Ok(()) => break,
Err(GuiError::Backend(msg)) if msg.starts_with("e2e.readiness:") => {
if Instant::now() >= deadline {
return Err(GuiError::Backend(format!(
"e2e.timeout: readiness auto-wait timed out: {msg}"
)));
}
self.pump()?;
self.ensure_running()?;
let remaining = deadline.saturating_duration_since(Instant::now());
let slice = poll_interval.min(Duration::from_millis(25)).min(remaining);
if !slice.is_zero() {
std::thread::sleep(slice);
}
}
Err(GuiError::UnsupportedWidget(_)) => {
let is_mock =
std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.e2e_mock_type_text(element.widget_id, text)?;
break;
}
}
if self
.ui
.backend_mut()
.native_type_text(element.widget_id, text)?
{
break;
}
return Err(GuiError::UnsupportedWidget("e2e.type_text"));
}
Err(err) => return Err(err),
}
}
self.complete_action(started)
}
fn check(&mut self, element: &Element, checked: bool) -> GuiResult<()> {
let started = Instant::now();
self.require_operation(element, Operation::Check)?;
self.wait_for_readiness(element.widget_id, started)?;
let deadline = started + self.action_timeout;
let poll_interval = Duration::from_millis(10);
loop {
let res = self.ui.backend_mut().e2e_check(element.widget_id, checked);
match res {
Ok(()) => break,
Err(GuiError::Backend(msg)) if msg.starts_with("e2e.readiness:") => {
if Instant::now() >= deadline {
return Err(GuiError::Backend(format!(
"e2e.timeout: readiness auto-wait timed out: {msg}"
)));
}
self.pump()?;
self.ensure_running()?;
let remaining = deadline.saturating_duration_since(Instant::now());
let slice = poll_interval.min(Duration::from_millis(25)).min(remaining);
if !slice.is_zero() {
std::thread::sleep(slice);
}
}
Err(GuiError::UnsupportedWidget(_)) => {
let is_mock =
std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.e2e_mock_check(element.widget_id, checked)?;
break;
}
}
if self.ui.backend_mut().native_click(element.widget_id)? {
break;
}
return Err(GuiError::UnsupportedWidget("e2e.check"));
}
Err(err) => return Err(err),
}
}
self.complete_action(started)
}
fn press(&mut self, element: &Element, chord: &str) -> GuiResult<()> {
let started = Instant::now();
self.require_operation(element, Operation::Press)?;
self.wait_for_readiness(element.widget_id, started)?;
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.e2e_mock_press(element.widget_id, chord)?;
}
} else {
return Err(GuiError::UnsupportedWidget("e2e.press"));
}
self.complete_action(started)
}
fn select(&mut self, element: &Element, index: usize) -> GuiResult<()> {
let started = Instant::now();
self.require_operation(element, Operation::Select)?;
self.wait_for_readiness(element.widget_id, started)?;
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.e2e_mock_select(element.widget_id, index)?;
}
} else {
return Err(GuiError::UnsupportedWidget("e2e.select"));
}
self.complete_action(started)
}
fn select_text(&mut self, element: &Element, start: usize, end: usize) -> GuiResult<()> {
let started = Instant::now();
self.require_operation(element, Operation::Select)?;
self.wait_for_readiness(element.widget_id, started)?;
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.e2e_mock_select_text(element.widget_id, start, end)?;
}
} else {
return Err(GuiError::UnsupportedWidget("e2e.select"));
}
self.complete_action(started)
}
fn set_value(&mut self, element: &Element, value: i32) -> GuiResult<()> {
let started = Instant::now();
self.require_operation(element, Operation::SetValue)?;
self.wait_for_readiness(element.widget_id, started)?;
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.e2e_mock_set_value(element.widget_id, value)?;
}
} else {
return Err(GuiError::UnsupportedWidget("e2e.set_value"));
}
self.complete_action(started)
}
fn scroll(&mut self, element: &Element, delta_x: f64, delta_y: f64) -> GuiResult<()> {
let started = Instant::now();
self.require_operation(element, Operation::Scroll)?;
self.wait_for_readiness(element.widget_id, started)?;
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.e2e_mock_scroll(element.widget_id, delta_x, delta_y)?;
}
} else {
return Err(GuiError::UnsupportedWidget("e2e.scroll"));
}
self.complete_action(started)
}
fn drag_to(&mut self, source: &Element, target: &Element) -> GuiResult<()> {
let started = Instant::now();
self.require_operation(source, Operation::DragTo)?;
self.validate_element(target)?;
self.wait_for_readiness(source.widget_id, started)?;
self.wait_for_readiness(target.widget_id, started)?;
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.e2e_mock_drag_to(source.widget_id, target.widget_id)?;
}
} else {
return Err(GuiError::UnsupportedWidget("e2e.drag_to"));
}
self.complete_action(started)
}
fn close(&mut self, element: &Element) -> GuiResult<()> {
let started = Instant::now();
self.require_operation(element, Operation::Close)?;
self.wait_for_readiness(element.widget_id, started)?;
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.e2e_mock_close(element.widget_id)?;
}
} else {
if self.ui.backend_mut().native_close(element.widget_id)? {
} else {
return Err(GuiError::UnsupportedWidget("e2e.close"));
}
}
self.complete_action(started)
}
pub fn wait_for_dialog(
&mut self,
locator: &Locator,
options: WaitOptions,
) -> GuiResult<DialogHandle> {
let elem = self.wait_for(locator, options)?;
let spec = self
.ui
.widget(elem.id())
.ok_or(GuiError::WidgetNotFound(elem.id().0))?;
if is_window_or_dialog(spec.kind) {
Ok(DialogHandle::new(elem.id(), spec.kind))
} else {
Err(GuiError::Backend(format!(
"e2e.dialog: widget {} is not a window or dialog (kind {:?})",
elem.id().0,
spec.kind
)))
}
}
pub fn wait_for_in_window(
&mut self,
window_id: WidgetId,
locator: &Locator,
options: WaitOptions,
) -> GuiResult<Element> {
self.wait_for(&locator.clone().in_window(Locator::id(window_id)), options)
}
pub fn respond_confirm_dialog(&mut self, token: u64, confirmed: bool) -> GuiResult<()> {
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.events
.push_back(UiEvent::DialogResponse { token, confirmed });
}
}
self.pump()?;
Ok(())
}
pub fn assert_screenshot_matches(
&mut self,
target: CaptureTarget,
baseline_name: &str,
options: &ImageDiffOptions,
) -> GuiResult<ImageDiffResult> {
let actual = self.screenshot(target.clone())?;
let backend_name = self.backend_name();
let base_dir = std::env::var("NATIVE_GUI_E2E_BASELINES_DIR")
.map(std::path::PathBuf::from)
.unwrap_or_else(|_| std::path::PathBuf::from("tests/e2e-baselines"));
let backend_dir = base_dir.join(backend_name);
let baseline_path = backend_dir.join(format!("{baseline_name}.png"));
let update_env = std::env::var("NATIVE_GUI_E2E_UPDATE_BASELINES")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false);
if update_env {
std::fs::create_dir_all(&backend_dir).map_err(|e| {
GuiError::Backend(format!(
"e2e.visual: failed to create baseline directory '{}': {e}",
backend_dir.display()
))
})?;
actual.save_png(&baseline_path)?;
let total = (actual.width as usize) * (actual.height as usize);
return Ok(ImageDiffResult {
passed: true,
mismatch_percentage: 0.0,
mismatched_pixels: 0,
total_pixels: total,
diff_bounds: None,
diff_image: None,
});
}
if !baseline_path.exists() {
return Err(GuiError::Backend(format!(
"e2e.visual: baseline image not found at '{}'. Run with NATIVE_GUI_E2E_UPDATE_BASELINES=1 to record it.",
baseline_path.display()
)));
}
let expected = CaptureImage::load_png(&baseline_path)?;
let mask_rects = self.resolve_mask_rects(&target, options)?;
let result = compare_images(&actual, &expected, options, &mask_rects)?;
if !result.passed {
let diff_dir = options.diff_output_dir.clone().unwrap_or_else(|| {
std::path::PathBuf::from("target/native-gui-e2e/diffs").join(backend_name)
});
let _ = std::fs::create_dir_all(&diff_dir);
let diff_file = diff_dir.join(format!("{baseline_name}_diff.png"));
let actual_file = diff_dir.join(format!("{baseline_name}_actual.png"));
if let Some(diff_img) = &result.diff_image {
let _ = diff_img.save_png(&diff_file);
}
let _ = actual.save_png(&actual_file);
return Err(GuiError::Backend(format!(
"e2e.visual: screenshot '{}' differs from baseline ({:.2}% mismatch, {} differing pixels). Diff saved to '{}'",
baseline_name,
result.mismatch_percentage,
result.mismatched_pixels,
diff_file.display()
)));
}
Ok(result)
}
pub fn expect_screenshot(&mut self, baseline_name: &str) -> GuiResult<ImageDiffResult> {
self.assert_screenshot_matches(
CaptureTarget::Viewport,
baseline_name,
&ImageDiffOptions::default(),
)
}
}
#[derive(Debug, Clone)]
pub struct Element {
widget_id: WidgetId,
session: Weak<()>,
_thread_affine: PhantomData<Rc<()>>,
}
impl Element {
pub fn id(&self) -> WidgetId {
self.widget_id
}
pub fn text<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<String> {
driver.require_operation(self, Operation::Text)?;
match driver.ui.backend().e2e_text(self.widget_id) {
Ok(text) => Ok(text),
Err(GuiError::UnsupportedWidget(_)) => {
if let Some(text) = driver.ui.backend().native_read_text(self.widget_id)? {
return Ok(text);
}
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
if let Some(spec) = driver.ui.widget(self.widget_id) {
return Ok(spec.text.clone().unwrap_or_default());
}
}
Err(GuiError::UnsupportedWidget("e2e.text"))
}
Err(err) => Err(err),
}
}
pub fn is_checked<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<bool> {
driver.require_operation(self, Operation::Checked)?;
match driver.ui.backend().e2e_checked(self.widget_id) {
Ok(checked) => Ok(checked),
Err(GuiError::UnsupportedWidget(_)) => {
if let Some(checked) = driver.ui.backend().native_read_checked(self.widget_id)? {
return Ok(checked);
}
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
if let Some(spec) = driver.ui.widget(self.widget_id) {
return Ok(spec.checked.unwrap_or(false));
}
}
Err(GuiError::UnsupportedWidget("e2e.checked"))
}
Err(err) => Err(err),
}
}
pub fn is_enabled<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<bool> {
driver.is_enabled(self)
}
pub fn is_visible<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<bool> {
driver.is_visible(self)
}
pub fn is_modal_eligible<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<bool> {
driver.validate_element(self)?;
driver.is_modal_eligible(self.widget_id)
}
pub fn value<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<i32> {
driver.value(self)
}
pub fn click<B: E2eBackend, H>(&self, driver: &mut Driver<B, H>) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
driver.click(self)
}
pub fn type_text<B: E2eBackend, H>(
&self,
driver: &mut Driver<B, H>,
text: &str,
) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
driver.type_text(self, text)
}
pub fn check<B: E2eBackend, H>(&self, driver: &mut Driver<B, H>, checked: bool) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
driver.check(self, checked)
}
pub fn press<B: E2eBackend, H>(&self, driver: &mut Driver<B, H>, chord: &str) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
driver.press(self, chord)
}
pub fn select<B: E2eBackend, H>(&self, driver: &mut Driver<B, H>, index: usize) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
driver.select(self, index)
}
pub fn select_text<B: E2eBackend, H>(
&self,
driver: &mut Driver<B, H>,
start: usize,
end: usize,
) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
driver.select_text(self, start, end)
}
pub fn set_value<B: E2eBackend, H>(
&self,
driver: &mut Driver<B, H>,
value: i32,
) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
driver.set_value(self, value)
}
pub fn scroll<B: E2eBackend, H>(
&self,
driver: &mut Driver<B, H>,
delta_x: f64,
delta_y: f64,
) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
driver.scroll(self, delta_x, delta_y)
}
pub fn drag_to<B: E2eBackend, H>(
&self,
driver: &mut Driver<B, H>,
target: &Element,
) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
driver.drag_to(self, target)
}
pub fn close<B: E2eBackend, H>(&self, driver: &mut Driver<B, H>) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
driver.close(self)
}
pub fn expect_text<B: E2eBackend, H>(
&self,
driver: &mut Driver<B, H>,
expected: &str,
options: WaitOptions,
) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
driver.wait_until(
options,
|driver| Ok(self.text(driver)?.as_str() == expected),
)
}
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::rc::Rc;
use super::*;
type Handler = Box<dyn for<'a> FnMut(&'a mut Ui<MockBackend>, UiEvent) -> GuiResult<LoopFlow>>;
fn driver() -> (Driver<MockBackend, Handler>, WidgetId, WidgetId) {
let mut ui = Ui::new(MockBackend::default());
let window = ui.create(WidgetKind::Window, Some("main")).expect("window");
let button = ui.create(WidgetKind::Button, Some("Save")).expect("button");
ui.attach(window, button).expect("attach button");
ui.show(window).expect("show window");
(
Driver::new(ui, Box::new(|_ui, _event| Ok(LoopFlow::Continue))),
window,
button,
)
}
#[test]
fn screenshot_mock_and_capture_routing_b945() {
let (mut driver, win, btn) = driver();
let win_shot = driver
.screenshot(CaptureTarget::Window(win))
.expect("window shot");
assert!(win_shot.width() > 0);
assert!(win_shot.height() > 0);
assert_eq!(
win_shot.data().len(),
(win_shot.width() * win_shot.height() * 4) as usize
);
let elem_shot = driver
.screenshot(CaptureTarget::Element(Locator::id(btn)))
.expect("elem shot");
assert!(elem_shot.width() > 0);
assert!(elem_shot.height() > 0);
assert_eq!(
elem_shot.data().len(),
(elem_shot.width() * elem_shot.height() * 4) as usize
);
let vp_shot = driver
.screenshot(CaptureTarget::Viewport)
.expect("viewport shot");
assert!(vp_shot.width() >= win_shot.width());
assert!(vp_shot.height() >= win_shot.height());
}
#[test]
fn locators_cover_bindings_metadata_and_parent_scopes() {
let (mut driver, window, button) = driver();
driver.bind_name(button, "save").expect("bind name");
driver
.bind_test_id(button, "save-button")
.expect("bind test id");
assert_eq!(
driver
.expect_one(&Locator::name("save"))
.expect("named button")
.id(),
button
);
assert_eq!(
driver
.expect_one(&Locator::test_id("save-button"))
.expect("test id")
.id(),
button
);
assert_eq!(
driver
.expect_one(&Locator::role(AccessibleRole::Button, "Save"))
.expect("role")
.id(),
button
);
assert_eq!(
driver
.find_all(&Locator::text("Save").in_window(Locator::id(window)))
.expect("scoped query")
.len(),
1
);
assert_eq!(
driver
.find_all(&Locator::kind(WidgetKind::Button).child_of(Locator::id(window)))
.expect("direct child query")
.len(),
1
);
assert_eq!(
driver
.find_all(&Locator::kind(WidgetKind::Button).descendant_of(Locator::id(window)))
.expect("descendant query")
.len(),
1
);
}
#[test]
fn ambiguous_queries_error_and_find_all_is_sorted() {
let (mut driver, window, first) = driver();
let second = driver
.ui_mut()
.create(WidgetKind::Button, Some("Save"))
.expect("second button");
driver
.ui_mut()
.attach(window, second)
.expect("attach second");
assert!(driver.find(&Locator::text("Save")).is_err());
assert_eq!(
driver
.find_all(&Locator::kind(WidgetKind::Button))
.expect("buttons")
.iter()
.map(Element::id)
.collect::<Vec<_>>(),
vec![first, second]
);
driver.bind_name(first, "save").expect("bind first name");
assert!(driver.bind_name(second, "save").is_err());
}
#[test]
fn click_delivers_the_normal_application_event() {
let clicked = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&clicked);
let mut ui = Ui::new(MockBackend::default());
let window = ui.create(WidgetKind::Window, Some("main")).expect("window");
let button = ui.create(WidgetKind::Button, Some("Save")).expect("button");
ui.attach(window, button).expect("attach button");
ui.show(window).expect("show window");
let mut driver = Driver::new(
ui,
Box::new(move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
seen.borrow_mut().push(event);
Ok(LoopFlow::Continue)
}) as Handler,
);
driver
.expect_one(&Locator::id(button))
.expect("button")
.click(&mut driver)
.expect("click");
assert_eq!(
*clicked.borrow(),
vec![UiEvent::Clicked { widget_id: button }]
);
}
#[test]
#[cfg(feature = "widgets-text")]
fn typing_inserts_at_the_unicode_character_selection_and_dispatches_event() {
let mut ui = Ui::new(MockBackend::default());
let input = ui
.create(WidgetKind::TextInput, Some("aéz"))
.expect("input");
ui.set_text_selection(input, 1, 2)
.expect("select character");
let seen = Rc::new(RefCell::new(Vec::new()));
let captured = Rc::clone(&seen);
let mut driver = Driver::new(
ui,
Box::new(move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
captured.borrow_mut().push(event);
Ok(LoopFlow::Continue)
}) as Handler,
);
driver
.expect_one(&Locator::id(input))
.expect("input element")
.type_text(&mut driver, "🙂")
.expect("type text");
assert_eq!(
driver
.expect_one(&Locator::id(input))
.expect("input")
.text(&driver),
Ok("a🙂z".to_owned())
);
assert!(seen.borrow().iter().any(|event| {
*event
== UiEvent::TextChanged {
widget_id: input,
text: "a🙂z".to_owned(),
}
}));
}
#[test]
#[cfg(feature = "widgets-choice")]
fn checkbox_action_is_idempotent_and_observed_through_events() {
let mut ui = Ui::new(MockBackend::default());
let checkbox = ui
.create(WidgetKind::Checkbox, Some("Enabled"))
.expect("checkbox");
ui.show(checkbox).expect("show checkbox");
let events = Rc::new(RefCell::new(Vec::new()));
let captured = Rc::clone(&events);
let mut driver = Driver::new(
ui,
Box::new(move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
captured.borrow_mut().push(event);
Ok(LoopFlow::Continue)
}) as Handler,
);
let element = driver.expect_one(&Locator::id(checkbox)).expect("element");
element.check(&mut driver, true).expect("check");
element.check(&mut driver, true).expect("repeat check");
assert!(element.is_checked(&driver).expect("checked state"));
assert_eq!(
*events.borrow(),
vec![UiEvent::Toggled {
widget_id: checkbox,
checked: true,
}]
);
}
#[test]
fn stale_foreign_and_timed_out_queries_fail_explicitly() {
let (mut first, _window, button) = driver();
let element = first.expect_one(&Locator::id(button)).expect("element");
let (second, _, _) = driver();
assert!(matches!(element.text(&second), Err(GuiError::Backend(_))));
first.ui_mut().remove(button).expect("remove button");
assert_eq!(
element.text(&first),
Err(GuiError::WidgetNotFound(button.0))
);
assert!(first.find(&Locator::kind(WidgetKind::Window)).is_ok());
assert!(first
.wait_for(
&Locator::text("not present"),
WaitOptions::new(Duration::from_millis(2)).poll_interval(Duration::from_millis(1)),
)
.is_err());
assert!(first
.wait_until(WaitOptions::new(Duration::ZERO), |_| Ok(false),)
.is_err());
}
#[test]
fn action_rejects_hidden_or_disabled_controls() {
let (mut driver, _, button) = driver();
driver.ui_mut().set_enabled(button, false).expect("disable");
let element = driver.expect_one(&Locator::id(button)).expect("button");
assert!(element.click(&mut driver).is_err());
driver.ui_mut().set_enabled(button, true).expect("enable");
driver.ui_mut().set_visible(button, false).expect("hide");
assert!(element.click(&mut driver).is_err());
}
#[test]
fn fidelity_refusal_has_no_side_effect_and_unknown_queries_error() {
let (driver, _, button) = driver();
let element = driver.expect_one(&Locator::id(button)).unwrap();
let mut driver = driver.with_input_mode(InputMode::HardwareNative);
assert_eq!(
element.click(&mut driver),
Err(GuiError::UnsupportedWidget("e2e.click"))
);
assert!(driver.ui().backend().events.is_empty());
assert_eq!(
driver
.ui()
.backend()
.e2e_capability(WidgetId(u64::MAX), Operation::Click),
Err(GuiError::WidgetNotFound(u64::MAX))
);
assert!(matches!(
driver.capability(&element, Operation::Press).unwrap(),
Capability::Unsupported { .. }
));
}
#[test]
fn wait_pump_is_bounded_when_handler_continually_enqueues_work() {
let mut ui = Ui::new(MockBackend::default());
let button = ui.create(WidgetKind::Button, Some("again")).unwrap();
ui.backend_mut()
.push_event(UiEvent::Clicked { widget_id: button });
let mut driver = Driver::new(ui, move |ui: &mut Ui<MockBackend>, _event| {
ui.backend_mut()
.push_event(UiEvent::Clicked { widget_id: button });
Ok(LoopFlow::Continue)
});
let start = Instant::now();
assert!(driver
.wait_until(WaitOptions::new(Duration::from_millis(10)), |_| Ok(false))
.is_err());
assert!(start.elapsed() < Duration::from_secs(5));
assert!(!driver.ui().backend().events.is_empty());
}
#[test]
fn handler_exit_stops_future_input_and_observation() {
let mut ui = Ui::new(MockBackend::default());
let button = ui.create(WidgetKind::Button, Some("Exit")).unwrap();
let mut driver = Driver::new(ui, |_ui: &mut Ui<MockBackend>, _event| Ok(LoopFlow::Exit));
let element = driver.expect_one(&Locator::id(button)).unwrap();
element.click(&mut driver).unwrap();
assert!(matches!(
element.click(&mut driver),
Err(GuiError::Backend(_))
));
assert!(matches!(element.text(&driver), Err(GuiError::Backend(_))));
}
#[test]
fn action_drains_multiple_bounded_slices_in_fifo_order() {
let mut ui = Ui::new(MockBackend::default());
let button = ui.create(WidgetKind::Button, Some("Run")).unwrap();
for index in 0..130 {
ui.backend_mut().push_event(UiEvent::ValueChanged {
widget_id: button,
value: index,
});
}
let events = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&events);
let mut driver = Driver::new(ui, move |_ui, event| {
seen.borrow_mut().push(event);
Ok(LoopFlow::Continue)
});
let element = driver.expect_one(&Locator::id(button)).unwrap();
element.click(&mut driver).unwrap();
assert_eq!(events.borrow().len(), 131);
assert_eq!(events.borrow()[130], UiEvent::Clicked { widget_id: button });
for index in 0..130 {
assert_eq!(
events.borrow()[index],
UiEvent::ValueChanged {
widget_id: button,
value: index as i32
}
);
}
assert!(driver.ui().backend().events.is_empty());
}
#[test]
#[cfg(feature = "widgets-text")]
fn press_dispatches_key_events_in_order() {
let mut ui = Ui::new(MockBackend::default());
let input = ui.create(WidgetKind::TextInput, Some("test")).unwrap();
let events = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&events);
let mut driver = Driver::new(ui, move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
seen.borrow_mut().push(event);
Ok(LoopFlow::Continue)
});
let element = driver.expect_one(&Locator::id(input)).unwrap();
element.press(&mut driver, "Ctrl+S").expect("press chord");
assert_eq!(
*events.borrow(),
vec![
UiEvent::KeyDown {
widget_id: input,
key: "S".into(),
ctrl: true,
shift: false,
alt: false,
},
UiEvent::KeyUp {
widget_id: input,
key: "S".into(),
ctrl: true,
shift: false,
alt: false,
},
]
);
events.borrow_mut().clear();
element.press(&mut driver, "x").expect("press char");
assert_eq!(
*events.borrow(),
vec![
UiEvent::KeyDown {
widget_id: input,
key: "x".into(),
ctrl: false,
shift: false,
alt: false,
},
UiEvent::Char {
widget_id: input,
text: "x".into(),
},
UiEvent::KeyUp {
widget_id: input,
key: "x".into(),
ctrl: false,
shift: false,
alt: false,
},
]
);
}
#[test]
#[cfg(all(feature = "widgets-text", feature = "widgets-data"))]
fn select_and_select_text_update_model_and_dispatch_selection_event() {
let mut ui = Ui::new(MockBackend::default());
let combo = ui.create(WidgetKind::DataList, None).unwrap();
ui.set_data_list_items(combo, &["first".into(), "second".into(), "third".into()])
.unwrap();
let input = ui
.create(WidgetKind::TextInput, Some("hello world"))
.unwrap();
let events = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&events);
let mut driver = Driver::new(ui, move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
seen.borrow_mut().push(event);
Ok(LoopFlow::Continue)
});
let combo_elem = driver.expect_one(&Locator::id(combo)).unwrap();
combo_elem
.select(&mut driver, 1)
.expect("select combo item");
assert_eq!(
*events.borrow(),
vec![UiEvent::SelectionChanged {
widget_id: combo,
selected: Some("second".into()),
index: Some(1),
}]
);
let input_elem = driver.expect_one(&Locator::id(input)).unwrap();
input_elem
.select_text(&mut driver, 0, 5)
.expect("select text");
assert_eq!(
driver
.ui()
.backend()
.created
.get(&input)
.unwrap()
.text_selection,
Some((0, 5))
);
}
#[test]
#[cfg(feature = "widgets-range")]
fn numeric_value_validates_range_and_emits_value_changed() {
let mut ui = Ui::new(MockBackend::default());
let slider = ui.create(WidgetKind::Slider, None).unwrap();
ui.set_range(slider, 0, 100).unwrap();
ui.set_value(slider, 10).unwrap();
let events = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&events);
let mut driver = Driver::new(ui, move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
seen.borrow_mut().push(event);
Ok(LoopFlow::Continue)
});
let elem = driver.expect_one(&Locator::id(slider)).unwrap();
assert_eq!(elem.value(&driver).unwrap(), 10);
elem.set_value(&mut driver, 50).expect("set valid value");
assert_eq!(elem.value(&driver).unwrap(), 50);
assert_eq!(
*events.borrow(),
vec![UiEvent::ValueChanged {
widget_id: slider,
value: 50,
}]
);
assert!(elem.set_value(&mut driver, 150).is_err());
assert!(elem.set_value(&mut driver, -10).is_err());
}
#[test]
fn scroll_updates_scroll_target() {
let mut ui = Ui::new(MockBackend::default());
let container = ui.create(WidgetKind::Container, None).unwrap();
let mut driver = Driver::new(ui, |_ui: &mut Ui<MockBackend>, _event| {
Ok(LoopFlow::Continue)
});
let elem = driver.expect_one(&Locator::id(container)).unwrap();
elem.scroll(&mut driver, 0.0, 20.0)
.expect("scroll container");
assert_eq!(
driver.ui().backend().scroll_anchors.get(&container),
Some(&20)
);
}
#[test]
#[cfg(feature = "widgets-data")]
fn drag_to_emits_drag_and_drop_events() {
let mut ui = Ui::new(MockBackend::default());
let list1 = ui.create(WidgetKind::ListView, None).unwrap();
let list2 = ui.create(WidgetKind::ListView, None).unwrap();
let events = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&events);
let mut driver = Driver::new(ui, move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
seen.borrow_mut().push(event);
Ok(LoopFlow::Continue)
});
let source = driver.expect_one(&Locator::id(list1)).unwrap();
let target = driver.expect_one(&Locator::id(list2)).unwrap();
source
.drag_to(&mut driver, &target)
.expect("drag to target");
assert_eq!(
*events.borrow(),
vec![
UiEvent::DragStarted {
widget_id: list1,
indices: vec![0],
},
UiEvent::Dropped {
widget_id: list2,
target_index: 0,
source_indices: vec![0],
},
]
);
}
#[test]
fn close_respects_close_guard_and_window_lifecycle() {
let mut ui = Ui::new(MockBackend::default());
let window = ui.create(WidgetKind::Window, Some("guarded")).unwrap();
ui.show(window).unwrap();
ui.set_close_guard(window, true).unwrap();
let events = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&events);
let mut driver = Driver::new(ui, move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
seen.borrow_mut().push(event);
Ok(LoopFlow::Continue)
});
let elem = driver.expect_one(&Locator::id(window)).unwrap();
elem.close(&mut driver).expect("close guarded window");
assert_eq!(
*events.borrow(),
vec![UiEvent::CloseRequested { widget_id: window }]
);
assert!(driver.ui().backend().shown.contains(&window));
events.borrow_mut().clear();
driver.ui_mut().set_close_guard(window, false).unwrap();
elem.close(&mut driver).expect("close unguarded window");
assert_eq!(
*events.borrow(),
vec![UiEvent::WindowClosed { widget_id: window }]
);
assert!(!driver.ui().backend().shown.contains(&window));
}
#[test]
fn readiness_auto_wait_waits_for_disabled_control_to_become_enabled() {
let mut ui = Ui::new(MockBackend::default());
let window = ui.create(WidgetKind::Window, Some("main")).unwrap();
let button = ui.create(WidgetKind::Button, Some("Submit")).unwrap();
ui.attach(window, button).unwrap();
ui.show(window).unwrap();
ui.set_enabled(button, false).unwrap();
let button_clone = button;
let clicked = Rc::new(RefCell::new(false));
let clicked_seen = Rc::clone(&clicked);
ui.backend_mut().push_event(UiEvent::FocusChanged {
widget_id: button,
focused: true,
});
let mut driver = Driver::new(ui, move |ui: &mut Ui<MockBackend>, event: UiEvent| {
if matches!(event, UiEvent::FocusChanged { .. }) {
ui.set_enabled(button_clone, true).unwrap();
} else if matches!(event, UiEvent::Clicked { widget_id } if widget_id == button_clone) {
*clicked_seen.borrow_mut() = true;
}
Ok(LoopFlow::Continue)
});
driver = driver.with_action_timeout(Duration::from_secs(5));
let element = driver.expect_one(&Locator::id(button)).unwrap();
element
.click(&mut driver)
.expect("auto-wait succeeds when control becomes enabled");
assert!(*clicked.borrow());
}
#[test]
fn modal_eligibility_blocks_non_modal_widgets_and_auto_waits_until_modal_closes() {
let mut ui = Ui::new(MockBackend::default());
let main_win = ui.create(WidgetKind::Window, Some("main")).unwrap();
let main_btn = ui.create(WidgetKind::Button, Some("MainBtn")).unwrap();
ui.attach(main_win, main_btn).unwrap();
ui.show(main_win).unwrap();
let modal_win = ui.create(WidgetKind::Window, Some("modal")).unwrap();
let modal_btn = ui.create(WidgetKind::Button, Some("ModalBtn")).unwrap();
ui.attach(modal_win, modal_btn).unwrap();
ui.show(modal_win).unwrap();
let mut driver = Driver::new(ui, |_ui: &mut Ui<MockBackend>, _event| {
Ok(LoopFlow::Continue)
});
driver.set_active_modal(Some(modal_win));
let modal_elem = driver.expect_one(&Locator::id(modal_btn)).unwrap();
let main_elem = driver.expect_one(&Locator::id(main_btn)).unwrap();
assert!(modal_elem.is_modal_eligible(&driver).unwrap());
assert!(!main_elem.is_modal_eligible(&driver).unwrap());
modal_elem
.click(&mut driver)
.expect("modal element click succeeds");
driver = driver.with_action_timeout(Duration::from_millis(50));
assert!(main_elem.click(&mut driver).is_err());
driver.set_active_modal(None);
assert!(main_elem.is_modal_eligible(&driver).unwrap());
main_elem
.click(&mut driver)
.expect("click succeeds after modal dismissed");
}
#[test]
fn element_status_readbacks() {
let (mut driver, _win, button) = driver();
let elem = driver.expect_one(&Locator::id(button)).unwrap();
assert!(elem.is_enabled(&driver).unwrap());
assert!(elem.is_visible(&driver).unwrap());
driver.ui_mut().set_enabled(button, false).unwrap();
assert!(!elem.is_enabled(&driver).unwrap());
driver.ui_mut().set_visible(button, false).unwrap();
assert!(!elem.is_visible(&driver).unwrap());
}
#[test]
fn screenshot_captures_window_element_and_viewport() {
let (mut driver, win, button) = driver();
let win_img = driver
.screenshot(CaptureTarget::Window(win))
.expect("window screenshot");
assert!(win_img.width() > 0);
assert!(win_img.height() > 0);
assert_eq!(
win_img.data().len(),
(win_img.width() * win_img.height() * 4) as usize
);
let elem_img = driver
.screenshot(CaptureTarget::Element(Locator::id(button)))
.expect("element screenshot");
assert!(elem_img.width() > 0);
assert!(elem_img.height() > 0);
let vp_img = driver
.screenshot(CaptureTarget::Viewport)
.expect("viewport screenshot");
assert!(vp_img.width() > 0);
assert!(vp_img.height() > 0);
let png = vp_img.to_png().expect("to png");
assert!(!png.is_empty());
}
#[test]
fn visual_assertions_identical_images_match() {
let pixels = [100u8, 150, 200, 255].repeat(16); let img1 = CaptureImage::new(4, 4, pixels.clone());
let img2 = CaptureImage::new(4, 4, pixels);
let options = ImageDiffOptions::default();
let result = img1.diff(&img2, &options).expect("diff");
assert!(result.passed());
assert_eq!(result.mismatched_pixels(), 0);
assert_eq!(result.mismatch_percentage(), 0.0);
assert_eq!(result.diff_bounds(), None);
}
#[test]
fn visual_assertions_pixel_difference_and_diff_bounds_detected() {
let mut pixels1 = [0u8, 0, 0, 255].repeat(100); let pixels2 = pixels1.clone();
for y in 3..=4 {
for x in 3..=4 {
let idx = ((y * 10 + x) * 4) as usize;
pixels1[idx] = 255;
}
}
let img1 = CaptureImage::new(10, 10, pixels1);
let img2 = CaptureImage::new(10, 10, pixels2);
let options = ImageDiffOptions::default();
let result = img1.diff(&img2, &options).expect("diff");
assert!(!result.passed());
assert_eq!(result.mismatched_pixels(), 4);
assert_eq!(result.mismatch_percentage(), 4.0); assert_eq!(result.diff_bounds(), Some(Rect::new(3, 3, 2, 2)));
let diff_img = result.diff_image().expect("diff image");
let diff_px = diff_img.pixel(3, 3).expect("pixel");
assert_eq!(diff_px, [255, 0, 128, 255]); let same_px = diff_img.pixel(0, 0).expect("pixel");
assert_ne!(same_px, [255, 0, 128, 255]); }
#[test]
fn visual_assertions_tolerance_allows_small_variations() {
let img1 = CaptureImage::new(2, 2, [100u8, 100, 100, 255].repeat(4));
let img2 = CaptureImage::new(2, 2, [103u8, 102, 101, 255].repeat(4));
let strict = ImageDiffOptions::new().with_tolerance(0);
let res_strict = img1.diff(&img2, &strict).expect("diff strict");
assert!(!res_strict.passed());
assert_eq!(res_strict.mismatched_pixels(), 4);
let lenient = ImageDiffOptions::new().with_tolerance(5);
let res_lenient = img1.diff(&img2, &lenient).expect("diff lenient");
assert!(res_lenient.passed());
assert_eq!(res_lenient.mismatched_pixels(), 0);
}
#[test]
fn visual_assertions_masked_regions_are_ignored() {
let mut pixels1 = [50u8, 50, 50, 255].repeat(100); let pixels2 = pixels1.clone();
for y in 5..8 {
for x in 5..8 {
let idx = ((y * 10 + x) * 4) as usize;
pixels1[idx] = 220;
}
}
let img1 = CaptureImage::new(10, 10, pixels1);
let img2 = CaptureImage::new(10, 10, pixels2);
let no_mask = ImageDiffOptions::default();
let res_no_mask = img1.diff(&img2, &no_mask).expect("no mask");
assert!(!res_no_mask.passed());
assert_eq!(res_no_mask.mismatched_pixels(), 9);
let masked = ImageDiffOptions::default().with_mask_rect(5, 5, 3, 3);
let resolved = vec![Rect::new(5, 5, 3, 3)];
let res_masked = compare_images(&img1, &img2, &masked, &resolved).expect("masked");
assert!(res_masked.passed());
assert_eq!(res_masked.mismatched_pixels(), 0);
assert_eq!(res_masked.total_pixels, 91); }
#[test]
fn png_encode_decode_round_trip() {
let width = 8u32;
let height = 6u32;
let mut raw = Vec::with_capacity((width * height * 4) as usize);
for y in 0..height {
for x in 0..width {
raw.push((x * 30) as u8);
raw.push((y * 40) as u8);
raw.push(180);
raw.push(255);
}
}
let original = CaptureImage::new(width, height, raw);
let encoded_png = original.to_png().expect("encode png");
assert!(encoded_png.len() > 8);
let decoded = CaptureImage::from_png(&encoded_png).expect("decode png");
assert_eq!(decoded.width(), original.width());
assert_eq!(decoded.height(), original.height());
assert_eq!(decoded.data(), original.data());
}
#[test]
fn visual_golden_baseline_lifecycle_and_intentional_failure() {
let scratch_dir =
std::env::temp_dir().join(format!("native_gui_e2e_test_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&scratch_dir);
let _ = std::fs::create_dir_all(&scratch_dir);
let orig_baseline_env = std::env::var("NATIVE_GUI_E2E_BASELINES_DIR").ok();
let orig_update_env = std::env::var("NATIVE_GUI_E2E_UPDATE_BASELINES").ok();
std::env::set_var("NATIVE_GUI_E2E_BASELINES_DIR", &scratch_dir);
let (mut driver, win, button) = driver();
std::env::remove_var("NATIVE_GUI_E2E_UPDATE_BASELINES");
let miss_err = driver.assert_screenshot_matches(
CaptureTarget::Window(win),
"sample_win",
&ImageDiffOptions::default(),
);
assert!(miss_err.is_err(), "missing baseline should fail");
std::env::set_var("NATIVE_GUI_E2E_UPDATE_BASELINES", "1");
let record_res = driver.assert_screenshot_matches(
CaptureTarget::Window(win),
"sample_win",
&ImageDiffOptions::default(),
);
assert!(record_res.is_ok(), "recording baseline should succeed");
std::env::remove_var("NATIVE_GUI_E2E_UPDATE_BASELINES");
let baseline_file = scratch_dir.join("mock").join("sample_win.png");
assert!(baseline_file.exists(), "baseline png must exist on disk");
let match_res = driver.assert_screenshot_matches(
CaptureTarget::Window(win),
"sample_win",
&ImageDiffOptions::default(),
);
assert!(match_res.is_ok(), "identical UI should match baseline");
driver.ui_mut().set_text(button, "MODIFIED_LABEL").unwrap();
let diff_dir = scratch_dir.join("diffs");
let fail_options = ImageDiffOptions::default().with_diff_output_dir(&diff_dir);
let fail_res = driver.assert_screenshot_matches(
CaptureTarget::Window(win),
"sample_win",
&fail_options,
);
assert!(fail_res.is_err(), "modified UI must fail visual assertion");
let diff_file = diff_dir.join("sample_win_diff.png");
let actual_file = diff_dir.join("sample_win_actual.png");
assert!(diff_file.exists(), "diff artifact png must be created");
assert!(actual_file.exists(), "actual artifact png must be created");
if let Some(val) = orig_baseline_env {
std::env::set_var("NATIVE_GUI_E2E_BASELINES_DIR", val);
} else {
std::env::remove_var("NATIVE_GUI_E2E_BASELINES_DIR");
}
if let Some(val) = orig_update_env {
std::env::set_var("NATIVE_GUI_E2E_UPDATE_BASELINES", val);
} else {
std::env::remove_var("NATIVE_GUI_E2E_UPDATE_BASELINES");
}
let _ = std::fs::remove_dir_all(&scratch_dir);
}
#[test]
#[cfg(all(feature = "widgets-containers", feature = "widgets-pickers"))]
fn dialog_and_secondary_window_automation_on_mock() {
let mut ui = Ui::new(MockBackend::default());
let main_win = ui.create(WidgetKind::Window, Some("Main Window")).unwrap();
ui.show(main_win).unwrap();
let sec_win = ui.create(WidgetKind::Window, Some("Settings")).unwrap();
let sec_btn = ui.create(WidgetKind::Button, Some("Save")).unwrap();
ui.attach(sec_win, sec_btn).unwrap();
ui.show(sec_win).unwrap();
let alert = ui
.create(WidgetKind::AlertDialog, Some("Confirm Exit"))
.unwrap();
let alert_ok = ui.create(WidgetKind::Button, Some("OK")).unwrap();
ui.attach(alert, alert_ok).unwrap();
ui.show(alert).unwrap();
let chooser = ui
.create(WidgetKind::FileChooserDialog, Some("Open File"))
.unwrap();
ui.show(chooser).unwrap();
let color_dlg = ui
.create(WidgetKind::ColorDialog, Some("Choose Color"))
.unwrap();
ui.set_color_dialog_data(
color_dlg,
native_gui_core::ColorDialogData::new(native_gui_core::Rgba::new(255, 0, 0, 255)),
)
.unwrap();
ui.show(color_dlg).unwrap();
let font_dlg = ui
.create(WidgetKind::FontDialog, Some("Choose Font"))
.unwrap();
ui.set_font_dialog_data(
font_dlg,
native_gui_core::FontDialogData::new(native_gui_core::FontDescriptor::new(
"Consolas", 14.0,
)),
)
.unwrap();
ui.show(font_dlg).unwrap();
let events = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&events);
let mut driver = Driver::new(ui, move |_ui, event| {
seen.borrow_mut().push(event);
Ok(LoopFlow::Continue)
});
let windows = driver.windows().expect("driver.windows()");
assert_eq!(windows.len(), 2);
let dialogs = driver.dialogs().expect("driver.dialogs()");
assert_eq!(dialogs.len(), 4);
let btn_in_sec = driver
.find_in_window(sec_win, &Locator::text("Save"))
.expect("find in window");
assert!(btn_in_sec.is_some());
assert_eq!(btn_in_sec.unwrap().id(), sec_btn);
let mut alert_handle = driver
.find_dialog(&Locator::kind(WidgetKind::AlertDialog))
.expect("find alert")
.expect("alert exists");
assert_eq!(alert_handle.id(), alert);
assert_eq!(alert_handle.title(&driver).unwrap(), "Confirm Exit");
let alert_img = alert_handle
.screenshot(&mut driver)
.expect("dialog screenshot");
assert!(alert_img.width() > 0 && alert_img.height() > 0);
alert_handle.accept(&mut driver).expect("accept alert");
assert_eq!(
*events.borrow(),
vec![UiEvent::Clicked {
widget_id: alert_ok
}]
);
events.borrow_mut().clear();
let mut chooser_handle = driver
.expect_dialog(&Locator::kind(WidgetKind::FileChooserDialog))
.expect("expect chooser");
chooser_handle
.choose_file(&mut driver, "C:/projects/sample-app/test.txt")
.expect("choose file");
assert_eq!(
*events.borrow(),
vec![UiEvent::TextChanged {
widget_id: chooser,
text: "C:/projects/sample-app/test.txt".into()
}]
);
events.borrow_mut().clear();
let mut color_handle = driver
.expect_dialog(&Locator::kind(WidgetKind::ColorDialog))
.expect("expect color dlg");
color_handle.accept(&mut driver).expect("accept color dlg");
assert_eq!(
*events.borrow(),
vec![UiEvent::ColorSelected {
widget_id: color_dlg,
color: Some(native_gui_core::Rgba::new(255, 0, 0, 255))
}]
);
events.borrow_mut().clear();
color_handle.cancel(&mut driver).expect("cancel color dlg");
assert_eq!(
*events.borrow(),
vec![UiEvent::ColorSelected {
widget_id: color_dlg,
color: None
}]
);
events.borrow_mut().clear();
let mut font_handle = driver
.expect_dialog(&Locator::kind(WidgetKind::FontDialog))
.expect("expect font dlg");
font_handle.accept(&mut driver).expect("accept font dlg");
assert!(matches!(
events.borrow().first(),
Some(UiEvent::FontSelected { widget_id, selection: Some(_) }) if *widget_id == font_dlg
));
events.borrow_mut().clear();
font_handle.cancel(&mut driver).expect("cancel font dlg");
assert_eq!(
*events.borrow(),
vec![UiEvent::FontSelected {
widget_id: font_dlg,
selection: None
}]
);
events.borrow_mut().clear();
}
#[test]
fn confirm_dialog_automation() {
let mut ui = Ui::new(MockBackend::default());
let main_win = ui.create(WidgetKind::Window, Some("Main")).unwrap();
ui.show(main_win).unwrap();
let token = ui
.show_confirm_dialog("Delete file?", "Are you sure?")
.expect("show confirm");
let events = Rc::new(RefCell::new(Vec::new()));
let seen = Rc::clone(&events);
let mut driver = Driver::new(ui, move |_ui, event| {
seen.borrow_mut().push(event);
Ok(LoopFlow::Continue)
});
let requests = driver.pending_confirm_requests();
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].0, token);
assert_eq!(requests[0].1, "Delete file?");
let dialogs = driver.dialogs().expect("dialogs");
assert_eq!(dialogs.len(), 1);
assert_eq!(dialogs[0].token(), Some(token));
driver
.respond_confirm_dialog(token, true)
.expect("respond confirm");
assert_eq!(
*events.borrow(),
vec![UiEvent::DialogResponse {
token,
confirmed: true
}]
);
}
#[test]
fn harness_backend_type_selection() {
assert_eq!(BackendType::Mock.as_str(), "mock");
assert_eq!(BackendType::Gtk.as_str(), "gtk");
assert_eq!(BackendType::Win32.as_str(), "win32");
assert_eq!(BackendType::Cocoa.as_str(), "cocoa");
assert!(BackendType::Mock.is_available());
assert_eq!(BackendType::platform_default(), BackendType::Mock);
assert!(!BackendType::Gtk.is_available());
assert!(!BackendType::Win32.is_available());
assert!(!BackendType::Cocoa.is_available());
for (name, expected) in [
("mock", BackendType::Mock),
("win32", BackendType::Win32),
(" WINDOWS ", BackendType::Win32),
("gtk", BackendType::Gtk),
("gtk4", BackendType::Gtk),
("cocoa", BackendType::Cocoa),
("macos", BackendType::Cocoa),
("appkit", BackendType::Cocoa),
] {
assert_eq!(BackendType::from_name(name), Some(expected));
}
assert_eq!(BackendType::from_name("unknown"), None);
}
#[test]
fn harness_refuses_native_requests_instead_of_running_mock() {
for backend in [BackendType::Gtk, BackendType::Win32, BackendType::Cocoa] {
let mut registry = ScenarioRegistry::new().with_config(HarnessConfig {
backend,
..HarnessConfig::default()
});
registry.register_fn("native_request", |_| {
panic!("a native request must not execute a Mock scenario")
});
let report = registry.run_all();
assert_eq!(report.total(), 1);
assert_eq!(report.passed(), 0);
assert_eq!(report.failed(), 1);
assert!(matches!(
&report.results[0].status,
ScenarioStatus::Failed(message)
if message.contains("e2e.unsupported_backend")
&& message.contains(backend.as_str())
));
}
}
#[test]
fn harness_scenario_execution_and_artifacts() {
let test_dir =
std::env::temp_dir().join(format!("native-gui-e2e-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&test_dir);
let config = HarnessConfig {
backend: BackendType::Mock,
default_timeout: Duration::from_secs(5),
step_timeout: Duration::from_secs(2),
artifacts_root: test_dir.clone(),
};
let mut registry = ScenarioRegistry::new().with_config(config);
registry.register_fn("scenario_success", |ctx| {
ctx.step("Create main window and button");
let win = ctx
.driver
.ui_mut()
.create(WidgetKind::Window, Some("App"))
.unwrap();
let btn = ctx
.driver
.ui_mut()
.create(WidgetKind::Button, Some("Submit"))
.unwrap();
ctx.driver.ui_mut().attach(btn, win).unwrap();
ctx.driver.ui_mut().show(win).unwrap();
ctx.driver.ui_mut().show(btn).unwrap();
ctx.step("Click submit button");
let el = ctx
.driver
.expect_one(&Locator::role(AccessibleRole::Button, "Submit"))?;
ctx.driver.click(&el)?;
assert!(!ctx.events().is_empty());
Ok(())
});
registry.register_fn("scenario_failure", |ctx| {
ctx.step("Initialize window");
let win = ctx
.driver
.ui_mut()
.create(WidgetKind::Window, Some("Error Window"))
.unwrap();
let label = ctx
.driver
.ui_mut()
.create(WidgetKind::Label, Some("Status Label"))
.unwrap();
ctx.driver.ui_mut().attach(label, win).unwrap();
ctx.driver.ui_mut().show(win).unwrap();
ctx.step("Simulate unexpected condition");
Err(GuiError::Backend(
"intentional test assertion failure".into(),
))
});
assert_eq!(registry.len(), 2);
assert!(!registry.is_empty());
let report = registry.run_all();
assert_eq!(report.total(), 2);
assert_eq!(report.passed(), 1);
assert_eq!(report.failed(), 1);
assert_eq!(report.skipped(), 0);
let pass_res = report
.results
.iter()
.find(|r| r.name == "scenario_success")
.unwrap();
assert!(pass_res.is_pass());
assert!(!pass_res.is_failure());
assert_eq!(pass_res.steps.len(), 2);
assert!(pass_res.artifacts_dir.is_none());
let fail_res = report
.results
.iter()
.find(|r| r.name == "scenario_failure")
.unwrap();
assert!(!fail_res.is_pass());
assert!(fail_res.is_failure());
assert_eq!(fail_res.steps.len(), 2);
let artifacts_path = fail_res.artifacts_dir.as_ref().expect("artifacts dir");
assert!(artifacts_path.exists());
assert!(artifacts_path.join("screenshot.png").exists());
assert!(artifacts_path.join("widget_tree.txt").exists());
assert!(artifacts_path.join("events.log").exists());
assert!(artifacts_path.join("error.txt").exists());
let tree_content = std::fs::read_to_string(artifacts_path.join("widget_tree.txt")).unwrap();
assert!(tree_content.contains("Window"));
assert!(tree_content.contains("Error Window"));
assert!(tree_content.contains("Label"));
assert!(tree_content.contains("Status Label"));
let err_content = std::fs::read_to_string(artifacts_path.join("error.txt")).unwrap();
assert!(err_content.contains("intentional test assertion failure"));
assert!(err_content.contains("1. Initialize window"));
assert!(err_content.contains("2. Simulate unexpected condition"));
let junit = report.to_junit_xml();
assert!(junit.contains("<testsuites tests=\"2\" failures=\"1\""));
assert!(junit.contains("<testcase name=\"scenario_success\""));
assert!(junit.contains("<testcase name=\"scenario_failure\""));
assert!(junit.contains("intentional test assertion failure"));
let json = report.to_json();
assert!(json.contains("\"total\": 2"));
assert!(json.contains("\"passed\": 1"));
assert!(json.contains("\"failed\": 1"));
assert!(json.contains("\"status\": \"passed\""));
assert!(json.contains("\"status\": \"failed\""));
let _ = std::fs::remove_dir_all(&test_dir);
}
#[test]
fn harness_scenario_filtering() {
let mut registry = ScenarioRegistry::new();
registry.register_fn("auth_login", |_ctx| Ok(()));
registry.register_fn("auth_logout", |_ctx| Ok(()));
registry.register_fn("settings_update", |_ctx| Ok(()));
let report_auth = registry.run_filtered("auth");
assert_eq!(report_auth.total(), 2);
assert_eq!(report_auth.passed(), 2);
let report_settings = registry.run_filtered("settings");
assert_eq!(report_settings.total(), 1);
assert_eq!(report_settings.passed(), 1);
let report_none = registry.run_filtered("nonexistent");
assert_eq!(report_none.total(), 0);
}
#[test]
#[cfg(feature = "widgets-text")]
fn dump_widget_tree_formatting() {
let mut ui = Ui::new(MockBackend::default());
let win = ui.create(WidgetKind::Window, Some("Main Window")).unwrap();
let cont = ui.create(WidgetKind::Container, None).unwrap();
let btn = ui.create(WidgetKind::Button, Some("OK")).unwrap();
let text = ui.create(WidgetKind::TextInput, Some("Hello")).unwrap();
ui.attach(cont, win).unwrap();
ui.attach(btn, cont).unwrap();
ui.attach(text, cont).unwrap();
ui.show(win).unwrap();
let dump = dump_widget_tree(&ui);
assert!(dump.contains("Window"));
assert!(dump.contains("\"Main Window\""));
assert!(dump.contains("Container"));
assert!(dump.contains("Button"));
assert!(dump.contains("\"OK\""));
assert!(dump.contains("TextInput"));
assert!(dump.contains("\"Hello\""));
}
}