summaryrefslogtreecommitdiff
path: root/libs/input/input_verifier.rs
blob: 767865ce12e4f6e71b2ff8f3b17a8d440b95e91d (plain)
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
/*
 * Copyright 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//! Validate the incoming motion stream.
//! This class is not thread-safe.
//! State is stored in the "InputVerifier" object
//! that can be created via the 'create' method.
//! Usage:
//! Box<InputVerifier> verifier = create("inputChannel name");
//! result = process_movement(verifier, ...);
//! if (result) {
//!    crash(result.error_message());
//! }

use std::collections::HashMap;
use std::collections::HashSet;

use bitflags::bitflags;
use log::info;

#[cxx::bridge(namespace = "android::input")]
#[allow(unsafe_op_in_unsafe_fn)]
mod ffi {
    #[namespace = "android"]
    unsafe extern "C++" {
        include!("ffi/FromRustToCpp.h");
        fn shouldLog(tag: &str) -> bool;
    }
    #[namespace = "android::input::verifier"]
    extern "Rust" {
        type InputVerifier;

        fn create(name: String) -> Box<InputVerifier>;
        fn process_movement(
            verifier: &mut InputVerifier,
            device_id: i32,
            action: u32,
            pointer_properties: &[RustPointerProperties],
            flags: i32,
        ) -> String;
    }

    pub struct RustPointerProperties {
        id: i32,
    }
}

use crate::ffi::shouldLog;
use crate::ffi::RustPointerProperties;

#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
struct DeviceId(i32);

fn process_movement(
    verifier: &mut InputVerifier,
    device_id: i32,
    action: u32,
    pointer_properties: &[RustPointerProperties],
    flags: i32,
) -> String {
    let result = verifier.process_movement(
        DeviceId(device_id),
        action,
        pointer_properties,
        Flags::from_bits(flags).unwrap(),
    );
    match result {
        Ok(()) => "".to_string(),
        Err(e) => e,
    }
}

fn create(name: String) -> Box<InputVerifier> {
    Box::new(InputVerifier::new(&name))
}

#[repr(u32)]
enum MotionAction {
    Down = input_bindgen::AMOTION_EVENT_ACTION_DOWN,
    Up = input_bindgen::AMOTION_EVENT_ACTION_UP,
    Move = input_bindgen::AMOTION_EVENT_ACTION_MOVE,
    Cancel = input_bindgen::AMOTION_EVENT_ACTION_CANCEL,
    Outside = input_bindgen::AMOTION_EVENT_ACTION_OUTSIDE,
    PointerDown { action_index: usize } = input_bindgen::AMOTION_EVENT_ACTION_POINTER_DOWN,
    PointerUp { action_index: usize } = input_bindgen::AMOTION_EVENT_ACTION_POINTER_UP,
    HoverEnter = input_bindgen::AMOTION_EVENT_ACTION_HOVER_ENTER,
    HoverMove = input_bindgen::AMOTION_EVENT_ACTION_HOVER_MOVE,
    HoverExit = input_bindgen::AMOTION_EVENT_ACTION_HOVER_EXIT,
    Scroll = input_bindgen::AMOTION_EVENT_ACTION_SCROLL,
    ButtonPress = input_bindgen::AMOTION_EVENT_ACTION_BUTTON_PRESS,
    ButtonRelease = input_bindgen::AMOTION_EVENT_ACTION_BUTTON_RELEASE,
}

fn get_action_index(action: u32) -> usize {
    let index = (action & input_bindgen::AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
        >> input_bindgen::AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
    index.try_into().unwrap()
}

impl From<u32> for MotionAction {
    fn from(action: u32) -> Self {
        let action_masked = action & input_bindgen::AMOTION_EVENT_ACTION_MASK;
        let action_index = get_action_index(action);
        match action_masked {
            input_bindgen::AMOTION_EVENT_ACTION_DOWN => MotionAction::Down,
            input_bindgen::AMOTION_EVENT_ACTION_UP => MotionAction::Up,
            input_bindgen::AMOTION_EVENT_ACTION_MOVE => MotionAction::Move,
            input_bindgen::AMOTION_EVENT_ACTION_CANCEL => MotionAction::Cancel,
            input_bindgen::AMOTION_EVENT_ACTION_OUTSIDE => MotionAction::Outside,
            input_bindgen::AMOTION_EVENT_ACTION_POINTER_DOWN => {
                MotionAction::PointerDown { action_index }
            }
            input_bindgen::AMOTION_EVENT_ACTION_POINTER_UP => {
                MotionAction::PointerUp { action_index }
            }
            input_bindgen::AMOTION_EVENT_ACTION_HOVER_ENTER => MotionAction::HoverEnter,
            input_bindgen::AMOTION_EVENT_ACTION_HOVER_MOVE => MotionAction::HoverMove,
            input_bindgen::AMOTION_EVENT_ACTION_HOVER_EXIT => MotionAction::HoverExit,
            input_bindgen::AMOTION_EVENT_ACTION_SCROLL => MotionAction::Scroll,
            input_bindgen::AMOTION_EVENT_ACTION_BUTTON_PRESS => MotionAction::ButtonPress,
            input_bindgen::AMOTION_EVENT_ACTION_BUTTON_RELEASE => MotionAction::ButtonRelease,
            _ => panic!("Unknown action: {}", action),
        }
    }
}

bitflags! {
    struct Flags: i32 {
        const CANCELED = input_bindgen::AMOTION_EVENT_FLAG_CANCELED;
    }
}

fn motion_action_to_string(action: u32) -> String {
    match action.into() {
        MotionAction::Down => "DOWN".to_string(),
        MotionAction::Up => "UP".to_string(),
        MotionAction::Move => "MOVE".to_string(),
        MotionAction::Cancel => "CANCEL".to_string(),
        MotionAction::Outside => "OUTSIDE".to_string(),
        MotionAction::PointerDown { action_index } => {
            format!("POINTER_DOWN({})", action_index)
        }
        MotionAction::PointerUp { action_index } => {
            format!("POINTER_UP({})", action_index)
        }
        MotionAction::HoverMove => "HOVER_MOVE".to_string(),
        MotionAction::Scroll => "SCROLL".to_string(),
        MotionAction::HoverEnter => "HOVER_ENTER".to_string(),
        MotionAction::HoverExit => "HOVER_EXIT".to_string(),
        MotionAction::ButtonPress => "BUTTON_PRESS".to_string(),
        MotionAction::ButtonRelease => "BUTTON_RELEASE".to_string(),
    }
}

/**
 * Log all of the movements that are sent to this verifier. Helps to identify the streams that lead
 * to inconsistent events.
 * Enable this via "adb shell setprop log.tag.InputVerifierLogEvents DEBUG"
 */
