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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! E2E screenshot gallery capture pipeline, dialogs, and multi-state scenarios.
//!
//! Provides automated, scriptable E2E scenarios for capturing native modal dialogs,
//! file/color/font pickers, and complex multi-state widget interactions (such as
//! live form validation error states and secondary tab views) for the documentation
//! screenshot gallery and cross-platform manifest.

use std::path::{Path, PathBuf};

use crate::e2e::{CaptureImage, CaptureTarget, Driver};
use crate::MockBackend;
use native_gui_core::error::{GuiError, GuiResult};
use native_gui_core::events::UiEvent;
#[cfg(feature = "widgets-pickers")]
use native_gui_core::pickers::{ColorDialogData, FontDescriptor, FontDialogData};
use native_gui_core::ui::{LoopFlow, Ui};
#[cfg(feature = "widgets-containers")]
use native_gui_core::widgets::AlertLevel;
use native_gui_core::widgets::{ContainerDirection, WidgetKind};
#[cfg(feature = "widgets-pickers")]
use native_gui_core::Rgba;

/// Metadata and execution spec for a screenshot gallery scenario.
#[derive(Debug, Clone)]
pub struct GalleryScenarioSpec {
    /// Identifier matching the example or scenario PNG name (e.g. `gui_widget_alert_dialog`).
    pub id: &'static str,
    /// Human-readable title for the gallery matrix.
    pub title: &'static str,
    /// Gallery section category (`"widget"`, `"dialog"`, `"application"`, `"state"`).
    pub category: &'static str,
    /// Detailed description of the scenario and visual state.
    pub description: &'static str,
    /// Documentation cross-reference link.
    pub widget_doc: &'static str,
}

/// Result of executing a single gallery capture scenario.
#[derive(Debug, Clone)]
pub struct GalleryCaptureResult {
    /// Scenario specification.
    pub spec: GalleryScenarioSpec,
    /// Captured image width in pixels.
    pub width: u32,
    /// Captured image height in pixels.
    pub height: u32,
    /// Path where the PNG was saved, if written to disk.
    pub output_path: Option<PathBuf>,
    /// File size in bytes.
    pub size_bytes: usize,
}

/// Registry of standard gallery capture scenarios.
pub fn standard_gallery_scenarios() -> Vec<GalleryScenarioSpec> {
    vec![
        #[cfg(feature = "widgets-containers")]
        GalleryScenarioSpec {
            id: "gui_widget_alert_dialog",
            title: "AlertDialog",
            category: "widget",
            description: "Modal warning alert dialog prompt with warning icon, explanatory message, and confirmation action.",
            widget_doc: "reference/widget-reference.md#alertdialog",
        },
        GalleryScenarioSpec {
            id: "gui_dialog_confirm",
            title: "ConfirmationDialog",
            category: "widget",
            description: "Modal confirmation prompt for unsaved changes with Save, Don't Save, and Cancel options.",
            widget_doc: "reference/widget-reference.md#alertdialog",
        },
        #[cfg(feature = "widgets-pickers")]
        GalleryScenarioSpec {
            id: "gui_widget_file_chooser_dialog",
            title: "FileChooserDialog",
            category: "widget",
            description: "Native file open and save dialog with directory navigation and file-type filters.",
            widget_doc: "reference/widget-reference.md#filechooserdialog",
        },
        #[cfg(feature = "widgets-pickers")]
        GalleryScenarioSpec {
            id: "gui_widget_color_dialog",
            title: "ColorPickerDialog",
            category: "widget",
            description: "Color picker dialog featuring custom palette swatches, RGB channel controls, and live color preview.",
            widget_doc: "reference/widget-reference.md#colordialog",
        },
        #[cfg(feature = "widgets-pickers")]
        GalleryScenarioSpec {
            id: "gui_widget_font_dialog",
            title: "FontPickerDialog",
            category: "widget",
            description: "Font chooser dialog selecting family, point size, bold/italic styles, and live preview rendering.",
            widget_doc: "reference/widget-reference.md#fontdialog",
        },
        GalleryScenarioSpec {
            id: "gui_form_validation",
            title: "Form Validation Errors",
            category: "state",
            description: "Active form validation error state displaying invalid field highlights, warning icons, and inline validation banners.",
            widget_doc: "examples-index.md#app-style-applications",
        },
        #[cfg(all(feature = "widgets-containers", feature = "widgets-choice"))]
        GalleryScenarioSpec {
            id: "gui_multi_state_tabs",
            title: "Multi-State Tabs",
            category: "state",
            description: "Secondary active tab state displaying advanced diagnostics, memory limits, and nested slider configuration.",
            widget_doc: "reference/widget-reference.md#tabs",
        },
    ]
}

