fantoccini/
actions.rs

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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Actions functionality for WebDriver.
#[cfg(doc)]
use crate::client::Client;
use crate::elements::Element;
#[cfg(doc)]
use crate::key::Key;
use std::fmt::Debug;
use std::time::Duration;
use webdriver::actions as WDActions;

/// An action not associated with an input device (e.g. pause).
///
/// See [17.4.1 General Actions](https://www.w3.org/TR/webdriver1/#general-actions) of the
/// WebDriver standard.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum NullAction {
    /// Pause for the specified duration.
    Pause {
        /// The pause duration.
        duration: Duration,
    },
}

impl NullAction {
    fn into_item(self) -> WDActions::NullActionItem {
        match self {
            NullAction::Pause { duration } => WDActions::NullActionItem::General(
                WDActions::GeneralAction::Pause(WDActions::PauseAction {
                    duration: Some(duration.as_millis() as u64),
                }),
            ),
        }
    }
}

/// An action performed with a keyboard.
///
/// See [17.4.2 Keyboard Actions](https://www.w3.org/TR/webdriver1/#keyboard-actions) of the
/// WebDriver standard.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum KeyAction {
    /// Pause action.
    /// Useful for adding pauses between other key actions.
    Pause {
        /// The pause duration, given in milliseconds.
        duration: Duration,
    },
    /// Key up action.
    Up {
        /// The key code, e.g. `'a'`. See the [`Key`] enum for special key codes.
        value: char,
    },
    /// Key down action.
    Down {
        /// The key code, e.g. `'a'`. See the [`Key`] enum for special key codes.
        value: char,
    },
}

impl KeyAction {
    fn into_item(self) -> WDActions::KeyActionItem {
        use webdriver::actions::{KeyAction as WDKeyAction, KeyDownAction, KeyUpAction};
        match self {
            KeyAction::Pause { duration } => WDActions::KeyActionItem::General(
                WDActions::GeneralAction::Pause(WDActions::PauseAction {
                    duration: Some(duration.as_millis() as u64),
                }),
            ),
            KeyAction::Up { value } => {
                WDActions::KeyActionItem::Key(WDKeyAction::Up(KeyUpAction {
                    value: value.to_string(),
                }))
            }
            KeyAction::Down { value } => {
                WDActions::KeyActionItem::Key(WDKeyAction::Down(KeyDownAction {
                    value: value.to_string(),
                }))
            }
        }
    }
}

/// Left mouse button constant for use with `PointerAction`.
pub const MOUSE_BUTTON_LEFT: u64 = 0;

/// Middle mouse button constant for use with `PointerAction`.
pub const MOUSE_BUTTON_MIDDLE: u64 = 1;

/// Right mouse button constant for use with `PointerAction`.
pub const MOUSE_BUTTON_RIGHT: u64 = 2;

/// An action performed with a pointer device.
///
/// This can be a mouse, pen or touch device.
///
/// See [17.4.3 Pointer Actions](https://www.w3.org/TR/webdriver1/#pointer-actions) of the
/// WebDriver standard.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum PointerAction {
    /// Pause action.
    /// Useful for adding pauses between other key actions.
    Pause {
        /// The pause duration, given in milliseconds.
        duration: Duration,
    },
    /// Pointer button down.
    Down {
        /// The mouse button index.
        ///
        /// The following constants are provided, but any mouse index can be used
        /// to represent the corresponding mouse button.
        /// - [`MOUSE_BUTTON_LEFT`]
        /// - [`MOUSE_BUTTON_MIDDLE`]
        /// - [`MOUSE_BUTTON_RIGHT`]
        button: u64,
    },
    /// Pointer button up.
    Up {
        /// The mouse button index.
        ///
        /// The following constants are provided, but any mouse index can be used
        /// to represent the corresponding mouse button.
        /// - [`MOUSE_BUTTON_LEFT`]
        /// - [`MOUSE_BUTTON_MIDDLE`]
        /// - [`MOUSE_BUTTON_RIGHT`]
        button: u64,
    },
    /// Move the pointer relative to the current position.
    ///
    /// The x and y offsets are relative to the current pointer position.
    MoveBy {
        /// The move duration.
        duration: Option<Duration>,
        /// `x` offset, in pixels.
        x: i64,
        /// `y` offset, in pixels.
        y: i64,
    },
    /// Move the pointer to a new position.
    ///
    /// The x and y offsets are relative to the top-left corner of the viewport.
    MoveTo {
        /// The move duration.
        duration: Option<Duration>,
        /// `x` offset, in pixels.
        x: i64,
        /// `y` offset, in pixels.
        y: i64,
    },
    /// Move the pointer to a position relative to the specified element.
    MoveToElement {
        /// The element to move the pointer in relation to. The `x` and `y` offsets are relative
        /// to this element's center position.
        element: Element,
        /// The move duration.
        duration: Option<Duration>,
        /// `x` offset, in pixels.
        x: i64,
        /// `y` offset, in pixels.
        y: i64,
    },
    /// Pointer cancel action. Used to cancel the current pointer action.
    Cancel,
}

