waterui-testing 0.3.0

Headless testing helpers for WaterUI
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
use std::time::{Duration, Instant};

use accesskit::{
    ActionRequest as AccessibilityActionRequest, TreeUpdate as AccessibilityTreeUpdate,
};
use hydrolysis::{
    FrameProfile, HeadlessRuntime, InputEvent, KeyCode, KeyState, Modifiers, PointerButton,
    PointerKind, TouchPhase,
};
use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System, get_current_pid};
use waterui_core::handler::AnyViewBuilder;
use waterui_core::{AnyView, Environment};

use crate::app::DriverMode;
use crate::semantics::NodeId;
use crate::snapshot::Snapshot;

const TEST_POINTER_ID: u64 = 0;

/// Virtual frame step applied per pump.
///
/// The animation clock advances by exactly this much on every pump, so
/// transition sampling is deterministic regardless of how fast the host
/// executes pumps — wall-clock scheduling jitter never leaks into captures.
pub const VIRTUAL_FRAME: Duration = Duration::from_millis(16);

pub trait A11yDriver {
    fn pump(
        &mut self,
        content: &AnyViewBuilder<AnyView>,
        env: &Environment,
        capture_snapshot: bool,
    ) -> DriverPumpResult;
    /// Advances the virtual animation clock by exactly `step` and pumps one
    /// frame without snapshot readback.
    fn pump_step(
        &mut self,
        step: Duration,
        content: &AnyViewBuilder<AnyView>,
        env: &Environment,
    ) -> DriverPumpResult;
    /// Whether the mounted runtime is quiescent: no queued input, no spawned
    /// work awaiting a drain, and no renderer-scheduled semantic work.
    fn is_settled(&self) -> bool;
    /// Whether a state change has been requested but not yet flushed, so the
    /// tree the last pump produced no longer reflects the app's state.
    ///
    /// Narrower than [`Self::is_settled`]: work that continues over future
    /// frames of its own accord (animations, gliding scrolls) does not count,
    /// so waiting on this terminates even in an app that never comes to rest.
    fn has_pending_semantic_update(&self) -> bool;
    /// The current virtual frame instant, if any pump has run yet. Perf runs
    /// seed their own frame clock from this so interleaved clocks stay
    /// monotone.
    fn clock(&self) -> Option<Instant> {
        None
    }
    /// Returns whether the runtime handled the accessibility action.
    fn perform_action(&mut self, request: AccessibilityActionRequest, env: &Environment) -> bool;
    fn hover_at(&mut self, x: f32, y: f32, env: &Environment);
    fn pointer_down(&mut self, x: f32, y: f32, env: &Environment);
    fn pointer_move(&mut self, x: f32, y: f32, env: &Environment);
    /// Presses and releases the secondary button, which is what opens a context
    /// menu.
    fn secondary_click(&mut self, x: f32, y: f32, env: &Environment);
    fn pointer_up(&mut self, x: f32, y: f32, env: &Environment);
    fn scroll_at(
        &mut self,
        x: f32,
        y: f32,
        dx: f32,
        dy: f32,
        is_line_delta: bool,
        env: &Environment,
    );
    fn text_input(&mut self, text: String, env: &Environment);
    fn key_press(&mut self, key: KeyCode, modifiers: Modifiers, env: &Environment);
    fn magnify_at(&mut self, x: f32, y: f32, factor: f32, env: &Environment);
    /// Returns whether anything held UI focus to clear.
    fn clear_ui_focus(&mut self, env: &Environment) -> bool;
    fn request_redraw(&mut self, content: &AnyViewBuilder<AnyView>, env: &Environment);
    fn pump_frame(&mut self, content: &AnyViewBuilder<AnyView>, env: &Environment) -> FrameTiming;
    fn pump_frame_at(
        &mut self,
        content: &AnyViewBuilder<AnyView>,
        env: &Environment,
        _at: Instant,
    ) -> FrameTiming {
        self.pump_frame(content, env)
    }
}

#[derive(Debug)]
pub struct DriverPumpResult {
    pub(crate) rebuilt: bool,
    pub(crate) tree_update: Option<AccessibilityTreeUpdate>,
    pub(crate) snapshot: Option<Snapshot>,
    pub(crate) ui_focus: Option<NodeId>,
}

/// Timing collected for one complete offscreen Hydrolysis frame.
#[derive(Clone, Copy, Debug, Default)]
pub struct FrameTiming {
    /// Wall-clock duration spent advancing one offscreen Hydrolysis frame.
    pub total: std::time::Duration,
    /// Whether the frame rebuilt scene/layout state.
    pub rebuilt: bool,
    /// Detailed Hydrolysis phase timings and counters.
    pub profile: FrameProfile,
    /// Process CPU / memory sample collected immediately after the frame.
    pub resources: ResourceSample,
}

/// Host process resource sample captured during a perf run.
#[derive(Clone, Copy, Debug, Default)]
pub struct ResourceSample {
    /// Process CPU usage percentage reported by the operating system.
    pub cpu_percent: f32,
    /// Resident memory in bytes.
    pub memory_bytes: u64,
}

