input_testing/
input_device_registry.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
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::input_device::InputDevice;
use crate::new_fake_device_info;
use anyhow::{Context as _, Error};
use async_utils::event::Event as AsyncEvent;
use fidl::endpoints;
use fidl_fuchsia_input::Key;
use fidl_fuchsia_input_injection::InputDeviceRegistryProxy;
use fidl_fuchsia_input_report::{
    Axis, ConsumerControlButton, ConsumerControlDescriptor, ConsumerControlInputDescriptor,
    ContactInputDescriptor, DeviceDescriptor, InputDeviceMarker, KeyboardDescriptor,
    KeyboardInputDescriptor, MouseDescriptor, MouseInputDescriptor, Range, TouchDescriptor,
    TouchInputDescriptor, TouchType, Unit, UnitType, TOUCH_MAX_CONTACTS,
};
use fidl_fuchsia_ui_test_input::MouseButton;

/// Implements the client side of the `fuchsia.input.injection.InputDeviceRegistry` protocol.
pub(crate) struct InputDeviceRegistry {
    proxy: InputDeviceRegistryProxy,
    got_input_reports_reader: AsyncEvent,
}

impl InputDeviceRegistry {
    pub fn new(proxy: InputDeviceRegistryProxy, got_input_reports_reader: AsyncEvent) -> Self {
        Self { proxy, got_input_reports_reader }
    }

