icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
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
//! The loop every action runs before it sends input: resolve on a fresh tree, scroll into
//! view, wait for stability, run the pure checks, then move the pointer and confirm with the
//! readings of the interface that handled the move. Failing checks wait in virtual time;
//! refusals return at once.

use std::num::NonZeroU16;
use std::sync::Arc;

use iced_core::event::Status;
use iced_core::{Event, window};
use icedwright_check::actionability::{
    self, ActionKind, ActionRequest, Enabled, Frames, LayerCursors, NotActionable,
};
use icedwright_check::input::{Gesture, gesture_events};
use icedwright_check::scroll::{ScrollAlign, ScrollStep, scroll_into_view};
use icedwright_locator::{AnyRole, Locator};
use icedwright_protocol::WindowId;
use icedwright_semantics::{Node, NodePath, SemanticTree};
use icedwright_types::{Logical, Point, VirtualDuration};

use super::error::{ActionError, ActionFailure, Blocker};
use super::ops::ScrollOrdinal;
use crate::error::{HarnessError, Result};
use crate::harness::{Harness, TestProgram};

/// What an action is aimed at: a locator, scoped to a window or not, or one node by path.
#[derive(Debug, Clone)]
pub(crate) struct Subject {
    pub(crate) locator: Locator<AnyRole>,
    pub(crate) window: Option<window::Id>,
    pub(crate) path: Option<NodePath>,
}

impl Subject {
    pub(crate) fn new(locator: Locator<AnyRole>, window: Option<window::Id>) -> Self {
        Self {
            locator,
            window,
            path: None,
        }
    }

    /// The node at `path` in `window`, described by the locator that led to it.
    pub(crate) fn at(&self, path: NodePath, window: window::Id) -> Self {
        Self {
            locator: self.locator.clone(),
            window: Some(window),
            path: Some(path),
        }
    }

    pub(crate) fn describe(&self) -> String {
        let locator = self.locator.to_rust_string("");
        match &self.path {
            Some(path) => format!("{path} (from {locator})"),
            None => locator,
        }
    }
}

/// A node an action found, with the tree it was found in.
#[derive(Debug, Clone)]
pub(crate) struct Found {
    pub(crate) tree: Arc<SemanticTree>,
    pub(crate) node: Node,
    pub(crate) window: window::Id,
}

impl Found {
    pub(crate) fn ordinal(&self) -> WindowId {
        self.node.window
    }

    pub(crate) fn path(&self) -> &NodePath {
        &self.node.path
    }
}

/// Whether, and why, the pointer is moved onto the node before the action is confirmed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Probe {
    /// Move the pointer and confirm cover, enabled state and scrims from its readings.
    Pointer,
    /// Move the pointer only when no source reports whether the field is editable.
    Editable,
    /// Leave covers to a later check and send nothing now.
    Deferred,
    /// Send nothing.
    None,
}

/// How to wait for one node.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Plan {
    pub(crate) kind: ActionKind,
    pub(crate) position: Option<Logical<Point>>,
    pub(crate) force: bool,
    pub(crate) trial: bool,
    pub(crate) timeout: VirtualDuration,
    pub(crate) steps: NonZeroU16,
    pub(crate) probe: Probe,
}

impl Plan {
    pub(crate) fn new(kind: ActionKind, timeout: VirtualDuration, probe: Probe) -> Self {
        Self {
            kind,
            position: None,
            force: false,
            trial: false,
            timeout,
            steps: NonZeroU16::MIN,
            probe,
        }
    }
}

/// A node that passed every check, and the point to act at.
#[derive(Debug, Clone)]
pub(crate) struct Ready {
    pub(crate) found: Found,
    pub(crate) point: Logical<Point>,
    pub(crate) attempts: u32,
    pub(crate) scrolls: Vec<ScrollStep>,
    pub(crate) statuses: Vec<Status>,
}

/// What ended an attempt that did not act.
enum Miss {
    Blocked(Blocker),
    Refused(ActionFailure),
}

/// A check run on every node found, before the actionability checks: what is decided from
/// the test and the node alone, such as the multi-click rule, is a refusal.
pub(crate) type Refusal<'a> = &'a dyn Fn(&Found) -> std::result::Result<(), ActionFailure>;

pub(crate) fn no_refusal(_: &Found) -> std::result::Result<(), ActionFailure> {
    Ok(())
}

/// The window the semantic tree numbers `ordinal`.
pub(crate) fn window_of<P: TestProgram>(h: &Harness<P>, ordinal: WindowId) -> Option<window::Id> {
    h.set
        .windows
        .values()
        .find(|state| WindowId(state.ordinal) == ordinal)
        .map(|state| state.info.id)
}

/// Where the pointer is in a window, or `None` when it is outside.
pub(crate) fn pointer<P: TestProgram>(
    h: &Harness<P>,
    window: window::Id,
) -> Option<Logical<Point>> {
    match h.surfaces.get(&window)?.cursor {
        iced_core::mouse::Cursor::Available(point) => Some(Logical(Point::new(point.x, point.y))),
        _ => None,
    }
}