pub struct HydrolysisA11yDriver {
    width: u32,
    height: u32,
    mode: DriverMode,
    runtime: Option<HeadlessRuntime>,
    /// Virtual frame clock: starts at the first pump's wall time and advances
    /// by a fixed step per pump, decoupling animation sampling from host
    /// scheduling. Perf pumps overwrite it so interleaved clocks stay
    /// monotone.
    clock: Option<Instant>,
    resources: ResourceSampler,
}

impl HydrolysisA11yDriver {
    pub(crate) const fn new(width: u32, height: u32, mode: DriverMode) -> Self {
        Self {
            width,
            height,
            mode,
            runtime: None,
            clock: None,
            resources: ResourceSampler::new(),
        }
    }

    fn runtime(
        &mut self,
        content: &AnyViewBuilder<AnyView>,
        env: &Environment,
    ) -> &mut HeadlessRuntime {
        self.runtime.get_or_insert_with(|| {
            HeadlessRuntime::new_for_tests(env.clone(), content.clone(), self.width, self.height)
        })
    }

    /// Advances the virtual clock by `step` and returns the new frame instant.
    fn tick(&mut self, step: Duration) -> Instant {
        let next = self
            .clock
            .map_or_else(Instant::now, |current| current + step);
        self.clock = Some(next);
        next
    }

    fn convert(result: hydrolysis::HeadlessPumpResult) -> DriverPumpResult {
        DriverPumpResult {
            rebuilt: result.rebuilt,
            tree_update: result.tree_update,
            snapshot: result.snapshot.map(|snapshot| Snapshot {
                width: snapshot.width,
                height: snapshot.height,
                rgba8: snapshot.rgba8,
            }),
            ui_focus: result.ui_focus.map(NodeId::from),
        }
    }
}

impl A11yDriver for HydrolysisA11yDriver {
    fn pump(
        &mut self,
        content: &AnyViewBuilder<AnyView>,
        env: &Environment,
        capture_snapshot: bool,
    ) -> DriverPumpResult {
        let at = self.tick(VIRTUAL_FRAME);
        let result = if capture_snapshot {
            self.runtime(content, env).pump_at(true, at)
        } else {
            match self.mode {
                DriverMode::Semantic => self.runtime(content, env).pump_semantic_at(at),
                DriverMode::Offscreen => self.runtime(content, env).pump_at(false, at),
            }
        };
        Self::convert(result)
    }

    fn pump_step(
        &mut self,
        step: Duration,
        content: &AnyViewBuilder<AnyView>,
        env: &Environment,
    ) -> DriverPumpResult {
        let at = self.tick(step);
        let result = match self.mode {
            DriverMode::Semantic => self.runtime(content, env).pump_semantic_at(at),
            DriverMode::Offscreen => self.runtime(content, env).pump_at(false, at),
        };
        Self::convert(result)
    }

    fn is_settled(&self) -> bool {
        self.runtime
            .as_ref()
            .is_none_or(HeadlessRuntime::is_settled)
    }

    fn has_pending_semantic_update(&self) -> bool {
        self.runtime
            .as_ref()
            .is_some_and(HeadlessRuntime::has_pending_semantic_update)
    }

    fn clock(&self) -> Option<Instant> {
        self.clock
    }

    fn perform_action(&mut self, request: AccessibilityActionRequest, env: &Environment) -> bool {
        let _ = env;
        self.runtime
            .as_mut()
            .expect("waterui-testing driver action requested before runtime initialization")
            .perform_accessibility_action(request)
    }

    fn hover_at(&mut self, x: f32, y: f32, _env: &Environment) {
        let runtime = self
            .runtime
            .as_mut()
            .expect("waterui-testing hover requested before runtime initialization");
        runtime.push_input_event(InputEvent::PointerMove {
            id: TEST_POINTER_ID,
            kind: PointerKind::Mouse,
            x,
            y,
        });
    }

    fn pointer_down(&mut self, x: f32, y: f32, _env: &Environment) {
        let runtime = self
            .runtime
            .as_mut()
            .expect("waterui-testing pointer down requested before runtime initialization");
        runtime.push_input_event(InputEvent::PointerDown {
            id: TEST_POINTER_ID,
            kind: PointerKind::Mouse,
            x,
            y,
            button: PointerButton::Primary,
        });
    }

    fn secondary_click(&mut self, x: f32, y: f32, _env: &Environment) {
        let runtime = self
            .runtime
            .as_mut()
            .expect("waterui-testing secondary click requested before runtime initialization");
        runtime.push_input_event(InputEvent::PointerDown {
            id: TEST_POINTER_ID,
            kind: PointerKind::Mouse,
            x,
            y,
            button: PointerButton::Secondary,
        });
        runtime.push_input_event(InputEvent::PointerUp {
            id: TEST_POINTER_ID,
            kind: PointerKind::Mouse,
            x,
            y,
            button: PointerButton::Secondary,
        });
    }