// ============================================================================
// Scenario Implementations
// ============================================================================

fn noop_handler(_ui: &mut Ui<MockBackend>, _ev: UiEvent) -> GuiResult<LoopFlow> {
    Ok(LoopFlow::Continue)
}

/// Scenario 1: Alert Dialog
#[cfg(feature = "widgets-containers")]
pub fn capture_scenario_alert_dialog() -> GuiResult<CaptureImage> {
    let mut ui = Ui::new(MockBackend::default());
    let window = ui.create(WidgetKind::Window, Some("Application Main Window"))?;
    let container = ui.create(WidgetKind::Container, None)?;
    ui.set_container_direction(container, ContainerDirection::Vertical)?;
    ui.attach(window, container)?;

    let label = ui.create(WidgetKind::Label, Some("Document Workspace: Untitled-1.rs"))?;
    let alert = ui.create(
        WidgetKind::AlertDialog,
        Some("Warning: You have unsaved changes that will be discarded. Do you wish to continue?"),
    )?;
    ui.set_alert_level(alert, AlertLevel::Warning)?;

    ui.attach(container, label)?;
    ui.attach(container, alert)?;
    ui.set_layout_root(window)?;
    ui.show(window)?;
    ui.show(alert)?;

    let mut driver = Driver::new(ui, noop_handler);
    driver.pump()?;
    driver.screenshot(CaptureTarget::Window(alert))
}

#[cfg(not(feature = "widgets-containers"))]
pub fn capture_scenario_alert_dialog() -> GuiResult<CaptureImage> {
    Err(GuiError::UnsupportedWidget("AlertDialog"))
}

/// Scenario 2: Confirmation Dialog
pub fn capture_scenario_confirm_dialog() -> GuiResult<CaptureImage> {
    let mut ui = Ui::new(MockBackend::default());
    let window = ui.create(WidgetKind::Window, Some("Editor Workspace"))?;
    let container = ui.create(WidgetKind::Container, None)?;
    ui.set_container_direction(container, ContainerDirection::Vertical)?;
    ui.attach(window, container)?;

    let dialog = ui.create(WidgetKind::Window, Some("Confirm Close"))?;
    let dialog_box = ui.create(WidgetKind::Container, None)?;
    ui.set_container_direction(dialog_box, ContainerDirection::Vertical)?;
    ui.attach(dialog, dialog_box)?;

    let msg = ui.create(
        WidgetKind::Label,
        Some("Save changes to 'annual_report_2026.csv' before exiting?"),
    )?;
    let btn_bar = ui.create(WidgetKind::Container, None)?;
    ui.set_container_direction(btn_bar, ContainerDirection::Horizontal)?;

    let btn_save = ui.create(WidgetKind::Button, Some("Save"))?;
    let btn_dont = ui.create(WidgetKind::Button, Some("Don't Save"))?;
    let btn_cancel = ui.create(WidgetKind::Button, Some("Cancel"))?;

    ui.attach(btn_bar, btn_save)?;
    ui.attach(btn_bar, btn_dont)?;
    ui.attach(btn_bar, btn_cancel)?;

    ui.attach(dialog_box, msg)?;
    ui.attach(dialog_box, btn_bar)?;

    ui.set_layout_root(window)?;
    ui.set_layout_root(dialog)?;
    ui.show(window)?;
    ui.show(dialog)?;

    let mut driver = Driver::new(ui, noop_handler);
    driver.pump()?;
    driver.screenshot(CaptureTarget::Window(dialog))
}