/// Finds the subject's node in a fresh tree. Not finding it yet is a blocker; strictness, a
/// wrong narrowing and an invalid pattern are errors.
pub(crate) fn find<P: TestProgram>(
    h: &mut Harness<P>,
    subject: &Subject,
) -> Result<std::result::Result<Found, Blocker>> {
    let tree = match subject.window {
        Some(window) => h.tree_of(window)?,
        None => h.tree()?,
    };
    let id = match &subject.path {
        Some(path) => match tree.find_path(path) {
            Some(id) => id,
            None => {
                return Ok(Err(Blocker::Check(NotActionable::Detached {
                    node: path.clone(),
                })));
            }
        },
        None => match icedwright_locator::resolve(&tree, &subject.locator) {
            Ok(id) => id,
            Err(error @ icedwright_locator::Error::NotFound { .. }) => {
                return Ok(Err(Blocker::NotAttached(error)));
            }
            Err(error) => return Err(error.into()),
        },
    };
    let Some(node) = tree.get(id).cloned() else {
        return Err(HarnessError::NoWindow.into());
    };
    let window = window_of(h, node.window).ok_or(HarnessError::NoWindow)?;
    Ok(Ok(Found { tree, node, window }))
}

/// Delivers one batch of events to a window and settles, or only delivers it.
pub(crate) fn deliver<P: TestProgram>(
    h: &mut Harness<P>,
    window: window::Id,
    batch: Vec<Event>,
    settle: bool,
) -> Result<Vec<Status>> {
    h.check_live()?;
    let (statuses, _) = h.deliver_input(window, batch, true, false)?;
    if settle {
        h.run_until_settled()?;
    }
    Ok(statuses)
}

/// Moves the pointer to `to` in `steps` frames, the last move collected in the interface that
/// handled it.
fn probe_move<P: TestProgram>(
    h: &mut Harness<P>,
    window: window::Id,
    to: Logical<Point>,
    steps: NonZeroU16,
    statuses: &mut Vec<Status>,
) -> Result<crate::harness::Probed> {
    let from = pointer(h, window);
    let layout = h.devices.layout.clone();
    let mut batches = gesture_events(&Gesture::Move { to, steps }, from, &layout);
    let last = batches.pop().unwrap_or_default();
    for batch in batches {
        statuses.extend(deliver(h, window, batch, true)?);
        h.next_frame()?;
    }
    let probed = h.send_probed(window, &last)?;
    statuses.extend(probed.statuses.iter().copied());
    Ok(probed)
}

/// Applies the scrolls that bring a node into view, falling back to the end-anchored offset
/// when a scrollable did not reach the one asked for.
fn apply_scrolls<P: TestProgram>(
    h: &mut Harness<P>,
    window: window::Id,
    steps: &[ScrollStep],
) -> Result {
    for step in steps {
        let offset = iced_core::Vector::new(step.offset.x, step.offset.y);
        let _ = h.operate(window, ScrollOrdinal::to(step.ordinal, offset))?;
        let reached = h
            .operate(window, ScrollOrdinal::read(step.ordinal))?
            .flatten();
        let missed =
            reached.is_some_and(|t| (t.x - offset.x).abs() > 0.5 || (t.y - offset.y).abs() > 0.5);
        if missed {
            let anchored = step.end_anchored();
            let anchored = iced_core::Vector::new(anchored.x, anchored.y);
            let _ = h.operate(window, ScrollOrdinal::to(step.ordinal, anchored))?;
        }
    }
    Ok(())
}

/// Whether anything can move the layout on its own: a frame or a widget timer is due.
fn animating<P: TestProgram>(h: &Harness<P>) -> bool {
    h.next_wake_up().is_some()
}

/// Whether a cover names the target or one of its ancestors, which is what the check falls
/// back to when an annotated target saw a levitating cursor but no node in the tree covers it.
pub(crate) fn covered_by_own_ancestor(
    tree: &SemanticTree,
    target: &NodePath,
    by: &NodePath,
) -> bool {
    let (Some(target), Some(by)) = (tree.find_path(target), tree.find_path(by)) else {
        return false;
    };
    target == by || tree.ancestors(target).any(|ancestor| ancestor == by)
}

/// Waits until the subject's node can take the action, and moves the pointer onto it when
/// the plan probes. Refusals are returned at once; everything else is retried until the
/// plan's timeout in virtual time.
pub(crate) fn actionable<P: TestProgram>(
    h: &mut Harness<P>,
    subject: &Subject,
    plan: &Plan,
    action: &'static str,
    refuse: Refusal<'_>,
) -> Result<Ready> {
    let deadline = h.now() + plan.timeout;
    let began = h.real_now();
    let mut attempts = 0u32;
    let mut scrolls = Vec::new();
    let mut statuses = Vec::new();
    loop {
        h.run_until_settled()?;
        attempts += 1;
        let blocker = match attempt(h, subject, plan, refuse, &mut scrolls, &mut statuses)? {
            Ok((found, point)) => {
                return Ok(Ready {
                    found,
                    point,
                    attempts,
                    scrolls,
                    statuses,
                });
            }
            Err(Miss::Refused(reason)) => {
                return Err(ActionError::new(action, subject.describe(), reason).into());
            }
            Err(Miss::Blocked(blocker)) => blocker,
        };
        let give_up =
            h.has_exited() || h.now() >= deadline || h.wait(deadline, began)?.ceiling_reached;
        if give_up {
            let reason = ActionFailure::Timeout {
                timeout: plan.timeout,
                attempts,
                last: Box::new(blocker),
            };
            return Err(ActionError::new(action, subject.describe(), reason).into());
        }
    }
}

