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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! What the harness remembers about input between actions, and the page-level devices:
//! [`Mouse`], [`Keyboard`] and [`Ime`].

use std::num::NonZeroU16;

use iced_core::keyboard::key::{Code, Named, Physical};
use iced_core::keyboard::{self, Key, Location};
use iced_core::{Event, input_method, mouse, window};
use icedwright_check::clicks::{PressHistory, RecordedPress, place_press};
use icedwright_check::input::{Gesture, gesture_events};
use icedwright_check::{ClickCount, KeyboardLayout};
use icedwright_types::input::{Chord, Keystroke, Modifier, ModifierSet, NamedKey};
use icedwright_types::{Logical, Point, Vector};

use super::error::{ActionError, ActionFailure};
use super::options::Click;
use super::pointer;
use crate::error::{HarnessError, Result};
use crate::harness::{Harness, TestProgram};

/// Input state kept per harness: every press of the test for click separation, the keyboard
/// layout, the modifiers held with `Keyboard::down`, and whether an action is between its
/// pointer events, when the delayed-tooltip rule waits.
#[derive(Debug, Default)]
pub(crate) struct Devices {
    pub(crate) history: PressHistory,
    pub(crate) layout: KeyboardLayout,
    held: ModifierSet,
    holding: u32,
}

impl Devices {
    /// Whether an action is part way through its pointer events.
    pub(crate) fn pointer_held(&self) -> bool {
        self.holding > 0
    }

    pub(crate) fn hold(&mut self) {
        self.holding += 1;
    }

    pub(crate) fn release(&mut self) {
        self.holding = self.holding.saturating_sub(1);
    }

    pub(crate) fn held(&self) -> ModifierSet {
        self.held
    }
}

impl<P: TestProgram> Harness<P> {
    /// The mouse, for input that is not aimed at one widget.
    pub fn mouse(&mut self) -> Mouse<'_, P> {
        Mouse { harness: self }
    }

    /// The keyboard, sending to the focused window.
    pub fn keyboard(&mut self) -> Keyboard<'_, P> {
        Keyboard { harness: self }
    }

    /// The input method, sending to the focused window.
    pub fn ime(&mut self) -> Ime<'_, P> {
        Ime { harness: self }
    }

    fn focused_window(&self) -> Result<window::Id> {
        Ok(self.focused().ok_or(HarnessError::NoWindow)?)
    }
}

/// The pointer in the focused window. Presses follow the click-separation rule as presses at a
/// fixed position, and the delayed-tooltip rule runs after each call.
#[must_use]
pub struct Mouse<'h, P: TestProgram> {
    harness: &'h mut Harness<P>,
}

impl<P: TestProgram> std::fmt::Debug for Mouse<'_, P> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Mouse").finish_non_exhaustive()
    }
}