impl PointerAction {
    fn into_item(self) -> WDActions::PointerActionItem {
        match self {
            PointerAction::Pause { duration } => WDActions::PointerActionItem::General(
                WDActions::GeneralAction::Pause(WDActions::PauseAction {
                    duration: Some(duration.as_millis() as u64),
                }),
            ),
            PointerAction::Down { button } => WDActions::PointerActionItem::Pointer(
                WDActions::PointerAction::Down(WDActions::PointerDownAction {
                    button,
                    ..Default::default()
                }),
            ),
            PointerAction::Up { button } => WDActions::PointerActionItem::Pointer(
                WDActions::PointerAction::Up(WDActions::PointerUpAction {
                    button,
                    ..Default::default()
                }),
            ),
            PointerAction::MoveBy { duration, x, y } => WDActions::PointerActionItem::Pointer(
                WDActions::PointerAction::Move(WDActions::PointerMoveAction {
                    duration: duration.map(|x| x.as_millis() as u64),
                    origin: WDActions::PointerOrigin::Pointer,
                    x: Some(x),
                    y: Some(y),
                    ..Default::default()
                }),
            ),
            PointerAction::MoveTo { duration, x, y } => WDActions::PointerActionItem::Pointer(
                WDActions::PointerAction::Move(WDActions::PointerMoveAction {
                    duration: duration.map(|x| x.as_millis() as u64),
                    origin: WDActions::PointerOrigin::Viewport,
                    x: Some(x),
                    y: Some(y),
                    ..Default::default()
                }),
            ),
            PointerAction::MoveToElement {
                element,
                duration,
                x,
                y,
            } => WDActions::PointerActionItem::Pointer(WDActions::PointerAction::Move(
                WDActions::PointerMoveAction {
                    duration: duration.map(|x| x.as_millis() as u64),
                    origin: WDActions::PointerOrigin::Element(element.element),
                    x: Some(x),
                    y: Some(y),
                    ..Default::default()
                },
            )),
            PointerAction::Cancel => {
                WDActions::PointerActionItem::Pointer(WDActions::PointerAction::Cancel)
            }
        }
    }
}

/// A sequence containing [`Null` actions](NullAction).
#[derive(Debug, Clone)]
pub struct NullActions {
    /// A unique identifier to distinguish this input source from others.
    ///
    /// Choose a meaningful string as it may be useful for debugging.
    id: String,
    /// The list of actions for this sequence.
    actions: Vec<NullAction>,
}

impl NullActions {
    /// Create a new NullActions sequence.
    ///
    /// The id can be any string but must uniquely identify this input source.
    pub fn new(id: String) -> Self {
        Self {
            id,
            actions: Vec::new(),
        }
    }
}

impl From<NullActions> for ActionSequence {
    fn from(na: NullActions) -> Self {
        ActionSequence(WDActions::ActionSequence {
            id: na.id,
            actions: WDActions::ActionsType::Null {
                actions: na.actions.into_iter().map(|x| x.into_item()).collect(),
            },
        })
    }
}

/// A sequence containing [`Key` actions](KeyAction).
#[derive(Debug, Clone)]
pub struct KeyActions {
    /// A unique identifier to distinguish this input source from others.
    ///
    /// Choose a meaningful string as it may be useful for debugging.
    id: String,
    /// The list of actions for this sequence.
    actions: Vec<KeyAction>,
}