fn attempt<P: TestProgram>(
    h: &mut Harness<P>,
    subject: &Subject,
    plan: &Plan,
    refuse: Refusal<'_>,
    scrolls: &mut Vec<ScrollStep>,
    statuses: &mut Vec<Status>,
) -> Result<std::result::Result<(Found, Logical<Point>), Miss>> {
    let mut found = match find(h, subject)? {
        Ok(found) => found,
        Err(blocker) => return Ok(Err(Miss::Blocked(blocker))),
    };
    if let Err(reason) = refuse(&found) {
        return Ok(Err(Miss::Refused(reason)));
    }
    for _ in 0..3 {
        let steps = scroll_into_view(&found.node, ScrollAlign::Nearest);
        if steps.is_empty() {
            break;
        }
        apply_scrolls(h, found.window, &steps)?;
        scrolls.extend(steps);
        found = match find(h, subject)? {
            Ok(found) => found,
            Err(blocker) => return Ok(Err(Miss::Blocked(blocker))),
        };
    }

    let checks = plan.kind.checks();
    let previous = if checks.stable && !plan.force && animating(h) {
        let before = found.tree.clone();
        h.next_frame()?;
        found = match find(h, subject)? {
            Ok(found) => found,
            Err(blocker) => return Ok(Err(Miss::Blocked(blocker))),
        };
        before
    } else {
        found.tree.clone()
    };

    let mut request = ActionRequest::new(plan.kind);
    if let Some(position) = plan.position {
        request = request.at(position);
    }
    if plan.force {
        request = request.force();
    }
    let path = found.path().clone();
    let none = LayerCursors::new();
    let first = actionability::check(
        Frames {
            current: &found.tree,
            previous: &previous,
            cursors: &none,
        },
        &path,
        &request,
    );
    let defer_covers = !plan.trial && matches!(plan.probe, Probe::Pointer | Probe::Deferred);
    let (point, enabled) = match first {
        Ok(ready) => (ready.point, ready.enabled),
        Err(NotActionable::Covered { at, .. } | NotActionable::PossiblyCovered { at, .. })
            if defer_covers =>
        {
            let enabled = if found.node.states.disabled.is_some() {
                Enabled::Known
            } else {
                Enabled::Probe
            };
            (at, enabled)
        }
        Err(error) => return Ok(Err(Miss::Blocked(Blocker::Check(error)))),
    };

    let probe = match plan.probe {
        Probe::Editable
            if found.node.states.readonly.is_none() && found.node.states.disabled.is_none() =>
        {
            true
        }
        Probe::Pointer => true,
        Probe::Editable | Probe::Deferred | Probe::None => false,
    };
    if plan.trial || plan.force || !probe {
        return Ok(Ok((found, point)));
    }

    let probed = probe_move(h, found.window, point, plan.steps, statuses)?;
    let after = actionability::check(
        Frames {
            current: &probed.tree,
            previous: &found.tree,
            cursors: &probed.cursors,
        },
        &path,
        &request,
    );
    if let Err(error) = after {
        let error = match error {
            NotActionable::Covered { ref by, .. }
                if covered_by_own_ancestor(&probed.tree, &path, by) =>
            {
                // Nothing in the tree explains the cover, so ask the pointer probe, which
                // names an `opaque` layer inference cannot see.
                let interaction = h.mouse_interaction(found.window)?;
                match actionability::confirm_pointer(&probed.tree, &path, point, interaction) {
                    Err(gap @ NotActionable::UnannotatedScrim { .. }) => gap,
                    _ => error,
                }
            }
            error => error,
        };
        return Ok(Err(Miss::Blocked(Blocker::Check(error))));
    }
    let interaction = h.mouse_interaction(found.window)?;
    match actionability::confirm_pointer(&probed.tree, &path, point, interaction) {
        Ok(()) => {}
        Err(NotActionable::NotEditable { .. }) if plan.probe != Probe::Editable => {}
        Err(NotActionable::Disabled { .. }) if !checks.enabled || enabled == Enabled::Known => {}
        Err(error) => return Ok(Err(Miss::Blocked(Blocker::Check(error)))),
    }
    let Some(node) = probed.tree.node_at(&path).cloned() else {
        return Ok(Err(Miss::Blocked(Blocker::Check(
            NotActionable::Detached { node: path },
        ))));
    };
    let found = Found {
        tree: probed.tree.clone(),
        node,
        window: found.window,
    };
    Ok(Ok((found, point)))
}