impl<P: TestProgram> Mouse<'_, P> {
    /// Moves the pointer in `steps` frames along a straight line, entering the window first
    /// when it is outside.
    pub fn move_to(&mut self, to: impl Into<Logical<Point>>, steps: NonZeroU16) -> Result {
        let h = &mut *self.harness;
        let window = h.focused_window()?;
        let from = super::engine::pointer(h, window);
        let layout = h.devices.layout.clone();
        let batches = gesture_events(
            &Gesture::Move {
                to: to.into(),
                steps,
            },
            from,
            &layout,
        );
        pointer::send_frames(h, window, batches)
    }

    /// Presses a button where the pointer is.
    pub fn down(&mut self, button: mouse::Button) -> Result {
        let h = &mut *self.harness;
        let window = h.focused_window()?;
        let at = super::engine::pointer(h, window).ok_or_else(|| {
            ActionError::new("mouse().down", "the pointer", ActionFailure::NoPointer)
        })?;
        place_fixed(h, window, button, at, "mouse().down")?;
        let _ = super::engine::deliver(
            h,
            window,
            vec![Event::Mouse(mouse::Event::ButtonPressed(button))],
            true,
        )?;
        Ok(())
    }

    /// Releases a button where the pointer is.
    pub fn up(&mut self, button: mouse::Button) -> Result {
        let h = &mut *self.harness;
        let window = h.focused_window()?;
        let _ = super::engine::deliver(
            h,
            window,
            vec![Event::Mouse(mouse::Event::ButtonReleased(button))],
            true,
        )?;
        Ok(())
    }

    /// Clicks at a window point, with the button, count and modifiers of `options`. A
    /// multi-click is refused on whatever under the point counts clicks with the real clock.
    pub fn click(&mut self, at: impl Into<Logical<Point>>, options: Click) -> Result {
        let at = at.into();
        let h = &mut *self.harness;
        let window = h.focused_window()?;
        let tree = h.tree_of(window)?;
        let ordinal = window_ordinal(h, window)?;
        let label = format!("the point {},{}", at.0.x.round(), at.0.y.round());
        if options.count != ClickCount::Single
            && let Some(id) = tree.hit_test(ordinal, at.0)
            && let Some(node) = tree.get(id)
        {
            icedwright_check::clicks::multi_click_allowed(&tree, &node.path).map_err(
                |refused| {
                    ActionError::new(
                        "mouse().click",
                        label.clone(),
                        ActionFailure::Refused(refused),
                    )
                },
            )?;
        }
        place_fixed(h, window, options.button, at, "mouse().click")?;
        let from = super::engine::pointer(h, window);
        let layout = h.devices.layout.clone();
        let gesture = Gesture::Click {
            at,
            button: options.button,
            count: options.count,
            modifiers: options.modifiers,
        };
        h.devices.hold();
        let sent = pointer::send_click(
            h,
            window,
            gesture_events(&gesture, from, &layout),
            options.count,
        );
        h.devices.release();
        sent?;
        h.run_until_settled()
    }

    /// One wheel scroll in pixels where the pointer is, closed so no scroll transaction stays
    /// open.
    pub fn wheel(&mut self, delta: impl Into<Logical<Vector>>) -> Result {
        let h = &mut *self.harness;
        let window = h.focused_window()?;
        let at = super::engine::pointer(h, window).ok_or_else(|| {
            ActionError::new("mouse().wheel", "the pointer", ActionFailure::NoPointer)
        })?;
        let layout = h.devices.layout.clone();
        let batches = gesture_events(
            &Gesture::Wheel {
                at,
                delta: delta.into(),
            },
            Some(at),
            &layout,
        );
        pointer::send_frames(h, window, batches)
    }

    /// The pointer leaves the window.
    pub fn leave(&mut self) -> Result {
        let h = &mut *self.harness;
        let window = h.focused_window()?;
        let _ = super::engine::deliver(
            h,
            window,
            vec![Event::Mouse(mouse::Event::CursorLeft)],
            true,
        )?;
        Ok(())
    }

    /// Where the pointer is in the focused window, or `None` when it is outside.
    #[must_use]
    pub fn position(&self) -> Option<Logical<Point>> {
        let window = self.harness.focused()?;
        super::engine::pointer(self.harness, window)
    }
}

fn window_ordinal<P: TestProgram>(
    h: &Harness<P>,
    window: window::Id,
) -> Result<icedwright_protocol::WindowId> {
    Ok(icedwright_protocol::WindowId(h.set.get(window)?.ordinal))
}

/// Applies click separation to a raw press at `at`, which cannot move, and records it.
fn place_fixed<P: TestProgram>(
    h: &mut Harness<P>,
    window: window::Id,
    button: mouse::Button,
    at: Logical<Point>,
    action: &'static str,
) -> Result {
    let tree = h.tree_of(window)?;
    let ordinal = window_ordinal(h, window)?;
    let label = format!("the point {},{}", at.0.x.round(), at.0.y.round());
    if let Some(id) = tree.hit_test(ordinal, at.0)
        && let Some(node) = tree.get(id)
    {
        place_press(&h.devices.history, &tree, &node.path, button, at, true)
            .map_err(|refused| ActionError::new(action, label, ActionFailure::Refused(refused)))?;
    }
    h.devices
        .history
        .record(RecordedPress::at(&tree, ordinal, button, at.0));
    Ok(())
}

/// The keyboard of the focused window, typing through the harness's layout.
#[must_use]
pub struct Keyboard<'h, P: TestProgram> {
    harness: &'h mut Harness<P>,
}