/// Scenario 3: File Chooser Dialog
#[cfg(feature = "widgets-pickers")]
pub fn capture_scenario_file_chooser() -> GuiResult<CaptureImage> {
    let mut ui = Ui::new(MockBackend::default());
    let window = ui.create(WidgetKind::Window, Some("Open Project File"))?;
    let chooser = ui.create(
        WidgetKind::FileChooserDialog,
        Some("Select Source Code (*.rs, *.toml)"),
    )?;
    ui.set_text(
        chooser,
        "C:\\Users\\alex\\Projects\\sample-app\\src\\main.rs",
    )?;
    ui.set_layout_root(window)?;
    ui.attach(window, chooser)?;
    ui.show(window)?;
    ui.show(chooser)?;

    let mut driver = Driver::new(ui, noop_handler);
    driver.pump()?;
    driver.screenshot(CaptureTarget::Window(chooser))
}

#[cfg(not(feature = "widgets-pickers"))]
pub fn capture_scenario_file_chooser() -> GuiResult<CaptureImage> {
    Err(GuiError::UnsupportedWidget("FileChooserDialog"))
}

/// Scenario 4: Color Picker Dialog
#[cfg(feature = "widgets-pickers")]
pub fn capture_scenario_color_picker() -> GuiResult<CaptureImage> {
    let mut ui = Ui::new(MockBackend::default());
    let window = ui.create(WidgetKind::Window, Some("Palette Selection"))?;
    let color_dialog = ui.create(WidgetKind::ColorDialog, Some("Choose Theme Accent Color"))?;
    let mut color_data = ColorDialogData::new(Rgba::new(42, 127, 255, 255));
    let _ = color_data.push_custom(Rgba::new(255, 69, 58, 255));
    let _ = color_data.push_custom(Rgba::new(48, 209, 88, 255));
    let _ = color_data.push_custom(Rgba::new(10, 132, 255, 255));
    ui.set_color_dialog_data(color_dialog, color_data)?;
    ui.set_layout_root(window)?;
    ui.attach(window, color_dialog)?;
    ui.show(window)?;
    ui.show(color_dialog)?;

    let mut driver = Driver::new(ui, noop_handler);
    driver.pump()?;
    driver.screenshot(CaptureTarget::Window(color_dialog))
}

#[cfg(not(feature = "widgets-pickers"))]
pub fn capture_scenario_color_picker() -> GuiResult<CaptureImage> {
    Err(GuiError::UnsupportedWidget("ColorDialog"))
}

/// Scenario 5: Font Picker Dialog
#[cfg(feature = "widgets-pickers")]
pub fn capture_scenario_font_picker() -> GuiResult<CaptureImage> {
    let mut ui = Ui::new(MockBackend::default());
    let window = ui.create(WidgetKind::Window, Some("Typography Settings"))?;
    let font_dialog = ui.create(WidgetKind::FontDialog, Some("Select Editor Font"))?;
    let font_data = FontDialogData::new(FontDescriptor::new("Segoe UI Variable Display", 13.5));
    ui.set_font_dialog_data(font_dialog, font_data)?;
    ui.set_layout_root(window)?;
    ui.attach(window, font_dialog)?;
    ui.show(window)?;
    ui.show(font_dialog)?;

    let mut driver = Driver::new(ui, noop_handler);
    driver.pump()?;
    driver.screenshot(CaptureTarget::Window(font_dialog))
}

#[cfg(not(feature = "widgets-pickers"))]
pub fn capture_scenario_font_picker() -> GuiResult<CaptureImage> {
    Err(GuiError::UnsupportedWidget("FontDialog"))
}

