input_synthesis/synthesizer.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 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
// Copyright 2020 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::derive_key_sequence;
use anyhow::{ensure, Error};
use async_trait::async_trait;
use fidl_fuchsia_input_report::MouseInputReport;
use fidl_fuchsia_ui_input::{KeyboardReport, Touch};
use log::debug;
use serde::{Deserialize, Deserializer};
use std::thread;
use std::time::Duration;
use {fidl_fuchsia_input as input, fidl_fuchsia_ui_input3 as input3, fuchsia_async as fasync};
// Abstracts over input injection services (which are provided by input device registries).
pub trait InputDeviceRegistry {
fn add_touchscreen_device(
&mut self,
width: u32,
height: u32,
) -> Result<Box<dyn InputDevice>, Error>;
fn add_keyboard_device(&mut self) -> Result<Box<dyn InputDevice>, Error>;
fn add_media_buttons_device(&mut self) -> Result<Box<dyn InputDevice>, Error>;
fn add_mouse_device(&mut self, width: u32, height: u32) -> Result<Box<dyn InputDevice>, Error>;
}
// Abstracts over the various interactions that a user might have with an input device.
// Note that the input-synthesis crate deliberately chooses not to "sub-type" input devices.
// This avoids additional code complexity, and allows the crate to support tests that
// deliberately send events that do not match the expected event type for a device.
#[async_trait(?Send)]
pub trait InputDevice {
/// Sends a media buttons report with the specified buttons pressed.
fn media_buttons(&mut self, pressed_buttons: Vec<MediaButton>, time: u64) -> Result<(), Error>;
/// Sends a keyboard report with keys defined mostly in terms of USB HID usage
/// page 7. This is sufficient for keyboard keys, but does not cover the full
/// extent of keys that Fuchsia supports. As result, the KeyboardReport is converted
/// internally into Fuchsia's encoding before being forwarded.
fn key_press(&mut self, keyboard: KeyboardReport, time: u64) -> Result<(), Error>;
/// Sends a keyboard report using the whole range of key codes. Key codes provided
/// are not modified or mapped in any way.
/// This differs from `key_press`, which performs special mapping for key codes
/// from USB HID Page 0x7.
fn key_press_raw(&mut self, keyboard: KeyboardReport, time: u64) -> Result<(), Error>;
fn key_press_usage(&mut self, usage: Option<u32>, time: u64) -> Result<(), Error>;
fn tap(&mut self, pos: Option<(u32, u32)>, time: u64) -> Result<(), Error>;
fn multi_finger_tap(&mut self, fingers: Option<Vec<Touch>>, time: u64) -> Result<(), Error>;
/// Sends a mouse report with the specified relative cursor movement and buttons pressed.
fn mouse(&mut self, report: MouseInputReport, time: u64) -> Result<(), Error>;
// Returns a `Future` which resolves when all input reports for this device
// have been sent to the FIDL peer, or when an error occurs.
//
// The possible errors are implementation-specific, but may include:
// * Errors reading from the FIDL peer
// * Errors writing to the FIDL peer
//
// # Resolves to
// * `Ok(())` if all reports were written successfully
// * `Err` otherwise
//
// # Note
// When the future resolves, input reports may still be sitting unread in the
// channel to the FIDL peer.
async fn flush(self: Box<Self>) -> Result<(), Error>;
}
/// The buttons supported by `media_button_event()`.
#[derive(PartialOrd, PartialEq, Ord, Eq)]
pub enum MediaButton {
VolumeUp,
VolumeDown,
MicMute,
FactoryReset,
Pause,
CameraDisable,
}
fn monotonic_nanos() -> Result<u64, Error> {
u64::try_from(zx::MonotonicInstant::get().into_nanos()).map_err(Into::into)
}
async fn repeat_with_delay(
times: usize,
delay: Duration,
device: &mut dyn InputDevice,
f1: impl Fn(usize, &mut dyn InputDevice) -> Result<(), Error>,
f2: impl Fn(usize, &mut dyn InputDevice) -> Result<(), Error>,
) -> Result<(), Error> {
for i in 0..times {
f1(i, device)?;
fasync::Timer::new(fasync::MonotonicInstant::after(delay.into())).await;
f2(i, device)?;
}
Ok(())
}
/// Sends a media buttons report with the specified buttons pressed.
pub async fn media_button_event<I: IntoIterator<Item = MediaButton>>(
pressed_buttons: I,
registry: &mut dyn InputDeviceRegistry,
) -> Result<(), Error> {
let mut input_device = registry.add_media_buttons_device()?;
input_device.media_buttons(pressed_buttons.into_iter().collect(), monotonic_nanos()?)?;
input_device.flush().await
}
/// A single key event to be replayed by `dispatch_key_events_async`.
///
/// See [crate::dispatch_key_events] for details of the key event type and the event timing.
///
/// For example, a key press like this:
///
/// ```ignore
/// Key1: _________/"""""""""""""""\\___________
/// ^ ^--- key released
/// `------------------- key pressed
/// |<------>| <-- duration_since_start (50ms)
/// |<---------------------->| duration_since_start (100ms)
/// ```
///
/// would be described with a sequence of two `TimedKeyEvent`s (pseudo-code):
///
/// ```
/// [
/// { Key1, 50ms, PRESSED },
/// { Key1, 100ms, RELEASED },
/// ]
/// ```
///
/// This is not overly useful in the case of a single key press, but is useful to model multiple
/// concurrent keypresses, while allowing an arbitrary interleaving of key events.
///
/// Consider a more complicated timing diagram like this one:
///
/// ```ignore
/// Key1: _________/"""""""""""""""\\_____________
/// Key2: ____/"""""""""""""""\\__________________
/// Key3: ______/"""""""""""""""\\________________
/// Key4: _____________/"""""""""""""""\\_________
/// Key5: ________________ __/""""""\\____________
/// Key6: ________/""""""\\_______________________
/// ```
///
/// It then becomes obvious how modeling individual events allows us to express this interaction.
/// Furthermore anchoring `duration_since_start` to the beginning of the key sequence (instead of,
/// for example, specifying the duration of each key press) gives a common time reference and makes
/// it fairly easy to express the intended key interaction in terms of a `TimedKeyEvent` sequence.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct TimedKeyEvent {
/// The [input::Key] which changed state.
pub key: input::Key,
/// The duration of time, relative to the start of the key event sequence that this `TimedKeyEvent`
/// is part of, at which this event happened at.
pub duration_since_start: Duration,
/// The type of state change that happened to `key`. Was it pressed, released or something
/// else.
pub event_type: input3::KeyEventType,
}
impl TimedKeyEvent {
/// Creates a new [TimedKeyEvent] to inject into the input pipeline. `key` is
/// the key to be pressed (using Fuchsia HID-like encoding), `type_` is the
/// event type (Pressed, or Released etc), and `duration_since_start` is the
/// duration since the start of the entire event sequence that the key event
/// should be scheduled at.
pub fn new(
key: input::Key,
type_: input3::KeyEventType,
duration_since_start: Duration,
) -> Self {
Self { key, duration_since_start, event_type: type_ }
}
/// Deserializes a vector of `TimedKeyEvent`.
/// A custom deserializer is used because Vec<_> does not work
/// with serde, and the [TimedKeyEvent] has constituents that don't
/// have a derived serde representation.
/// See: https://github.com/serde-rs/serde/issues/723#issuecomment-382501277
pub fn vec<'de, D>(deserializer: D) -> Result<Vec<TimedKeyEvent>, D::Error>
where
D: Deserializer<'de>,
{
// Should correspond to TimedKeyEvent, except all fields are described by their underlying
// primitive values.
#[derive(Deserialize, Debug)]
struct TimedKeyEventDes {
// The Fuchsia encoded USB HID key, per input::Key.
key: u32,
// A Duration.
duration_millis: u64,
// An input3::TimedKeyEventType.
#[serde(rename = "type")]
type_: u32,
}
impl Into<TimedKeyEvent> for TimedKeyEventDes {
/// Reconstructs the typed elements of [TimedKeyEvent] from primitives.
fn into(self) -> TimedKeyEvent {
TimedKeyEvent::new(
input::Key::from_primitive(self.key)
.unwrap_or_else(|| panic!("Key::from_primitive failed on: {:?}", &self)),
input3::KeyEventType::from_primitive(self.type_).unwrap_or_else(|| {
panic!("KeyEventType::from_primitive failed on: {:?}", &self)
}),
Duration::from_millis(self.duration_millis),
)
}
}
let v = Vec::deserialize(deserializer)?;
Ok(v.into_iter().map(|a: TimedKeyEventDes| a.into()).collect())
}
}
/// Replays the sequence of events (see [Replayer::replay]) with the correct timing.
struct Replayer<'a> {
// Invariant: pressed_keys.iter() must use ascending iteration
// ordering.
pressed_keys: std::collections::BTreeSet<input::Key>,
// The input device registry to use.
registry: &'a mut dyn InputDeviceRegistry,
}
impl<'a> Replayer<'a> {
fn new(registry: &'a mut dyn InputDeviceRegistry) -> Self {
Replayer { pressed_keys: std::collections::BTreeSet::new(), registry }
}
/// Replays the given sequence of key events with the correct timing spacing
/// between the events.
///
/// All timing in [TimedKeyEvent] is relative to the instance in the monotonic clock base at which
/// we started replaying the entire event sequence. The replay returns an error in case
/// the events are not sequenced with strictly increasing timestamps.
async fn replay<'b: 'a>(&mut self, events: &'b [TimedKeyEvent]) -> Result<(), Error> {
let mut last_key_event_at = Duration::from_micros(0);
// Verify that the key events are scheduled in a nondecreasing timestamp sequence.
for key_event in events {
if key_event.duration_since_start < last_key_event_at {
return Err(anyhow::anyhow!(
concat!(
"TimedKeyEvent was requested out of sequence: ",
"TimedKeyEvent: {:?}, low watermark for duration_since_start: {:?}"
),
&key_event,
last_key_event_at
));
}
if key_event.duration_since_start == last_key_event_at {
// If you see this error message, read the documentation for how to send key events
// correctly in the TimedKeyEvent documentation.
return Err(anyhow::anyhow!(
concat!(
"TimedKeyEvent was requested at the same time instant as a previous event. ",
"This is not allowed, each key event must happen at a distinct timestamp: ",
"TimedKeyEvent: {:?}, low watermark for duration_since_start: {:?}"
),
&key_event,
last_key_event_at
));
}
last_key_event_at = key_event.duration_since_start;
}
let mut input_device = self.registry.add_keyboard_device()?;
let started_at = monotonic_nanos()?;
for key_event in events {
use input3::KeyEventType;
match key_event.event_type {
KeyEventType::Pressed | KeyEventType::Sync => {
self.pressed_keys.insert(key_event.key.clone());
}
KeyEventType::Released | KeyEventType::Cancel => {
self.pressed_keys.remove(&key_event.key);
}
}
// The sequence below should be an async task. The complicating factor is that
// input_device lifetime needs to be 'static for this to be schedulable on a
// fuchsia::async::Task. So for the time being, we skip that part.
let processed_at = Duration::from_nanos(monotonic_nanos()? - started_at);
let desired_at = &key_event.duration_since_start;
if processed_at < *desired_at {
fasync::Timer::new(fasync::MonotonicInstant::after(
(*desired_at - processed_at).into(),
))
.await;
}
input_device.key_press_raw(self.make_input_report(), monotonic_nanos()?)?;
}
input_device.flush().await
}
/// Creates a keyboard report based on the keys that are currently pressed.
///
/// The pressed keys are always reported in the nondecreasing order of their respective key
/// codes, so a single distinct key chord will be always reported as a single distinct
/// `KeyboardReport`.
fn make_input_report(&self) -> KeyboardReport {
KeyboardReport {
pressed_keys: self.pressed_keys.iter().map(|k| k.into_primitive()).collect(),
}
}
}
/// Dispatches the supplied `events` into a keyboard device registered into `registry`, honoring
/// the timing sequence that is described in them to the extent that they are possible to schedule.
pub(crate) async fn dispatch_key_events_async(
events: &[TimedKeyEvent],
registry: &mut dyn InputDeviceRegistry,
) -> Result<(), Error> {
Replayer::new(registry).replay(events).await
}
pub(crate) async fn keyboard_event(
usage: u32,
duration: Duration,
registry: &mut dyn InputDeviceRegistry,
) -> Result<(), Error> {
let mut input_device = registry.add_keyboard_device()?;
repeat_with_delay(
1,
duration,
input_device.as_mut(),
|_i, device| {
// Key pressed.
device.key_press_usage(Some(usage), monotonic_nanos()?)
},
|_i, device| {
// Key released.
device.key_press_usage(None, monotonic_nanos()?)
},
)
.await?;
input_device.flush().await
}
/// Simulates `input` being typed on a keyboard, with `key_event_duration` between key events.
///
/// # Requirements
/// * `input` must be non-empty
/// * `input` must only contain characters representable using the current keyboard layout
/// and locale. (At present, it is assumed that the current layout and locale are
/// `US-QWERTY` and `en-US`, respectively.)
///
/// # Resolves to
/// * `Ok(())` if the arguments met the requirements above, and the events were successfully
/// injected.
/// * `Err(Error)` otherwise.
///
/// # Corner case handling
/// * `key_event_duration` of zero is permitted, and will result in events being generated as
/// quickly as possible.
pub async fn text(
input: String,
key_event_duration: Duration,
registry: &mut dyn InputDeviceRegistry,
) -> Result<(), Error> {
let mut input_device = registry.add_keyboard_device()?;
let key_sequence = derive_key_sequence(&keymaps::US_QWERTY, &input)
.ok_or_else(|| anyhow::format_err!("Cannot translate text to key sequence"))?;
debug!(input:% = input, key_sequence:?, key_event_duration:?; "synthesizer::text");
let mut key_iter = key_sequence.into_iter().peekable();
while let Some(keyboard) = key_iter.next() {
input_device.key_press(keyboard, monotonic_nanos()?)?;
if key_iter.peek().is_some() {
thread::sleep(key_event_duration);
}
}
input_device.flush().await
}
pub async fn tap_event(
x: u32,
y: u32,
width: u32,
height: u32,
tap_event_count: usize,
duration: Duration,
registry: &mut dyn InputDeviceRegistry,
) -> Result<(), Error> {
let mut input_device = registry.add_touchscreen_device(width, height)?;
let tap_duration = duration / tap_event_count as u32;
repeat_with_delay(
tap_event_count,
tap_duration,
input_device.as_mut(),
|_i, device| {
// Touch down.
device.tap(Some((x, y)), monotonic_nanos()?)
},
|_i, device| {
// Touch up.
device.tap(None, monotonic_nanos()?)
},
)
.await?;
input_device.flush().await
}
pub(crate) async fn multi_finger_tap_event(
fingers: Vec<Touch>,
width: u32,
height: u32,
tap_event_count: usize,
duration: Duration,
registry: &mut dyn InputDeviceRegistry,
) -> Result<(), Error> {
let mut input_device = registry.add_touchscreen_device(width, height)?;
let multi_finger_tap_duration = duration / tap_event_count as u32;
repeat_with_delay(
tap_event_count,
multi_finger_tap_duration,
input_device.as_mut(),
|_i, device| {
// Touch down.
device.multi_finger_tap(Some(fingers.clone()), monotonic_nanos()?)
},
|_i, device| {
// Touch up.
device.multi_finger_tap(None, monotonic_nanos()?)
},
)
.await?;
input_device.flush().await
}
pub(crate) async fn swipe(
x0: u32,
y0: u32,
x1: u32,
y1: u32,
width: u32,
height: u32,
move_event_count: usize,
duration: Duration,
registry: &mut dyn InputDeviceRegistry,
) -> Result<(), Error> {
multi_finger_swipe(
vec![(x0, y0)],
vec![(x1, y1)],
width,
height,
move_event_count,
duration,
registry,
)
.await
}
pub(crate) async fn multi_finger_swipe(
start_fingers: Vec<(u32, u32)>,
end_fingers: Vec<(u32, u32)>,
width: u32,
height: u32,
move_event_count: usize,
duration: Duration,
registry: &mut dyn InputDeviceRegistry,
) -> Result<(), Error> {
ensure!(
start_fingers.len() == end_fingers.len(),
"start_fingers.len() != end_fingers.len() ({} != {})",
start_fingers.len(),
end_fingers.len()
);
ensure!(
u32::try_from(start_fingers.len() + 1).is_ok(),
"fingers exceed capacity of `finger_id`!"
);
let mut input_device = registry.add_touchscreen_device(width, height)?;
// Note: coordinates are coverted to `f64` before subtraction, because u32 subtraction
// would overflow when swiping from higher coordinates to lower coordinates.
let finger_delta_x = start_fingers
.iter()
.zip(end_fingers.iter())
.map(|((start_x, _start_y), (end_x, _end_y))| {
(*end_x as f64 - *start_x as f64) / std::cmp::max(move_event_count, 1) as f64
})
.collect::<Vec<_>>();
let finger_delta_y = start_fingers
.iter()
.zip(end_fingers.iter())
.map(|((_start_x, start_y), (_end_x, end_y))| {
(*end_y as f64 - *start_y as f64) / std::cmp::max(move_event_count, 1) as f64
})
.collect::<Vec<_>>();
let swipe_event_delay = if move_event_count > 1 {
// We have move_event_count + 2 events:
// DOWN
// MOVE x move_event_count
// UP
// so we need (move_event_count + 1) delays.
duration / (move_event_count + 1) as u32
} else {
duration
};
repeat_with_delay(
move_event_count + 2, // +2 to account for DOWN and UP events
swipe_event_delay,
input_device.as_mut(),
|i, device| {
let time = monotonic_nanos()?;
match i {
// DOWN
0 => device.multi_finger_tap(
Some(
start_fingers
.iter()
.enumerate()
.map(|(finger_index, (x, y))| Touch {
finger_id: (finger_index + 1) as u32,
x: *x as i32,
y: *y as i32,
width: 0,
height: 0,
})
.collect(),
),
time,
),
// MOVE
i if i <= move_event_count => device.multi_finger_tap(
Some(
start_fingers
.iter()
.enumerate()
.map(|(finger_index, (x, y))| Touch {
finger_id: (finger_index + 1) as u32,
x: (*x as f64 + (i as f64 * finger_delta_x[finger_index]).round())
as i32,
y: (*y as f64 + (i as f64 * finger_delta_y[finger_index]).round())
as i32,
width: 0,
height: 0,
})
.collect(),
),
time,
),
// UP
i if i == (move_event_count + 1) => device.multi_finger_tap(None, time),
i => panic!("unexpected loop iteration {}", i),
}
},
|_, _| Ok(()),
)
.await?;
input_device.flush().await
}
/// The buttons supported by `mouse()`.
pub type MouseButton = u8;
pub async fn add_mouse_device(
width: u32,
height: u32,
registry: &mut dyn InputDeviceRegistry,
) -> Result<Box<dyn InputDevice>, Error> {
registry.add_mouse_device(width, height)
}
#[cfg(test)]
mod tests {
use super::*;
use anyhow::Context as _;
use fuchsia_async as fasync;
use serde::Deserialize;
#[derive(Deserialize, Debug, Eq, PartialEq)]
struct KeyEventsRequest {
#[serde(default, deserialize_with = "TimedKeyEvent::vec")]
pub key_events: Vec<TimedKeyEvent>,
}
#[test]
fn deserialize_key_event() -> Result<(), Error> {
let request_json = r#"{
"key_events": [
{
"key": 458756,
"duration_millis": 100,
"type": 1
}
]
}"#;
let event: KeyEventsRequest = serde_json::from_str(&request_json)?;
assert_eq!(
event,
KeyEventsRequest {
key_events: vec![TimedKeyEvent {
key: input::Key::A,
duration_since_start: Duration::from_millis(100),
event_type: input3::KeyEventType::Pressed,
},],
}
);
Ok(())
}
#[test]
fn deserialize_key_event_maformed_input() {
let tests: Vec<&'static str> = vec![
// "type" has a wrong value.
r#"{
"key_events": [
{
"key": 458756,
"duration_millis": 100,
"type": 99999,
}
]
}"#,
// "key" has a value that is too small.
r#"{
"key_events": [
{
"key": 12,
"duration_millis": 100,
"type": 1,
}
]
}"#,
// "type" is missing.
r#"{
"key_events": [
{
"key": 12,
"duration_millis": 100,
}
]
}"#,
// "duration" is missing.
r#"{
"key_events": [
{
"key": 458756,
"type": 1
}
]
}"#,
// "key" is missing.
r#"{
"key_events": [
{
"duration_millis": 100,
"type": 1
}
]
}"#,
];
for test in tests.iter() {
serde_json::from_str::<KeyEventsRequest>(test)
.expect_err(&format!("malformed input should not parse: {}", &test));
}
}
mod event_synthesis {
use super::*;
use fidl::endpoints;
use fidl_fuchsia_input_report::MOUSE_MAX_NUM_BUTTONS;
use fidl_fuchsia_ui_input::{
InputDeviceMarker, InputDeviceProxy as FidlInputDeviceProxy, InputDeviceRequest,
InputDeviceRequestStream, InputReport, MediaButtonsReport, MouseReport,
TouchscreenReport,
};
use futures::stream::StreamExt;
use std::collections::HashSet;
// Like `InputReport`, but with the `Box`-ed items inlined.
struct InlineInputReport {
event_time: u64,
keyboard: Option<KeyboardReport>,
media_buttons: Option<MediaButtonsReport>,
touchscreen: Option<TouchscreenReport>,
mouse: Option<MouseReport>,
}
impl InlineInputReport {
fn new(input_report: InputReport) -> Self {
Self {
event_time: input_report.event_time,
keyboard: input_report.keyboard.map(|boxed| *boxed),
media_buttons: input_report.media_buttons.map(|boxed| *boxed),
touchscreen: input_report.touchscreen.map(|boxed| *boxed),
mouse: input_report.mouse.map(|boxed| *boxed),
}
}
}
// An `impl InputDeviceRegistry` which provides access to the `InputDeviceRequest`s sent to
// the device registered with the `InputDeviceRegistry`. Assumes that only one device is
// registered.
struct FakeInputDeviceRegistry {
event_stream: Option<InputDeviceRequestStream>,
}
impl InputDeviceRegistry for FakeInputDeviceRegistry {
fn add_touchscreen_device(
&mut self,
_width: u32,
_height: u32,
) -> Result<Box<dyn InputDevice>, Error> {
self.add_device()
}
fn add_keyboard_device(&mut self) -> Result<Box<dyn InputDevice>, Error> {
self.add_device()
}
fn add_media_buttons_device(&mut self) -> Result<Box<dyn InputDevice>, Error> {
self.add_device()
}
fn add_mouse_device(
&mut self,
_width: u32,
_height: u32,
) -> Result<Box<dyn InputDevice>, Error> {
self.add_device()
}
}
impl FakeInputDeviceRegistry {
fn new() -> Self {
Self { event_stream: None }
}
async fn get_events(self: Self) -> Vec<Result<InlineInputReport, String>> {
match self.event_stream {
Some(event_stream) => {
event_stream
.map(|fidl_result| match fidl_result {
Ok(InputDeviceRequest::DispatchReport { report, .. }) => {
Ok(InlineInputReport::new(report))
}
Err(fidl_error) => Err(format!("FIDL error: {}", fidl_error)),
})
.collect()
.await
}
None => vec![Err(format!(
"called get_events() on InputDeviceRegistry with no `event_stream`"
))],
}
}
fn add_device(&mut self) -> Result<Box<dyn InputDevice>, Error> {
let (proxy, event_stream) =
endpoints::create_proxy_and_stream::<InputDeviceMarker>();
self.event_stream = Some(event_stream);
Ok(Box::new(FakeInputDevice::new(proxy)))
}
}
/// Returns a u32 representation of `buttons`, where each u8 of `buttons` is an id of a button and
/// indicates the position of a bit to set.
///
/// This supports hashsets containing numbers from 1 to fidl_input_report::MOUSE_MAX_NUM_BUTTONS.
///
/// # Parameters
/// - `buttons`: The hashset containing the position of bits to be set.
///
/// # Example
/// ```
/// let bits = get_u32_from_buttons(&HashSet::from_iter(vec![1, 3, 5]).into_iter());
/// assert_eq!(bits, 21 /* ...00010101 */)
/// ```
pub fn get_u32_from_buttons(buttons: &HashSet<MouseButton>) -> u32 {
let mut bits: u32 = 0;
for button in buttons {
if *button > 0 && *button <= MOUSE_MAX_NUM_BUTTONS as u8 {
bits = ((1 as u32) << *button - 1) | bits;
}
}
bits
}
// Provides an `impl InputDevice` which forwards requests to a `FidlInputDeviceProxy`.
// Useful when a test wants to inspect the requests to an `InputDevice`.
struct FakeInputDevice {
fidl_proxy: FidlInputDeviceProxy,
}
#[async_trait(?Send)]
impl InputDevice for FakeInputDevice {
fn media_buttons(
&mut self,
pressed_buttons: Vec<MediaButton>,
time: u64,
) -> Result<(), Error> {
self.fidl_proxy
.dispatch_report(&InputReport {
event_time: time,
keyboard: None,
media_buttons: Some(Box::new(MediaButtonsReport {
volume_up: pressed_buttons.contains(&MediaButton::VolumeUp),
volume_down: pressed_buttons.contains(&MediaButton::VolumeDown),
mic_mute: pressed_buttons.contains(&MediaButton::MicMute),
reset: pressed_buttons.contains(&MediaButton::FactoryReset),
pause: pressed_buttons.contains(&MediaButton::Pause),
camera_disable: pressed_buttons.contains(&MediaButton::CameraDisable),
})),
mouse: None,
stylus: None,
touchscreen: None,
sensor: None,
trace_id: 0,
})
.map_err(Into::into)
}
fn key_press(&mut self, keyboard: KeyboardReport, time: u64) -> Result<(), Error> {
self.key_press_raw(keyboard, time)
}
fn key_press_raw(&mut self, keyboard: KeyboardReport, time: u64) -> Result<(), Error> {
self.fidl_proxy
.dispatch_report(&InputReport {
event_time: time,
keyboard: Some(Box::new(keyboard)),
media_buttons: None,
mouse: None,
stylus: None,
touchscreen: None,
sensor: None,
trace_id: 0,
})
.map_err(Into::into)
}
fn key_press_usage(&mut self, usage: Option<u32>, time: u64) -> Result<(), Error> {
self.key_press(
KeyboardReport {
pressed_keys: match usage {
Some(usage) => vec![usage],
None => vec![],
},
},
time,
)
.map_err(Into::into)
}
fn tap(&mut self, pos: Option<(u32, u32)>, time: u64) -> Result<(), Error> {
match pos {
Some((x, y)) => self.multi_finger_tap(
Some(vec![Touch {
finger_id: 1,
x: x as i32,
y: y as i32,
width: 0,
height: 0,
}]),
time,
),
None => self.multi_finger_tap(None, time),
}
.map_err(Into::into)
}
fn multi_finger_tap(
&mut self,
fingers: Option<Vec<Touch>>,
time: u64,
) -> Result<(), Error> {
self.fidl_proxy
.dispatch_report(&InputReport {
event_time: time,
keyboard: None,
media_buttons: None,
mouse: None,
stylus: None,
touchscreen: Some(Box::new(TouchscreenReport {
touches: match fingers {
Some(fingers) => fingers,
None => vec![],
},
})),
sensor: None,
trace_id: 0,
})
.map_err(Into::into)
}
fn mouse(&mut self, report: MouseInputReport, time: u64) -> Result<(), Error> {
self.fidl_proxy
.dispatch_report(&InputReport {
event_time: time,
keyboard: None,
media_buttons: None,
mouse: Some(Box::new(MouseReport {
rel_x: report.movement_x.unwrap() as i32,
rel_y: report.movement_y.unwrap() as i32,
rel_hscroll: report.scroll_h.unwrap_or(0) as i32,
rel_vscroll: report.scroll_v.unwrap_or(0) as i32,
pressed_buttons: match report.pressed_buttons {
Some(buttons) => {
get_u32_from_buttons(&HashSet::from_iter(buttons.into_iter()))
}
None => 0,
},
})),
stylus: None,
touchscreen: None,
sensor: None,
trace_id: 0,
})
.map_err(Into::into)
}
async fn flush(self: Box<Self>) -> Result<(), Error> {
Ok(())
}
}
impl FakeInputDevice {
fn new(fidl_proxy: FidlInputDeviceProxy) -> Self {
Self { fidl_proxy }
}
}
/// Transforms an `IntoIterator<Item = Result<InlineInputReport, _>>` into a
/// `Vec<Result</* $field-specific-type */, _>>`, by projecting `$field` out of the
/// `InlineInputReport`s.
macro_rules! project {
( $events:expr, $field:ident ) => {
$events
.into_iter()
.map(|result| result.map(|report| report.$field))
.collect::<Vec<_>>()
};
}
#[fasync::run_singlethreaded(test)]
async fn media_event_report() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
media_button_event(
vec![
MediaButton::VolumeUp,
MediaButton::MicMute,
MediaButton::Pause,
MediaButton::CameraDisable,
],
&mut fake_event_listener,
)
.await?;
assert_eq!(
project!(fake_event_listener.get_events().await, media_buttons),
[Ok(Some(MediaButtonsReport {
volume_up: true,
volume_down: false,
mic_mute: true,
reset: false,
pause: true,
camera_disable: true,
}))]
);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn keyboard_event_report() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
keyboard_event(40, Duration::from_millis(0), &mut fake_event_listener).await?;
assert_eq!(
project!(fake_event_listener.get_events().await, keyboard),
[
Ok(Some(KeyboardReport { pressed_keys: vec![40] })),
Ok(Some(KeyboardReport { pressed_keys: vec![] }))
]
);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn dispatch_key_events() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
// Configures a two-key chord:
// A: _/^^^^^\___
// B: __/^^^\____
dispatch_key_events_async(
&vec![
TimedKeyEvent::new(
input::Key::A,
input3::KeyEventType::Pressed,
Duration::from_millis(10),
),
TimedKeyEvent::new(
input::Key::B,
input3::KeyEventType::Pressed,
Duration::from_millis(20),
),
TimedKeyEvent::new(
input::Key::B,
input3::KeyEventType::Released,
Duration::from_millis(50),
),
TimedKeyEvent::new(
input::Key::A,
input3::KeyEventType::Released,
Duration::from_millis(60),
),
],
&mut fake_event_listener,
)
.await?;
assert_eq!(
project!(fake_event_listener.get_events().await, keyboard),
[
Ok(Some(KeyboardReport { pressed_keys: vec![input::Key::A.into_primitive()] })),
Ok(Some(KeyboardReport {
pressed_keys: vec![
input::Key::A.into_primitive(),
input::Key::B.into_primitive()
]
})),
Ok(Some(KeyboardReport { pressed_keys: vec![input::Key::A.into_primitive()] })),
Ok(Some(KeyboardReport { pressed_keys: vec![] }))
]
);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn dispatch_key_events_in_wrong_sequence() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
// Configures a two-key chord in the wrong temporal order.
let result = dispatch_key_events_async(
&vec![
TimedKeyEvent::new(
input::Key::A,
input3::KeyEventType::Pressed,
Duration::from_millis(20),
),
TimedKeyEvent::new(
input::Key::B,
input3::KeyEventType::Pressed,
Duration::from_millis(10),
),
],
&mut fake_event_listener,
)
.await;
match result {
Err(_) => Ok(()),
Ok(_) => Err(anyhow::anyhow!("expected error but got Ok")),
}
}
#[fasync::run_singlethreaded(test)]
async fn dispatch_key_events_with_same_timestamp() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
// Configures a two-key chord in the wrong temporal order.
let result = dispatch_key_events_async(
&vec![
TimedKeyEvent::new(
input::Key::A,
input3::KeyEventType::Pressed,
Duration::from_millis(20),
),
TimedKeyEvent::new(
input::Key::B,
input3::KeyEventType::Pressed,
Duration::from_millis(20),
),
],
&mut fake_event_listener,
)
.await;
match result {
Err(_) => Ok(()),
Ok(_) => Err(anyhow::anyhow!("expected error but got Ok")),
}
}
#[fasync::run_singlethreaded(test)]
async fn text_event_report() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
text("A".to_string(), Duration::from_millis(0), &mut fake_event_listener).await?;
assert_eq!(
project!(fake_event_listener.get_events().await, keyboard),
[
Ok(Some(KeyboardReport { pressed_keys: vec![225] })),
Ok(Some(KeyboardReport { pressed_keys: vec![4, 225] })),
Ok(Some(KeyboardReport { pressed_keys: vec![] })),
]
);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn multi_finger_tap_event_report() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
let fingers = vec![
Touch { finger_id: 1, x: 0, y: 0, width: 0, height: 0 },
Touch { finger_id: 2, x: 20, y: 20, width: 0, height: 0 },
Touch { finger_id: 3, x: 40, y: 40, width: 0, height: 0 },
Touch { finger_id: 4, x: 60, y: 60, width: 0, height: 0 },
];
multi_finger_tap_event(
fingers,
1000,
1000,
1,
Duration::from_millis(0),
&mut fake_event_listener,
)
.await?;
assert_eq!(
project!(fake_event_listener.get_events().await, touchscreen),
[
Ok(Some(TouchscreenReport {
touches: vec![
Touch { finger_id: 1, x: 0, y: 0, width: 0, height: 0 },
Touch { finger_id: 2, x: 20, y: 20, width: 0, height: 0 },
Touch { finger_id: 3, x: 40, y: 40, width: 0, height: 0 },
Touch { finger_id: 4, x: 60, y: 60, width: 0, height: 0 },
],
})),
Ok(Some(TouchscreenReport { touches: vec![] })),
]
);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn tap_event_report() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
tap_event(10, 10, 1000, 1000, 1, Duration::from_millis(0), &mut fake_event_listener)
.await?;
assert_eq!(
project!(fake_event_listener.get_events().await, touchscreen),
[
Ok(Some(TouchscreenReport {
touches: vec![Touch { finger_id: 1, x: 10, y: 10, width: 0, height: 0 }]
})),
Ok(Some(TouchscreenReport { touches: vec![] })),
]
);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn swipe_event_report() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
swipe(
10,
10,
100,
100,
1000,
1000,
2,
Duration::from_millis(0),
&mut fake_event_listener,
)
.await?;
assert_eq!(
project!(fake_event_listener.get_events().await, touchscreen),
[
Ok(Some(TouchscreenReport {
touches: vec![Touch { finger_id: 1, x: 10, y: 10, width: 0, height: 0 }],
})),
Ok(Some(TouchscreenReport {
touches: vec![Touch { finger_id: 1, x: 55, y: 55, width: 0, height: 0 }],
})),
Ok(Some(TouchscreenReport {
touches: vec![Touch { finger_id: 1, x: 100, y: 100, width: 0, height: 0 }],
})),
Ok(Some(TouchscreenReport { touches: vec![] })),
]
);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn swipe_event_report_inverted() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
swipe(
100,
100,
10,
10,
1000,
1000,
2,
Duration::from_millis(0),
&mut fake_event_listener,
)
.await?;
assert_eq!(
project!(fake_event_listener.get_events().await, touchscreen),
[
Ok(Some(TouchscreenReport {
touches: vec![Touch { finger_id: 1, x: 100, y: 100, width: 0, height: 0 }],
})),
Ok(Some(TouchscreenReport {
touches: vec![Touch { finger_id: 1, x: 55, y: 55, width: 0, height: 0 }],
})),
Ok(Some(TouchscreenReport {
touches: vec![Touch { finger_id: 1, x: 10, y: 10, width: 0, height: 0 }],
})),
Ok(Some(TouchscreenReport { touches: vec![] })),
]
);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn multi_finger_swipe_event_report() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
multi_finger_swipe(
vec![(10, 10), (20, 20), (30, 30)],
vec![(100, 100), (120, 120), (150, 150)],
1000,
1000,
2,
Duration::from_millis(0),
&mut fake_event_listener,
)
.await?;
assert_eq!(
project!(fake_event_listener.get_events().await, touchscreen),
[
Ok(Some(TouchscreenReport {
touches: vec![
Touch { finger_id: 1, x: 10, y: 10, width: 0, height: 0 },
Touch { finger_id: 2, x: 20, y: 20, width: 0, height: 0 },
Touch { finger_id: 3, x: 30, y: 30, width: 0, height: 0 }
],
})),
Ok(Some(TouchscreenReport {
touches: vec![
Touch { finger_id: 1, x: 55, y: 55, width: 0, height: 0 },
Touch { finger_id: 2, x: 70, y: 70, width: 0, height: 0 },
Touch { finger_id: 3, x: 90, y: 90, width: 0, height: 0 }
],
})),
Ok(Some(TouchscreenReport {
touches: vec![
Touch { finger_id: 1, x: 100, y: 100, width: 0, height: 0 },
Touch { finger_id: 2, x: 120, y: 120, width: 0, height: 0 },
Touch { finger_id: 3, x: 150, y: 150, width: 0, height: 0 }
],
})),
Ok(Some(TouchscreenReport { touches: vec![] })),
]
);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn multi_finger_swipe_event_report_inverted() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
multi_finger_swipe(
vec![(100, 100), (120, 120), (150, 150)],
vec![(10, 10), (20, 20), (30, 30)],
1000,
1000,
2,
Duration::from_millis(0),
&mut fake_event_listener,
)
.await?;
assert_eq!(
project!(fake_event_listener.get_events().await, touchscreen),
[
Ok(Some(TouchscreenReport {
touches: vec![
Touch { finger_id: 1, x: 100, y: 100, width: 0, height: 0 },
Touch { finger_id: 2, x: 120, y: 120, width: 0, height: 0 },
Touch { finger_id: 3, x: 150, y: 150, width: 0, height: 0 }
],
})),
Ok(Some(TouchscreenReport {
touches: vec![
Touch { finger_id: 1, x: 55, y: 55, width: 0, height: 0 },
Touch { finger_id: 2, x: 70, y: 70, width: 0, height: 0 },
Touch { finger_id: 3, x: 90, y: 90, width: 0, height: 0 }
],
})),
Ok(Some(TouchscreenReport {
touches: vec![
Touch { finger_id: 1, x: 10, y: 10, width: 0, height: 0 },
Touch { finger_id: 2, x: 20, y: 20, width: 0, height: 0 },
Touch { finger_id: 3, x: 30, y: 30, width: 0, height: 0 }
],
})),
Ok(Some(TouchscreenReport { touches: vec![] })),
]
);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn multi_finger_swipe_event_zero_move_events() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
multi_finger_swipe(
vec![(10, 10), (20, 20), (30, 30)],
vec![(100, 100), (120, 120), (150, 150)],
1000,
1000,
0,
Duration::from_millis(0),
&mut fake_event_listener,
)
.await?;
assert_eq!(
project!(fake_event_listener.get_events().await, touchscreen),
[
Ok(Some(TouchscreenReport {
touches: vec![
Touch { finger_id: 1, x: 10, y: 10, width: 0, height: 0 },
Touch { finger_id: 2, x: 20, y: 20, width: 0, height: 0 },
Touch { finger_id: 3, x: 30, y: 30, width: 0, height: 0 }
],
})),
Ok(Some(TouchscreenReport { touches: vec![] })),
]
);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn mouse_event_report() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
add_mouse_device(100, 100, &mut fake_event_listener).await?.mouse(
MouseInputReport {
movement_x: Some(10),
movement_y: Some(15),
..Default::default()
},
monotonic_nanos()?,
)?;
assert_eq!(
project!(fake_event_listener.get_events().await, mouse),
[Ok(Some(MouseReport {
rel_x: 10,
rel_y: 15,
pressed_buttons: 0,
rel_hscroll: 0,
rel_vscroll: 0
})),]
);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn events_use_monotonic_time() -> Result<(), Error> {
let mut fake_event_listener = FakeInputDeviceRegistry::new();
let synthesis_start_time = monotonic_nanos()?;
media_button_event(
vec![
MediaButton::VolumeUp,
MediaButton::MicMute,
MediaButton::Pause,
MediaButton::CameraDisable,
],
&mut fake_event_listener,
)
.await?;
let synthesis_end_time = monotonic_nanos()?;
let fidl_result = fake_event_listener
.get_events()
.await
.into_iter()
.nth(0)
.expect("received 0 events");
let timestamp =
fidl_result.map_err(anyhow::Error::msg).context("fidl call")?.event_time;
// Note well: neither condition is sufficient on its own, to verify that
// `synthesizer` has used the correct clock. For example:
//
// * `timestamp >= synthesis_start_time` would be true for a `UNIX_EPOCH` clock
// with the correct time, since the elapsed time from 1970-01-01T00:00:00+00:00
// to now is (much) larger than the elapsed time from boot to `synthesis_start_time`
// * `timestamp <= synthesis_end_time` would be true for a `UNIX_EPOCH` clock
// has been recently set to 0, because `synthesis_end_time` is highly unlikely to
// be near 0 (as it is monotonic from boot)
//
// By bracketing between monotonic clock reads before and after the event generation,
// this test avoids the hazards above. The test also avoids the hazard of using a
// fixed offset from the start time (which could flake on a slow builder).
assert!(
timestamp >= synthesis_start_time,
"timestamp={} should be >= start={}",
timestamp,
synthesis_start_time
);
assert!(
timestamp <= synthesis_end_time,
"timestamp={} should be <= end={}",
timestamp,
synthesis_end_time
);
Ok(())
}
}
mod device_registration {
use super::*;
use assert_matches::assert_matches;
#[derive(Debug)]
enum DeviceType {
Keyboard,
MediaButtons,
Touchscreen,
Mouse,
}
// An `impl InputDeviceRegistry` which provides access to the `DeviceType`s which have been
// registered with the `InputDeviceRegistry`.
struct FakeInputDeviceRegistry {
device_types: Vec<DeviceType>,
}
impl InputDeviceRegistry for FakeInputDeviceRegistry {
fn add_touchscreen_device(
&mut self,
_width: u32,
_height: u32,
) -> Result<Box<dyn InputDevice>, Error> {
self.add_device(DeviceType::Touchscreen)
}
fn add_keyboard_device(&mut self) -> Result<Box<dyn InputDevice>, Error> {
self.add_device(DeviceType::Keyboard)
}
fn add_media_buttons_device(&mut self) -> Result<Box<dyn InputDevice>, Error> {
self.add_device(DeviceType::MediaButtons)
}
fn add_mouse_device(
&mut self,
_width: u32,
_height: u32,
) -> Result<Box<dyn InputDevice>, Error> {
self.add_device(DeviceType::Mouse)
}
}
impl FakeInputDeviceRegistry {
fn new() -> Self {
Self { device_types: vec![] }
}
fn add_device(
&mut self,
device_type: DeviceType,
) -> Result<Box<dyn InputDevice>, Error> {
self.device_types.push(device_type);
Ok(Box::new(FakeInputDevice))
}
}
// Provides an `impl InputDevice` which always returns `Ok(())`. Useful when the
// events themselves are not important to the test.
struct FakeInputDevice;
#[async_trait(?Send)]
impl InputDevice for FakeInputDevice {
fn media_buttons(
&mut self,
_pressed_buttons: Vec<MediaButton>,
_time: u64,
) -> Result<(), Error> {
Ok(())
}
fn key_press(&mut self, _keyboard: KeyboardReport, _time: u64) -> Result<(), Error> {
Ok(())
}
fn key_press_raw(
&mut self,
_keyboard: KeyboardReport,
_time: u64,
) -> Result<(), Error> {
Ok(())
}
fn key_press_usage(&mut self, _usage: Option<u32>, _time: u64) -> Result<(), Error> {
Ok(())
}
fn tap(&mut self, _pos: Option<(u32, u32)>, _time: u64) -> Result<(), Error> {
Ok(())
}
fn multi_finger_tap(
&mut self,
_fingers: Option<Vec<Touch>>,
_time: u64,
) -> Result<(), Error> {
Ok(())
}
fn mouse(&mut self, _report: MouseInputReport, _time: u64) -> Result<(), Error> {
Ok(())
}
async fn flush(self: Box<Self>) -> Result<(), Error> {
Ok(())
}
}
#[fasync::run_until_stalled(test)]
async fn media_button_event_registers_media_buttons_device() -> Result<(), Error> {
let mut registry = FakeInputDeviceRegistry::new();
media_button_event(vec![], &mut registry).await?;
assert_matches!(registry.device_types.as_slice(), [DeviceType::MediaButtons]);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn keyboard_event_registers_keyboard() -> Result<(), Error> {
let mut registry = FakeInputDeviceRegistry::new();
keyboard_event(40, Duration::from_millis(0), &mut registry).await?;
assert_matches!(registry.device_types.as_slice(), [DeviceType::Keyboard]);
Ok(())
}
#[fasync::run_until_stalled(test)]
async fn text_event_registers_keyboard() -> Result<(), Error> {
let mut registry = FakeInputDeviceRegistry::new();
text("A".to_string(), Duration::from_millis(0), &mut registry).await?;
assert_matches!(registry.device_types.as_slice(), [DeviceType::Keyboard]);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn multi_finger_tap_event_registers_touchscreen() -> Result<(), Error> {
let mut registry = FakeInputDeviceRegistry::new();
multi_finger_tap_event(vec![], 1000, 1000, 1, Duration::from_millis(0), &mut registry)
.await?;
assert_matches!(registry.device_types.as_slice(), [DeviceType::Touchscreen]);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn tap_event_registers_touchscreen() -> Result<(), Error> {
let mut registry = FakeInputDeviceRegistry::new();
tap_event(0, 0, 1000, 1000, 1, Duration::from_millis(0), &mut registry).await?;
assert_matches!(registry.device_types.as_slice(), [DeviceType::Touchscreen]);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn swipe_registers_touchscreen() -> Result<(), Error> {
let mut registry = FakeInputDeviceRegistry::new();
swipe(0, 0, 1, 1, 1000, 1000, 1, Duration::from_millis(0), &mut registry).await?;
assert_matches!(registry.device_types.as_slice(), [DeviceType::Touchscreen]);
Ok(())
}
#[fasync::run_singlethreaded(test)]
async fn multi_finger_swipe_registers_touchscreen() -> Result<(), Error> {
let mut registry = FakeInputDeviceRegistry::new();
multi_finger_swipe(
vec![],
vec![],
1000,
1000,
1,
Duration::from_millis(0),
&mut registry,
)
.await?;
assert_matches!(registry.device_types.as_slice(), [DeviceType::Touchscreen]);
Ok(())
}
#[fasync::run_until_stalled(test)]
async fn add_mouse_device_registers_mouse_device() -> Result<(), Error> {
let mut registry = FakeInputDeviceRegistry::new();
add_mouse_device(100, 100, &mut registry).await?;
assert_matches!(registry.device_types.as_slice(), [DeviceType::Mouse]);
Ok(())
}
}
}