impl<P: TestProgram> std::fmt::Debug for Keyboard<'_, P> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Keyboard").finish_non_exhaustive()
    }
}

fn modifier_of(key: Keystroke) -> Option<Modifier> {
    match key {
        Keystroke::Named(NamedKey::Shift) => Some(Modifier::Shift),
        Keystroke::Named(NamedKey::Control) => Some(Modifier::Control),
        Keystroke::Named(NamedKey::Alt) => Some(Modifier::Alt),
        Keystroke::Named(NamedKey::Super | NamedKey::Meta) => Some(Modifier::Meta),
        _ => None,
    }
}

fn modifier_event(modifier: Modifier, down: bool, held: ModifierSet) -> Event {
    let (named, code) = match modifier {
        Modifier::Shift => (Named::Shift, Code::ShiftLeft),
        Modifier::Alt => (Named::Alt, Code::AltLeft),
        Modifier::Meta => (Named::Super, Code::SuperLeft),
        _ => (Named::Control, Code::ControlLeft),
    };
    let key = Key::Named(named);
    let physical_key = Physical::Code(code);
    Event::Keyboard(if down {
        keyboard::Event::KeyPressed {
            key: key.clone(),
            modified_key: key,
            physical_key,
            location: Location::Left,
            modifiers: held.into(),
            text: None,
            repeat: false,
        }
    } else {
        keyboard::Event::KeyReleased {
            key: key.clone(),
            modified_key: key,
            physical_key,
            location: Location::Left,
            modifiers: held.into(),
        }
    })
}

fn is_modifier_key(key: &Key) -> bool {
    matches!(
        key,
        Key::Named(Named::Shift | Named::Control | Named::Alt | Named::Super | Named::AltGraph)
    )
}

/// The press or the release of `key` alone, as the layout sends it with `held` down.
fn key_event(
    key: Keystroke,
    held: ModifierSet,
    layout: &KeyboardLayout,
    down: bool,
) -> Option<Event> {
    let batches = gesture_events(&Gesture::Chord(Chord::new(held, key)), None, layout);
    batches.into_iter().flatten().find(|event| match event {
        Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) if down => !is_modifier_key(key),
        Event::Keyboard(keyboard::Event::KeyReleased { key, .. }) if !down => !is_modifier_key(key),
        _ => false,
    })
}

impl<P: TestProgram> Keyboard<'_, P> {
    /// Presses and releases a chord, its modifiers around it.
    #[track_caller]
    pub fn press(&mut self, chord: Chord) -> Result {
        let h = &mut *self.harness;
        let window = h.focused_window()?;
        pointer::send_keys(
            h,
            window,
            &Gesture::Chord(chord),
            icedwright_types::VirtualDuration::ZERO,
            None,
        )
    }

    /// Holds a key down. A modifier stays held for later presses until [`Keyboard::up`].
    pub fn down(&mut self, key: Keystroke) -> Result {
        let h = &mut *self.harness;
        let window = h.focused_window()?;
        let events = match modifier_of(key) {
            Some(modifier) => {
                let held = h.devices.held.with(modifier);
                h.devices.held = held;
                vec![
                    Event::Keyboard(keyboard::Event::ModifiersChanged(held.into())),
                    modifier_event(modifier, true, held),
                ]
            }
            None => key_event(key, h.devices.held, &h.devices.layout, true)
                .into_iter()
                .collect(),
        };
        let _ = super::engine::deliver(h, window, events, true)?;
        Ok(())
    }

    /// Releases a key held with [`Keyboard::down`].
    pub fn up(&mut self, key: Keystroke) -> Result {
        let h = &mut *self.harness;
        let window = h.focused_window()?;
        let events = match modifier_of(key) {
            Some(modifier) => {
                let before = h.devices.held;
                let after: ModifierSet = before.iter().filter(|m| *m != modifier).collect();
                h.devices.held = after;
                vec![
                    modifier_event(modifier, false, before),
                    Event::Keyboard(keyboard::Event::ModifiersChanged(after.into())),
                ]
            }
            None => key_event(key, h.devices.held, &h.devices.layout, false)
                .into_iter()
                .collect(),
        };
        let _ = super::engine::deliver(h, window, events, true)?;
        Ok(())
    }

    /// Types text key by key through the layout. A character the layout cannot type is sent
    /// as an input method commit.
    #[track_caller]
    pub fn type_text(&mut self, text: &str) -> Result {
        let h = &mut *self.harness;
        let window = h.focused_window()?;
        pointer::send_keys(
            h,
            window,
            &Gesture::Type(text.to_owned()),
            icedwright_types::VirtualDuration::ZERO,
            None,
        )
    }

    /// Inserts text as one input method commit, with no key events.
    pub fn insert_text(&mut self, text: &str) -> Result {
        let h = &mut *self.harness;
        let window = h.focused_window()?;
        pointer::send_keys(
            h,
            window,
            &Gesture::Commit(text.to_owned()),
            icedwright_types::VirtualDuration::ZERO,
            None,
        )
    }

    /// Changes the keyboard layout for later input.
    pub fn layout(&mut self, layout: KeyboardLayout) {
        self.harness.devices.layout = layout;
    }

    /// The modifiers held with [`Keyboard::down`].
    #[must_use]
    pub fn held(&self) -> ModifierSet {
        self.harness.devices.held()
    }
}