impl KeyActions {
    /// Create a new KeyActions sequence.
    ///
    /// The id can be any string but must uniquely identify this input source.
    pub fn new(id: String) -> Self {
        Self {
            id,
            actions: Vec::new(),
        }
    }
}

impl From<KeyActions> for ActionSequence {
    fn from(ka: KeyActions) -> Self {
        ActionSequence(WDActions::ActionSequence {
            id: ka.id,
            actions: WDActions::ActionsType::Key {
                actions: ka.actions.into_iter().map(|x| x.into_item()).collect(),
            },
        })
    }
}

/// A sequence containing [`Pointer` actions](PointerAction) for a mouse.
#[derive(Debug, Clone)]
pub struct MouseActions {
    /// A unique identifier to distinguish this input source from others.
    ///
    /// Choose a meaningful string as it may be useful for debugging.
    id: String,
    /// The list of actions for this sequence.
    actions: Vec<PointerAction>,
}

impl MouseActions {
    /// Create a new `MouseActions` sequence.
    ///
    /// The id can be any string but must uniquely identify this input source.
    pub fn new(id: String) -> Self {
        Self {
            id,
            actions: Vec::new(),
        }
    }
}

impl From<MouseActions> for ActionSequence {
    fn from(ma: MouseActions) -> Self {
        ActionSequence(WDActions::ActionSequence {
            id: ma.id,
            actions: WDActions::ActionsType::Pointer {
                parameters: WDActions::PointerActionParameters {
                    pointer_type: WDActions::PointerType::Mouse,
                },
                actions: ma.actions.into_iter().map(|x| x.into_item()).collect(),
            },
        })
    }
}

/// A sequence containing [`Pointer` actions](PointerAction) for a pen device.
#[derive(Debug, Clone)]
pub struct PenActions {
    /// A unique identifier to distinguish this input source from others.
    ///
    /// Choose a meaningful string as it may be useful for debugging.
    id: String,
    /// The list of actions for this sequence.
    actions: Vec<PointerAction>,
}

impl PenActions {
    /// Create a new `PenActions` sequence.
    ///
    /// The id can be any string but must uniquely identify this input source.
    pub fn new(id: String) -> Self {
        Self {
            id,
            actions: Vec::new(),
        }
    }
}

impl From<PenActions> for ActionSequence {
    fn from(pa: PenActions) -> Self {
        ActionSequence(WDActions::ActionSequence {
            id: pa.id,
            actions: WDActions::ActionsType::Pointer {
                parameters: WDActions::PointerActionParameters {
                    pointer_type: WDActions::PointerType::Pen,
                },
                actions: pa.actions.into_iter().map(|x| x.into_item()).collect(),
            },
        })
    }
}

/// A sequence containing [`Pointer` actions](PointerAction) for a touch device.
#[derive(Debug, Clone)]
pub struct TouchActions {
    /// A unique identifier to distinguish this input source from others.
    ///
    /// Choose a meaningful string as it may be useful for debugging.
    id: String,
    /// The list of actions for this sequence.
    actions: Vec<PointerAction>,
}

impl TouchActions {
    /// Create a new `TouchActions` sequence.
    ///
    /// The id can be any string but must uniquely identify this input source.
    pub fn new(id: String) -> Self {
        Self {
            id,
            actions: Vec::new(),
        }
    }
}

impl From<TouchActions> for ActionSequence {
    fn from(ta: TouchActions) -> Self {
        ActionSequence(WDActions::ActionSequence {
            id: ta.id,
            actions: WDActions::ActionsType::Pointer {
                parameters: WDActions::PointerActionParameters {
                    pointer_type: WDActions::PointerType::Touch,
                },
                actions: ta.actions.into_iter().map(|x| x.into_item()).collect(),
            },
        })
    }
}

/// A sequence of actions to be performed.
///
/// See the documentation for [`Actions`] for more details.
#[derive(Debug)]
pub struct ActionSequence(pub(crate) WDActions::ActionSequence);