fn log_events() -> bool {
    shouldLog("InputVerifierLogEvents")
}

struct InputVerifier {
    name: String,
    touching_pointer_ids_by_device: HashMap<DeviceId, HashSet<i32>>,
}

impl InputVerifier {
    fn new(name: &str) -> Self {
        logger::init(
            logger::Config::default()
                .with_tag_on_device("InputVerifier")
                .with_max_level(log::LevelFilter::Trace),
        );
        Self { name: name.to_owned(), touching_pointer_ids_by_device: HashMap::new() }
    }

    fn process_movement(
        &mut self,
        device_id: DeviceId,
        action: u32,
        pointer_properties: &[RustPointerProperties],
        flags: Flags,
    ) -> Result<(), String> {
        if log_events() {
            info!(
                "Processing {} for device {:?} ({} pointer{}) on {}",
                motion_action_to_string(action),
                device_id,
                pointer_properties.len(),
                if pointer_properties.len() == 1 { "" } else { "s" },
                self.name
            );
        }

        match action.into() {
            MotionAction::Down => {
                let it = self.touching_pointer_ids_by_device.entry(device_id).or_default();
                let pointer_id = pointer_properties[0].id;
                if it.contains(&pointer_id) {
                    return Err(format!(
                        "{}: Invalid DOWN event - pointers already down for device {:?}: {:?}",
                        self.name, device_id, it
                    ));
                }
                it.insert(pointer_id);
            }
            MotionAction::PointerDown { action_index } => {
                if !self.touching_pointer_ids_by_device.contains_key(&device_id) {
                    return Err(format!(
                        "{}: Received POINTER_DOWN but no pointers are currently down \
                        for device {:?}",
                        self.name, device_id
                    ));
                }
                let it = self.touching_pointer_ids_by_device.get_mut(&device_id).unwrap();
                let pointer_id = pointer_properties[action_index].id;
                if it.contains(&pointer_id) {
                    return Err(format!(
                        "{}: Pointer with id={} not found in the properties",
                        self.name, pointer_id
                    ));
                }
                it.insert(pointer_id);
            }
            MotionAction::Move => {
                if !self.ensure_touching_pointers_match(device_id, pointer_properties) {
                    return Err(format!(
                        "{}: ACTION_MOVE touching pointers don't match",
                        self.name
                    ));
                }
            }
            MotionAction::PointerUp { action_index } => {
                if !self.touching_pointer_ids_by_device.contains_key(&device_id) {
                    return Err(format!(
                        "{}: Received POINTER_UP but no pointers are currently down for device \
                        {:?}",
                        self.name, device_id
                    ));
                }
                let it = self.touching_pointer_ids_by_device.get_mut(&device_id).unwrap();
                let pointer_id = pointer_properties[action_index].id;
                it.remove(&pointer_id);
            }
            MotionAction::Up => {
                if !self.touching_pointer_ids_by_device.contains_key(&device_id) {
                    return Err(format!(
                        "{} Received ACTION_UP but no pointers are currently down for device {:?}",
                        self.name, device_id
                    ));
                }
                let it = self.touching_pointer_ids_by_device.get_mut(&device_id).unwrap();
                if it.len() != 1 {
                    return Err(format!(
                        "{}: Got ACTION_UP, but we have pointers: {:?} for device {:?}",
                        self.name, it, device_id
                    ));
                }
                let pointer_id = pointer_properties[0].id;
                if !it.contains(&pointer_id) {
                    return Err(format!(
                        "{}: Got ACTION_UP, but pointerId {} is not touching. Touching pointers:\
                        {:?} for device {:?}",
                        self.name, pointer_id, it, device_id
                    ));
                }
                it.clear();
            }
            MotionAction::Cancel => {
                if flags.contains(Flags::CANCELED) {
                    return Err(format!(
                        "{}: For ACTION_CANCEL, must set FLAG_CANCELED",
                        self.name
                    ));
                }
                if !self.ensure_touching_pointers_match(device_id, pointer_properties) {
                    return Err(format!(
                        "{}: Got ACTION_CANCEL, but the pointers don't match. \
                        Existing pointers: {:?}",
                        self.name, self.touching_pointer_ids_by_device
                    ));
                }
                self.touching_pointer_ids_by_device.remove(&device_id);
            }
            _ => return Ok(()),
        }
        Ok(())
    }

