use crate::e2e::{CaptureImage, CaptureTarget, Driver, E2eBackend, Element, Locator};
use crate::MockBackend;
use native_gui_core::error::{GuiError, GuiResult};
use native_gui_core::events::UiEvent;
use native_gui_core::ui::{LoopFlow, Ui};
use native_gui_core::widgets::{WidgetId, WidgetKind};
pub fn is_dialog(kind: WidgetKind) -> bool {
kind.is_dialog()
}
pub fn is_window_or_dialog(kind: WidgetKind) -> bool {
kind.is_window_like()
}
#[derive(Debug, Clone)]
pub struct DialogHandle {
widget_id: WidgetId,
kind: WidgetKind,
token: Option<u64>,
}
impl DialogHandle {
pub fn new(widget_id: WidgetId, kind: WidgetKind) -> Self {
Self {
widget_id,
kind,
token: None,
}
}
pub fn for_token(widget_id: WidgetId, token: u64) -> Self {
#[cfg(feature = "widgets-containers")]
let kind = WidgetKind::AlertDialog;
#[cfg(not(feature = "widgets-containers"))]
let kind = WidgetKind::Window;
Self {
widget_id,
kind,
token: Some(token),
}
}
pub fn id(&self) -> WidgetId {
self.widget_id
}
pub fn kind(&self) -> WidgetKind {
self.kind
}
pub fn token(&self) -> Option<u64> {
self.token
}
pub fn element<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> Element {
driver.element(self.widget_id)
}
pub fn title<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<String> {
let spec = driver
.ui
.widget(self.widget_id)
.ok_or(GuiError::WidgetNotFound(self.widget_id.0))?;
if let Some(text) = &spec.text {
return Ok(text.clone());
}
if let Some(name) = &spec.accessibility.name {
return Ok(name.clone());
}
Ok(String::new())
}
pub fn find<B: E2eBackend, H>(
&self,
driver: &Driver<B, H>,
locator: &Locator,
) -> GuiResult<Option<Element>> {
driver.find(&locator.clone().in_window(Locator::id(self.widget_id)))
}
pub fn expect_one<B: E2eBackend, H>(
&self,
driver: &Driver<B, H>,
locator: &Locator,
) -> GuiResult<Element> {
driver.expect_one(&locator.clone().in_window(Locator::id(self.widget_id)))
}
pub fn click<B: E2eBackend, H>(
&self,
driver: &mut Driver<B, H>,
locator: &Locator,
) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
let elem = self.expect_one(driver, locator)?;
elem.click(driver)
}
pub fn fill<B: E2eBackend, H>(
&mut self,
driver: &mut Driver<B, H>,
locator: &Locator,
text: &str,
) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
let elem = self.expect_one(driver, locator)?;
elem.type_text(driver, text)
}
pub fn choose_file<B: E2eBackend, H>(
&mut self,
driver: &mut Driver<B, H>,
path: &str,
) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
#[cfg(feature = "widgets-pickers")]
let is_chooser = self.kind == WidgetKind::FileChooserDialog;
#[cfg(not(feature = "widgets-pickers"))]
let is_chooser = false;
if is_chooser {
driver.ui_mut().set_text(self.widget_id, path)?;
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
if is_mock {
let any_mut: &mut dyn std::any::Any = driver.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.events.push_back(UiEvent::TextChanged {
widget_id: self.widget_id,
text: path.to_owned(),
});
}
}
driver.pump()?;
Ok(())
} else {
#[cfg(feature = "widgets-text")]
{
let input_loc = Locator::kind(WidgetKind::TextInput);
if let Some(input) = self.find(driver, &input_loc)? {
input.type_text(driver, path)
} else {
Err(GuiError::Backend(format!(
"e2e.dialog: cannot choose file on widget of kind {:?}",
self.kind
)))
}
}
#[cfg(not(feature = "widgets-text"))]
{
let _ = path;
Err(GuiError::Backend(format!(
"e2e.dialog: cannot choose file on widget of kind {:?}",
self.kind
)))
}
}
}
pub fn accept<B: E2eBackend, H>(&mut self, driver: &mut Driver<B, H>) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
if let Some(token) = self.token {
return driver.respond_confirm_dialog(token, true);
}
#[cfg(feature = "widgets-pickers")]
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
#[cfg(feature = "widgets-pickers")]
let is_file_chooser = self.kind == WidgetKind::FileChooserDialog;
#[cfg(not(feature = "widgets-pickers"))]
let is_file_chooser = false;
if is_file_chooser || self.kind == WidgetKind::Window {
self.click_button_or_close(
driver,
&[
"OK", "Ok", "Save", "Submit", "Yes", "Accept", "Confirm", "Open",
],
true,
)?;
} else {
match self.kind {
#[cfg(feature = "widgets-pickers")]
WidgetKind::ColorDialog => {
if is_mock {
let initial = driver
.ui
.widget(self.widget_id)
.and_then(|s| s.color_dialog_data.as_ref())
.map(|d| d.initial)
.unwrap_or_else(|| native_gui_core::Rgba::new(0, 0, 0, 255));
let any_mut: &mut dyn std::any::Any = driver.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.inject_color_dialog_result(self.widget_id, Some(initial));
mock.events.push_back(UiEvent::ColorSelected {
widget_id: self.widget_id,
color: Some(initial),
});
}
}
}
#[cfg(feature = "widgets-pickers")]
WidgetKind::FontDialog => {
if is_mock {
let data = driver
.ui
.widget(self.widget_id)
.and_then(|s| s.font_dialog_data.clone());
let desc = data.as_ref().map(|d| d.initial.clone()).unwrap_or_else(|| {
native_gui_core::FontDescriptor::new("sans-serif", 12.0)
});
let effects = data.as_ref().map(|d| d.effects).unwrap_or_default();
let any_mut: &mut dyn std::any::Any = driver.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.inject_font_dialog_result(
self.widget_id,
Some((desc.clone(), effects)),
);
mock.events.push_back(UiEvent::FontSelected {
widget_id: self.widget_id,
selection: Some((desc, effects)),
});
}
}
}
#[cfg(feature = "widgets-containers")]
WidgetKind::AlertDialog => {
self.click_button_or_close(
driver,
&[
"OK", "Ok", "Save", "Submit", "Yes", "Accept", "Confirm", "Open",
],
false,
)?;
}
_ => {
self.close(driver)?;
}
}
}
if driver.active_modal() == Some(self.widget_id) {
driver.set_active_modal(None);
}
driver.pump()?;
Ok(())
}
fn click_button_or_close<B: E2eBackend, H>(
&self,
driver: &mut Driver<B, H>,
labels: &[&str],
scan_all_buttons: bool,
) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
let mut clicked = false;
for label in labels {
let btn_loc = Locator::text(*label).child_of(Locator::id(self.widget_id));
if let Ok(Some(btn)) = driver.find(&btn_loc) {
btn.click(driver)?;
clicked = true;
break;
}
}
if !clicked && scan_all_buttons {
let any_btn = Locator::kind(WidgetKind::Button).in_window(Locator::id(self.widget_id));
if let Ok(buttons) = driver.find_all(&any_btn) {
for btn in buttons {
if let Ok(txt) = btn.text(driver) {
if labels.iter().any(|&l| l.eq_ignore_ascii_case(&txt)) {
btn.click(driver)?;
clicked = true;
break;
}
}
}
}
}
if !clicked {
self.close(driver)?;
}
Ok(())
}
pub fn cancel<B: E2eBackend, H>(&mut self, driver: &mut Driver<B, H>) -> GuiResult<()>
where
H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
if let Some(token) = self.token {
return driver.respond_confirm_dialog(token, false);
}
#[cfg(feature = "widgets-pickers")]
let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
match self.kind {
#[cfg(feature = "widgets-pickers")]
WidgetKind::ColorDialog => {
if is_mock {
let any_mut: &mut dyn std::any::Any = driver.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.inject_color_dialog_result(self.widget_id, None);
mock.events.push_back(UiEvent::ColorSelected {
widget_id: self.widget_id,
color: None,
});
}
}
}
#[cfg(feature = "widgets-pickers")]
WidgetKind::FontDialog => {
if is_mock {
let any_mut: &mut dyn std::any::Any = driver.ui.backend_mut();
if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
mock.inject_font_dialog_result(self.widget_id, None);
mock.events.push_back(UiEvent::FontSelected {
widget_id: self.widget_id,
selection: None,
});
}
}
}
_ => {
let cancel_labels = [
"Cancel", "cancel", "No", "no", "Close", "close", "Discard", "Abort",
];
let mut clicked = false;
for label in &cancel_labels {
let btn_loc = Locator::text(*label).child_of(Locator::id(self.widget_id));
if let Ok(Some(btn)) = driver.find(&btn_loc) {
btn.click(driver)?;
clicked = true;
break;
}
}
if !clicked {
let any_btn =
Locator::kind(WidgetKind::Button).in_window(Locator::id(self.widget_id));
if let Ok(buttons) = driver.find_all(&any_btn) {
for btn in buttons {
if let Ok(txt) = btn.text(driver) {
if cancel_labels.iter().any(|&l| l.eq_ignore_ascii_case(&txt)) {
btn.click(driver)?;
clicked = true;
break;
}
}
}
}
}
if !clicked {
self.close(driver)?;
}
}
}
if driver.active_modal() == Some(self.widget_id) {
driver.set_active_modal(None);
}
driver.pump()?;
Ok(())
}
pub fn screenshot<B: E2eBackend, H>(
&self,
driver: &mut Driver<B, H>,
) -> GuiResult<CaptureImage> {
driver.screenshot(CaptureTarget::Window(self.widget_id))
}
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>,
{
let elem = driver.element(self.widget_id);
elem.close(driver)
}
}