/// The input method of the focused window.
#[must_use]
pub struct Ime<'h, P: TestProgram> {
    harness: &'h mut Harness<P>,
}

impl<P: TestProgram> std::fmt::Debug for Ime<'_, P> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Ime").finish_non_exhaustive()
    }
}

/// The focused window, if its widgets have enabled the input method, as winit requires
/// before it sends any input method event.
fn ime_window<P: TestProgram>(h: &Harness<P>, action: &'static str) -> Result<window::Id> {
    let window = h.focused_window()?;
    if matches!(
        h.input_method(window)?,
        iced_core::InputMethod::Enabled { .. }
    ) {
        return Ok(window);
    }
    let title = h.window_info(window)?.title.clone();
    Err(ActionError::new(
        action,
        "the focused window",
        ActionFailure::ImeNotEnabled { window: title },
    )
    .into())
}

impl<P: TestProgram> Ime<'_, P> {
    fn send(&mut self, action: &'static str, events: Vec<input_method::Event>) -> Result {
        let h = &mut *self.harness;
        let window = ime_window(h, action)?;
        let events = events.into_iter().map(Event::InputMethod).collect();
        let _ = super::engine::deliver(h, window, events, true)?;
        Ok(())
    }

    /// The input method opens. Fails with [`ActionFailure::ImeNotEnabled`] unless a widget in
    /// the focused window has enabled it, as do the other input method events.
    pub fn open(&mut self) -> Result {
        self.send("ime().open", vec![input_method::Event::Opened])
    }

    /// The composition so far, with the selection inside it.
    pub fn preedit(&mut self, text: &str, cursor: Option<std::ops::Range<usize>>) -> Result {
        self.send(
            "ime().preedit",
            vec![input_method::Event::Preedit(text.to_owned(), cursor)],
        )
    }

    /// Commits text.
    pub fn commit(&mut self, text: &str) -> Result {
        self.send(
            "ime().commit",
            vec![input_method::Event::Commit(text.to_owned())],
        )
    }

    /// The input method closes.
    pub fn close(&mut self) -> Result {
        self.send("ime().close", vec![input_method::Event::Closed])
    }

    /// A whole composition: opened, one preedit per step, cleared, committed.
    pub fn compose(&mut self, steps: &[&str], result: &str) -> Result {
        let h = &mut *self.harness;
        let window = ime_window(h, "ime().compose")?;
        let gesture = Gesture::Compose {
            steps: steps.iter().map(|s| (*s).to_owned()).collect(),
            result: result.to_owned(),
        };
        pointer::send_keys(
            h,
            window,
            &gesture,
            icedwright_types::VirtualDuration::ZERO,
            None,
        )
    }

    /// What the focused window's widgets last asked the input method for.
    pub fn requested(&self) -> Result<iced_core::InputMethod> {
        let window = self.harness.focused_window()?;
        Ok(self.harness.input_method(window)?.clone())
    }
}