/// Scenario 6: Form Validation Error State
#[cfg(feature = "widgets-text")]
pub fn capture_scenario_form_validation() -> GuiResult<CaptureImage> {
    let mut ui = Ui::new(MockBackend::default());
    let window = ui.create(
        WidgetKind::Window,
        Some("Account Registration - Validation Required"),
    )?;
    let container = ui.create(WidgetKind::Container, None)?;
    ui.set_container_direction(container, ContainerDirection::Vertical)?;
    ui.attach(window, container)?;

    // Title & Error Banner
    let banner = ui.create(
        WidgetKind::Label,
        Some("[!] Error: Please correct 3 highlighted issues before submitting."),
    )?;
    ui.attach(container, banner)?;

    // Name field
    let name_lbl = ui.create(WidgetKind::Label, Some("User Name: *"))?;
    let name_input = ui.create(WidgetKind::TextInput, Some("usr"))?;
    let name_err = ui.create(
        WidgetKind::Label,
        Some("x Name must be at least 4 characters long"),
    )?;
    ui.attach(container, name_lbl)?;
    ui.attach(container, name_input)?;
    ui.attach(container, name_err)?;

    // Email field
    let email_lbl = ui.create(WidgetKind::Label, Some("Email Address: *"))?;
    let email_input = ui.create(WidgetKind::TextInput, Some("developer@"))?;
    let email_err = ui.create(
        WidgetKind::Label,
        Some("x Please enter a valid email address (e.g. dev@example.com)"),
    )?;
    ui.attach(container, email_lbl)?;
    ui.attach(container, email_input)?;
    ui.attach(container, email_err)?;

    // Submit button
    let submit_btn = ui.create(WidgetKind::Button, Some("Register Account"))?;
    ui.attach(container, submit_btn)?;

    ui.set_layout_root(window)?;
    ui.show(window)?;

    let mut driver = Driver::new(ui, noop_handler);
    driver.pump()?;
    driver.screenshot(CaptureTarget::Window(window))
}

#[cfg(not(feature = "widgets-text"))]
pub fn capture_scenario_form_validation() -> GuiResult<CaptureImage> {
    Err(GuiError::UnsupportedWidget("TextInput"))
}

#[cfg(not(all(feature = "widgets-containers", feature = "widgets-choice")))]
pub fn capture_scenario_multi_state_tabs() -> GuiResult<CaptureImage> {
    Err(GuiError::UnsupportedWidget("Tabs"))
}

