native-gui-mock 1.0.0

Headless Mock backend and in-process E2E testing framework for Native GUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Dialog and secondary-window automation.
//!
//! Provides handles and helpers to locate, query, drive, and screenshot
//! secondary windows, alerts, message boxes, pickers (file, color, font),
//! and custom modal or modeless dialog surfaces.

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};

/// Returns `true` if `kind` represents a standard dialog widget.
pub fn is_dialog(kind: WidgetKind) -> bool {
    kind.is_dialog()
}

/// Returns `true` if `kind` represents a top-level surface (window or dialog).
pub fn is_window_or_dialog(kind: WidgetKind) -> bool {
    kind.is_window_like()
}

/// A handle to a live dialog or secondary window during an E2E test session.
#[derive(Debug, Clone)]
pub struct DialogHandle {
    widget_id: WidgetId,
    kind: WidgetKind,
    token: Option<u64>,
}

impl DialogHandle {
    /// Creates a dialog handle from a widget ID and kind.
    pub fn new(widget_id: WidgetId, kind: WidgetKind) -> Self {
        Self {
            widget_id,
            kind,
            token: None,
        }
    }

    /// Creates a dialog handle representing a programmatic confirm dialog with a token.
    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),
        }
    }

    /// Returns the widget identifier of this dialog.
    pub fn id(&self) -> WidgetId {
        self.widget_id
    }

    /// Returns the widget kind of this dialog.
    pub fn kind(&self) -> WidgetKind {
        self.kind
    }

    /// Returns the programmatic dialog token, if this handle represents a confirm dialog.
    pub fn token(&self) -> Option<u64> {
        self.token
    }

    /// Returns an [`Element`] handle to this dialog surface.
    pub fn element<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> Element {
        driver.element(self.widget_id)
    }

    /// Reads the title or caption of this dialog.
    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())
    }

    /// Finds a single child element matching `locator` scoped inside this dialog.
    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)))
    }

    /// Expects exactly one child element matching `locator` scoped inside this dialog.
    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)))
    }

    /// Clicks a child control within this dialog.
    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)
    }

    /// Types text into an editable child control inside this dialog.
    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)
    }

    /// Picks a file or directory path in a file chooser dialog.
    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 {
            // Update widget text and dispatch change
            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")]
            {
                // Search for an input inside this dialog to fill
                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
                )))
            }
        }
    }

    /// Accepts or confirms the dialog (clicking OK / Save / Submit, or answering Yes).
    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(())
    }

    /// Cancels or dismisses the dialog (clicking Cancel / Close / No).
    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(())
    }

    /// Captures a screenshot of this dialog window.
    pub fn screenshot<B: E2eBackend, H>(
        &self,
        driver: &mut Driver<B, H>,
    ) -> GuiResult<CaptureImage> {
        driver.screenshot(CaptureTarget::Window(self.widget_id))
    }

    /// Closes this dialog surface.
    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)
    }
}