    /// Registers a touchscreen device, with in injection coordinate space that spans [-1000, 1000]
    /// on both axes.
    /// # Returns
    /// A `input_device::InputDevice`, which can be used to send events to the
    /// `fuchsia.input.report.InputDevice` that has been registered with the
    /// `fuchsia.input.injection.InputDeviceRegistry` service.
    pub async fn add_touchscreen_device(
        &mut self,
        min_x: i64,
        max_x: i64,
        min_y: i64,
        max_y: i64,
    ) -> Result<InputDevice, Error> {
        self.add_device(DeviceDescriptor {
            touch: Some(TouchDescriptor {
                input: Some(TouchInputDescriptor {
                    contacts: Some(
                        std::iter::repeat(ContactInputDescriptor {
                            position_x: Some(Axis {
                                range: Range { min: min_x, max: max_x },
                                unit: Unit { type_: UnitType::Other, exponent: 0 },
                            }),
                            position_y: Some(Axis {
                                range: Range { min: min_y, max: max_y },
                                unit: Unit { type_: UnitType::Other, exponent: 0 },
                            }),
                            contact_width: Some(Axis {
                                range: Range { min: min_x, max: max_x },
                                unit: Unit { type_: UnitType::Other, exponent: 0 },
                            }),
                            contact_height: Some(Axis {
                                range: Range { min: min_y, max: max_y },
                                unit: Unit { type_: UnitType::Other, exponent: 0 },
                            }),
                            ..Default::default()
                        })
                        .take(
                            usize::try_from(TOUCH_MAX_CONTACTS)
                                .context("usize is impossibly small")?,
                        )
                        .collect(),
                    ),
                    max_contacts: Some(TOUCH_MAX_CONTACTS),
                    touch_type: Some(TouchType::Touchscreen),
                    buttons: Some(vec![]),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        })
        .await
    }

    /// Registers a media buttons device.
    /// # Returns
    /// A `input_device::InputDevice`, which can be used to send events to the
    /// `fuchsia.input.report.InputDevice` that has been registered with the
    /// `fuchsia.input.injection.InputDeviceRegistry` service.
    pub async fn add_media_buttons_device(&mut self) -> Result<InputDevice, Error> {
        self.add_device(DeviceDescriptor {
            consumer_control: Some(ConsumerControlDescriptor {
                input: Some(ConsumerControlInputDescriptor {
                    buttons: Some(vec![
                        ConsumerControlButton::VolumeUp,
                        ConsumerControlButton::VolumeDown,
                        ConsumerControlButton::Pause,
                        ConsumerControlButton::FactoryReset,
                        ConsumerControlButton::MicMute,
                        ConsumerControlButton::Reboot,
                        ConsumerControlButton::CameraDisable,
                    ]),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        })
        .await
    }

    /// Registers a keyboard device.
    /// # Returns
    /// An `input_device::InputDevice`, which can be used to send events to the
    /// `fuchsia.input.report.InputDevice` that has been registered with the
    /// `fuchsia.input.injection.InputDeviceRegistry` service.
    pub async fn add_keyboard_device(&mut self) -> Result<InputDevice, Error> {
        // Generate a `Vec` of all known keys.
        // * Because there is no direct way to iterate over enum values, we iterate
        //   over the values corresponding to `Key::A` and `Key::MediaVolumeDecrement`.
        // * Some values in the range have no corresponding enum value. For example,
        //   the value 0x00070065 sits between `NonUsBackslash` (0x00070064), and
        //   `KeypadEquals` (0x00070067). Such primitives are removed by `filter_map()`.
        //
        // TODO(https://fxbug.dev/42059900): Extend to include all values of the Key enum.
        let all_keys: Vec<Key> = (Key::A.into_primitive()
            ..=Key::MediaVolumeDecrement.into_primitive())
            .filter_map(Key::from_primitive)
            .collect();
        self.add_device(DeviceDescriptor {
            // Required for DeviceDescriptor.
            device_information: Some(new_fake_device_info()),
            keyboard: Some(KeyboardDescriptor {
                input: Some(KeyboardInputDescriptor {
                    keys3: Some(all_keys),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        })
        .await
    }

    pub async fn add_mouse_device(&mut self) -> Result<InputDevice, Error> {
        self.add_device(DeviceDescriptor {
            // Required for DeviceDescriptor.
            device_information: Some(new_fake_device_info()),
            mouse: Some(MouseDescriptor {
                input: Some(MouseInputDescriptor {
                    movement_x: Some(Axis {
                        range: Range { min: -1000, max: 1000 },
                        unit: Unit { type_: UnitType::Other, exponent: 0 },
                    }),
                    movement_y: Some(Axis {
                        range: Range { min: -1000, max: 1000 },
                        unit: Unit { type_: UnitType::Other, exponent: 0 },
                    }),
                    // `scroll_v` and `scroll_h` are range of tick number on
                    // driver's report. [-100, 100] should be enough for
                    // testing.
                    scroll_v: Some(Axis {
                        range: Range { min: -100, max: 100 },
                        unit: Unit { type_: UnitType::Other, exponent: 0 },
                    }),
                    scroll_h: Some(Axis {
                        range: Range { min: -100, max: 100 },
                        unit: Unit { type_: UnitType::Other, exponent: 0 },
                    }),
                    // Match to the values of fuchsia.ui.test.input.MouseButton.
                    buttons: Some(
                        (MouseButton::First.into_primitive()..=MouseButton::Third.into_primitive())
                            .map(|b| {
                                b.try_into().expect("failed to convert mouse button to primitive")
                            })
                            .collect(),
                    ),
                    position_x: None,
                    position_y: None,
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        })
        .await
    }

    /// Adds a device to the `InputDeviceRegistry` FIDL server connected to this
    /// `InputDeviceRegistry` struct.
    ///
    /// # Returns
    /// A `input_device::InputDevice`, which can be used to send events to the
    /// `fuchsia.input.report.InputDevice` that has been registered with the
    /// `fuchsia.input.injection.InputDeviceRegistry` service.
    async fn add_device(&self, descriptor: DeviceDescriptor) -> Result<InputDevice, Error> {
        let (client_end, request_stream) = endpoints::create_request_stream::<InputDeviceMarker>();
        let mut device: InputDevice =
            InputDevice::new(request_stream, descriptor, self.got_input_reports_reader.clone());

        let res = self.proxy.register_and_get_device_info(client_end).await?;
        let device_id = res.device_id.expect("missing device_id");
        device.device_id = device_id;

        Ok(device)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fidl_fuchsia_input_injection::{
        InputDeviceRegistryMarker, InputDeviceRegistryRegisterAndGetDeviceInfoResponse,
        InputDeviceRegistryRequest,
    };
    use fidl_fuchsia_input_report::InputReportsReaderMarker;
    use fuchsia_async as fasync;
    use futures::StreamExt;
    use test_case::test_case;

    enum TestDeviceType {
        TouchScreen,
        MediaButtons,
        Keyboard,
        Mouse,
    }

    async fn add_device_for_test(
        registry: &mut InputDeviceRegistry,
        ty: TestDeviceType,
    ) -> Result<InputDevice, Error> {
        match ty {
            TestDeviceType::TouchScreen => registry.add_touchscreen_device(1, 1000, 1, 1000).await,
            TestDeviceType::MediaButtons => registry.add_media_buttons_device().await,
            TestDeviceType::Keyboard => registry.add_keyboard_device().await,
            TestDeviceType::Mouse => registry.add_mouse_device().await,
        }
    }

    #[test_case(TestDeviceType::TouchScreen =>
                matches Ok(DeviceDescriptor {
                    touch: Some(TouchDescriptor {
                        input: Some(TouchInputDescriptor { .. }),
                        ..
                    }),
                    .. });
                "touchscreen_device")]
    #[test_case(TestDeviceType::MediaButtons =>
                matches Ok(DeviceDescriptor {
                    consumer_control: Some(ConsumerControlDescriptor {
                        input: Some(ConsumerControlInputDescriptor { .. }),
                        ..
                    }),
                    .. });
                "media_buttons_device")]
    #[test_case(TestDeviceType::Keyboard =>
                matches Ok(DeviceDescriptor {
                    keyboard: Some(KeyboardDescriptor { .. }),
                    ..
                });
                "keyboard_device")]
    #[test_case(TestDeviceType::Mouse =>
                matches Ok(DeviceDescriptor {
                    mouse: Some(MouseDescriptor { .. }),
                    ..
                });
                "mouse_device")]
    #[fasync::run_singlethreaded(test)]
    async fn add_device_registers_correct_device_type(
        device_type: TestDeviceType,
    ) -> Result<DeviceDescriptor, Error> {
        let (registry_proxy, mut registry_request_stream) =
            endpoints::create_proxy_and_stream::<InputDeviceRegistryMarker>();
        let mut input_device_registry = InputDeviceRegistry {
            proxy: registry_proxy,
            got_input_reports_reader: AsyncEvent::new(),
        };

        let add_device_fut = add_device_for_test(&mut input_device_registry, device_type);

        let input_device_proxy_fut = async {
            // `input_device_registry` should send a `Register` messgage to `registry_request_stream`.
            // Use `registry_request_stream` to grab the `ClientEnd` of the device added above,
            // and convert the `ClientEnd` into an `InputDeviceProxy`.
            //
            // Here only handle InputDeviceRegistryRequest once.
            let input_device_proxy = match registry_request_stream
                .next()
                .await
                .expect("stream read should yield Some")
                .expect("fidl read")
            {
                InputDeviceRegistryRequest::Register { .. } => {
                    unreachable!("InputDeviceRegistryRequest::Register should not be called");
                }
                InputDeviceRegistryRequest::RegisterAndGetDeviceInfo {
                    device, responder, ..
                } => {
                    responder
                        .send(InputDeviceRegistryRegisterAndGetDeviceInfoResponse {
                            device_id: Some(1),
                            ..Default::default()
                        })
                        .expect("RegisterAndGetDeviceInfo send response failed");

                    device
                }
            }
            .into_proxy();

            input_device_proxy
        };

        let (add_device_res, input_device_proxy) =
            futures::join!(add_device_fut, input_device_proxy_fut);

        let input_device = add_device_res.expect("add_device failed");
        assert_ne!(input_device.device_id, 0);

        let input_device_get_descriptor = input_device_proxy.get_descriptor().await;

        let input_device_server_fut = input_device.flush();

        // Avoid unrelated `panic()`: `InputDevice` requires clients to get an input
        // reports reader, to help debug integration test failures where no component
        // read events from the fake device.
        let (_input_reports_reader_proxy, input_reports_reader_server_end) =
            endpoints::create_proxy::<InputReportsReaderMarker>();
        let _ = input_device_proxy.get_input_reports_reader(input_reports_reader_server_end);

        std::mem::drop(input_device_proxy); // Terminate stream served by `input_device_server_fut`.
        input_device_server_fut.await;

        input_device_get_descriptor.map_err(anyhow::Error::from)
    }
}