/// Scenario 7: Multi-State Tabs
#[cfg(all(feature = "widgets-containers", feature = "widgets-choice"))]
pub fn capture_scenario_multi_state_tabs() -> GuiResult<CaptureImage> {
    let mut ui = Ui::new(MockBackend::default());
    let window = ui.create(
        WidgetKind::Window,
        Some("System Configuration - Advanced Settings"),
    )?;
    let container = ui.create(WidgetKind::Container, None)?;
    ui.set_container_direction(container, ContainerDirection::Vertical)?;
    ui.attach(window, container)?;

    // Tabs widget: pages are its attached children, in attach order,
    // mirroring `examples/gui_multi_state_tabs.rs`.
    let tabs = ui.create(WidgetKind::Tabs, None)?;
    ui.attach(container, tabs)?;
    ui.set_min_size(tabs, 520, 260)?;

    // General page
    let general = ui.create(WidgetKind::Container, None)?;
    ui.set_container_direction(general, ContainerDirection::Vertical)?;
    ui.attach(tabs, general)?;
    let general_hint = ui.create(
        WidgetKind::Label,
        Some("Profile-wide defaults apply to every network location."),
    )?;
    ui.attach(general, general_hint)?;

    // Network page
    let network = ui.create(WidgetKind::Container, None)?;
    ui.set_container_direction(network, ContainerDirection::Vertical)?;
    ui.attach(tabs, network)?;
    let network_hint = ui.create(
        WidgetKind::Label,
        Some("Auto-detect proxy settings (WPAD) for the active interface."),
    )?;
    ui.attach(network, network_hint)?;

    // Advanced pane controls
    let pane = ui.create(WidgetKind::Container, None)?;
    ui.set_container_direction(pane, ContainerDirection::Vertical)?;
    ui.attach(tabs, pane)?;

    let desc = ui.create(
        WidgetKind::Label,
        Some("Hardware Acceleration & Diagnostics Subsystem:"),
    )?;
    let chk_gpu = ui.create(
        WidgetKind::Checkbox,
        Some("Enable High-DPI Vulkan Compositor"),
    )?;
    ui.set_checked(chk_gpu, true)?;

    let chk_logs = ui.create(
        WidgetKind::Checkbox,
        Some("Verbose Ring Buffer Event Tracing"),
    )?;
    ui.set_checked(chk_logs, true)?;

    #[cfg(feature = "widgets-range")]
    let slider_lbl = ui.create(WidgetKind::Label, Some("Memory Pool Size: 512 MB"))?;
    #[cfg(feature = "widgets-range")]
    let slider = ui.create(WidgetKind::Slider, None)?;
    #[cfg(feature = "widgets-range")]
    ui.set_range(slider, 64, 2048)?;
    #[cfg(feature = "widgets-range")]
    ui.set_value(slider, 512)?;

    ui.attach(pane, desc)?;
    ui.attach(pane, chk_gpu)?;
    ui.attach(pane, chk_logs)?;
    #[cfg(feature = "widgets-range")]
    ui.attach(pane, slider_lbl)?;
    #[cfg(feature = "widgets-range")]
    ui.attach(pane, slider)?;

    let tab_labels = vec![
        "General".to_string(),
        "Network & Proxy".to_string(),
        "Advanced Diagnostics (Active)".to_string(),
    ];
    ui.set_tab_items(tabs, &tab_labels)?;
    ui.set_selected_index(tabs, 2)?; // Select Advanced tab

    ui.set_layout_root(window)?;
    ui.show(window)?;

    let mut driver = Driver::new(ui, noop_handler);
    driver.pump()?;
    driver.screenshot(CaptureTarget::Window(window))
}

/// Executes a scenario by its id and returns the captured image.
pub fn capture_scenario_by_id(id: &str) -> GuiResult<CaptureImage> {
    match id {
        "gui_widget_alert_dialog" => capture_scenario_alert_dialog(),
        "gui_dialog_confirm" => capture_scenario_confirm_dialog(),
        "gui_widget_file_chooser_dialog" => capture_scenario_file_chooser(),
        "gui_widget_color_dialog" => capture_scenario_color_picker(),
        "gui_widget_font_dialog" => capture_scenario_font_picker(),
        "gui_form_validation" => capture_scenario_form_validation(),
        "gui_multi_state_tabs" => capture_scenario_multi_state_tabs(),
        other => Err(GuiError::Backend(format!(
            "e2e.gallery: unknown scenario id '{other}'"
        ))),
    }
}

/// Runs all standard gallery scenarios and writes PNG captures to `output_dir`.
pub fn run_all_gallery_captures(
    output_dir: impl AsRef<Path>,
) -> GuiResult<Vec<GalleryCaptureResult>> {
    let out_dir = output_dir.as_ref();
    std::fs::create_dir_all(out_dir)
        .map_err(|e| GuiError::Backend(format!("e2e.gallery: failed to create output dir: {e}")))?;

    let scenarios = standard_gallery_scenarios();
    let mut results = Vec::new();

    for spec in scenarios {
        let img = capture_scenario_by_id(spec.id)?;
        let file_name = format!("{}.png", spec.id);
        let dest = out_dir.join(&file_name);
        img.save_png(&dest)?;

        let size_bytes = std::fs::metadata(&dest)
            .map(|m| m.len() as usize)
            .unwrap_or(0);

        results.push(GalleryCaptureResult {
            spec,
            width: img.width,
            height: img.height,
            output_path: Some(dest),
            size_bytes,
        });
    }

    Ok(results)
}