/// A source capable of providing inputs for a browser action chain.
///
/// See [input source](https://www.w3.org/TR/webdriver1/#dfn-input-sources) in the
/// WebDriver standard.
///
/// Each sequence type implements `InputSource` which provides a `pause()` and a `then()`
/// method. Each call to `pause()` or `then()` represents one tick for this sequence.
pub trait InputSource: Into<ActionSequence> {
    /// The action type associated with this `InputSource`.
    type Action;

    /// Add a pause action to the sequence for this input source.
    #[must_use]
    fn pause(self, duration: Duration) -> Self;

    /// Add the specified action to the sequence for this input source.
    #[must_use]
    fn then(self, action: Self::Action) -> Self;
}

impl InputSource for NullActions {
    type Action = NullAction;

    fn pause(self, duration: Duration) -> Self {
        self.then(NullAction::Pause { duration })
    }

    fn then(mut self, action: Self::Action) -> Self {
        self.actions.push(action);
        self
    }
}

impl InputSource for KeyActions {
    type Action = KeyAction;

    fn pause(self, duration: Duration) -> Self {
        self.then(KeyAction::Pause { duration })
    }

    fn then(mut self, action: Self::Action) -> Self {
        self.actions.push(action);
        self
    }
}

impl InputSource for MouseActions {
    type Action = PointerAction;

    fn pause(self, duration: Duration) -> Self {
        self.then(PointerAction::Pause { duration })
    }

    fn then(mut self, action: Self::Action) -> Self {
        self.actions.push(action);
        self
    }
}

impl InputSource for PenActions {
    type Action = PointerAction;

    fn pause(self, duration: Duration) -> Self {
        self.then(PointerAction::Pause { duration })
    }

    fn then(mut self, action: Self::Action) -> Self {
        self.actions.push(action);
        self
    }
}

impl InputSource for TouchActions {
    type Action = PointerAction;

    fn pause(self, duration: Duration) -> Self {
        self.then(PointerAction::Pause { duration })
    }

    fn then(mut self, action: Self::Action) -> Self {
        self.actions.push(action);
        self
    }
}

/// A list of action sequences to be performed via [`Client::perform_actions()`]
///
/// An [`ActionSequence`] is a sequence of actions of a specific type.
///
/// Multiple sequences can be represented as a table, where each row contains a
/// sequence and each column is 1 "tick" of time. The duration of any given tick
/// will be equal to the longest duration of any individual action in that column.
///
/// See the following example diagram:
///
/// ```ignore
///   Tick ->              1         2                     3
/// |===================================================================
/// | KeyActions        |  Down   |  Up                 |  Pause  |
/// |-------------------------------------------------------------------
/// | PointerActions    |  Down   |  Pause (2 seconds)  |  Up     |
/// |-------------------------------------------------------------------
/// | (other sequence)  |  Pause  |  Pause              |  Pause  |
/// |===================================================================
/// ```
///
/// At tick 1, both a `KeyAction::Down` and a `PointerAction::Down` are triggered
/// simultaneously.
///
/// At tick 2, only a `KeyAction::Up` is triggered. Meanwhile the pointer sequence
/// has a `PointerAction::Pause` for 2 seconds. Note that tick 3 does not start
/// until all of the actions from tick 2 have completed, including any pauses.
///
/// At tick 3, only a `PointerAction::Up` is triggered.
///
/// The bottom sequence is just to show that other sequences can be added. This could
/// be any of `NullActions`, `KeyActions` or `PointerActions`. There is no theoretical
/// limit to the number of sequences that can be specified.
#[derive(Debug, Default)]
pub struct Actions {
    pub(crate) sequences: Vec<ActionSequence>,
}

impl Actions {
    /// Append the specified sequence to the list of sequences.
    #[must_use]
    pub fn and(mut self, sequence: impl Into<ActionSequence>) -> Self {
        self.sequences.push(sequence.into());
        self
    }
}

impl<T> From<T> for Actions
where
    T: Into<ActionSequence>,
{
    fn from(sequence: T) -> Self {
        Self {
            sequences: vec![sequence.into()],
        }
    }
}

impl<T> From<Vec<T>> for Actions
where
    T: Into<ActionSequence>,
{
    fn from(sequences: Vec<T>) -> Self {
        Self {
            sequences: sequences.into_iter().map(|x| x.into()).collect(),
        }
    }
}