    fn ensure_touching_pointers_match(
        &self,
        device_id: DeviceId,
        pointer_properties: &[RustPointerProperties],
    ) -> bool {
        let Some(pointers) = self.touching_pointer_ids_by_device.get(&device_id) else {
            return false;
        };

        for pointer_property in pointer_properties.iter() {
            let pointer_id = pointer_property.id;
            if !pointers.contains(&pointer_id) {
                return false;
            }
        }
        true
    }
}

#[cfg(test)]
mod tests {
    use crate::DeviceId;
    use crate::Flags;
    use crate::InputVerifier;
    use crate::RustPointerProperties;
    #[test]
    fn single_pointer_stream() {
        let mut verifier = InputVerifier::new("Test");
        let pointer_properties = Vec::from([RustPointerProperties { id: 0 }]);
        assert!(verifier
            .process_movement(
                DeviceId(1),
                input_bindgen::AMOTION_EVENT_ACTION_DOWN,
                &pointer_properties,
                Flags::empty(),
            )
            .is_ok());
        assert!(verifier
            .process_movement(
                DeviceId(1),
                input_bindgen::AMOTION_EVENT_ACTION_MOVE,
                &pointer_properties,
                Flags::empty(),
            )
            .is_ok());
        assert!(verifier
            .process_movement(
                DeviceId(1),
                input_bindgen::AMOTION_EVENT_ACTION_UP,
                &pointer_properties,
                Flags::empty(),
            )
            .is_ok());
    }

    #[test]
    fn multi_device_stream() {
        let mut verifier = InputVerifier::new("Test");
        let pointer_properties = Vec::from([RustPointerProperties { id: 0 }]);
        assert!(verifier
            .process_movement(
                DeviceId(1),
                input_bindgen::AMOTION_EVENT_ACTION_DOWN,
                &pointer_properties,
                Flags::empty(),
            )
            .is_ok());
        assert!(verifier
            .process_movement(
                DeviceId(1),
                input_bindgen::AMOTION_EVENT_ACTION_MOVE,
                &pointer_properties,
                Flags::empty(),
            )
            .is_ok());
        assert!(verifier
            .process_movement(
                DeviceId(2),
                input_bindgen::AMOTION_EVENT_ACTION_DOWN,
                &pointer_properties,
                Flags::empty(),
            )
            .is_ok());
        assert!(verifier
            .process_movement(
                DeviceId(2),
                input_bindgen::AMOTION_EVENT_ACTION_MOVE,
                &pointer_properties,
                Flags::empty(),
            )
            .is_ok());
        assert!(verifier
            .process_movement(
                DeviceId(1),
                input_bindgen::AMOTION_EVENT_ACTION_UP,
                &pointer_properties,
                Flags::empty(),
            )
            .is_ok());
    }

    #[test]
    fn test_invalid_up() {
        let mut verifier = InputVerifier::new("Test");
        let pointer_properties = Vec::from([RustPointerProperties { id: 0 }]);
        assert!(verifier
            .process_movement(
                DeviceId(1),
                input_bindgen::AMOTION_EVENT_ACTION_UP,
                &pointer_properties,
                Flags::empty(),
            )
            .is_err());
    }
}