    fn pointer_move(&mut self, x: f32, y: f32, _env: &Environment) {
        let runtime = self
            .runtime
            .as_mut()
            .expect("waterui-testing pointer move requested before runtime initialization");
        runtime.push_input_event(InputEvent::PointerMove {
            id: TEST_POINTER_ID,
            kind: PointerKind::Mouse,
            x,
            y,
        });
    }

    fn pointer_up(&mut self, x: f32, y: f32, _env: &Environment) {
        let runtime = self
            .runtime
            .as_mut()
            .expect("waterui-testing pointer up requested before runtime initialization");
        runtime.push_input_event(InputEvent::PointerUp {
            id: TEST_POINTER_ID,
            kind: PointerKind::Mouse,
            x,
            y,
            button: PointerButton::Primary,
        });
    }

    fn scroll_at(
        &mut self,
        x: f32,
        y: f32,
        dx: f32,
        dy: f32,
        is_line_delta: bool,
        _env: &Environment,
    ) {
        let runtime = self
            .runtime
            .as_mut()
            .expect("waterui-testing scroll requested before runtime initialization");
        runtime.push_input_event(InputEvent::Scroll {
            x,
            y,
            dx,
            dy,
            is_line_delta,
        });
    }

    fn text_input(&mut self, text: String, _env: &Environment) {
        let runtime = self
            .runtime
            .as_mut()
            .expect("waterui-testing text_input requested before runtime initialization");
        runtime.push_input_event(InputEvent::TextInput { text });
    }

    fn key_press(&mut self, key: KeyCode, modifiers: Modifiers, _env: &Environment) {
        let runtime = self
            .runtime
            .as_mut()
            .expect("waterui-testing key_press requested before runtime initialization");
        runtime.push_input_event(InputEvent::Key {
            logical_key: key.to_w3c_key(),
            // A synthesized keystroke has no physical key behind it.
            physical_code: hydrolysis::keyboard_types::Code::Unidentified,
            repeat: false,
            key,
            state: KeyState::Pressed,
            modifiers,
        });
    }

    fn magnify_at(&mut self, x: f32, y: f32, factor: f32, _env: &Environment) {
        let runtime = self
            .runtime
            .as_mut()
            .expect("waterui-testing magnify requested before runtime initialization");
        runtime.push_input_event(InputEvent::Magnification {
            x,
            y,
            delta: 0.0,
            phase: TouchPhase::Started,
        });
        runtime.push_input_event(InputEvent::Magnification {
            x,
            y,
            delta: factor - 1.0,
            phase: TouchPhase::Moved,
        });
        runtime.push_input_event(InputEvent::Magnification {
            x,
            y,
            delta: 0.0,
            phase: TouchPhase::Ended,
        });
    }

    fn clear_ui_focus(&mut self, _env: &Environment) -> bool {
        self.runtime
            .as_mut()
            .expect("waterui-testing clear_ui_focus requested before runtime initialization")
            .clear_ui_focus()
    }

    fn request_redraw(&mut self, content: &AnyViewBuilder<AnyView>, env: &Environment) {
        self.runtime(content, env).request_redraw();
    }

    fn pump_frame(&mut self, content: &AnyViewBuilder<AnyView>, env: &Environment) -> FrameTiming {
        let at = self.tick(VIRTUAL_FRAME);
        self.pump_frame_at(content, env, at)
    }

    fn pump_frame_at(
        &mut self,
        content: &AnyViewBuilder<AnyView>,
        env: &Environment,
        at: Instant,
    ) -> FrameTiming {
        // Adopt the caller's clock so interleaved semantic pumps stay monotone.
        self.clock = Some(at);
        let started_at = std::time::Instant::now();
        let outcome = self.runtime(content, env).pump_at(false, at);
        FrameTiming {
            total: outcome.profile.total.max(started_at.elapsed()),
            rebuilt: outcome.rebuilt,
            profile: outcome.profile,
            resources: self.resources.sample(),
        }
    }
}

struct ResourceSampler {
    system: Option<System>,
    pid: Option<sysinfo::Pid>,
}

impl ResourceSampler {
    const fn new() -> Self {
        Self {
            system: None,
            pid: None,
        }
    }

    fn sample(&mut self) -> ResourceSample {
        let pid = *self.pid.get_or_insert_with(|| {
            get_current_pid().expect("waterui-testing perf: failed to resolve current process id")
        });
        let system = self.system.get_or_insert_with(|| {
            let mut system = System::new();
            system.refresh_processes_specifics(
                ProcessesToUpdate::Some(&[pid]),
                true,
                ProcessRefreshKind::nothing().with_cpu().with_memory(),
            );
            system
        });
        system.refresh_processes_specifics(
            ProcessesToUpdate::Some(&[pid]),
            true,
            ProcessRefreshKind::nothing().with_cpu().with_memory(),
        );
        let process = system
            .process(pid)
            .expect("waterui-testing perf: current process disappeared during sampling");
        ResourceSample {
            cpu_percent: process.cpu_usage(),
            memory_bytes: process.memory(),
        }
    }
}