• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <cinttypes>
18 #include <memory>
19 #include <optional>
20 
21 #include <CursorInputMapper.h>
22 #include <InputDevice.h>
23 #include <InputMapper.h>
24 #include <InputReader.h>
25 #include <InputReaderBase.h>
26 #include <InputReaderFactory.h>
27 #include <JoystickInputMapper.h>
28 #include <KeyboardInputMapper.h>
29 #include <MultiTouchInputMapper.h>
30 #include <PeripheralController.h>
31 #include <SensorInputMapper.h>
32 #include <SingleTouchInputMapper.h>
33 #include <SwitchInputMapper.h>
34 #include <TestInputListener.h>
35 #include <TestInputListenerMatchers.h>
36 #include <TouchInputMapper.h>
37 #include <UinputDevice.h>
38 #include <VibratorInputMapper.h>
39 #include <android-base/thread_annotations.h>
40 #include <ftl/enum.h>
41 #include <gtest/gtest.h>
42 #include <gui/constants.h>
43 #include <ui/Rotation.h>
44 
45 #include <thread>
46 #include "FakeEventHub.h"
47 #include "FakeInputReaderPolicy.h"
48 #include "FakePointerController.h"
49 #include "InputMapperTest.h"
50 #include "InstrumentedInputReader.h"
51 #include "TestConstants.h"
52 #include "input/DisplayViewport.h"
53 #include "input/Input.h"
54 
55 namespace android {
56 
57 using namespace ftl::flag_operators;
58 using testing::AllOf;
59 using std::chrono_literals::operator""ms;
60 
61 // Arbitrary display properties.
62 static constexpr int32_t DISPLAY_ID = 0;
63 static const std::string DISPLAY_UNIQUE_ID = "local:1";
64 static constexpr int32_t SECONDARY_DISPLAY_ID = DISPLAY_ID + 1;
65 static const std::string SECONDARY_DISPLAY_UNIQUE_ID = "local:2";
66 static constexpr int32_t DISPLAY_WIDTH = 480;
67 static constexpr int32_t DISPLAY_HEIGHT = 800;
68 static constexpr int32_t VIRTUAL_DISPLAY_ID = 1;
69 static constexpr int32_t VIRTUAL_DISPLAY_WIDTH = 400;
70 static constexpr int32_t VIRTUAL_DISPLAY_HEIGHT = 500;
71 static const char* VIRTUAL_DISPLAY_UNIQUE_ID = "virtual:1";
72 static constexpr std::optional<uint8_t> NO_PORT = std::nullopt; // no physical port is specified
73 
74 static constexpr int32_t FIRST_SLOT = 0;
75 static constexpr int32_t SECOND_SLOT = 1;
76 static constexpr int32_t THIRD_SLOT = 2;
77 static constexpr int32_t INVALID_TRACKING_ID = -1;
78 static constexpr int32_t FIRST_TRACKING_ID = 0;
79 static constexpr int32_t SECOND_TRACKING_ID = 1;
80 static constexpr int32_t THIRD_TRACKING_ID = 2;
81 static constexpr int32_t LIGHT_BRIGHTNESS = 0x55000000;
82 static constexpr int32_t LIGHT_COLOR = 0x7F448866;
83 static constexpr int32_t LIGHT_PLAYER_ID = 2;
84 
85 static constexpr int32_t ACTION_POINTER_0_DOWN =
86         AMOTION_EVENT_ACTION_POINTER_DOWN | (0 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
87 static constexpr int32_t ACTION_POINTER_0_UP =
88         AMOTION_EVENT_ACTION_POINTER_UP | (0 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
89 static constexpr int32_t ACTION_POINTER_1_DOWN =
90         AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
91 static constexpr int32_t ACTION_POINTER_1_UP =
92         AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
93 
94 static constexpr uint32_t STYLUS_FUSION_SOURCE =
95         AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_BLUETOOTH_STYLUS;
96 
97 // Minimum timestamp separation between subsequent input events from a Bluetooth device.
98 static constexpr nsecs_t MIN_BLUETOOTH_TIMESTAMP_DELTA = ms2ns(4);
99 // Maximum smoothing time delta so that we don't generate events too far into the future.
100 constexpr static nsecs_t MAX_BLUETOOTH_SMOOTHING_DELTA = ms2ns(32);
101 
102 template<typename T>
min(T a,T b)103 static inline T min(T a, T b) {
104     return a < b ? a : b;
105 }
106 
avg(float x,float y)107 static inline float avg(float x, float y) {
108     return (x + y) / 2;
109 }
110 
111 // Mapping for light color name and the light color
112 const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
113                                                                   {"green", LightColor::GREEN},
114                                                                   {"blue", LightColor::BLUE}};
115 
getInverseRotation(ui::Rotation orientation)116 static ui::Rotation getInverseRotation(ui::Rotation orientation) {
117     switch (orientation) {
118         case ui::ROTATION_90:
119             return ui::ROTATION_270;
120         case ui::ROTATION_270:
121             return ui::ROTATION_90;
122         default:
123             return orientation;
124     }
125 }
126 
assertAxisResolution(MultiTouchInputMapper & mapper,int axis,float resolution)127 static void assertAxisResolution(MultiTouchInputMapper& mapper, int axis, float resolution) {
128     InputDeviceInfo info;
129     mapper.populateDeviceInfo(info);
130 
131     const InputDeviceInfo::MotionRange* motionRange =
132             info.getMotionRange(axis, AINPUT_SOURCE_TOUCHSCREEN);
133     ASSERT_NEAR(motionRange->resolution, resolution, EPSILON);
134 }
135 
assertAxisNotPresent(MultiTouchInputMapper & mapper,int axis)136 static void assertAxisNotPresent(MultiTouchInputMapper& mapper, int axis) {
137     InputDeviceInfo info;
138     mapper.populateDeviceInfo(info);
139 
140     const InputDeviceInfo::MotionRange* motionRange =
141             info.getMotionRange(axis, AINPUT_SOURCE_TOUCHSCREEN);
142     ASSERT_EQ(nullptr, motionRange);
143 }
144 
dumpReader(InputReader & reader)145 [[maybe_unused]] static void dumpReader(InputReader& reader) {
146     std::string dump;
147     reader.dump(dump);
148     std::istringstream iss(dump);
149     for (std::string line; std::getline(iss, line);) {
150         ALOGE("%s", line.c_str());
151         std::this_thread::sleep_for(std::chrono::milliseconds(1));
152     }
153 }
154 
155 // --- FakeInputMapper ---
156 
157 class FakeInputMapper : public InputMapper {
158     uint32_t mSources;
159     int32_t mKeyboardType;
160     int32_t mMetaState;
161     KeyedVector<int32_t, int32_t> mKeyCodeStates;
162     KeyedVector<int32_t, int32_t> mScanCodeStates;
163     KeyedVector<int32_t, int32_t> mSwitchStates;
164     // fake mapping which would normally come from keyCharacterMap
165     std::unordered_map<int32_t, int32_t> mKeyCodeMapping;
166     std::vector<int32_t> mSupportedKeyCodes;
167 
168     std::mutex mLock;
169     std::condition_variable mStateChangedCondition;
170     bool mConfigureWasCalled GUARDED_BY(mLock);
171     bool mResetWasCalled GUARDED_BY(mLock);
172     bool mProcessWasCalled GUARDED_BY(mLock);
173     RawEvent mLastEvent GUARDED_BY(mLock);
174 
175     std::optional<DisplayViewport> mViewport;
176 public:
FakeInputMapper(InputDeviceContext & deviceContext,const InputReaderConfiguration & readerConfig,uint32_t sources)177     FakeInputMapper(InputDeviceContext& deviceContext, const InputReaderConfiguration& readerConfig,
178                     uint32_t sources)
179           : InputMapper(deviceContext, readerConfig),
180             mSources(sources),
181             mKeyboardType(AINPUT_KEYBOARD_TYPE_NONE),
182             mMetaState(0),
183             mConfigureWasCalled(false),
184             mResetWasCalled(false),
185             mProcessWasCalled(false) {}
186 
~FakeInputMapper()187     virtual ~FakeInputMapper() {}
188 
setKeyboardType(int32_t keyboardType)189     void setKeyboardType(int32_t keyboardType) {
190         mKeyboardType = keyboardType;
191     }
192 
setMetaState(int32_t metaState)193     void setMetaState(int32_t metaState) {
194         mMetaState = metaState;
195     }
196 
assertConfigureWasCalled()197     void assertConfigureWasCalled() {
198         std::unique_lock<std::mutex> lock(mLock);
199         base::ScopedLockAssertion assumeLocked(mLock);
200         const bool configureCalled =
201                 mStateChangedCondition.wait_for(lock, WAIT_TIMEOUT, [this]() REQUIRES(mLock) {
202                     return mConfigureWasCalled;
203                 });
204         if (!configureCalled) {
205             FAIL() << "Expected configure() to have been called.";
206         }
207         mConfigureWasCalled = false;
208     }
209 
assertResetWasCalled()210     void assertResetWasCalled() {
211         std::unique_lock<std::mutex> lock(mLock);
212         base::ScopedLockAssertion assumeLocked(mLock);
213         const bool resetCalled =
214                 mStateChangedCondition.wait_for(lock, WAIT_TIMEOUT, [this]() REQUIRES(mLock) {
215                     return mResetWasCalled;
216                 });
217         if (!resetCalled) {
218             FAIL() << "Expected reset() to have been called.";
219         }
220         mResetWasCalled = false;
221     }
222 
assertProcessWasCalled(RawEvent * outLastEvent=nullptr)223     void assertProcessWasCalled(RawEvent* outLastEvent = nullptr) {
224         std::unique_lock<std::mutex> lock(mLock);
225         base::ScopedLockAssertion assumeLocked(mLock);
226         const bool processCalled =
227                 mStateChangedCondition.wait_for(lock, WAIT_TIMEOUT, [this]() REQUIRES(mLock) {
228                     return mProcessWasCalled;
229                 });
230         if (!processCalled) {
231             FAIL() << "Expected process() to have been called.";
232         }
233         if (outLastEvent) {
234             *outLastEvent = mLastEvent;
235         }
236         mProcessWasCalled = false;
237     }
238 
setKeyCodeState(int32_t keyCode,int32_t state)239     void setKeyCodeState(int32_t keyCode, int32_t state) {
240         mKeyCodeStates.replaceValueFor(keyCode, state);
241     }
242 
setScanCodeState(int32_t scanCode,int32_t state)243     void setScanCodeState(int32_t scanCode, int32_t state) {
244         mScanCodeStates.replaceValueFor(scanCode, state);
245     }
246 
setSwitchState(int32_t switchCode,int32_t state)247     void setSwitchState(int32_t switchCode, int32_t state) {
248         mSwitchStates.replaceValueFor(switchCode, state);
249     }
250 
addSupportedKeyCode(int32_t keyCode)251     void addSupportedKeyCode(int32_t keyCode) {
252         mSupportedKeyCodes.push_back(keyCode);
253     }
254 
addKeyCodeMapping(int32_t fromKeyCode,int32_t toKeyCode)255     void addKeyCodeMapping(int32_t fromKeyCode, int32_t toKeyCode) {
256         mKeyCodeMapping.insert_or_assign(fromKeyCode, toKeyCode);
257     }
258 
259 private:
getSources() const260     uint32_t getSources() const override { return mSources; }
261 
populateDeviceInfo(InputDeviceInfo & deviceInfo)262     void populateDeviceInfo(InputDeviceInfo& deviceInfo) override {
263         InputMapper::populateDeviceInfo(deviceInfo);
264 
265         if (mKeyboardType != AINPUT_KEYBOARD_TYPE_NONE) {
266             deviceInfo.setKeyboardType(mKeyboardType);
267         }
268     }
269 
reconfigure(nsecs_t,const InputReaderConfiguration & config,ConfigurationChanges changes)270     std::list<NotifyArgs> reconfigure(nsecs_t, const InputReaderConfiguration& config,
271                                       ConfigurationChanges changes) override {
272         std::scoped_lock<std::mutex> lock(mLock);
273         mConfigureWasCalled = true;
274 
275         // Find the associated viewport if exist.
276         const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
277         if (displayPort && changes.test(InputReaderConfiguration::Change::DISPLAY_INFO)) {
278             mViewport = config.getDisplayViewportByPort(*displayPort);
279         }
280 
281         mStateChangedCondition.notify_all();
282         return {};
283     }
284 
reset(nsecs_t)285     std::list<NotifyArgs> reset(nsecs_t) override {
286         std::scoped_lock<std::mutex> lock(mLock);
287         mResetWasCalled = true;
288         mStateChangedCondition.notify_all();
289         return {};
290     }
291 
process(const RawEvent * rawEvent)292     std::list<NotifyArgs> process(const RawEvent* rawEvent) override {
293         std::scoped_lock<std::mutex> lock(mLock);
294         mLastEvent = *rawEvent;
295         mProcessWasCalled = true;
296         mStateChangedCondition.notify_all();
297         return {};
298     }
299 
getKeyCodeState(uint32_t,int32_t keyCode)300     int32_t getKeyCodeState(uint32_t, int32_t keyCode) override {
301         ssize_t index = mKeyCodeStates.indexOfKey(keyCode);
302         return index >= 0 ? mKeyCodeStates.valueAt(index) : AKEY_STATE_UNKNOWN;
303     }
304 
getKeyCodeForKeyLocation(int32_t locationKeyCode) const305     int32_t getKeyCodeForKeyLocation(int32_t locationKeyCode) const override {
306         auto it = mKeyCodeMapping.find(locationKeyCode);
307         return it != mKeyCodeMapping.end() ? it->second : locationKeyCode;
308     }
309 
getScanCodeState(uint32_t,int32_t scanCode)310     int32_t getScanCodeState(uint32_t, int32_t scanCode) override {
311         ssize_t index = mScanCodeStates.indexOfKey(scanCode);
312         return index >= 0 ? mScanCodeStates.valueAt(index) : AKEY_STATE_UNKNOWN;
313     }
314 
getSwitchState(uint32_t,int32_t switchCode)315     int32_t getSwitchState(uint32_t, int32_t switchCode) override {
316         ssize_t index = mSwitchStates.indexOfKey(switchCode);
317         return index >= 0 ? mSwitchStates.valueAt(index) : AKEY_STATE_UNKNOWN;
318     }
319 
320     // Return true if the device has non-empty key layout.
markSupportedKeyCodes(uint32_t,const std::vector<int32_t> & keyCodes,uint8_t * outFlags)321     bool markSupportedKeyCodes(uint32_t, const std::vector<int32_t>& keyCodes,
322                                uint8_t* outFlags) override {
323         for (size_t i = 0; i < keyCodes.size(); i++) {
324             for (size_t j = 0; j < mSupportedKeyCodes.size(); j++) {
325                 if (keyCodes[i] == mSupportedKeyCodes[j]) {
326                     outFlags[i] = 1;
327                 }
328             }
329         }
330         bool result = mSupportedKeyCodes.size() > 0;
331         return result;
332     }
333 
getMetaState()334     virtual int32_t getMetaState() {
335         return mMetaState;
336     }
337 
fadePointer()338     virtual void fadePointer() {
339     }
340 
getAssociatedDisplay()341     virtual std::optional<int32_t> getAssociatedDisplay() {
342         if (mViewport) {
343             return std::make_optional(mViewport->displayId);
344         }
345         return std::nullopt;
346     }
347 };
348 
349 // --- InputReaderPolicyTest ---
350 class InputReaderPolicyTest : public testing::Test {
351 protected:
352     sp<FakeInputReaderPolicy> mFakePolicy;
353 
SetUp()354     void SetUp() override { mFakePolicy = sp<FakeInputReaderPolicy>::make(); }
TearDown()355     void TearDown() override { mFakePolicy.clear(); }
356 };
357 
358 /**
359  * Check that empty set of viewports is an acceptable configuration.
360  * Also try to get internal viewport two different ways - by type and by uniqueId.
361  *
362  * There will be confusion if two viewports with empty uniqueId and identical type are present.
363  * Such configuration is not currently allowed.
364  */
TEST_F(InputReaderPolicyTest,Viewports_GetCleared)365 TEST_F(InputReaderPolicyTest, Viewports_GetCleared) {
366     static const std::string uniqueId = "local:0";
367 
368     // We didn't add any viewports yet, so there shouldn't be any.
369     std::optional<DisplayViewport> internalViewport =
370             mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
371     ASSERT_FALSE(internalViewport);
372 
373     // Add an internal viewport, then clear it
374     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
375                                     /*isActive=*/true, uniqueId, NO_PORT, ViewportType::INTERNAL);
376 
377     // Check matching by uniqueId
378     internalViewport = mFakePolicy->getDisplayViewportByUniqueId(uniqueId);
379     ASSERT_TRUE(internalViewport);
380     ASSERT_EQ(ViewportType::INTERNAL, internalViewport->type);
381 
382     // Check matching by viewport type
383     internalViewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
384     ASSERT_TRUE(internalViewport);
385     ASSERT_EQ(uniqueId, internalViewport->uniqueId);
386 
387     mFakePolicy->clearViewports();
388     // Make sure nothing is found after clear
389     internalViewport = mFakePolicy->getDisplayViewportByUniqueId(uniqueId);
390     ASSERT_FALSE(internalViewport);
391     internalViewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
392     ASSERT_FALSE(internalViewport);
393 }
394 
TEST_F(InputReaderPolicyTest,Viewports_GetByType)395 TEST_F(InputReaderPolicyTest, Viewports_GetByType) {
396     const std::string internalUniqueId = "local:0";
397     const std::string externalUniqueId = "local:1";
398     const std::string virtualUniqueId1 = "virtual:2";
399     const std::string virtualUniqueId2 = "virtual:3";
400     constexpr int32_t virtualDisplayId1 = 2;
401     constexpr int32_t virtualDisplayId2 = 3;
402 
403     // Add an internal viewport
404     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
405                                     /*isActive=*/true, internalUniqueId, NO_PORT,
406                                     ViewportType::INTERNAL);
407     // Add an external viewport
408     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
409                                     /*isActive=*/true, externalUniqueId, NO_PORT,
410                                     ViewportType::EXTERNAL);
411     // Add an virtual viewport
412     mFakePolicy->addDisplayViewport(virtualDisplayId1, DISPLAY_WIDTH, DISPLAY_HEIGHT,
413                                     ui::ROTATION_0, /*isActive=*/true, virtualUniqueId1, NO_PORT,
414                                     ViewportType::VIRTUAL);
415     // Add another virtual viewport
416     mFakePolicy->addDisplayViewport(virtualDisplayId2, DISPLAY_WIDTH, DISPLAY_HEIGHT,
417                                     ui::ROTATION_0, /*isActive=*/true, virtualUniqueId2, NO_PORT,
418                                     ViewportType::VIRTUAL);
419 
420     // Check matching by type for internal
421     std::optional<DisplayViewport> internalViewport =
422             mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
423     ASSERT_TRUE(internalViewport);
424     ASSERT_EQ(internalUniqueId, internalViewport->uniqueId);
425 
426     // Check matching by type for external
427     std::optional<DisplayViewport> externalViewport =
428             mFakePolicy->getDisplayViewportByType(ViewportType::EXTERNAL);
429     ASSERT_TRUE(externalViewport);
430     ASSERT_EQ(externalUniqueId, externalViewport->uniqueId);
431 
432     // Check matching by uniqueId for virtual viewport #1
433     std::optional<DisplayViewport> virtualViewport1 =
434             mFakePolicy->getDisplayViewportByUniqueId(virtualUniqueId1);
435     ASSERT_TRUE(virtualViewport1);
436     ASSERT_EQ(ViewportType::VIRTUAL, virtualViewport1->type);
437     ASSERT_EQ(virtualUniqueId1, virtualViewport1->uniqueId);
438     ASSERT_EQ(virtualDisplayId1, virtualViewport1->displayId);
439 
440     // Check matching by uniqueId for virtual viewport #2
441     std::optional<DisplayViewport> virtualViewport2 =
442             mFakePolicy->getDisplayViewportByUniqueId(virtualUniqueId2);
443     ASSERT_TRUE(virtualViewport2);
444     ASSERT_EQ(ViewportType::VIRTUAL, virtualViewport2->type);
445     ASSERT_EQ(virtualUniqueId2, virtualViewport2->uniqueId);
446     ASSERT_EQ(virtualDisplayId2, virtualViewport2->displayId);
447 }
448 
449 
450 /**
451  * We can have 2 viewports of the same kind. We can distinguish them by uniqueId, and confirm
452  * that lookup works by checking display id.
453  * Check that 2 viewports of each kind is possible, for all existing viewport types.
454  */
TEST_F(InputReaderPolicyTest,Viewports_TwoOfSameType)455 TEST_F(InputReaderPolicyTest, Viewports_TwoOfSameType) {
456     const std::string uniqueId1 = "uniqueId1";
457     const std::string uniqueId2 = "uniqueId2";
458     constexpr int32_t displayId1 = 2;
459     constexpr int32_t displayId2 = 3;
460 
461     std::vector<ViewportType> types = {ViewportType::INTERNAL, ViewportType::EXTERNAL,
462                                        ViewportType::VIRTUAL};
463     for (const ViewportType& type : types) {
464         mFakePolicy->clearViewports();
465         // Add a viewport
466         mFakePolicy->addDisplayViewport(displayId1, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
467                                         /*isActive=*/true, uniqueId1, NO_PORT, type);
468         // Add another viewport
469         mFakePolicy->addDisplayViewport(displayId2, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
470                                         /*isActive=*/true, uniqueId2, NO_PORT, type);
471 
472         // Check that correct display viewport was returned by comparing the display IDs.
473         std::optional<DisplayViewport> viewport1 =
474                 mFakePolicy->getDisplayViewportByUniqueId(uniqueId1);
475         ASSERT_TRUE(viewport1);
476         ASSERT_EQ(displayId1, viewport1->displayId);
477         ASSERT_EQ(type, viewport1->type);
478 
479         std::optional<DisplayViewport> viewport2 =
480                 mFakePolicy->getDisplayViewportByUniqueId(uniqueId2);
481         ASSERT_TRUE(viewport2);
482         ASSERT_EQ(displayId2, viewport2->displayId);
483         ASSERT_EQ(type, viewport2->type);
484 
485         // When there are multiple viewports of the same kind, and uniqueId is not specified
486         // in the call to getDisplayViewport, then that situation is not supported.
487         // The viewports can be stored in any order, so we cannot rely on the order, since that
488         // is just implementation detail.
489         // However, we can check that it still returns *a* viewport, we just cannot assert
490         // which one specifically is returned.
491         std::optional<DisplayViewport> someViewport = mFakePolicy->getDisplayViewportByType(type);
492         ASSERT_TRUE(someViewport);
493     }
494 }
495 
496 /**
497  * When we have multiple internal displays make sure we always return the default display when
498  * querying by type.
499  */
TEST_F(InputReaderPolicyTest,Viewports_ByTypeReturnsDefaultForInternal)500 TEST_F(InputReaderPolicyTest, Viewports_ByTypeReturnsDefaultForInternal) {
501     const std::string uniqueId1 = "uniqueId1";
502     const std::string uniqueId2 = "uniqueId2";
503     constexpr int32_t nonDefaultDisplayId = 2;
504     static_assert(nonDefaultDisplayId != ADISPLAY_ID_DEFAULT,
505                   "Test display ID should not be ADISPLAY_ID_DEFAULT");
506 
507     // Add the default display first and ensure it gets returned.
508     mFakePolicy->clearViewports();
509     mFakePolicy->addDisplayViewport(ADISPLAY_ID_DEFAULT, DISPLAY_WIDTH, DISPLAY_HEIGHT,
510                                     ui::ROTATION_0, /*isActive=*/true, uniqueId1, NO_PORT,
511                                     ViewportType::INTERNAL);
512     mFakePolicy->addDisplayViewport(nonDefaultDisplayId, DISPLAY_WIDTH, DISPLAY_HEIGHT,
513                                     ui::ROTATION_0, /*isActive=*/true, uniqueId2, NO_PORT,
514                                     ViewportType::INTERNAL);
515 
516     std::optional<DisplayViewport> viewport =
517             mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
518     ASSERT_TRUE(viewport);
519     ASSERT_EQ(ADISPLAY_ID_DEFAULT, viewport->displayId);
520     ASSERT_EQ(ViewportType::INTERNAL, viewport->type);
521 
522     // Add the default display second to make sure order doesn't matter.
523     mFakePolicy->clearViewports();
524     mFakePolicy->addDisplayViewport(nonDefaultDisplayId, DISPLAY_WIDTH, DISPLAY_HEIGHT,
525                                     ui::ROTATION_0, /*isActive=*/true, uniqueId2, NO_PORT,
526                                     ViewportType::INTERNAL);
527     mFakePolicy->addDisplayViewport(ADISPLAY_ID_DEFAULT, DISPLAY_WIDTH, DISPLAY_HEIGHT,
528                                     ui::ROTATION_0, /*isActive=*/true, uniqueId1, NO_PORT,
529                                     ViewportType::INTERNAL);
530 
531     viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
532     ASSERT_TRUE(viewport);
533     ASSERT_EQ(ADISPLAY_ID_DEFAULT, viewport->displayId);
534     ASSERT_EQ(ViewportType::INTERNAL, viewport->type);
535 }
536 
537 /**
538  * Check getDisplayViewportByPort
539  */
TEST_F(InputReaderPolicyTest,Viewports_GetByPort)540 TEST_F(InputReaderPolicyTest, Viewports_GetByPort) {
541     constexpr ViewportType type = ViewportType::EXTERNAL;
542     const std::string uniqueId1 = "uniqueId1";
543     const std::string uniqueId2 = "uniqueId2";
544     constexpr int32_t displayId1 = 1;
545     constexpr int32_t displayId2 = 2;
546     const uint8_t hdmi1 = 0;
547     const uint8_t hdmi2 = 1;
548     const uint8_t hdmi3 = 2;
549 
550     mFakePolicy->clearViewports();
551     // Add a viewport that's associated with some display port that's not of interest.
552     mFakePolicy->addDisplayViewport(displayId1, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
553                                     /*isActive=*/true, uniqueId1, hdmi3, type);
554     // Add another viewport, connected to HDMI1 port
555     mFakePolicy->addDisplayViewport(displayId2, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
556                                     /*isActive=*/true, uniqueId2, hdmi1, type);
557 
558     // Check that correct display viewport was returned by comparing the display ports.
559     std::optional<DisplayViewport> hdmi1Viewport = mFakePolicy->getDisplayViewportByPort(hdmi1);
560     ASSERT_TRUE(hdmi1Viewport);
561     ASSERT_EQ(displayId2, hdmi1Viewport->displayId);
562     ASSERT_EQ(uniqueId2, hdmi1Viewport->uniqueId);
563 
564     // Check that we can still get the same viewport using the uniqueId
565     hdmi1Viewport = mFakePolicy->getDisplayViewportByUniqueId(uniqueId2);
566     ASSERT_TRUE(hdmi1Viewport);
567     ASSERT_EQ(displayId2, hdmi1Viewport->displayId);
568     ASSERT_EQ(uniqueId2, hdmi1Viewport->uniqueId);
569     ASSERT_EQ(type, hdmi1Viewport->type);
570 
571     // Check that we cannot find a port with "HDMI2", because we never added one
572     std::optional<DisplayViewport> hdmi2Viewport = mFakePolicy->getDisplayViewportByPort(hdmi2);
573     ASSERT_FALSE(hdmi2Viewport);
574 }
575 
576 // --- InputReaderTest ---
577 
578 class InputReaderTest : public testing::Test {
579 protected:
580     std::unique_ptr<TestInputListener> mFakeListener;
581     sp<FakeInputReaderPolicy> mFakePolicy;
582     std::shared_ptr<FakeEventHub> mFakeEventHub;
583     std::unique_ptr<InstrumentedInputReader> mReader;
584 
SetUp()585     void SetUp() override {
586         mFakeEventHub = std::make_unique<FakeEventHub>();
587         mFakePolicy = sp<FakeInputReaderPolicy>::make();
588         mFakeListener = std::make_unique<TestInputListener>();
589 
590         mReader = std::make_unique<InstrumentedInputReader>(mFakeEventHub, mFakePolicy,
591                                                             *mFakeListener);
592     }
593 
TearDown()594     void TearDown() override {
595         mFakeListener.reset();
596         mFakePolicy.clear();
597     }
598 
addDevice(int32_t eventHubId,const std::string & name,ftl::Flags<InputDeviceClass> classes,const PropertyMap * configuration)599     void addDevice(int32_t eventHubId, const std::string& name,
600                    ftl::Flags<InputDeviceClass> classes, const PropertyMap* configuration) {
601         mFakeEventHub->addDevice(eventHubId, name, classes);
602 
603         if (configuration) {
604             mFakeEventHub->addConfigurationMap(eventHubId, configuration);
605         }
606         mFakeEventHub->finishDeviceScan();
607         mReader->loopOnce();
608         mReader->loopOnce();
609         ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
610         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyInputDevicesChangedWasCalled());
611         ASSERT_NO_FATAL_FAILURE(mFakeEventHub->assertQueueIsEmpty());
612     }
613 
disableDevice(int32_t deviceId)614     void disableDevice(int32_t deviceId) {
615         mFakePolicy->addDisabledDevice(deviceId);
616         mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::ENABLED_STATE);
617     }
618 
enableDevice(int32_t deviceId)619     void enableDevice(int32_t deviceId) {
620         mFakePolicy->removeDisabledDevice(deviceId);
621         mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::ENABLED_STATE);
622     }
623 
addDeviceWithFakeInputMapper(int32_t deviceId,int32_t eventHubId,const std::string & name,ftl::Flags<InputDeviceClass> classes,uint32_t sources,const PropertyMap * configuration)624     FakeInputMapper& addDeviceWithFakeInputMapper(int32_t deviceId, int32_t eventHubId,
625                                                   const std::string& name,
626                                                   ftl::Flags<InputDeviceClass> classes,
627                                                   uint32_t sources,
628                                                   const PropertyMap* configuration) {
629         std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, name);
630         FakeInputMapper& mapper =
631                 device->addMapper<FakeInputMapper>(eventHubId,
632                                                    mFakePolicy->getReaderConfiguration(), sources);
633         mReader->pushNextDevice(device);
634         addDevice(eventHubId, name, classes, configuration);
635         return mapper;
636     }
637 };
638 
TEST_F(InputReaderTest,PolicyGetInputDevices)639 TEST_F(InputReaderTest, PolicyGetInputDevices) {
640     ASSERT_NO_FATAL_FAILURE(addDevice(1, "keyboard", InputDeviceClass::KEYBOARD, nullptr));
641     ASSERT_NO_FATAL_FAILURE(addDevice(2, "ignored", ftl::Flags<InputDeviceClass>(0),
642                                       nullptr)); // no classes so device will be ignored
643 
644     // Should also have received a notification describing the new input devices.
645     const std::vector<InputDeviceInfo>& inputDevices = mFakePolicy->getInputDevices();
646     ASSERT_EQ(1U, inputDevices.size());
647     ASSERT_EQ(END_RESERVED_ID + 1, inputDevices[0].getId());
648     ASSERT_STREQ("keyboard", inputDevices[0].getIdentifier().name.c_str());
649     ASSERT_EQ(AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC, inputDevices[0].getKeyboardType());
650     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, inputDevices[0].getSources());
651     ASSERT_EQ(0U, inputDevices[0].getMotionRanges().size());
652 }
653 
TEST_F(InputReaderTest,InputDeviceRecreatedOnSysfsNodeChanged)654 TEST_F(InputReaderTest, InputDeviceRecreatedOnSysfsNodeChanged) {
655     ASSERT_NO_FATAL_FAILURE(addDevice(1, "keyboard", InputDeviceClass::KEYBOARD, nullptr));
656     mFakeEventHub->setSysfsRootPath(1, "xyz");
657 
658     // Should also have received a notification describing the new input device.
659     ASSERT_EQ(1U, mFakePolicy->getInputDevices().size());
660     InputDeviceInfo inputDevice = mFakePolicy->getInputDevices()[0];
661     ASSERT_EQ(0U, inputDevice.getLights().size());
662 
663     RawLightInfo infoMonolight = {.id = 123,
664                                   .name = "mono_keyboard_backlight",
665                                   .maxBrightness = 255,
666                                   .flags = InputLightClass::BRIGHTNESS,
667                                   .path = ""};
668     mFakeEventHub->addRawLightInfo(/*rawId=*/123, std::move(infoMonolight));
669     mReader->sysfsNodeChanged("xyz");
670     mReader->loopOnce();
671 
672     // Should also have received a notification describing the new recreated input device.
673     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
674     inputDevice = mFakePolicy->getInputDevices()[0];
675     ASSERT_EQ(1U, inputDevice.getLights().size());
676 }
677 
TEST_F(InputReaderTest,GetMergedInputDevices)678 TEST_F(InputReaderTest, GetMergedInputDevices) {
679     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
680     constexpr int32_t eventHubIds[2] = {END_RESERVED_ID, END_RESERVED_ID + 1};
681     // Add two subdevices to device
682     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
683     // Must add at least one mapper or the device will be ignored!
684     device->addMapper<FakeInputMapper>(eventHubIds[0], mFakePolicy->getReaderConfiguration(),
685                                        AINPUT_SOURCE_KEYBOARD);
686     device->addMapper<FakeInputMapper>(eventHubIds[1], mFakePolicy->getReaderConfiguration(),
687                                        AINPUT_SOURCE_KEYBOARD);
688 
689     // Push same device instance for next device to be added, so they'll have same identifier.
690     mReader->pushNextDevice(device);
691     mReader->pushNextDevice(device);
692     ASSERT_NO_FATAL_FAILURE(
693             addDevice(eventHubIds[0], "fake1", InputDeviceClass::KEYBOARD, nullptr));
694     ASSERT_NO_FATAL_FAILURE(
695             addDevice(eventHubIds[1], "fake2", InputDeviceClass::KEYBOARD, nullptr));
696 
697     // Two devices will be merged to one input device as they have same identifier
698     ASSERT_EQ(1U, mFakePolicy->getInputDevices().size());
699 }
700 
TEST_F(InputReaderTest,GetMergedInputDevicesEnabled)701 TEST_F(InputReaderTest, GetMergedInputDevicesEnabled) {
702     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
703     constexpr int32_t eventHubIds[2] = {END_RESERVED_ID, END_RESERVED_ID + 1};
704     // Add two subdevices to device
705     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
706     // Must add at least one mapper or the device will be ignored!
707     device->addMapper<FakeInputMapper>(eventHubIds[0], mFakePolicy->getReaderConfiguration(),
708                                        AINPUT_SOURCE_KEYBOARD);
709     device->addMapper<FakeInputMapper>(eventHubIds[1], mFakePolicy->getReaderConfiguration(),
710                                        AINPUT_SOURCE_KEYBOARD);
711 
712     // Push same device instance for next device to be added, so they'll have same identifier.
713     mReader->pushNextDevice(device);
714     mReader->pushNextDevice(device);
715     // Sensor device is initially disabled
716     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubIds[0], "fake1",
717                                       InputDeviceClass::KEYBOARD | InputDeviceClass::SENSOR,
718                                       nullptr));
719     // Device is disabled because the only sub device is a sensor device and disabled initially.
720     ASSERT_FALSE(mFakeEventHub->isDeviceEnabled(eventHubIds[0]));
721     ASSERT_FALSE(device->isEnabled());
722     ASSERT_NO_FATAL_FAILURE(
723             addDevice(eventHubIds[1], "fake2", InputDeviceClass::KEYBOARD, nullptr));
724     // The merged device is enabled if any sub device is enabled
725     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(eventHubIds[1]));
726     ASSERT_TRUE(device->isEnabled());
727 }
728 
TEST_F(InputReaderTest,WhenEnabledChanges_SendsDeviceResetNotification)729 TEST_F(InputReaderTest, WhenEnabledChanges_SendsDeviceResetNotification) {
730     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
731     constexpr ftl::Flags<InputDeviceClass> deviceClass(InputDeviceClass::KEYBOARD);
732     constexpr int32_t eventHubId = 1;
733     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
734     // Must add at least one mapper or the device will be ignored!
735     device->addMapper<FakeInputMapper>(eventHubId, mFakePolicy->getReaderConfiguration(),
736                                        AINPUT_SOURCE_KEYBOARD);
737     mReader->pushNextDevice(device);
738     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
739 
740     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasCalled(nullptr));
741 
742     NotifyDeviceResetArgs resetArgs;
743     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
744     ASSERT_EQ(deviceId, resetArgs.deviceId);
745 
746     ASSERT_EQ(device->isEnabled(), true);
747     disableDevice(deviceId);
748     mReader->loopOnce();
749 
750     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
751     ASSERT_EQ(deviceId, resetArgs.deviceId);
752     ASSERT_EQ(device->isEnabled(), false);
753 
754     disableDevice(deviceId);
755     mReader->loopOnce();
756     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasNotCalled());
757     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasNotCalled());
758     ASSERT_EQ(device->isEnabled(), false);
759 
760     enableDevice(deviceId);
761     mReader->loopOnce();
762     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
763     ASSERT_EQ(deviceId, resetArgs.deviceId);
764     ASSERT_EQ(device->isEnabled(), true);
765 }
766 
TEST_F(InputReaderTest,GetKeyCodeState_ForwardsRequestsToMappers)767 TEST_F(InputReaderTest, GetKeyCodeState_ForwardsRequestsToMappers) {
768     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
769     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
770     constexpr int32_t eventHubId = 1;
771     FakeInputMapper& mapper =
772             addDeviceWithFakeInputMapper(deviceId, eventHubId, "fake", deviceClass,
773                                          AINPUT_SOURCE_KEYBOARD, nullptr);
774     mapper.setKeyCodeState(AKEYCODE_A, AKEY_STATE_DOWN);
775 
776     ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getKeyCodeState(0,
777             AINPUT_SOURCE_ANY, AKEYCODE_A))
778             << "Should return unknown when the device id is >= 0 but unknown.";
779 
780     ASSERT_EQ(AKEY_STATE_UNKNOWN,
781               mReader->getKeyCodeState(deviceId, AINPUT_SOURCE_TRACKBALL, AKEYCODE_A))
782             << "Should return unknown when the device id is valid but the sources are not "
783                "supported by the device.";
784 
785     ASSERT_EQ(AKEY_STATE_DOWN,
786               mReader->getKeyCodeState(deviceId, AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL,
787                                        AKEYCODE_A))
788             << "Should return value provided by mapper when device id is valid and the device "
789                "supports some of the sources.";
790 
791     ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getKeyCodeState(-1,
792             AINPUT_SOURCE_TRACKBALL, AKEYCODE_A))
793             << "Should return unknown when the device id is < 0 but the sources are not supported by any device.";
794 
795     ASSERT_EQ(AKEY_STATE_DOWN, mReader->getKeyCodeState(-1,
796             AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL, AKEYCODE_A))
797             << "Should return value provided by mapper when device id is < 0 and one of the devices supports some of the sources.";
798 }
799 
TEST_F(InputReaderTest,GetKeyCodeForKeyLocation_ForwardsRequestsToMappers)800 TEST_F(InputReaderTest, GetKeyCodeForKeyLocation_ForwardsRequestsToMappers) {
801     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
802     constexpr int32_t eventHubId = 1;
803     FakeInputMapper& mapper = addDeviceWithFakeInputMapper(deviceId, eventHubId, "keyboard",
804                                                            InputDeviceClass::KEYBOARD,
805                                                            AINPUT_SOURCE_KEYBOARD, nullptr);
806     mapper.addKeyCodeMapping(AKEYCODE_Y, AKEYCODE_Z);
807 
808     ASSERT_EQ(AKEYCODE_UNKNOWN, mReader->getKeyCodeForKeyLocation(0, AKEYCODE_Y))
809             << "Should return unknown when the device with the specified id is not found.";
810 
811     ASSERT_EQ(AKEYCODE_Z, mReader->getKeyCodeForKeyLocation(deviceId, AKEYCODE_Y))
812             << "Should return correct mapping when device id is valid and mapping exists.";
813 
814     ASSERT_EQ(AKEYCODE_A, mReader->getKeyCodeForKeyLocation(deviceId, AKEYCODE_A))
815             << "Should return the location key code when device id is valid and there's no "
816                "mapping.";
817 }
818 
TEST_F(InputReaderTest,GetKeyCodeForKeyLocation_NoKeyboardMapper)819 TEST_F(InputReaderTest, GetKeyCodeForKeyLocation_NoKeyboardMapper) {
820     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
821     constexpr int32_t eventHubId = 1;
822     FakeInputMapper& mapper = addDeviceWithFakeInputMapper(deviceId, eventHubId, "joystick",
823                                                            InputDeviceClass::JOYSTICK,
824                                                            AINPUT_SOURCE_GAMEPAD, nullptr);
825     mapper.addKeyCodeMapping(AKEYCODE_Y, AKEYCODE_Z);
826 
827     ASSERT_EQ(AKEYCODE_UNKNOWN, mReader->getKeyCodeForKeyLocation(deviceId, AKEYCODE_Y))
828             << "Should return unknown when the device id is valid but there is no keyboard mapper";
829 }
830 
TEST_F(InputReaderTest,GetScanCodeState_ForwardsRequestsToMappers)831 TEST_F(InputReaderTest, GetScanCodeState_ForwardsRequestsToMappers) {
832     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
833     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
834     constexpr int32_t eventHubId = 1;
835     FakeInputMapper& mapper =
836             addDeviceWithFakeInputMapper(deviceId, eventHubId, "fake", deviceClass,
837                                          AINPUT_SOURCE_KEYBOARD, nullptr);
838     mapper.setScanCodeState(KEY_A, AKEY_STATE_DOWN);
839 
840     ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getScanCodeState(0,
841             AINPUT_SOURCE_ANY, KEY_A))
842             << "Should return unknown when the device id is >= 0 but unknown.";
843 
844     ASSERT_EQ(AKEY_STATE_UNKNOWN,
845               mReader->getScanCodeState(deviceId, AINPUT_SOURCE_TRACKBALL, KEY_A))
846             << "Should return unknown when the device id is valid but the sources are not "
847                "supported by the device.";
848 
849     ASSERT_EQ(AKEY_STATE_DOWN,
850               mReader->getScanCodeState(deviceId, AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL,
851                                         KEY_A))
852             << "Should return value provided by mapper when device id is valid and the device "
853                "supports some of the sources.";
854 
855     ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getScanCodeState(-1,
856             AINPUT_SOURCE_TRACKBALL, KEY_A))
857             << "Should return unknown when the device id is < 0 but the sources are not supported by any device.";
858 
859     ASSERT_EQ(AKEY_STATE_DOWN, mReader->getScanCodeState(-1,
860             AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL, KEY_A))
861             << "Should return value provided by mapper when device id is < 0 and one of the devices supports some of the sources.";
862 }
863 
TEST_F(InputReaderTest,GetSwitchState_ForwardsRequestsToMappers)864 TEST_F(InputReaderTest, GetSwitchState_ForwardsRequestsToMappers) {
865     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
866     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
867     constexpr int32_t eventHubId = 1;
868     FakeInputMapper& mapper =
869             addDeviceWithFakeInputMapper(deviceId, eventHubId, "fake", deviceClass,
870                                          AINPUT_SOURCE_KEYBOARD, nullptr);
871     mapper.setSwitchState(SW_LID, AKEY_STATE_DOWN);
872 
873     ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getSwitchState(0,
874             AINPUT_SOURCE_ANY, SW_LID))
875             << "Should return unknown when the device id is >= 0 but unknown.";
876 
877     ASSERT_EQ(AKEY_STATE_UNKNOWN,
878               mReader->getSwitchState(deviceId, AINPUT_SOURCE_TRACKBALL, SW_LID))
879             << "Should return unknown when the device id is valid but the sources are not "
880                "supported by the device.";
881 
882     ASSERT_EQ(AKEY_STATE_DOWN,
883               mReader->getSwitchState(deviceId, AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL,
884                                       SW_LID))
885             << "Should return value provided by mapper when device id is valid and the device "
886                "supports some of the sources.";
887 
888     ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getSwitchState(-1,
889             AINPUT_SOURCE_TRACKBALL, SW_LID))
890             << "Should return unknown when the device id is < 0 but the sources are not supported by any device.";
891 
892     ASSERT_EQ(AKEY_STATE_DOWN, mReader->getSwitchState(-1,
893             AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL, SW_LID))
894             << "Should return value provided by mapper when device id is < 0 and one of the devices supports some of the sources.";
895 }
896 
TEST_F(InputReaderTest,MarkSupportedKeyCodes_ForwardsRequestsToMappers)897 TEST_F(InputReaderTest, MarkSupportedKeyCodes_ForwardsRequestsToMappers) {
898     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
899     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
900     constexpr int32_t eventHubId = 1;
901     FakeInputMapper& mapper =
902             addDeviceWithFakeInputMapper(deviceId, eventHubId, "fake", deviceClass,
903                                          AINPUT_SOURCE_KEYBOARD, nullptr);
904 
905     mapper.addSupportedKeyCode(AKEYCODE_A);
906     mapper.addSupportedKeyCode(AKEYCODE_B);
907 
908     const std::vector<int32_t> keyCodes{AKEYCODE_A, AKEYCODE_B, AKEYCODE_1, AKEYCODE_2};
909     uint8_t flags[4] = { 0, 0, 0, 1 };
910 
911     ASSERT_FALSE(mReader->hasKeys(0, AINPUT_SOURCE_ANY, keyCodes, flags))
912             << "Should return false when device id is >= 0 but unknown.";
913     ASSERT_TRUE(!flags[0] && !flags[1] && !flags[2] && !flags[3]);
914 
915     flags[3] = 1;
916     ASSERT_FALSE(mReader->hasKeys(deviceId, AINPUT_SOURCE_TRACKBALL, keyCodes, flags))
917             << "Should return false when device id is valid but the sources are not supported by "
918                "the device.";
919     ASSERT_TRUE(!flags[0] && !flags[1] && !flags[2] && !flags[3]);
920 
921     flags[3] = 1;
922     ASSERT_TRUE(mReader->hasKeys(deviceId, AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL,
923                                  keyCodes, flags))
924             << "Should return value provided by mapper when device id is valid and the device "
925                "supports some of the sources.";
926     ASSERT_TRUE(flags[0] && flags[1] && !flags[2] && !flags[3]);
927 
928     flags[3] = 1;
929     ASSERT_FALSE(mReader->hasKeys(-1, AINPUT_SOURCE_TRACKBALL, keyCodes, flags))
930             << "Should return false when the device id is < 0 but the sources are not supported by "
931                "any device.";
932     ASSERT_TRUE(!flags[0] && !flags[1] && !flags[2] && !flags[3]);
933 
934     flags[3] = 1;
935     ASSERT_TRUE(
936             mReader->hasKeys(-1, AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL, keyCodes, flags))
937             << "Should return value provided by mapper when device id is < 0 and one of the "
938                "devices supports some of the sources.";
939     ASSERT_TRUE(flags[0] && flags[1] && !flags[2] && !flags[3]);
940 }
941 
TEST_F(InputReaderTest,LoopOnce_WhenDeviceScanFinished_SendsConfigurationChanged)942 TEST_F(InputReaderTest, LoopOnce_WhenDeviceScanFinished_SendsConfigurationChanged) {
943     constexpr int32_t eventHubId = 1;
944     addDevice(eventHubId, "ignored", InputDeviceClass::KEYBOARD, nullptr);
945 
946     NotifyConfigurationChangedArgs args;
947 
948     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasCalled(&args));
949     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
950 }
951 
TEST_F(InputReaderTest,LoopOnce_ForwardsRawEventsToMappers)952 TEST_F(InputReaderTest, LoopOnce_ForwardsRawEventsToMappers) {
953     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
954     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
955     constexpr nsecs_t when = 0;
956     constexpr int32_t eventHubId = 1;
957     constexpr nsecs_t readTime = 2;
958     FakeInputMapper& mapper =
959             addDeviceWithFakeInputMapper(deviceId, eventHubId, "fake", deviceClass,
960                                          AINPUT_SOURCE_KEYBOARD, nullptr);
961 
962     mFakeEventHub->enqueueEvent(when, readTime, eventHubId, EV_KEY, KEY_A, 1);
963     mReader->loopOnce();
964     ASSERT_NO_FATAL_FAILURE(mFakeEventHub->assertQueueIsEmpty());
965 
966     RawEvent event;
967     ASSERT_NO_FATAL_FAILURE(mapper.assertProcessWasCalled(&event));
968     ASSERT_EQ(when, event.when);
969     ASSERT_EQ(readTime, event.readTime);
970     ASSERT_EQ(eventHubId, event.deviceId);
971     ASSERT_EQ(EV_KEY, event.type);
972     ASSERT_EQ(KEY_A, event.code);
973     ASSERT_EQ(1, event.value);
974 }
975 
TEST_F(InputReaderTest,DeviceReset_RandomId)976 TEST_F(InputReaderTest, DeviceReset_RandomId) {
977     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
978     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
979     constexpr int32_t eventHubId = 1;
980     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
981     // Must add at least one mapper or the device will be ignored!
982     device->addMapper<FakeInputMapper>(eventHubId, mFakePolicy->getReaderConfiguration(),
983                                        AINPUT_SOURCE_KEYBOARD);
984     mReader->pushNextDevice(device);
985     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
986 
987     NotifyDeviceResetArgs resetArgs;
988     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
989     int32_t prevId = resetArgs.id;
990 
991     disableDevice(deviceId);
992     mReader->loopOnce();
993     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
994     ASSERT_NE(prevId, resetArgs.id);
995     prevId = resetArgs.id;
996 
997     enableDevice(deviceId);
998     mReader->loopOnce();
999     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1000     ASSERT_NE(prevId, resetArgs.id);
1001     prevId = resetArgs.id;
1002 
1003     disableDevice(deviceId);
1004     mReader->loopOnce();
1005     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1006     ASSERT_NE(prevId, resetArgs.id);
1007     prevId = resetArgs.id;
1008 }
1009 
TEST_F(InputReaderTest,DeviceReset_GenerateIdWithInputReaderSource)1010 TEST_F(InputReaderTest, DeviceReset_GenerateIdWithInputReaderSource) {
1011     constexpr int32_t deviceId = 1;
1012     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
1013     constexpr int32_t eventHubId = 1;
1014     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
1015     // Must add at least one mapper or the device will be ignored!
1016     device->addMapper<FakeInputMapper>(eventHubId, mFakePolicy->getReaderConfiguration(),
1017                                        AINPUT_SOURCE_KEYBOARD);
1018     mReader->pushNextDevice(device);
1019     ASSERT_NO_FATAL_FAILURE(addDevice(deviceId, "fake", deviceClass, nullptr));
1020 
1021     NotifyDeviceResetArgs resetArgs;
1022     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1023     ASSERT_EQ(IdGenerator::Source::INPUT_READER, IdGenerator::getSource(resetArgs.id));
1024 }
1025 
TEST_F(InputReaderTest,Device_CanDispatchToDisplay)1026 TEST_F(InputReaderTest, Device_CanDispatchToDisplay) {
1027     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1028     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
1029     constexpr int32_t eventHubId = 1;
1030     const char* DEVICE_LOCATION = "USB1";
1031     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
1032     FakeInputMapper& mapper =
1033             device->addMapper<FakeInputMapper>(eventHubId, mFakePolicy->getReaderConfiguration(),
1034                                                AINPUT_SOURCE_TOUCHSCREEN);
1035     mReader->pushNextDevice(device);
1036 
1037     const uint8_t hdmi1 = 1;
1038 
1039     // Associated touch screen with second display.
1040     mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi1);
1041 
1042     // Add default and second display.
1043     mFakePolicy->clearViewports();
1044     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
1045                                     /*isActive=*/true, "local:0", NO_PORT, ViewportType::INTERNAL);
1046     mFakePolicy->addDisplayViewport(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
1047                                     ui::ROTATION_0, /*isActive=*/true, "local:1", hdmi1,
1048                                     ViewportType::EXTERNAL);
1049     mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::DISPLAY_INFO);
1050     mReader->loopOnce();
1051 
1052     // Add the device, and make sure all of the callbacks are triggered.
1053     // The device is added after the input port associations are processed since
1054     // we do not yet support dynamic device-to-display associations.
1055     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1056     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasCalled());
1057     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
1058     ASSERT_NO_FATAL_FAILURE(mapper.assertConfigureWasCalled());
1059 
1060     // Device should only dispatch to the specified display.
1061     ASSERT_EQ(deviceId, device->getId());
1062     ASSERT_FALSE(mReader->canDispatchToDisplay(deviceId, DISPLAY_ID));
1063     ASSERT_TRUE(mReader->canDispatchToDisplay(deviceId, SECONDARY_DISPLAY_ID));
1064 
1065     // Can't dispatch event from a disabled device.
1066     disableDevice(deviceId);
1067     mReader->loopOnce();
1068     ASSERT_FALSE(mReader->canDispatchToDisplay(deviceId, SECONDARY_DISPLAY_ID));
1069 }
1070 
TEST_F(InputReaderTest,WhenEnabledChanges_AllSubdevicesAreUpdated)1071 TEST_F(InputReaderTest, WhenEnabledChanges_AllSubdevicesAreUpdated) {
1072     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1073     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
1074     constexpr int32_t eventHubIds[2] = {END_RESERVED_ID, END_RESERVED_ID + 1};
1075     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
1076     // Must add at least one mapper or the device will be ignored!
1077     device->addMapper<FakeInputMapper>(eventHubIds[0], mFakePolicy->getReaderConfiguration(),
1078                                        AINPUT_SOURCE_KEYBOARD);
1079     device->addMapper<FakeInputMapper>(eventHubIds[1], mFakePolicy->getReaderConfiguration(),
1080                                        AINPUT_SOURCE_KEYBOARD);
1081     mReader->pushNextDevice(device);
1082     mReader->pushNextDevice(device);
1083     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubIds[0], "fake1", deviceClass, nullptr));
1084     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubIds[1], "fake2", deviceClass, nullptr));
1085 
1086     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasCalled(nullptr));
1087 
1088     NotifyDeviceResetArgs resetArgs;
1089     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1090     ASSERT_EQ(deviceId, resetArgs.deviceId);
1091     ASSERT_TRUE(device->isEnabled());
1092     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(eventHubIds[0]));
1093     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(eventHubIds[1]));
1094 
1095     disableDevice(deviceId);
1096     mReader->loopOnce();
1097 
1098     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1099     ASSERT_EQ(deviceId, resetArgs.deviceId);
1100     ASSERT_FALSE(device->isEnabled());
1101     ASSERT_FALSE(mFakeEventHub->isDeviceEnabled(eventHubIds[0]));
1102     ASSERT_FALSE(mFakeEventHub->isDeviceEnabled(eventHubIds[1]));
1103 
1104     enableDevice(deviceId);
1105     mReader->loopOnce();
1106 
1107     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1108     ASSERT_EQ(deviceId, resetArgs.deviceId);
1109     ASSERT_TRUE(device->isEnabled());
1110     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(eventHubIds[0]));
1111     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(eventHubIds[1]));
1112 }
1113 
TEST_F(InputReaderTest,GetKeyCodeState_ForwardsRequestsToSubdeviceMappers)1114 TEST_F(InputReaderTest, GetKeyCodeState_ForwardsRequestsToSubdeviceMappers) {
1115     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1116     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
1117     constexpr int32_t eventHubIds[2] = {END_RESERVED_ID, END_RESERVED_ID + 1};
1118     // Add two subdevices to device
1119     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
1120     FakeInputMapper& mapperDevice1 =
1121             device->addMapper<FakeInputMapper>(eventHubIds[0],
1122                                                mFakePolicy->getReaderConfiguration(),
1123                                                AINPUT_SOURCE_KEYBOARD);
1124     FakeInputMapper& mapperDevice2 =
1125             device->addMapper<FakeInputMapper>(eventHubIds[1],
1126                                                mFakePolicy->getReaderConfiguration(),
1127                                                AINPUT_SOURCE_KEYBOARD);
1128     mReader->pushNextDevice(device);
1129     mReader->pushNextDevice(device);
1130     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubIds[0], "fake1", deviceClass, nullptr));
1131     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubIds[1], "fake2", deviceClass, nullptr));
1132 
1133     mapperDevice1.setKeyCodeState(AKEYCODE_A, AKEY_STATE_DOWN);
1134     mapperDevice2.setKeyCodeState(AKEYCODE_B, AKEY_STATE_DOWN);
1135 
1136     ASSERT_EQ(AKEY_STATE_DOWN,
1137               mReader->getKeyCodeState(deviceId, AINPUT_SOURCE_KEYBOARD, AKEYCODE_A));
1138     ASSERT_EQ(AKEY_STATE_DOWN,
1139               mReader->getKeyCodeState(deviceId, AINPUT_SOURCE_KEYBOARD, AKEYCODE_B));
1140     ASSERT_EQ(AKEY_STATE_UNKNOWN,
1141               mReader->getKeyCodeState(deviceId, AINPUT_SOURCE_KEYBOARD, AKEYCODE_C));
1142 }
1143 
TEST_F(InputReaderTest,ChangingPointerCaptureNotifiesInputListener)1144 TEST_F(InputReaderTest, ChangingPointerCaptureNotifiesInputListener) {
1145     NotifyPointerCaptureChangedArgs args;
1146 
1147     auto request = mFakePolicy->setPointerCapture(true);
1148     mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::POINTER_CAPTURE);
1149     mReader->loopOnce();
1150     mFakeListener->assertNotifyCaptureWasCalled(&args);
1151     ASSERT_TRUE(args.request.enable) << "Pointer Capture should be enabled.";
1152     ASSERT_EQ(args.request, request) << "Pointer Capture sequence number should match.";
1153 
1154     mFakePolicy->setPointerCapture(false);
1155     mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::POINTER_CAPTURE);
1156     mReader->loopOnce();
1157     mFakeListener->assertNotifyCaptureWasCalled(&args);
1158     ASSERT_FALSE(args.request.enable) << "Pointer Capture should be disabled.";
1159 
1160     // Verify that the Pointer Capture state is not updated when the configuration value
1161     // does not change.
1162     mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::POINTER_CAPTURE);
1163     mReader->loopOnce();
1164     mFakeListener->assertNotifyCaptureWasNotCalled();
1165 }
1166 
1167 class FakeVibratorInputMapper : public FakeInputMapper {
1168 public:
FakeVibratorInputMapper(InputDeviceContext & deviceContext,const InputReaderConfiguration & readerConfig,uint32_t sources)1169     FakeVibratorInputMapper(InputDeviceContext& deviceContext,
1170                             const InputReaderConfiguration& readerConfig, uint32_t sources)
1171           : FakeInputMapper(deviceContext, readerConfig, sources) {}
1172 
getVibratorIds()1173     std::vector<int32_t> getVibratorIds() override { return getDeviceContext().getVibratorIds(); }
1174 };
1175 
TEST_F(InputReaderTest,VibratorGetVibratorIds)1176 TEST_F(InputReaderTest, VibratorGetVibratorIds) {
1177     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1178     ftl::Flags<InputDeviceClass> deviceClass =
1179             InputDeviceClass::KEYBOARD | InputDeviceClass::VIBRATOR;
1180     constexpr int32_t eventHubId = 1;
1181     const char* DEVICE_LOCATION = "BLUETOOTH";
1182     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
1183     FakeVibratorInputMapper& mapper =
1184             device->addMapper<FakeVibratorInputMapper>(eventHubId,
1185                                                        mFakePolicy->getReaderConfiguration(),
1186                                                        AINPUT_SOURCE_KEYBOARD);
1187     mReader->pushNextDevice(device);
1188 
1189     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1190     ASSERT_NO_FATAL_FAILURE(mapper.assertConfigureWasCalled());
1191 
1192     ASSERT_EQ(mapper.getVibratorIds().size(), 2U);
1193     ASSERT_EQ(mReader->getVibratorIds(deviceId).size(), 2U);
1194 }
1195 
1196 // --- FakePeripheralController ---
1197 
1198 class FakePeripheralController : public PeripheralControllerInterface {
1199 public:
FakePeripheralController(InputDeviceContext & deviceContext)1200     FakePeripheralController(InputDeviceContext& deviceContext) : mDeviceContext(deviceContext) {}
1201 
~FakePeripheralController()1202     ~FakePeripheralController() override {}
1203 
getEventHubId() const1204     int32_t getEventHubId() const { return getDeviceContext().getEventHubId(); }
1205 
populateDeviceInfo(InputDeviceInfo * deviceInfo)1206     void populateDeviceInfo(InputDeviceInfo* deviceInfo) override {}
1207 
dump(std::string & dump)1208     void dump(std::string& dump) override {}
1209 
getBatteryCapacity(int32_t batteryId)1210     std::optional<int32_t> getBatteryCapacity(int32_t batteryId) override {
1211         return getDeviceContext().getBatteryCapacity(batteryId);
1212     }
1213 
getBatteryStatus(int32_t batteryId)1214     std::optional<int32_t> getBatteryStatus(int32_t batteryId) override {
1215         return getDeviceContext().getBatteryStatus(batteryId);
1216     }
1217 
setLightColor(int32_t lightId,int32_t color)1218     bool setLightColor(int32_t lightId, int32_t color) override {
1219         getDeviceContext().setLightBrightness(lightId, color >> 24);
1220         return true;
1221     }
1222 
getLightColor(int32_t lightId)1223     std::optional<int32_t> getLightColor(int32_t lightId) override {
1224         std::optional<int32_t> result = getDeviceContext().getLightBrightness(lightId);
1225         if (!result.has_value()) {
1226             return std::nullopt;
1227         }
1228         return result.value() << 24;
1229     }
1230 
setLightPlayerId(int32_t lightId,int32_t playerId)1231     bool setLightPlayerId(int32_t lightId, int32_t playerId) override { return true; }
1232 
getLightPlayerId(int32_t lightId)1233     std::optional<int32_t> getLightPlayerId(int32_t lightId) override { return std::nullopt; }
1234 
1235 private:
1236     InputDeviceContext& mDeviceContext;
getDeviceId()1237     inline int32_t getDeviceId() { return mDeviceContext.getId(); }
getDeviceContext()1238     inline InputDeviceContext& getDeviceContext() { return mDeviceContext; }
getDeviceContext() const1239     inline InputDeviceContext& getDeviceContext() const { return mDeviceContext; }
1240 };
1241 
TEST_F(InputReaderTest,BatteryGetCapacity)1242 TEST_F(InputReaderTest, BatteryGetCapacity) {
1243     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1244     ftl::Flags<InputDeviceClass> deviceClass =
1245             InputDeviceClass::KEYBOARD | InputDeviceClass::BATTERY;
1246     constexpr int32_t eventHubId = 1;
1247     const char* DEVICE_LOCATION = "BLUETOOTH";
1248     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
1249     FakePeripheralController& controller =
1250             device->addController<FakePeripheralController>(eventHubId);
1251     mReader->pushNextDevice(device);
1252 
1253     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1254 
1255     ASSERT_EQ(controller.getBatteryCapacity(FakeEventHub::DEFAULT_BATTERY),
1256               FakeEventHub::BATTERY_CAPACITY);
1257     ASSERT_EQ(mReader->getBatteryCapacity(deviceId), FakeEventHub::BATTERY_CAPACITY);
1258 }
1259 
TEST_F(InputReaderTest,BatteryGetStatus)1260 TEST_F(InputReaderTest, BatteryGetStatus) {
1261     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1262     ftl::Flags<InputDeviceClass> deviceClass =
1263             InputDeviceClass::KEYBOARD | InputDeviceClass::BATTERY;
1264     constexpr int32_t eventHubId = 1;
1265     const char* DEVICE_LOCATION = "BLUETOOTH";
1266     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
1267     FakePeripheralController& controller =
1268             device->addController<FakePeripheralController>(eventHubId);
1269     mReader->pushNextDevice(device);
1270 
1271     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1272 
1273     ASSERT_EQ(controller.getBatteryStatus(FakeEventHub::DEFAULT_BATTERY),
1274               FakeEventHub::BATTERY_STATUS);
1275     ASSERT_EQ(mReader->getBatteryStatus(deviceId), FakeEventHub::BATTERY_STATUS);
1276 }
1277 
TEST_F(InputReaderTest,BatteryGetDevicePath)1278 TEST_F(InputReaderTest, BatteryGetDevicePath) {
1279     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1280     ftl::Flags<InputDeviceClass> deviceClass =
1281             InputDeviceClass::KEYBOARD | InputDeviceClass::BATTERY;
1282     constexpr int32_t eventHubId = 1;
1283     const char* DEVICE_LOCATION = "BLUETOOTH";
1284     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
1285     device->addController<FakePeripheralController>(eventHubId);
1286     mReader->pushNextDevice(device);
1287 
1288     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1289 
1290     ASSERT_EQ(mReader->getBatteryDevicePath(deviceId), FakeEventHub::BATTERY_DEVPATH);
1291 }
1292 
TEST_F(InputReaderTest,LightGetColor)1293 TEST_F(InputReaderTest, LightGetColor) {
1294     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1295     ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD | InputDeviceClass::LIGHT;
1296     constexpr int32_t eventHubId = 1;
1297     const char* DEVICE_LOCATION = "BLUETOOTH";
1298     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
1299     FakePeripheralController& controller =
1300             device->addController<FakePeripheralController>(eventHubId);
1301     mReader->pushNextDevice(device);
1302     RawLightInfo info = {.id = 1,
1303                          .name = "Mono",
1304                          .maxBrightness = 255,
1305                          .flags = InputLightClass::BRIGHTNESS,
1306                          .path = ""};
1307     mFakeEventHub->addRawLightInfo(/*rawId=*/1, std::move(info));
1308     mFakeEventHub->fakeLightBrightness(/*rawId=*/1, 0x55);
1309 
1310     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1311 
1312     ASSERT_TRUE(controller.setLightColor(/*lightId=*/1, LIGHT_BRIGHTNESS));
1313     ASSERT_EQ(controller.getLightColor(/*lightId=*/1), LIGHT_BRIGHTNESS);
1314     ASSERT_TRUE(mReader->setLightColor(deviceId, /*lightId=*/1, LIGHT_BRIGHTNESS));
1315     ASSERT_EQ(mReader->getLightColor(deviceId, /*lightId=*/1), LIGHT_BRIGHTNESS);
1316 }
1317 
1318 // --- InputReaderIntegrationTest ---
1319 
1320 // These tests create and interact with the InputReader only through its interface.
1321 // The InputReader is started during SetUp(), which starts its processing in its own
1322 // thread. The tests use linux uinput to emulate input devices.
1323 // NOTE: Interacting with the physical device while these tests are running may cause
1324 // the tests to fail.
1325 class InputReaderIntegrationTest : public testing::Test {
1326 protected:
1327     std::unique_ptr<TestInputListener> mTestListener;
1328     sp<FakeInputReaderPolicy> mFakePolicy;
1329     std::unique_ptr<InputReaderInterface> mReader;
1330 
1331     std::shared_ptr<FakePointerController> mFakePointerController;
1332 
SetUp()1333     void SetUp() override {
1334 #if !defined(__ANDROID__)
1335         GTEST_SKIP();
1336 #endif
1337         mFakePolicy = sp<FakeInputReaderPolicy>::make();
1338         mFakePointerController = std::make_shared<FakePointerController>();
1339         mFakePolicy->setPointerController(mFakePointerController);
1340 
1341         setupInputReader();
1342     }
1343 
TearDown()1344     void TearDown() override {
1345 #if !defined(__ANDROID__)
1346         return;
1347 #endif
1348         ASSERT_EQ(mReader->stop(), OK);
1349         mReader.reset();
1350         mTestListener.reset();
1351         mFakePolicy.clear();
1352     }
1353 
findDeviceByName(const std::string & name)1354     std::optional<InputDeviceInfo> findDeviceByName(const std::string& name) {
1355         const std::vector<InputDeviceInfo> inputDevices = mFakePolicy->getInputDevices();
1356         const auto& it = std::find_if(inputDevices.begin(), inputDevices.end(),
1357                                       [&name](const InputDeviceInfo& info) {
1358                                           return info.getIdentifier().name == name;
1359                                       });
1360         return it != inputDevices.end() ? std::make_optional(*it) : std::nullopt;
1361     }
1362 
setupInputReader()1363     void setupInputReader() {
1364         mTestListener = std::make_unique<TestInputListener>(/*eventHappenedTimeout=*/2000ms,
1365                                                             /*eventDidNotHappenTimeout=*/30ms);
1366 
1367         mReader = std::make_unique<InputReader>(std::make_shared<EventHub>(), mFakePolicy,
1368                                                 *mTestListener);
1369         ASSERT_EQ(mReader->start(), OK);
1370 
1371         // Since this test is run on a real device, all the input devices connected
1372         // to the test device will show up in mReader. We wait for those input devices to
1373         // show up before beginning the tests.
1374         ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1375         ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyInputDevicesChangedWasCalled());
1376         ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
1377     }
1378 };
1379 
TEST_F(InputReaderIntegrationTest,TestInvalidDevice)1380 TEST_F(InputReaderIntegrationTest, TestInvalidDevice) {
1381     // An invalid input device that is only used for this test.
1382     class InvalidUinputDevice : public UinputDevice {
1383     public:
1384         InvalidUinputDevice() : UinputDevice("Invalid Device", /*productId=*/99) {}
1385 
1386     private:
1387         void configureDevice(int fd, uinput_user_dev* device) override {}
1388     };
1389 
1390     const size_t numDevices = mFakePolicy->getInputDevices().size();
1391 
1392     // UinputDevice does not set any event or key bits, so InputReader should not
1393     // consider it as a valid device.
1394     std::unique_ptr<UinputDevice> invalidDevice = createUinputDevice<InvalidUinputDevice>();
1395     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesNotChanged());
1396     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasNotCalled());
1397     ASSERT_EQ(numDevices, mFakePolicy->getInputDevices().size());
1398 
1399     invalidDevice.reset();
1400     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesNotChanged());
1401     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasNotCalled());
1402     ASSERT_EQ(numDevices, mFakePolicy->getInputDevices().size());
1403 }
1404 
TEST_F(InputReaderIntegrationTest,AddNewDevice)1405 TEST_F(InputReaderIntegrationTest, AddNewDevice) {
1406     const size_t initialNumDevices = mFakePolicy->getInputDevices().size();
1407 
1408     std::unique_ptr<UinputHomeKey> keyboard = createUinputDevice<UinputHomeKey>();
1409     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1410     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
1411     ASSERT_EQ(initialNumDevices + 1, mFakePolicy->getInputDevices().size());
1412 
1413     const auto device = findDeviceByName(keyboard->getName());
1414     ASSERT_TRUE(device.has_value());
1415     ASSERT_EQ(AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC, device->getKeyboardType());
1416     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, device->getSources());
1417     ASSERT_EQ(0U, device->getMotionRanges().size());
1418 
1419     keyboard.reset();
1420     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1421     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
1422     ASSERT_EQ(initialNumDevices, mFakePolicy->getInputDevices().size());
1423 }
1424 
TEST_F(InputReaderIntegrationTest,SendsEventsToInputListener)1425 TEST_F(InputReaderIntegrationTest, SendsEventsToInputListener) {
1426     std::unique_ptr<UinputHomeKey> keyboard = createUinputDevice<UinputHomeKey>();
1427     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1428 
1429     NotifyConfigurationChangedArgs configChangedArgs;
1430     ASSERT_NO_FATAL_FAILURE(
1431             mTestListener->assertNotifyConfigurationChangedWasCalled(&configChangedArgs));
1432     int32_t prevId = configChangedArgs.id;
1433     nsecs_t prevTimestamp = configChangedArgs.eventTime;
1434 
1435     NotifyKeyArgs keyArgs;
1436     keyboard->pressAndReleaseHomeKey();
1437     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(&keyArgs));
1438     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
1439     ASSERT_NE(prevId, keyArgs.id);
1440     prevId = keyArgs.id;
1441     ASSERT_LE(prevTimestamp, keyArgs.eventTime);
1442     ASSERT_LE(keyArgs.eventTime, keyArgs.readTime);
1443     prevTimestamp = keyArgs.eventTime;
1444 
1445     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(&keyArgs));
1446     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
1447     ASSERT_NE(prevId, keyArgs.id);
1448     ASSERT_LE(prevTimestamp, keyArgs.eventTime);
1449     ASSERT_LE(keyArgs.eventTime, keyArgs.readTime);
1450 }
1451 
TEST_F(InputReaderIntegrationTest,ExternalStylusesButtons)1452 TEST_F(InputReaderIntegrationTest, ExternalStylusesButtons) {
1453     std::unique_ptr<UinputExternalStylus> stylus = createUinputDevice<UinputExternalStylus>();
1454     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1455 
1456     const auto device = findDeviceByName(stylus->getName());
1457     ASSERT_TRUE(device.has_value());
1458 
1459     // An external stylus with buttons should also be recognized as a keyboard.
1460     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_STYLUS, device->getSources())
1461             << "Unexpected source " << inputEventSourceToString(device->getSources()).c_str();
1462     ASSERT_EQ(AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC, device->getKeyboardType());
1463 
1464     const auto DOWN =
1465             AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN), WithSource(AINPUT_SOURCE_KEYBOARD));
1466     const auto UP = AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP), WithSource(AINPUT_SOURCE_KEYBOARD));
1467 
1468     stylus->pressAndReleaseKey(BTN_STYLUS);
1469     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(
1470             AllOf(DOWN, WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY))));
1471     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(
1472             AllOf(UP, WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY))));
1473 
1474     stylus->pressAndReleaseKey(BTN_STYLUS2);
1475     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(
1476             AllOf(DOWN, WithKeyCode(AKEYCODE_STYLUS_BUTTON_SECONDARY))));
1477     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(
1478             AllOf(UP, WithKeyCode(AKEYCODE_STYLUS_BUTTON_SECONDARY))));
1479 
1480     stylus->pressAndReleaseKey(BTN_STYLUS3);
1481     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(
1482             AllOf(DOWN, WithKeyCode(AKEYCODE_STYLUS_BUTTON_TERTIARY))));
1483     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(
1484             AllOf(UP, WithKeyCode(AKEYCODE_STYLUS_BUTTON_TERTIARY))));
1485 }
1486 
TEST_F(InputReaderIntegrationTest,KeyboardWithStylusButtons)1487 TEST_F(InputReaderIntegrationTest, KeyboardWithStylusButtons) {
1488     std::unique_ptr<UinputKeyboard> keyboard =
1489             createUinputDevice<UinputKeyboard>("KeyboardWithStylusButtons", /*productId=*/99,
1490                                                std::initializer_list<int>{KEY_Q, KEY_W, KEY_E,
1491                                                                           KEY_R, KEY_T, KEY_Y,
1492                                                                           BTN_STYLUS, BTN_STYLUS2,
1493                                                                           BTN_STYLUS3});
1494     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1495 
1496     const auto device = findDeviceByName(keyboard->getName());
1497     ASSERT_TRUE(device.has_value());
1498 
1499     // An alphabetical keyboard that reports stylus buttons should not be recognized as a stylus.
1500     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, device->getSources())
1501             << "Unexpected source " << inputEventSourceToString(device->getSources()).c_str();
1502     ASSERT_EQ(AINPUT_KEYBOARD_TYPE_ALPHABETIC, device->getKeyboardType());
1503 }
1504 
TEST_F(InputReaderIntegrationTest,HidUsageKeyboardIsNotAStylus)1505 TEST_F(InputReaderIntegrationTest, HidUsageKeyboardIsNotAStylus) {
1506     // Create a Uinput keyboard that simulates a keyboard that can report HID usage codes. The
1507     // hid-input driver reports HID usage codes using the value for EV_MSC MSC_SCAN event.
1508     std::unique_ptr<UinputKeyboardWithHidUsage> keyboard =
1509             createUinputDevice<UinputKeyboardWithHidUsage>(
1510                     std::initializer_list<int>{KEY_VOLUMEUP, KEY_VOLUMEDOWN});
1511     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1512 
1513     const auto device = findDeviceByName(keyboard->getName());
1514     ASSERT_TRUE(device.has_value());
1515 
1516     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, device->getSources())
1517             << "Unexpected source " << inputEventSourceToString(device->getSources()).c_str();
1518 
1519     // If a device supports reporting HID usage codes, it shouldn't automatically support
1520     // stylus keys.
1521     const std::vector<int> keycodes{AKEYCODE_STYLUS_BUTTON_PRIMARY};
1522     uint8_t outFlags[] = {0};
1523     ASSERT_TRUE(mReader->hasKeys(device->getId(), AINPUT_SOURCE_KEYBOARD, keycodes, outFlags));
1524     ASSERT_EQ(0, outFlags[0]) << "Keyboard should not have stylus button";
1525 }
1526 
1527 /**
1528  * The Steam controller sends BTN_GEAR_DOWN and BTN_GEAR_UP for the two "paddle" buttons
1529  * on the back. In this test, we make sure that BTN_GEAR_DOWN / BTN_WHEEL and BTN_GEAR_UP
1530  * are passed to the listener.
1531  */
1532 static_assert(BTN_GEAR_DOWN == BTN_WHEEL);
TEST_F(InputReaderIntegrationTest,SendsGearDownAndUpToInputListener)1533 TEST_F(InputReaderIntegrationTest, SendsGearDownAndUpToInputListener) {
1534     std::unique_ptr<UinputSteamController> controller = createUinputDevice<UinputSteamController>();
1535     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1536     NotifyKeyArgs keyArgs;
1537 
1538     controller->pressAndReleaseKey(BTN_GEAR_DOWN);
1539     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(&keyArgs)); // ACTION_DOWN
1540     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(&keyArgs)); // ACTION_UP
1541     ASSERT_EQ(BTN_GEAR_DOWN, keyArgs.scanCode);
1542 
1543     controller->pressAndReleaseKey(BTN_GEAR_UP);
1544     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(&keyArgs)); // ACTION_DOWN
1545     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(&keyArgs)); // ACTION_UP
1546     ASSERT_EQ(BTN_GEAR_UP, keyArgs.scanCode);
1547 }
1548 
1549 // --- TouchIntegrationTest ---
1550 
1551 class BaseTouchIntegrationTest : public InputReaderIntegrationTest {
1552 protected:
1553     const std::string UNIQUE_ID = "local:0";
1554 
SetUp()1555     void SetUp() override {
1556 #if !defined(__ANDROID__)
1557         GTEST_SKIP();
1558 #endif
1559         InputReaderIntegrationTest::SetUp();
1560         // At least add an internal display.
1561         setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
1562                                      UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
1563 
1564         mDevice = createUinputDevice<UinputTouchScreen>(Rect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT));
1565         ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1566         ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
1567         const auto info = findDeviceByName(mDevice->getName());
1568         ASSERT_TRUE(info);
1569         mDeviceInfo = *info;
1570     }
1571 
setDisplayInfoAndReconfigure(int32_t displayId,int32_t width,int32_t height,ui::Rotation orientation,const std::string & uniqueId,std::optional<uint8_t> physicalPort,ViewportType viewportType)1572     void setDisplayInfoAndReconfigure(int32_t displayId, int32_t width, int32_t height,
1573                                       ui::Rotation orientation, const std::string& uniqueId,
1574                                       std::optional<uint8_t> physicalPort,
1575                                       ViewportType viewportType) {
1576         mFakePolicy->addDisplayViewport(displayId, width, height, orientation, /*isActive=*/true,
1577                                         uniqueId, physicalPort, viewportType);
1578         mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::DISPLAY_INFO);
1579     }
1580 
assertReceivedMotion(int32_t action,const std::vector<Point> & points)1581     void assertReceivedMotion(int32_t action, const std::vector<Point>& points) {
1582         NotifyMotionArgs args;
1583         ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1584         EXPECT_EQ(action, args.action);
1585         ASSERT_EQ(points.size(), args.getPointerCount());
1586         for (size_t i = 0; i < args.getPointerCount(); i++) {
1587             EXPECT_EQ(points[i].x, args.pointerCoords[i].getX());
1588             EXPECT_EQ(points[i].y, args.pointerCoords[i].getY());
1589         }
1590     }
1591 
1592     std::unique_ptr<UinputTouchScreen> mDevice;
1593     InputDeviceInfo mDeviceInfo;
1594 };
1595 
1596 enum class TouchIntegrationTestDisplays { DISPLAY_INTERNAL, DISPLAY_INPUT_PORT, DISPLAY_UNIQUE_ID };
1597 
1598 class TouchIntegrationTest : public BaseTouchIntegrationTest,
1599                              public testing::WithParamInterface<TouchIntegrationTestDisplays> {
1600 protected:
1601     static constexpr std::optional<uint8_t> DISPLAY_PORT = 0;
1602     const std::string INPUT_PORT = "uinput_touch/input0";
1603 
SetUp()1604     void SetUp() override {
1605 #if !defined(__ANDROID__)
1606         GTEST_SKIP();
1607 #endif
1608         if (GetParam() == TouchIntegrationTestDisplays::DISPLAY_INTERNAL) {
1609             BaseTouchIntegrationTest::SetUp();
1610             return;
1611         }
1612 
1613         // setup policy with a input-port or UniqueId association to the display
1614         bool isInputPortAssociation =
1615                 GetParam() == TouchIntegrationTestDisplays::DISPLAY_INPUT_PORT;
1616 
1617         mFakePolicy = sp<FakeInputReaderPolicy>::make();
1618         if (isInputPortAssociation) {
1619             mFakePolicy->addInputPortAssociation(INPUT_PORT, DISPLAY_PORT.value());
1620         } else {
1621             mFakePolicy->addInputUniqueIdAssociation(INPUT_PORT, UNIQUE_ID);
1622         }
1623         mFakePointerController = std::make_shared<FakePointerController>();
1624         mFakePolicy->setPointerController(mFakePointerController);
1625 
1626         InputReaderIntegrationTest::setupInputReader();
1627 
1628         mDevice = createUinputDevice<UinputTouchScreen>(Rect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT),
1629                                                         INPUT_PORT);
1630         ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1631 
1632         // Add a display linked to a physical port or UniqueId.
1633         setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
1634                                      UNIQUE_ID, isInputPortAssociation ? DISPLAY_PORT : NO_PORT,
1635                                      ViewportType::INTERNAL);
1636         ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1637         ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
1638         const auto info = findDeviceByName(mDevice->getName());
1639         ASSERT_TRUE(info);
1640         mDeviceInfo = *info;
1641     }
1642 };
1643 
TEST_P(TouchIntegrationTest,MultiTouchDeviceSource)1644 TEST_P(TouchIntegrationTest, MultiTouchDeviceSource) {
1645     // The UinputTouchScreen is an MT device that supports MT_TOOL_TYPE and also supports stylus
1646     // buttons. It should show up as a touchscreen, stylus, and keyboard (for reporting button
1647     // presses).
1648     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS | AINPUT_SOURCE_KEYBOARD,
1649               mDeviceInfo.getSources());
1650 }
1651 
TEST_P(TouchIntegrationTest,InputEvent_ProcessSingleTouch)1652 TEST_P(TouchIntegrationTest, InputEvent_ProcessSingleTouch) {
1653     NotifyMotionArgs args;
1654     const Point centerPoint = mDevice->getCenterPoint();
1655 
1656     // ACTION_DOWN
1657     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1658     mDevice->sendDown(centerPoint);
1659     mDevice->sendSync();
1660     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1661     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
1662 
1663     // ACTION_MOVE
1664     mDevice->sendMove(centerPoint + Point(1, 1));
1665     mDevice->sendSync();
1666     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1667     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
1668 
1669     // ACTION_UP
1670     mDevice->sendUp();
1671     mDevice->sendSync();
1672     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1673     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
1674 }
1675 
TEST_P(TouchIntegrationTest,InputEvent_ProcessMultiTouch)1676 TEST_P(TouchIntegrationTest, InputEvent_ProcessMultiTouch) {
1677     NotifyMotionArgs args;
1678     const Point centerPoint = mDevice->getCenterPoint();
1679 
1680     // ACTION_DOWN
1681     mDevice->sendSlot(FIRST_SLOT);
1682     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1683     mDevice->sendDown(centerPoint);
1684     mDevice->sendSync();
1685     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1686     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
1687 
1688     // ACTION_POINTER_DOWN (Second slot)
1689     const Point secondPoint = centerPoint + Point(100, 100);
1690     mDevice->sendSlot(SECOND_SLOT);
1691     mDevice->sendTrackingId(SECOND_TRACKING_ID);
1692     mDevice->sendDown(secondPoint);
1693     mDevice->sendSync();
1694     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1695     ASSERT_EQ(ACTION_POINTER_1_DOWN, args.action);
1696 
1697     // ACTION_MOVE (Second slot)
1698     mDevice->sendMove(secondPoint + Point(1, 1));
1699     mDevice->sendSync();
1700     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1701     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
1702 
1703     // ACTION_POINTER_UP (Second slot)
1704     mDevice->sendPointerUp();
1705     mDevice->sendSync();
1706     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1707     ASSERT_EQ(ACTION_POINTER_1_UP, args.action);
1708 
1709     // ACTION_UP
1710     mDevice->sendSlot(FIRST_SLOT);
1711     mDevice->sendUp();
1712     mDevice->sendSync();
1713     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1714     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
1715 }
1716 
1717 /**
1718  * What happens when a pointer goes up while another pointer moves in the same frame? Are POINTER_UP
1719  * events guaranteed to contain the same data as a preceding MOVE, or can they contain different
1720  * data?
1721  * In this test, we try to send a change in coordinates in Pointer 0 in the same frame as the
1722  * liftoff of Pointer 1. We check that POINTER_UP event is generated first, and the MOVE event
1723  * for Pointer 0 only is generated after.
1724  * Suppose we are only interested in learning the movement of Pointer 0. If we only observe MOVE
1725  * events, we will not miss any information.
1726  * Even though the Pointer 1 up event contains updated Pointer 0 coordinates, there is another MOVE
1727  * event generated afterwards that contains the newest movement of pointer 0.
1728  * This is important for palm rejection. If there is a subsequent InputListener stage that detects
1729  * palms, and wants to cancel Pointer 1, then it is safe to simply drop POINTER_1_UP event without
1730  * losing information about non-palm pointers.
1731  */
TEST_P(TouchIntegrationTest,MultiTouch_PointerMoveAndSecondPointerUp)1732 TEST_P(TouchIntegrationTest, MultiTouch_PointerMoveAndSecondPointerUp) {
1733     NotifyMotionArgs args;
1734     const Point centerPoint = mDevice->getCenterPoint();
1735 
1736     // ACTION_DOWN
1737     mDevice->sendSlot(FIRST_SLOT);
1738     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1739     mDevice->sendDown(centerPoint);
1740     mDevice->sendSync();
1741     assertReceivedMotion(AMOTION_EVENT_ACTION_DOWN, {centerPoint});
1742 
1743     // ACTION_POINTER_DOWN (Second slot)
1744     const Point secondPoint = centerPoint + Point(100, 100);
1745     mDevice->sendSlot(SECOND_SLOT);
1746     mDevice->sendTrackingId(SECOND_TRACKING_ID);
1747     mDevice->sendDown(secondPoint);
1748     mDevice->sendSync();
1749     assertReceivedMotion(ACTION_POINTER_1_DOWN, {centerPoint, secondPoint});
1750 
1751     // ACTION_MOVE (First slot)
1752     mDevice->sendSlot(FIRST_SLOT);
1753     mDevice->sendMove(centerPoint + Point(5, 5));
1754     // ACTION_POINTER_UP (Second slot)
1755     mDevice->sendSlot(SECOND_SLOT);
1756     mDevice->sendPointerUp();
1757     // Send a single sync for the above 2 pointer updates
1758     mDevice->sendSync();
1759 
1760     // First, we should get POINTER_UP for the second pointer
1761     assertReceivedMotion(ACTION_POINTER_1_UP,
1762                          {/*first pointer */ centerPoint + Point(5, 5),
1763                           /*second pointer*/ secondPoint});
1764 
1765     // Next, the MOVE event for the first pointer
1766     assertReceivedMotion(AMOTION_EVENT_ACTION_MOVE, {centerPoint + Point(5, 5)});
1767 }
1768 
1769 /**
1770  * Similar scenario as above. The difference is that when the second pointer goes up, it will first
1771  * move, and then it will go up, all in the same frame.
1772  * In this scenario, the movement of the second pointer just prior to liftoff is ignored, and never
1773  * gets sent to the listener.
1774  */
TEST_P(TouchIntegrationTest,MultiTouch_PointerMoveAndSecondPointerMoveAndUp)1775 TEST_P(TouchIntegrationTest, MultiTouch_PointerMoveAndSecondPointerMoveAndUp) {
1776     NotifyMotionArgs args;
1777     const Point centerPoint = mDevice->getCenterPoint();
1778 
1779     // ACTION_DOWN
1780     mDevice->sendSlot(FIRST_SLOT);
1781     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1782     mDevice->sendDown(centerPoint);
1783     mDevice->sendSync();
1784     assertReceivedMotion(AMOTION_EVENT_ACTION_DOWN, {centerPoint});
1785 
1786     // ACTION_POINTER_DOWN (Second slot)
1787     const Point secondPoint = centerPoint + Point(100, 100);
1788     mDevice->sendSlot(SECOND_SLOT);
1789     mDevice->sendTrackingId(SECOND_TRACKING_ID);
1790     mDevice->sendDown(secondPoint);
1791     mDevice->sendSync();
1792     assertReceivedMotion(ACTION_POINTER_1_DOWN, {centerPoint, secondPoint});
1793 
1794     // ACTION_MOVE (First slot)
1795     mDevice->sendSlot(FIRST_SLOT);
1796     mDevice->sendMove(centerPoint + Point(5, 5));
1797     // ACTION_POINTER_UP (Second slot)
1798     mDevice->sendSlot(SECOND_SLOT);
1799     mDevice->sendMove(secondPoint + Point(6, 6));
1800     mDevice->sendPointerUp();
1801     // Send a single sync for the above 2 pointer updates
1802     mDevice->sendSync();
1803 
1804     // First, we should get POINTER_UP for the second pointer
1805     // The movement of the second pointer during the liftoff frame is ignored.
1806     // The coordinates 'secondPoint + Point(6, 6)' are never sent to the listener.
1807     assertReceivedMotion(ACTION_POINTER_1_UP,
1808                          {/*first pointer */ centerPoint + Point(5, 5),
1809                           /*second pointer*/ secondPoint});
1810 
1811     // Next, the MOVE event for the first pointer
1812     assertReceivedMotion(AMOTION_EVENT_ACTION_MOVE, {centerPoint + Point(5, 5)});
1813 }
1814 
TEST_P(TouchIntegrationTest,InputEvent_ProcessPalm)1815 TEST_P(TouchIntegrationTest, InputEvent_ProcessPalm) {
1816     NotifyMotionArgs args;
1817     const Point centerPoint = mDevice->getCenterPoint();
1818 
1819     // ACTION_DOWN
1820     mDevice->sendSlot(FIRST_SLOT);
1821     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1822     mDevice->sendDown(centerPoint);
1823     mDevice->sendSync();
1824     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1825     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
1826 
1827     // ACTION_POINTER_DOWN (second slot)
1828     const Point secondPoint = centerPoint + Point(100, 100);
1829     mDevice->sendSlot(SECOND_SLOT);
1830     mDevice->sendTrackingId(SECOND_TRACKING_ID);
1831     mDevice->sendDown(secondPoint);
1832     mDevice->sendSync();
1833     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1834     ASSERT_EQ(ACTION_POINTER_1_DOWN, args.action);
1835 
1836     // ACTION_MOVE (second slot)
1837     mDevice->sendMove(secondPoint + Point(1, 1));
1838     mDevice->sendSync();
1839     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1840     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
1841 
1842     // Send MT_TOOL_PALM (second slot), which indicates that the touch IC has determined this to be
1843     // a palm event.
1844     // Expect to receive the ACTION_POINTER_UP with cancel flag.
1845     mDevice->sendToolType(MT_TOOL_PALM);
1846     mDevice->sendSync();
1847     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1848     ASSERT_EQ(ACTION_POINTER_1_UP, args.action);
1849     ASSERT_EQ(AMOTION_EVENT_FLAG_CANCELED, args.flags);
1850 
1851     // Send up to second slot, expect first slot send moving.
1852     mDevice->sendPointerUp();
1853     mDevice->sendSync();
1854     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1855     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
1856 
1857     // Send ACTION_UP (first slot)
1858     mDevice->sendSlot(FIRST_SLOT);
1859     mDevice->sendUp();
1860     mDevice->sendSync();
1861 
1862     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1863     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
1864 }
1865 
TEST_P(TouchIntegrationTest,NotifiesPolicyWhenStylusGestureStarted)1866 TEST_P(TouchIntegrationTest, NotifiesPolicyWhenStylusGestureStarted) {
1867     const Point centerPoint = mDevice->getCenterPoint();
1868 
1869     // Send down with the pen tool selected. The policy should be notified of the stylus presence.
1870     mDevice->sendSlot(FIRST_SLOT);
1871     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1872     mDevice->sendToolType(MT_TOOL_PEN);
1873     mDevice->sendDown(centerPoint);
1874     mDevice->sendSync();
1875     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
1876             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
1877                   WithToolType(ToolType::STYLUS))));
1878 
1879     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertStylusGestureNotified(mDeviceInfo.getId()));
1880 
1881     // Release the stylus touch.
1882     mDevice->sendUp();
1883     mDevice->sendSync();
1884     ASSERT_NO_FATAL_FAILURE(
1885             mTestListener->assertNotifyMotionWasCalled(WithMotionAction(AMOTION_EVENT_ACTION_UP)));
1886 
1887     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertStylusGestureNotNotified());
1888 
1889     // Touch down with the finger, without the pen tool selected. The policy is not notified.
1890     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1891     mDevice->sendToolType(MT_TOOL_FINGER);
1892     mDevice->sendDown(centerPoint);
1893     mDevice->sendSync();
1894     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
1895             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
1896                   WithToolType(ToolType::FINGER))));
1897 
1898     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertStylusGestureNotNotified());
1899 
1900     mDevice->sendUp();
1901     mDevice->sendSync();
1902     ASSERT_NO_FATAL_FAILURE(
1903             mTestListener->assertNotifyMotionWasCalled(WithMotionAction(AMOTION_EVENT_ACTION_UP)));
1904 
1905     // Send a move event with the stylus tool without BTN_TOUCH to generate a hover enter.
1906     // The policy should be notified of the stylus presence.
1907     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1908     mDevice->sendToolType(MT_TOOL_PEN);
1909     mDevice->sendMove(centerPoint);
1910     mDevice->sendSync();
1911     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
1912             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
1913                   WithToolType(ToolType::STYLUS))));
1914 
1915     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertStylusGestureNotified(mDeviceInfo.getId()));
1916 }
1917 
1918 INSTANTIATE_TEST_SUITE_P(TouchIntegrationTestDisplayVariants, TouchIntegrationTest,
1919                          testing::Values(TouchIntegrationTestDisplays::DISPLAY_INTERNAL,
1920                                          TouchIntegrationTestDisplays::DISPLAY_INPUT_PORT,
1921                                          TouchIntegrationTestDisplays::DISPLAY_UNIQUE_ID));
1922 
1923 // --- StylusButtonIntegrationTest ---
1924 
1925 // Verify the behavior of button presses reported by various kinds of styluses, including buttons
1926 // reported by the touchscreen's device, by a fused external stylus, and by an un-fused external
1927 // stylus.
1928 template <typename UinputStylusDevice>
1929 class StylusButtonIntegrationTest : public BaseTouchIntegrationTest {
1930 protected:
SetUp()1931     void SetUp() override {
1932 #if !defined(__ANDROID__)
1933         GTEST_SKIP();
1934 #endif
1935         BaseTouchIntegrationTest::SetUp();
1936         mTouchscreen = mDevice.get();
1937         mTouchscreenInfo = mDeviceInfo;
1938 
1939         setUpStylusDevice();
1940     }
1941 
1942     UinputStylusDevice* mStylus{nullptr};
1943     InputDeviceInfo mStylusInfo{};
1944 
1945     UinputTouchScreen* mTouchscreen{nullptr};
1946     InputDeviceInfo mTouchscreenInfo{};
1947 
1948 private:
1949     // When we are attempting to test stylus button events that are sent from the touchscreen,
1950     // use the same Uinput device for the touchscreen and the stylus.
1951     template <typename T = UinputStylusDevice>
setUpStylusDevice()1952     std::enable_if_t<std::is_same_v<UinputTouchScreen, T>, void> setUpStylusDevice() {
1953         mStylus = mDevice.get();
1954         mStylusInfo = mDeviceInfo;
1955     }
1956 
1957     // When we are attempting to stylus buttons from an external stylus being merged with touches
1958     // from a touchscreen, create a new Uinput device through which stylus buttons can be injected.
1959     template <typename T = UinputStylusDevice>
setUpStylusDevice()1960     std::enable_if_t<!std::is_same_v<UinputTouchScreen, T>, void> setUpStylusDevice() {
1961         mStylusDeviceLifecycleTracker = createUinputDevice<T>();
1962         mStylus = mStylusDeviceLifecycleTracker.get();
1963         ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1964         ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
1965         const auto info = findDeviceByName(mStylus->getName());
1966         ASSERT_TRUE(info);
1967         mStylusInfo = *info;
1968     }
1969 
1970     std::unique_ptr<UinputStylusDevice> mStylusDeviceLifecycleTracker{};
1971 
1972     // Hide the base class's device to expose it with a different name for readability.
1973     using BaseTouchIntegrationTest::mDevice;
1974     using BaseTouchIntegrationTest::mDeviceInfo;
1975 };
1976 
1977 using StylusButtonIntegrationTestTypes =
1978         ::testing::Types<UinputTouchScreen, UinputExternalStylus, UinputExternalStylusWithPressure>;
1979 TYPED_TEST_SUITE(StylusButtonIntegrationTest, StylusButtonIntegrationTestTypes);
1980 
TYPED_TEST(StylusButtonIntegrationTest,DISABLED_StylusButtonsGenerateKeyEvents)1981 TYPED_TEST(StylusButtonIntegrationTest, DISABLED_StylusButtonsGenerateKeyEvents) {
1982     const auto stylusId = TestFixture::mStylusInfo.getId();
1983 
1984     TestFixture::mStylus->pressKey(BTN_STYLUS);
1985     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
1986             AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN), WithSource(AINPUT_SOURCE_KEYBOARD),
1987                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
1988 
1989     TestFixture::mStylus->releaseKey(BTN_STYLUS);
1990     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
1991             AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP), WithSource(AINPUT_SOURCE_KEYBOARD),
1992                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
1993 }
1994 
TYPED_TEST(StylusButtonIntegrationTest,DISABLED_StylusButtonsSurroundingTouchGesture)1995 TYPED_TEST(StylusButtonIntegrationTest, DISABLED_StylusButtonsSurroundingTouchGesture) {
1996     const Point centerPoint = TestFixture::mTouchscreen->getCenterPoint();
1997     const auto touchscreenId = TestFixture::mTouchscreenInfo.getId();
1998     const auto stylusId = TestFixture::mStylusInfo.getId();
1999 
2000     // Press the stylus button.
2001     TestFixture::mStylus->pressKey(BTN_STYLUS);
2002     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2003             AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN), WithSource(AINPUT_SOURCE_KEYBOARD),
2004                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2005 
2006     // Start and finish a stylus gesture.
2007     TestFixture::mTouchscreen->sendSlot(FIRST_SLOT);
2008     TestFixture::mTouchscreen->sendTrackingId(FIRST_TRACKING_ID);
2009     TestFixture::mTouchscreen->sendToolType(MT_TOOL_PEN);
2010     TestFixture::mTouchscreen->sendDown(centerPoint);
2011     TestFixture::mTouchscreen->sendSync();
2012     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2013             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2014                   WithToolType(ToolType::STYLUS),
2015                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY),
2016                   WithDeviceId(touchscreenId))));
2017     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2018             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
2019                   WithToolType(ToolType::STYLUS),
2020                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY),
2021                   WithDeviceId(touchscreenId))));
2022 
2023     TestFixture::mTouchscreen->sendTrackingId(INVALID_TRACKING_ID);
2024     TestFixture::mTouchscreen->sendSync();
2025     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2026             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
2027                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2028                   WithDeviceId(touchscreenId))));
2029     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2030             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2031                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2032                   WithDeviceId(touchscreenId))));
2033 
2034     // Release the stylus button.
2035     TestFixture::mStylus->releaseKey(BTN_STYLUS);
2036     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2037             AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP), WithSource(AINPUT_SOURCE_KEYBOARD),
2038                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2039 }
2040 
TYPED_TEST(StylusButtonIntegrationTest,DISABLED_StylusButtonsSurroundingHoveringTouchGesture)2041 TYPED_TEST(StylusButtonIntegrationTest, DISABLED_StylusButtonsSurroundingHoveringTouchGesture) {
2042     const Point centerPoint = TestFixture::mTouchscreen->getCenterPoint();
2043     const auto touchscreenId = TestFixture::mTouchscreenInfo.getId();
2044     const auto stylusId = TestFixture::mStylusInfo.getId();
2045     auto toolTypeDevice =
2046             AllOf(WithToolType(ToolType::STYLUS), WithDeviceId(touchscreenId));
2047 
2048     // Press the stylus button.
2049     TestFixture::mStylus->pressKey(BTN_STYLUS);
2050     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2051             AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN), WithSource(AINPUT_SOURCE_KEYBOARD),
2052                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2053 
2054     // Start hovering with the stylus.
2055     TestFixture::mTouchscreen->sendSlot(FIRST_SLOT);
2056     TestFixture::mTouchscreen->sendTrackingId(FIRST_TRACKING_ID);
2057     TestFixture::mTouchscreen->sendToolType(MT_TOOL_PEN);
2058     TestFixture::mTouchscreen->sendMove(centerPoint);
2059     TestFixture::mTouchscreen->sendSync();
2060     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2061             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2062                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2063     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2064             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2065                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2066     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2067             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
2068                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2069 
2070     // Touch down with the stylus.
2071     TestFixture::mTouchscreen->sendTrackingId(FIRST_TRACKING_ID);
2072     TestFixture::mTouchscreen->sendToolType(MT_TOOL_PEN);
2073     TestFixture::mTouchscreen->sendDown(centerPoint);
2074     TestFixture::mTouchscreen->sendSync();
2075     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2076             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
2077                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2078 
2079     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2080             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2081                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2082 
2083     // Stop touching with the stylus, and start hovering.
2084     TestFixture::mTouchscreen->sendUp();
2085     TestFixture::mTouchscreen->sendTrackingId(FIRST_TRACKING_ID);
2086     TestFixture::mTouchscreen->sendToolType(MT_TOOL_PEN);
2087     TestFixture::mTouchscreen->sendMove(centerPoint);
2088     TestFixture::mTouchscreen->sendSync();
2089     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2090             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_UP),
2091                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2092     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2093             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2094                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2095     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2096             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2097                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2098 
2099     // Stop hovering.
2100     TestFixture::mTouchscreen->sendTrackingId(INVALID_TRACKING_ID);
2101     TestFixture::mTouchscreen->sendSync();
2102     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2103             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
2104                   WithButtonState(0))));
2105     // TODO(b/257971675): Fix inconsistent button state when exiting hover.
2106     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2107             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
2108                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2109 
2110     // Release the stylus button.
2111     TestFixture::mStylus->releaseKey(BTN_STYLUS);
2112     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2113             AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP), WithSource(AINPUT_SOURCE_KEYBOARD),
2114                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2115 }
2116 
TYPED_TEST(StylusButtonIntegrationTest,DISABLED_StylusButtonsWithinTouchGesture)2117 TYPED_TEST(StylusButtonIntegrationTest, DISABLED_StylusButtonsWithinTouchGesture) {
2118     const Point centerPoint = TestFixture::mTouchscreen->getCenterPoint();
2119     const auto touchscreenId = TestFixture::mTouchscreenInfo.getId();
2120     const auto stylusId = TestFixture::mStylusInfo.getId();
2121 
2122     // Start a stylus gesture.
2123     TestFixture::mTouchscreen->sendSlot(FIRST_SLOT);
2124     TestFixture::mTouchscreen->sendTrackingId(FIRST_TRACKING_ID);
2125     TestFixture::mTouchscreen->sendToolType(MT_TOOL_PEN);
2126     TestFixture::mTouchscreen->sendDown(centerPoint);
2127     TestFixture::mTouchscreen->sendSync();
2128     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2129             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2130                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2131                   WithDeviceId(touchscreenId))));
2132 
2133     // Press and release a stylus button. Each change in button state also generates a MOVE event.
2134     TestFixture::mStylus->pressKey(BTN_STYLUS);
2135     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2136             AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN), WithSource(AINPUT_SOURCE_KEYBOARD),
2137                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2138     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2139             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
2140                   WithToolType(ToolType::STYLUS),
2141                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY),
2142                   WithDeviceId(touchscreenId))));
2143     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2144             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
2145                   WithToolType(ToolType::STYLUS),
2146                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY),
2147                   WithDeviceId(touchscreenId))));
2148 
2149     TestFixture::mStylus->releaseKey(BTN_STYLUS);
2150     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2151             AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP), WithSource(AINPUT_SOURCE_KEYBOARD),
2152                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2153     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2154             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
2155                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2156                   WithDeviceId(touchscreenId))));
2157     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2158             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
2159                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2160                   WithDeviceId(touchscreenId))));
2161 
2162     // Finish the stylus gesture.
2163     TestFixture::mTouchscreen->sendTrackingId(INVALID_TRACKING_ID);
2164     TestFixture::mTouchscreen->sendSync();
2165     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2166             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2167                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2168                   WithDeviceId(touchscreenId))));
2169 }
2170 
TYPED_TEST(StylusButtonIntegrationTest,DISABLED_StylusButtonMotionEventsDisabled)2171 TYPED_TEST(StylusButtonIntegrationTest, DISABLED_StylusButtonMotionEventsDisabled) {
2172     TestFixture::mFakePolicy->setStylusButtonMotionEventsEnabled(false);
2173     TestFixture::mReader->requestRefreshConfiguration(
2174             InputReaderConfiguration::Change::STYLUS_BUTTON_REPORTING);
2175 
2176     const Point centerPoint = TestFixture::mTouchscreen->getCenterPoint();
2177     const auto touchscreenId = TestFixture::mTouchscreenInfo.getId();
2178     const auto stylusId = TestFixture::mStylusInfo.getId();
2179 
2180     // Start a stylus gesture. By the time this event is processed, the configuration change that
2181     // was requested is guaranteed to be completed.
2182     TestFixture::mTouchscreen->sendSlot(FIRST_SLOT);
2183     TestFixture::mTouchscreen->sendTrackingId(FIRST_TRACKING_ID);
2184     TestFixture::mTouchscreen->sendToolType(MT_TOOL_PEN);
2185     TestFixture::mTouchscreen->sendDown(centerPoint);
2186     TestFixture::mTouchscreen->sendSync();
2187     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2188             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2189                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2190                   WithDeviceId(touchscreenId))));
2191 
2192     // Press and release a stylus button. Each change only generates a MOVE motion event.
2193     // Key events are unaffected.
2194     TestFixture::mStylus->pressKey(BTN_STYLUS);
2195     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2196             AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN), WithSource(AINPUT_SOURCE_KEYBOARD),
2197                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2198     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2199             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
2200                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2201                   WithDeviceId(touchscreenId))));
2202 
2203     TestFixture::mStylus->releaseKey(BTN_STYLUS);
2204     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2205             AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP), WithSource(AINPUT_SOURCE_KEYBOARD),
2206                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2207     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2208             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
2209                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2210                   WithDeviceId(touchscreenId))));
2211 
2212     // Finish the stylus gesture.
2213     TestFixture::mTouchscreen->sendTrackingId(INVALID_TRACKING_ID);
2214     TestFixture::mTouchscreen->sendSync();
2215     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2216             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2217                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2218                   WithDeviceId(touchscreenId))));
2219 }
2220 
2221 // --- ExternalStylusIntegrationTest ---
2222 
2223 // Verify the behavior of an external stylus. An external stylus can report pressure or button
2224 // data independently of the touchscreen, which is then sent as a MotionEvent as part of an
2225 // ongoing stylus gesture that is being emitted by the touchscreen.
2226 using ExternalStylusIntegrationTest = BaseTouchIntegrationTest;
2227 
TEST_F(ExternalStylusIntegrationTest,ExternalStylusConnectionChangesTouchscreenSource)2228 TEST_F(ExternalStylusIntegrationTest, ExternalStylusConnectionChangesTouchscreenSource) {
2229     // Create an external stylus capable of reporting pressure data that
2230     // should be fused with a touch pointer.
2231     std::unique_ptr<UinputExternalStylusWithPressure> stylus =
2232             createUinputDevice<UinputExternalStylusWithPressure>();
2233     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
2234     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
2235     const auto stylusInfo = findDeviceByName(stylus->getName());
2236     ASSERT_TRUE(stylusInfo);
2237 
2238     // Connecting an external stylus changes the source of the touchscreen.
2239     const auto deviceInfo = findDeviceByName(mDevice->getName());
2240     ASSERT_TRUE(deviceInfo);
2241     ASSERT_TRUE(isFromSource(deviceInfo->getSources(), STYLUS_FUSION_SOURCE));
2242 }
2243 
TEST_F(ExternalStylusIntegrationTest,DISABLED_FusedExternalStylusPressureReported)2244 TEST_F(ExternalStylusIntegrationTest, DISABLED_FusedExternalStylusPressureReported) {
2245     const Point centerPoint = mDevice->getCenterPoint();
2246 
2247     // Create an external stylus capable of reporting pressure data that
2248     // should be fused with a touch pointer.
2249     std::unique_ptr<UinputExternalStylusWithPressure> stylus =
2250             createUinputDevice<UinputExternalStylusWithPressure>();
2251     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
2252     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
2253     const auto stylusInfo = findDeviceByName(stylus->getName());
2254     ASSERT_TRUE(stylusInfo);
2255 
2256     ASSERT_EQ(AINPUT_SOURCE_STYLUS | AINPUT_SOURCE_KEYBOARD, stylusInfo->getSources());
2257 
2258     const auto touchscreenId = mDeviceInfo.getId();
2259 
2260     // Set a pressure value on the stylus. It doesn't generate any events.
2261     const auto& RAW_PRESSURE_MAX = UinputExternalStylusWithPressure::RAW_PRESSURE_MAX;
2262     stylus->setPressure(100);
2263     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2264 
2265     // Start a finger gesture, and ensure it shows up as stylus gesture
2266     // with the pressure set by the external stylus.
2267     mDevice->sendSlot(FIRST_SLOT);
2268     mDevice->sendTrackingId(FIRST_TRACKING_ID);
2269     mDevice->sendToolType(MT_TOOL_FINGER);
2270     mDevice->sendDown(centerPoint);
2271     mDevice->sendSync();
2272     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2273             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithToolType(ToolType::STYLUS),
2274                   WithButtonState(0), WithSource(STYLUS_FUSION_SOURCE), WithDeviceId(touchscreenId),
2275                   WithPressure(100.f / RAW_PRESSURE_MAX))));
2276 
2277     // Change the pressure on the external stylus, and ensure the touchscreen generates a MOVE
2278     // event with the updated pressure.
2279     stylus->setPressure(200);
2280     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2281             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE), WithToolType(ToolType::STYLUS),
2282                   WithButtonState(0), WithSource(STYLUS_FUSION_SOURCE), WithDeviceId(touchscreenId),
2283                   WithPressure(200.f / RAW_PRESSURE_MAX))));
2284 
2285     // The external stylus did not generate any events.
2286     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2287     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasNotCalled());
2288 }
2289 
TEST_F(ExternalStylusIntegrationTest,DISABLED_FusedExternalStylusPressureNotReported)2290 TEST_F(ExternalStylusIntegrationTest, DISABLED_FusedExternalStylusPressureNotReported) {
2291     const Point centerPoint = mDevice->getCenterPoint();
2292 
2293     // Create an external stylus capable of reporting pressure data that
2294     // should be fused with a touch pointer.
2295     std::unique_ptr<UinputExternalStylusWithPressure> stylus =
2296             createUinputDevice<UinputExternalStylusWithPressure>();
2297     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
2298     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
2299     const auto stylusInfo = findDeviceByName(stylus->getName());
2300     ASSERT_TRUE(stylusInfo);
2301 
2302     ASSERT_EQ(AINPUT_SOURCE_STYLUS | AINPUT_SOURCE_KEYBOARD, stylusInfo->getSources());
2303 
2304     const auto touchscreenId = mDeviceInfo.getId();
2305 
2306     // Set a pressure value of 0 on the stylus. It doesn't generate any events.
2307     const auto& RAW_PRESSURE_MAX = UinputExternalStylusWithPressure::RAW_PRESSURE_MAX;
2308     // Send a non-zero value first to prevent the kernel from consuming the zero event.
2309     stylus->setPressure(100);
2310     stylus->setPressure(0);
2311     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2312 
2313     // Start a finger gesture. The touch device will withhold generating any touches for
2314     // up to 72 milliseconds while waiting for pressure data from the external stylus.
2315     mDevice->sendSlot(FIRST_SLOT);
2316     mDevice->sendTrackingId(FIRST_TRACKING_ID);
2317     mDevice->sendToolType(MT_TOOL_FINGER);
2318     mDevice->sendDown(centerPoint);
2319     auto waitUntil = std::chrono::system_clock::now() +
2320             std::chrono::milliseconds(ns2ms(EXTERNAL_STYLUS_DATA_TIMEOUT));
2321     mDevice->sendSync();
2322     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled(waitUntil));
2323 
2324     // Since the external stylus did not report a pressure value within the timeout,
2325     // it shows up as a finger pointer.
2326     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2327             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2328                   WithSource(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS),
2329                   WithToolType(ToolType::FINGER), WithDeviceId(touchscreenId), WithPressure(1.f))));
2330 
2331     // Change the pressure on the external stylus. Since the pressure was not present at the start
2332     // of the gesture, it is ignored for now.
2333     stylus->setPressure(200);
2334     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2335 
2336     // Finish the finger gesture.
2337     mDevice->sendTrackingId(INVALID_TRACKING_ID);
2338     mDevice->sendSync();
2339     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2340             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2341                   WithSource(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS),
2342                   WithToolType(ToolType::FINGER))));
2343 
2344     // Start a new gesture. Since we have a valid pressure value, it shows up as a stylus.
2345     mDevice->sendTrackingId(FIRST_TRACKING_ID);
2346     mDevice->sendToolType(MT_TOOL_FINGER);
2347     mDevice->sendDown(centerPoint);
2348     mDevice->sendSync();
2349     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2350             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithSource(STYLUS_FUSION_SOURCE),
2351                   WithToolType(ToolType::STYLUS), WithButtonState(0), WithDeviceId(touchscreenId),
2352                   WithPressure(200.f / RAW_PRESSURE_MAX))));
2353 
2354     // The external stylus did not generate any events.
2355     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2356     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasNotCalled());
2357 }
2358 
TEST_F(ExternalStylusIntegrationTest,DISABLED_UnfusedExternalStylus)2359 TEST_F(ExternalStylusIntegrationTest, DISABLED_UnfusedExternalStylus) {
2360     const Point centerPoint = mDevice->getCenterPoint();
2361 
2362     // Create an external stylus device that does not support pressure. It should not affect any
2363     // touch pointers.
2364     std::unique_ptr<UinputExternalStylus> stylus = createUinputDevice<UinputExternalStylus>();
2365     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
2366     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
2367     const auto stylusInfo = findDeviceByName(stylus->getName());
2368     ASSERT_TRUE(stylusInfo);
2369 
2370     ASSERT_EQ(AINPUT_SOURCE_STYLUS | AINPUT_SOURCE_KEYBOARD, stylusInfo->getSources());
2371 
2372     const auto touchscreenId = mDeviceInfo.getId();
2373 
2374     // Start a finger gesture and ensure a finger pointer is generated for it, without waiting for
2375     // pressure data from the external stylus.
2376     mDevice->sendSlot(FIRST_SLOT);
2377     mDevice->sendTrackingId(FIRST_TRACKING_ID);
2378     mDevice->sendToolType(MT_TOOL_FINGER);
2379     mDevice->sendDown(centerPoint);
2380     auto waitUntil = std::chrono::system_clock::now() +
2381             std::chrono::milliseconds(ns2ms(EXTERNAL_STYLUS_DATA_TIMEOUT));
2382     mDevice->sendSync();
2383     ASSERT_NO_FATAL_FAILURE(
2384             mTestListener->assertNotifyMotionWasCalled(AllOf(WithMotionAction(
2385                                                                      AMOTION_EVENT_ACTION_DOWN),
2386                                                              WithToolType(ToolType::FINGER),
2387                                                              WithSource(AINPUT_SOURCE_TOUCHSCREEN |
2388                                                                         AINPUT_SOURCE_STYLUS),
2389                                                              WithButtonState(0),
2390                                                              WithDeviceId(touchscreenId),
2391                                                              WithPressure(1.f)),
2392                                                        waitUntil));
2393 
2394     // The external stylus did not generate any events.
2395     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2396     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasNotCalled());
2397 }
2398 
2399 // --- InputDeviceTest ---
2400 class InputDeviceTest : public testing::Test {
2401 protected:
2402     static const char* DEVICE_NAME;
2403     static const char* DEVICE_LOCATION;
2404     static const int32_t DEVICE_ID;
2405     static const int32_t DEVICE_GENERATION;
2406     static const int32_t DEVICE_CONTROLLER_NUMBER;
2407     static const ftl::Flags<InputDeviceClass> DEVICE_CLASSES;
2408     static const int32_t EVENTHUB_ID;
2409     static const std::string DEVICE_BLUETOOTH_ADDRESS;
2410 
2411     std::shared_ptr<FakeEventHub> mFakeEventHub;
2412     sp<FakeInputReaderPolicy> mFakePolicy;
2413     std::unique_ptr<TestInputListener> mFakeListener;
2414     std::unique_ptr<InstrumentedInputReader> mReader;
2415     std::shared_ptr<InputDevice> mDevice;
2416 
SetUp()2417     void SetUp() override {
2418         mFakeEventHub = std::make_unique<FakeEventHub>();
2419         mFakePolicy = sp<FakeInputReaderPolicy>::make();
2420         mFakeListener = std::make_unique<TestInputListener>();
2421         mReader = std::make_unique<InstrumentedInputReader>(mFakeEventHub, mFakePolicy,
2422                                                             *mFakeListener);
2423         InputDeviceIdentifier identifier;
2424         identifier.name = DEVICE_NAME;
2425         identifier.location = DEVICE_LOCATION;
2426         identifier.bluetoothAddress = DEVICE_BLUETOOTH_ADDRESS;
2427         mDevice = std::make_shared<InputDevice>(mReader->getContext(), DEVICE_ID, DEVICE_GENERATION,
2428                                                 identifier);
2429         mReader->pushNextDevice(mDevice);
2430         mFakeEventHub->addDevice(EVENTHUB_ID, DEVICE_NAME, ftl::Flags<InputDeviceClass>(0));
2431         mReader->loopOnce();
2432     }
2433 
TearDown()2434     void TearDown() override {
2435         mFakeListener.reset();
2436         mFakePolicy.clear();
2437     }
2438 };
2439 
2440 const char* InputDeviceTest::DEVICE_NAME = "device";
2441 const char* InputDeviceTest::DEVICE_LOCATION = "USB1";
2442 const int32_t InputDeviceTest::DEVICE_ID = END_RESERVED_ID + 1000;
2443 const int32_t InputDeviceTest::DEVICE_GENERATION = 2;
2444 const int32_t InputDeviceTest::DEVICE_CONTROLLER_NUMBER = 0;
2445 const ftl::Flags<InputDeviceClass> InputDeviceTest::DEVICE_CLASSES =
2446         InputDeviceClass::KEYBOARD | InputDeviceClass::TOUCH | InputDeviceClass::JOYSTICK;
2447 const int32_t InputDeviceTest::EVENTHUB_ID = 1;
2448 const std::string InputDeviceTest::DEVICE_BLUETOOTH_ADDRESS = "11:AA:22:BB:33:CC";
2449 
TEST_F(InputDeviceTest,ImmutableProperties)2450 TEST_F(InputDeviceTest, ImmutableProperties) {
2451     ASSERT_EQ(DEVICE_ID, mDevice->getId());
2452     ASSERT_STREQ(DEVICE_NAME, mDevice->getName().c_str());
2453     ASSERT_EQ(ftl::Flags<InputDeviceClass>(0), mDevice->getClasses());
2454 }
2455 
TEST_F(InputDeviceTest,WhenDeviceCreated_EnabledIsFalse)2456 TEST_F(InputDeviceTest, WhenDeviceCreated_EnabledIsFalse) {
2457     ASSERT_EQ(mDevice->isEnabled(), false);
2458 }
2459 
TEST_F(InputDeviceTest,WhenNoMappersAreRegistered_DeviceIsIgnored)2460 TEST_F(InputDeviceTest, WhenNoMappersAreRegistered_DeviceIsIgnored) {
2461     // Configuration.
2462     InputReaderConfiguration config;
2463     std::list<NotifyArgs> unused = mDevice->configure(ARBITRARY_TIME, config, /*changes=*/{});
2464 
2465     // Reset.
2466     unused += mDevice->reset(ARBITRARY_TIME);
2467 
2468     NotifyDeviceResetArgs resetArgs;
2469     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
2470     ASSERT_EQ(ARBITRARY_TIME, resetArgs.eventTime);
2471     ASSERT_EQ(DEVICE_ID, resetArgs.deviceId);
2472 
2473     // Metadata.
2474     ASSERT_TRUE(mDevice->isIgnored());
2475     ASSERT_EQ(AINPUT_SOURCE_UNKNOWN, mDevice->getSources());
2476 
2477     InputDeviceInfo info = mDevice->getDeviceInfo();
2478     ASSERT_EQ(DEVICE_ID, info.getId());
2479     ASSERT_STREQ(DEVICE_NAME, info.getIdentifier().name.c_str());
2480     ASSERT_EQ(AINPUT_KEYBOARD_TYPE_NONE, info.getKeyboardType());
2481     ASSERT_EQ(AINPUT_SOURCE_UNKNOWN, info.getSources());
2482 
2483     // State queries.
2484     ASSERT_EQ(0, mDevice->getMetaState());
2485 
2486     ASSERT_EQ(AKEY_STATE_UNKNOWN, mDevice->getKeyCodeState(AINPUT_SOURCE_KEYBOARD, 0))
2487             << "Ignored device should return unknown key code state.";
2488     ASSERT_EQ(AKEY_STATE_UNKNOWN, mDevice->getScanCodeState(AINPUT_SOURCE_KEYBOARD, 0))
2489             << "Ignored device should return unknown scan code state.";
2490     ASSERT_EQ(AKEY_STATE_UNKNOWN, mDevice->getSwitchState(AINPUT_SOURCE_KEYBOARD, 0))
2491             << "Ignored device should return unknown switch state.";
2492 
2493     const std::vector<int32_t> keyCodes{AKEYCODE_A, AKEYCODE_B};
2494     uint8_t flags[2] = { 0, 1 };
2495     ASSERT_FALSE(mDevice->markSupportedKeyCodes(AINPUT_SOURCE_KEYBOARD, keyCodes, flags))
2496             << "Ignored device should never mark any key codes.";
2497     ASSERT_EQ(0, flags[0]) << "Flag for unsupported key should be unchanged.";
2498     ASSERT_EQ(1, flags[1]) << "Flag for unsupported key should be unchanged.";
2499 }
2500 
TEST_F(InputDeviceTest,WhenMappersAreRegistered_DeviceIsNotIgnoredAndForwardsRequestsToMappers)2501 TEST_F(InputDeviceTest, WhenMappersAreRegistered_DeviceIsNotIgnoredAndForwardsRequestsToMappers) {
2502     // Configuration.
2503     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "key", "value");
2504 
2505     FakeInputMapper& mapper1 =
2506             mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2507                                                 AINPUT_SOURCE_KEYBOARD);
2508     mapper1.setKeyboardType(AINPUT_KEYBOARD_TYPE_ALPHABETIC);
2509     mapper1.setMetaState(AMETA_ALT_ON);
2510     mapper1.addSupportedKeyCode(AKEYCODE_A);
2511     mapper1.addSupportedKeyCode(AKEYCODE_B);
2512     mapper1.setKeyCodeState(AKEYCODE_A, AKEY_STATE_DOWN);
2513     mapper1.setKeyCodeState(AKEYCODE_B, AKEY_STATE_UP);
2514     mapper1.setScanCodeState(2, AKEY_STATE_DOWN);
2515     mapper1.setScanCodeState(3, AKEY_STATE_UP);
2516     mapper1.setSwitchState(4, AKEY_STATE_DOWN);
2517 
2518     FakeInputMapper& mapper2 =
2519             mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2520                                                 AINPUT_SOURCE_TOUCHSCREEN);
2521     mapper2.setMetaState(AMETA_SHIFT_ON);
2522 
2523     InputReaderConfiguration config;
2524     std::list<NotifyArgs> unused = mDevice->configure(ARBITRARY_TIME, config, /*changes=*/{});
2525 
2526     std::optional<std::string> propertyValue = mDevice->getConfiguration().getString("key");
2527     ASSERT_TRUE(propertyValue.has_value())
2528             << "Device should have read configuration during configuration phase.";
2529     ASSERT_EQ("value", *propertyValue);
2530 
2531     ASSERT_NO_FATAL_FAILURE(mapper1.assertConfigureWasCalled());
2532     ASSERT_NO_FATAL_FAILURE(mapper2.assertConfigureWasCalled());
2533 
2534     // Reset
2535     unused += mDevice->reset(ARBITRARY_TIME);
2536     ASSERT_NO_FATAL_FAILURE(mapper1.assertResetWasCalled());
2537     ASSERT_NO_FATAL_FAILURE(mapper2.assertResetWasCalled());
2538 
2539     NotifyDeviceResetArgs resetArgs;
2540     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
2541     ASSERT_EQ(ARBITRARY_TIME, resetArgs.eventTime);
2542     ASSERT_EQ(DEVICE_ID, resetArgs.deviceId);
2543 
2544     // Metadata.
2545     ASSERT_FALSE(mDevice->isIgnored());
2546     ASSERT_EQ(uint32_t(AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TOUCHSCREEN), mDevice->getSources());
2547 
2548     InputDeviceInfo info = mDevice->getDeviceInfo();
2549     ASSERT_EQ(DEVICE_ID, info.getId());
2550     ASSERT_STREQ(DEVICE_NAME, info.getIdentifier().name.c_str());
2551     ASSERT_EQ(AINPUT_KEYBOARD_TYPE_ALPHABETIC, info.getKeyboardType());
2552     ASSERT_EQ(uint32_t(AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TOUCHSCREEN), info.getSources());
2553 
2554     // State queries.
2555     ASSERT_EQ(AMETA_ALT_ON | AMETA_SHIFT_ON, mDevice->getMetaState())
2556             << "Should query mappers and combine meta states.";
2557 
2558     ASSERT_EQ(AKEY_STATE_UNKNOWN, mDevice->getKeyCodeState(AINPUT_SOURCE_TRACKBALL, AKEYCODE_A))
2559             << "Should return unknown key code state when source not supported.";
2560     ASSERT_EQ(AKEY_STATE_UNKNOWN, mDevice->getScanCodeState(AINPUT_SOURCE_TRACKBALL, AKEYCODE_A))
2561             << "Should return unknown scan code state when source not supported.";
2562     ASSERT_EQ(AKEY_STATE_UNKNOWN, mDevice->getSwitchState(AINPUT_SOURCE_TRACKBALL, AKEYCODE_A))
2563             << "Should return unknown switch state when source not supported.";
2564 
2565     ASSERT_EQ(AKEY_STATE_DOWN, mDevice->getKeyCodeState(AINPUT_SOURCE_KEYBOARD, AKEYCODE_A))
2566             << "Should query mapper when source is supported.";
2567     ASSERT_EQ(AKEY_STATE_UP, mDevice->getScanCodeState(AINPUT_SOURCE_KEYBOARD, 3))
2568             << "Should query mapper when source is supported.";
2569     ASSERT_EQ(AKEY_STATE_DOWN, mDevice->getSwitchState(AINPUT_SOURCE_KEYBOARD, 4))
2570             << "Should query mapper when source is supported.";
2571 
2572     const std::vector<int32_t> keyCodes{AKEYCODE_A, AKEYCODE_B, AKEYCODE_1, AKEYCODE_2};
2573     uint8_t flags[4] = { 0, 0, 0, 1 };
2574     ASSERT_FALSE(mDevice->markSupportedKeyCodes(AINPUT_SOURCE_TRACKBALL, keyCodes, flags))
2575             << "Should do nothing when source is unsupported.";
2576     ASSERT_EQ(0, flags[0]) << "Flag should be unchanged when source is unsupported.";
2577     ASSERT_EQ(0, flags[1]) << "Flag should be unchanged when source is unsupported.";
2578     ASSERT_EQ(0, flags[2]) << "Flag should be unchanged when source is unsupported.";
2579     ASSERT_EQ(1, flags[3]) << "Flag should be unchanged when source is unsupported.";
2580 
2581     ASSERT_TRUE(mDevice->markSupportedKeyCodes(AINPUT_SOURCE_KEYBOARD, keyCodes, flags))
2582             << "Should query mapper when source is supported.";
2583     ASSERT_EQ(1, flags[0]) << "Flag for supported key should be set.";
2584     ASSERT_EQ(1, flags[1]) << "Flag for supported key should be set.";
2585     ASSERT_EQ(0, flags[2]) << "Flag for unsupported key should be unchanged.";
2586     ASSERT_EQ(1, flags[3]) << "Flag for unsupported key should be unchanged.";
2587 
2588     // Event handling.
2589     RawEvent event;
2590     event.deviceId = EVENTHUB_ID;
2591     unused += mDevice->process(&event, 1);
2592 
2593     ASSERT_NO_FATAL_FAILURE(mapper1.assertProcessWasCalled());
2594     ASSERT_NO_FATAL_FAILURE(mapper2.assertProcessWasCalled());
2595 }
2596 
2597 // A single input device is associated with a specific display. Check that:
2598 // 1. Device is disabled if the viewport corresponding to the associated display is not found
2599 // 2. Device is disabled when setEnabled API is called
TEST_F(InputDeviceTest,Configure_AssignsDisplayPort)2600 TEST_F(InputDeviceTest, Configure_AssignsDisplayPort) {
2601     mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2602                                         AINPUT_SOURCE_TOUCHSCREEN);
2603 
2604     // First Configuration.
2605     std::list<NotifyArgs> unused =
2606             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2607                                /*changes=*/{});
2608 
2609     // Device should be enabled by default.
2610     ASSERT_TRUE(mDevice->isEnabled());
2611 
2612     // Prepare associated info.
2613     constexpr uint8_t hdmi = 1;
2614     const std::string UNIQUE_ID = "local:1";
2615 
2616     mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi);
2617     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2618                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2619     // Device should be disabled because it is associated with a specific display via
2620     // input port <-> display port association, but the corresponding display is not found
2621     ASSERT_FALSE(mDevice->isEnabled());
2622 
2623     // Prepare displays.
2624     mFakePolicy->addDisplayViewport(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
2625                                     ui::ROTATION_0, /*isActive=*/true, UNIQUE_ID, hdmi,
2626                                     ViewportType::INTERNAL);
2627     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2628                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2629     ASSERT_TRUE(mDevice->isEnabled());
2630 
2631     // Device should be disabled after set disable.
2632     mFakePolicy->addDisabledDevice(mDevice->getId());
2633     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2634                                  InputReaderConfiguration::Change::ENABLED_STATE);
2635     ASSERT_FALSE(mDevice->isEnabled());
2636 
2637     // Device should still be disabled even found the associated display.
2638     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2639                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2640     ASSERT_FALSE(mDevice->isEnabled());
2641 }
2642 
TEST_F(InputDeviceTest,Configure_AssignsDisplayUniqueId)2643 TEST_F(InputDeviceTest, Configure_AssignsDisplayUniqueId) {
2644     // Device should be enabled by default.
2645     mFakePolicy->clearViewports();
2646     mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2647                                         AINPUT_SOURCE_KEYBOARD);
2648     std::list<NotifyArgs> unused =
2649             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2650                                /*changes=*/{});
2651     ASSERT_TRUE(mDevice->isEnabled());
2652 
2653     // Device should be disabled because it is associated with a specific display, but the
2654     // corresponding display is not found.
2655     mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, DISPLAY_UNIQUE_ID);
2656     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2657                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2658     ASSERT_FALSE(mDevice->isEnabled());
2659 
2660     // Device should be enabled when a display is found.
2661     mFakePolicy->addDisplayViewport(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
2662                                     ui::ROTATION_0, /* isActive= */ true, DISPLAY_UNIQUE_ID,
2663                                     NO_PORT, ViewportType::INTERNAL);
2664     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2665                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2666     ASSERT_TRUE(mDevice->isEnabled());
2667 
2668     // Device should be disabled after set disable.
2669     mFakePolicy->addDisabledDevice(mDevice->getId());
2670     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2671                                  InputReaderConfiguration::Change::ENABLED_STATE);
2672     ASSERT_FALSE(mDevice->isEnabled());
2673 
2674     // Device should still be disabled even found the associated display.
2675     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2676                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2677     ASSERT_FALSE(mDevice->isEnabled());
2678 }
2679 
TEST_F(InputDeviceTest,Configure_UniqueId_CorrectlyMatches)2680 TEST_F(InputDeviceTest, Configure_UniqueId_CorrectlyMatches) {
2681     mFakePolicy->clearViewports();
2682     mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2683                                         AINPUT_SOURCE_KEYBOARD);
2684     std::list<NotifyArgs> unused =
2685             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2686                                /*changes=*/{});
2687 
2688     mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, DISPLAY_UNIQUE_ID);
2689     mFakePolicy->addDisplayViewport(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
2690                                     ui::ROTATION_0, /* isActive= */ true, DISPLAY_UNIQUE_ID,
2691                                     NO_PORT, ViewportType::INTERNAL);
2692     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2693                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2694     ASSERT_EQ(DISPLAY_UNIQUE_ID, mDevice->getAssociatedDisplayUniqueId());
2695 }
2696 
2697 /**
2698  * This test reproduces a crash caused by a dangling reference that remains after device is added
2699  * and removed. The reference is accessed in InputDevice::dump(..);
2700  */
TEST_F(InputDeviceTest,DumpDoesNotCrash)2701 TEST_F(InputDeviceTest, DumpDoesNotCrash) {
2702     constexpr int32_t TEST_EVENTHUB_ID = 10;
2703     mFakeEventHub->addDevice(TEST_EVENTHUB_ID, "Test EventHub device", InputDeviceClass::BATTERY);
2704 
2705     InputDevice device(mReader->getContext(), /*id=*/1, /*generation=*/2, /*identifier=*/{});
2706     device.addEventHubDevice(TEST_EVENTHUB_ID, mFakePolicy->getReaderConfiguration());
2707     device.removeEventHubDevice(TEST_EVENTHUB_ID);
2708     std::string dumpStr, eventHubDevStr;
2709     device.dump(dumpStr, eventHubDevStr);
2710 }
2711 
TEST_F(InputDeviceTest,GetBluetoothAddress)2712 TEST_F(InputDeviceTest, GetBluetoothAddress) {
2713     const auto& address = mReader->getBluetoothAddress(DEVICE_ID);
2714     ASSERT_TRUE(address);
2715     ASSERT_EQ(DEVICE_BLUETOOTH_ADDRESS, *address);
2716 }
2717 
2718 // --- SwitchInputMapperTest ---
2719 
2720 class SwitchInputMapperTest : public InputMapperTest {
2721 protected:
2722 };
2723 
TEST_F(SwitchInputMapperTest,GetSources)2724 TEST_F(SwitchInputMapperTest, GetSources) {
2725     SwitchInputMapper& mapper = constructAndAddMapper<SwitchInputMapper>();
2726 
2727     ASSERT_EQ(uint32_t(AINPUT_SOURCE_SWITCH), mapper.getSources());
2728 }
2729 
TEST_F(SwitchInputMapperTest,GetSwitchState)2730 TEST_F(SwitchInputMapperTest, GetSwitchState) {
2731     SwitchInputMapper& mapper = constructAndAddMapper<SwitchInputMapper>();
2732 
2733     mFakeEventHub->setSwitchState(EVENTHUB_ID, SW_LID, 1);
2734     ASSERT_EQ(1, mapper.getSwitchState(AINPUT_SOURCE_ANY, SW_LID));
2735 
2736     mFakeEventHub->setSwitchState(EVENTHUB_ID, SW_LID, 0);
2737     ASSERT_EQ(0, mapper.getSwitchState(AINPUT_SOURCE_ANY, SW_LID));
2738 }
2739 
TEST_F(SwitchInputMapperTest,Process)2740 TEST_F(SwitchInputMapperTest, Process) {
2741     SwitchInputMapper& mapper = constructAndAddMapper<SwitchInputMapper>();
2742     std::list<NotifyArgs> out;
2743     out = process(mapper, ARBITRARY_TIME, READ_TIME, EV_SW, SW_LID, 1);
2744     ASSERT_TRUE(out.empty());
2745     out = process(mapper, ARBITRARY_TIME, READ_TIME, EV_SW, SW_JACK_PHYSICAL_INSERT, 1);
2746     ASSERT_TRUE(out.empty());
2747     out = process(mapper, ARBITRARY_TIME, READ_TIME, EV_SW, SW_HEADPHONE_INSERT, 0);
2748     ASSERT_TRUE(out.empty());
2749     out = process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
2750 
2751     ASSERT_EQ(1u, out.size());
2752     const NotifySwitchArgs& args = std::get<NotifySwitchArgs>(*out.begin());
2753     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
2754     ASSERT_EQ((1U << SW_LID) | (1U << SW_JACK_PHYSICAL_INSERT), args.switchValues);
2755     ASSERT_EQ((1U << SW_LID) | (1U << SW_JACK_PHYSICAL_INSERT) | (1 << SW_HEADPHONE_INSERT),
2756             args.switchMask);
2757     ASSERT_EQ(uint32_t(0), args.policyFlags);
2758 }
2759 
2760 // --- VibratorInputMapperTest ---
2761 class VibratorInputMapperTest : public InputMapperTest {
2762 protected:
SetUp()2763     void SetUp() override { InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::VIBRATOR); }
2764 };
2765 
TEST_F(VibratorInputMapperTest,GetSources)2766 TEST_F(VibratorInputMapperTest, GetSources) {
2767     VibratorInputMapper& mapper = constructAndAddMapper<VibratorInputMapper>();
2768 
2769     ASSERT_EQ(AINPUT_SOURCE_UNKNOWN, mapper.getSources());
2770 }
2771 
TEST_F(VibratorInputMapperTest,GetVibratorIds)2772 TEST_F(VibratorInputMapperTest, GetVibratorIds) {
2773     VibratorInputMapper& mapper = constructAndAddMapper<VibratorInputMapper>();
2774 
2775     ASSERT_EQ(mapper.getVibratorIds().size(), 2U);
2776 }
2777 
TEST_F(VibratorInputMapperTest,Vibrate)2778 TEST_F(VibratorInputMapperTest, Vibrate) {
2779     constexpr uint8_t DEFAULT_AMPLITUDE = 192;
2780     constexpr int32_t VIBRATION_TOKEN = 100;
2781     VibratorInputMapper& mapper = constructAndAddMapper<VibratorInputMapper>();
2782 
2783     VibrationElement pattern(2);
2784     VibrationSequence sequence(2);
2785     pattern.duration = std::chrono::milliseconds(200);
2786     pattern.channels = {{/*vibratorId=*/0, DEFAULT_AMPLITUDE / 2},
2787                         {/*vibratorId=*/1, DEFAULT_AMPLITUDE}};
2788     sequence.addElement(pattern);
2789     pattern.duration = std::chrono::milliseconds(500);
2790     pattern.channels = {{/*vibratorId=*/0, DEFAULT_AMPLITUDE / 4},
2791                         {/*vibratorId=*/1, DEFAULT_AMPLITUDE}};
2792     sequence.addElement(pattern);
2793 
2794     std::vector<int64_t> timings = {0, 1};
2795     std::vector<uint8_t> amplitudes = {DEFAULT_AMPLITUDE, DEFAULT_AMPLITUDE / 2};
2796 
2797     ASSERT_FALSE(mapper.isVibrating());
2798     // Start vibrating
2799     std::list<NotifyArgs> out = mapper.vibrate(sequence, /*repeat=*/-1, VIBRATION_TOKEN);
2800     ASSERT_TRUE(mapper.isVibrating());
2801     // Verify vibrator state listener was notified.
2802     mReader->loopOnce();
2803     ASSERT_EQ(1u, out.size());
2804     const NotifyVibratorStateArgs& vibrateArgs = std::get<NotifyVibratorStateArgs>(*out.begin());
2805     ASSERT_EQ(DEVICE_ID, vibrateArgs.deviceId);
2806     ASSERT_TRUE(vibrateArgs.isOn);
2807     // Stop vibrating
2808     out = mapper.cancelVibrate(VIBRATION_TOKEN);
2809     ASSERT_FALSE(mapper.isVibrating());
2810     // Verify vibrator state listener was notified.
2811     mReader->loopOnce();
2812     ASSERT_EQ(1u, out.size());
2813     const NotifyVibratorStateArgs& cancelArgs = std::get<NotifyVibratorStateArgs>(*out.begin());
2814     ASSERT_EQ(DEVICE_ID, cancelArgs.deviceId);
2815     ASSERT_FALSE(cancelArgs.isOn);
2816 }
2817 
2818 // --- SensorInputMapperTest ---
2819 
2820 class SensorInputMapperTest : public InputMapperTest {
2821 protected:
2822     static const int32_t ACCEL_RAW_MIN;
2823     static const int32_t ACCEL_RAW_MAX;
2824     static const int32_t ACCEL_RAW_FUZZ;
2825     static const int32_t ACCEL_RAW_FLAT;
2826     static const int32_t ACCEL_RAW_RESOLUTION;
2827 
2828     static const int32_t GYRO_RAW_MIN;
2829     static const int32_t GYRO_RAW_MAX;
2830     static const int32_t GYRO_RAW_FUZZ;
2831     static const int32_t GYRO_RAW_FLAT;
2832     static const int32_t GYRO_RAW_RESOLUTION;
2833 
2834     static const float GRAVITY_MS2_UNIT;
2835     static const float DEGREE_RADIAN_UNIT;
2836 
2837     void prepareAccelAxes();
2838     void prepareGyroAxes();
2839     void setAccelProperties();
2840     void setGyroProperties();
SetUp()2841     void SetUp() override { InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::SENSOR); }
2842 };
2843 
2844 const int32_t SensorInputMapperTest::ACCEL_RAW_MIN = -32768;
2845 const int32_t SensorInputMapperTest::ACCEL_RAW_MAX = 32768;
2846 const int32_t SensorInputMapperTest::ACCEL_RAW_FUZZ = 16;
2847 const int32_t SensorInputMapperTest::ACCEL_RAW_FLAT = 0;
2848 const int32_t SensorInputMapperTest::ACCEL_RAW_RESOLUTION = 8192;
2849 
2850 const int32_t SensorInputMapperTest::GYRO_RAW_MIN = -2097152;
2851 const int32_t SensorInputMapperTest::GYRO_RAW_MAX = 2097152;
2852 const int32_t SensorInputMapperTest::GYRO_RAW_FUZZ = 16;
2853 const int32_t SensorInputMapperTest::GYRO_RAW_FLAT = 0;
2854 const int32_t SensorInputMapperTest::GYRO_RAW_RESOLUTION = 1024;
2855 
2856 const float SensorInputMapperTest::GRAVITY_MS2_UNIT = 9.80665f;
2857 const float SensorInputMapperTest::DEGREE_RADIAN_UNIT = 0.0174533f;
2858 
prepareAccelAxes()2859 void SensorInputMapperTest::prepareAccelAxes() {
2860     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_X, ACCEL_RAW_MIN, ACCEL_RAW_MAX, ACCEL_RAW_FUZZ,
2861                                    ACCEL_RAW_FLAT, ACCEL_RAW_RESOLUTION);
2862     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_Y, ACCEL_RAW_MIN, ACCEL_RAW_MAX, ACCEL_RAW_FUZZ,
2863                                    ACCEL_RAW_FLAT, ACCEL_RAW_RESOLUTION);
2864     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_Z, ACCEL_RAW_MIN, ACCEL_RAW_MAX, ACCEL_RAW_FUZZ,
2865                                    ACCEL_RAW_FLAT, ACCEL_RAW_RESOLUTION);
2866 }
2867 
prepareGyroAxes()2868 void SensorInputMapperTest::prepareGyroAxes() {
2869     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_RX, GYRO_RAW_MIN, GYRO_RAW_MAX, GYRO_RAW_FUZZ,
2870                                    GYRO_RAW_FLAT, GYRO_RAW_RESOLUTION);
2871     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_RY, GYRO_RAW_MIN, GYRO_RAW_MAX, GYRO_RAW_FUZZ,
2872                                    GYRO_RAW_FLAT, GYRO_RAW_RESOLUTION);
2873     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_RZ, GYRO_RAW_MIN, GYRO_RAW_MAX, GYRO_RAW_FUZZ,
2874                                    GYRO_RAW_FLAT, GYRO_RAW_RESOLUTION);
2875 }
2876 
setAccelProperties()2877 void SensorInputMapperTest::setAccelProperties() {
2878     mFakeEventHub->addSensorAxis(EVENTHUB_ID, /* absCode */ 0, InputDeviceSensorType::ACCELEROMETER,
2879                                  /* sensorDataIndex */ 0);
2880     mFakeEventHub->addSensorAxis(EVENTHUB_ID, /* absCode */ 1, InputDeviceSensorType::ACCELEROMETER,
2881                                  /* sensorDataIndex */ 1);
2882     mFakeEventHub->addSensorAxis(EVENTHUB_ID, /* absCode */ 2, InputDeviceSensorType::ACCELEROMETER,
2883                                  /* sensorDataIndex */ 2);
2884     mFakeEventHub->setMscEvent(EVENTHUB_ID, MSC_TIMESTAMP);
2885     addConfigurationProperty("sensor.accelerometer.reportingMode", "0");
2886     addConfigurationProperty("sensor.accelerometer.maxDelay", "100000");
2887     addConfigurationProperty("sensor.accelerometer.minDelay", "5000");
2888     addConfigurationProperty("sensor.accelerometer.power", "1.5");
2889 }
2890 
setGyroProperties()2891 void SensorInputMapperTest::setGyroProperties() {
2892     mFakeEventHub->addSensorAxis(EVENTHUB_ID, /* absCode */ 3, InputDeviceSensorType::GYROSCOPE,
2893                                  /* sensorDataIndex */ 0);
2894     mFakeEventHub->addSensorAxis(EVENTHUB_ID, /* absCode */ 4, InputDeviceSensorType::GYROSCOPE,
2895                                  /* sensorDataIndex */ 1);
2896     mFakeEventHub->addSensorAxis(EVENTHUB_ID, /* absCode */ 5, InputDeviceSensorType::GYROSCOPE,
2897                                  /* sensorDataIndex */ 2);
2898     mFakeEventHub->setMscEvent(EVENTHUB_ID, MSC_TIMESTAMP);
2899     addConfigurationProperty("sensor.gyroscope.reportingMode", "0");
2900     addConfigurationProperty("sensor.gyroscope.maxDelay", "100000");
2901     addConfigurationProperty("sensor.gyroscope.minDelay", "5000");
2902     addConfigurationProperty("sensor.gyroscope.power", "0.8");
2903 }
2904 
TEST_F(SensorInputMapperTest,GetSources)2905 TEST_F(SensorInputMapperTest, GetSources) {
2906     SensorInputMapper& mapper = constructAndAddMapper<SensorInputMapper>();
2907 
2908     ASSERT_EQ(static_cast<uint32_t>(AINPUT_SOURCE_SENSOR), mapper.getSources());
2909 }
2910 
TEST_F(SensorInputMapperTest,ProcessAccelerometerSensor)2911 TEST_F(SensorInputMapperTest, ProcessAccelerometerSensor) {
2912     setAccelProperties();
2913     prepareAccelAxes();
2914     SensorInputMapper& mapper = constructAndAddMapper<SensorInputMapper>();
2915 
2916     ASSERT_TRUE(mapper.enableSensor(InputDeviceSensorType::ACCELEROMETER,
2917                                     std::chrono::microseconds(10000),
2918                                     std::chrono::microseconds(0)));
2919     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(EVENTHUB_ID));
2920     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_X, 20000);
2921     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_Y, -20000);
2922     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_Z, 40000);
2923     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_TIMESTAMP, 1000);
2924     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
2925 
2926     NotifySensorArgs args;
2927     std::vector<float> values = {20000.0f / ACCEL_RAW_RESOLUTION * GRAVITY_MS2_UNIT,
2928                                  -20000.0f / ACCEL_RAW_RESOLUTION * GRAVITY_MS2_UNIT,
2929                                  40000.0f / ACCEL_RAW_RESOLUTION * GRAVITY_MS2_UNIT};
2930 
2931     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifySensorWasCalled(&args));
2932     ASSERT_EQ(args.source, AINPUT_SOURCE_SENSOR);
2933     ASSERT_EQ(args.deviceId, DEVICE_ID);
2934     ASSERT_EQ(args.sensorType, InputDeviceSensorType::ACCELEROMETER);
2935     ASSERT_EQ(args.accuracy, InputDeviceSensorAccuracy::ACCURACY_HIGH);
2936     ASSERT_EQ(args.hwTimestamp, ARBITRARY_TIME);
2937     ASSERT_EQ(args.values, values);
2938     mapper.flushSensor(InputDeviceSensorType::ACCELEROMETER);
2939 }
2940 
TEST_F(SensorInputMapperTest,ProcessGyroscopeSensor)2941 TEST_F(SensorInputMapperTest, ProcessGyroscopeSensor) {
2942     setGyroProperties();
2943     prepareGyroAxes();
2944     SensorInputMapper& mapper = constructAndAddMapper<SensorInputMapper>();
2945 
2946     ASSERT_TRUE(mapper.enableSensor(InputDeviceSensorType::GYROSCOPE,
2947                                     std::chrono::microseconds(10000),
2948                                     std::chrono::microseconds(0)));
2949     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(EVENTHUB_ID));
2950     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_RX, 20000);
2951     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_RY, -20000);
2952     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_RZ, 40000);
2953     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_TIMESTAMP, 1000);
2954     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
2955 
2956     NotifySensorArgs args;
2957     std::vector<float> values = {20000.0f / GYRO_RAW_RESOLUTION * DEGREE_RADIAN_UNIT,
2958                                  -20000.0f / GYRO_RAW_RESOLUTION * DEGREE_RADIAN_UNIT,
2959                                  40000.0f / GYRO_RAW_RESOLUTION * DEGREE_RADIAN_UNIT};
2960 
2961     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifySensorWasCalled(&args));
2962     ASSERT_EQ(args.source, AINPUT_SOURCE_SENSOR);
2963     ASSERT_EQ(args.deviceId, DEVICE_ID);
2964     ASSERT_EQ(args.sensorType, InputDeviceSensorType::GYROSCOPE);
2965     ASSERT_EQ(args.accuracy, InputDeviceSensorAccuracy::ACCURACY_HIGH);
2966     ASSERT_EQ(args.hwTimestamp, ARBITRARY_TIME);
2967     ASSERT_EQ(args.values, values);
2968     mapper.flushSensor(InputDeviceSensorType::GYROSCOPE);
2969 }
2970 
2971 // --- KeyboardInputMapperTest ---
2972 
2973 class KeyboardInputMapperTest : public InputMapperTest {
2974 protected:
2975     const std::string UNIQUE_ID = "local:0";
2976     const KeyboardLayoutInfo DEVICE_KEYBOARD_LAYOUT_INFO = KeyboardLayoutInfo("en-US", "qwerty");
2977     void prepareDisplay(ui::Rotation orientation);
2978 
2979     void testDPadKeyRotation(KeyboardInputMapper& mapper, int32_t originalScanCode,
2980                              int32_t originalKeyCode, int32_t rotatedKeyCode,
2981                              int32_t displayId = ADISPLAY_ID_NONE);
2982 };
2983 
2984 /* Similar to setDisplayInfoAndReconfigure, but pre-populates all parameters except for the
2985  * orientation.
2986  */
prepareDisplay(ui::Rotation orientation)2987 void KeyboardInputMapperTest::prepareDisplay(ui::Rotation orientation) {
2988     setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, orientation, UNIQUE_ID,
2989                                  NO_PORT, ViewportType::INTERNAL);
2990 }
2991 
testDPadKeyRotation(KeyboardInputMapper & mapper,int32_t originalScanCode,int32_t originalKeyCode,int32_t rotatedKeyCode,int32_t displayId)2992 void KeyboardInputMapperTest::testDPadKeyRotation(KeyboardInputMapper& mapper,
2993                                                   int32_t originalScanCode, int32_t originalKeyCode,
2994                                                   int32_t rotatedKeyCode, int32_t displayId) {
2995     NotifyKeyArgs args;
2996 
2997     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, originalScanCode, 1);
2998     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
2999     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3000     ASSERT_EQ(originalScanCode, args.scanCode);
3001     ASSERT_EQ(rotatedKeyCode, args.keyCode);
3002     ASSERT_EQ(displayId, args.displayId);
3003 
3004     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, originalScanCode, 0);
3005     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3006     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3007     ASSERT_EQ(originalScanCode, args.scanCode);
3008     ASSERT_EQ(rotatedKeyCode, args.keyCode);
3009     ASSERT_EQ(displayId, args.displayId);
3010 }
3011 
TEST_F(KeyboardInputMapperTest,GetSources)3012 TEST_F(KeyboardInputMapperTest, GetSources) {
3013     KeyboardInputMapper& mapper =
3014             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3015                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3016 
3017     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, mapper.getSources());
3018 }
3019 
TEST_F(KeyboardInputMapperTest,Process_SimpleKeyPress)3020 TEST_F(KeyboardInputMapperTest, Process_SimpleKeyPress) {
3021     const int32_t USAGE_A = 0x070004;
3022     const int32_t USAGE_UNKNOWN = 0x07ffff;
3023     mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, POLICY_FLAG_WAKE);
3024     mFakeEventHub->addKey(EVENTHUB_ID, 0, USAGE_A, AKEYCODE_A, POLICY_FLAG_WAKE);
3025     mFakeEventHub->addKey(EVENTHUB_ID, 0, KEY_NUMLOCK, AKEYCODE_NUM_LOCK, POLICY_FLAG_WAKE);
3026     mFakeEventHub->addKey(EVENTHUB_ID, 0, KEY_CAPSLOCK, AKEYCODE_CAPS_LOCK, POLICY_FLAG_WAKE);
3027     mFakeEventHub->addKey(EVENTHUB_ID, 0, KEY_SCROLLLOCK, AKEYCODE_SCROLL_LOCK, POLICY_FLAG_WAKE);
3028 
3029     KeyboardInputMapper& mapper =
3030             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3031                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3032     // Initial metastate is AMETA_NONE.
3033     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3034 
3035     // Key down by scan code.
3036     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_HOME, 1);
3037     NotifyKeyArgs args;
3038     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3039     ASSERT_EQ(DEVICE_ID, args.deviceId);
3040     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3041     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
3042     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3043     ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
3044     ASSERT_EQ(KEY_HOME, args.scanCode);
3045     ASSERT_EQ(AMETA_NONE, args.metaState);
3046     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3047     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3048     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
3049 
3050     // Key up by scan code.
3051     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_HOME, 0);
3052     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3053     ASSERT_EQ(DEVICE_ID, args.deviceId);
3054     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3055     ASSERT_EQ(ARBITRARY_TIME + 1, args.eventTime);
3056     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3057     ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
3058     ASSERT_EQ(KEY_HOME, args.scanCode);
3059     ASSERT_EQ(AMETA_NONE, args.metaState);
3060     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3061     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3062     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
3063 
3064     // Key down by usage code.
3065     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_SCAN, USAGE_A);
3066     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, 0, 1);
3067     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3068     ASSERT_EQ(DEVICE_ID, args.deviceId);
3069     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3070     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
3071     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3072     ASSERT_EQ(AKEYCODE_A, args.keyCode);
3073     ASSERT_EQ(0, args.scanCode);
3074     ASSERT_EQ(AMETA_NONE, args.metaState);
3075     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3076     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3077     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
3078 
3079     // Key up by usage code.
3080     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_SCAN, USAGE_A);
3081     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, 0, 0);
3082     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3083     ASSERT_EQ(DEVICE_ID, args.deviceId);
3084     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3085     ASSERT_EQ(ARBITRARY_TIME + 1, args.eventTime);
3086     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3087     ASSERT_EQ(AKEYCODE_A, args.keyCode);
3088     ASSERT_EQ(0, args.scanCode);
3089     ASSERT_EQ(AMETA_NONE, args.metaState);
3090     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3091     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3092     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
3093 
3094     // Key down with unknown scan code or usage code.
3095     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_SCAN, USAGE_UNKNOWN);
3096     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UNKNOWN, 1);
3097     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3098     ASSERT_EQ(DEVICE_ID, args.deviceId);
3099     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3100     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
3101     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3102     ASSERT_EQ(0, args.keyCode);
3103     ASSERT_EQ(KEY_UNKNOWN, args.scanCode);
3104     ASSERT_EQ(AMETA_NONE, args.metaState);
3105     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3106     ASSERT_EQ(0U, args.policyFlags);
3107     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
3108 
3109     // Key up with unknown scan code or usage code.
3110     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_SCAN, USAGE_UNKNOWN);
3111     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_UNKNOWN, 0);
3112     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3113     ASSERT_EQ(DEVICE_ID, args.deviceId);
3114     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3115     ASSERT_EQ(ARBITRARY_TIME + 1, args.eventTime);
3116     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3117     ASSERT_EQ(0, args.keyCode);
3118     ASSERT_EQ(KEY_UNKNOWN, args.scanCode);
3119     ASSERT_EQ(AMETA_NONE, args.metaState);
3120     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3121     ASSERT_EQ(0U, args.policyFlags);
3122     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
3123 }
3124 
TEST_F(KeyboardInputMapperTest,Process_KeyRemapping)3125 TEST_F(KeyboardInputMapperTest, Process_KeyRemapping) {
3126     mFakeEventHub->addKey(EVENTHUB_ID, KEY_A, 0, AKEYCODE_A, 0);
3127     mFakeEventHub->addKey(EVENTHUB_ID, KEY_B, 0, AKEYCODE_B, 0);
3128     mFakeEventHub->addKeyRemapping(EVENTHUB_ID, AKEYCODE_A, AKEYCODE_B);
3129 
3130     KeyboardInputMapper& mapper =
3131             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3132                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3133 
3134     // Key down by scan code.
3135     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_A, 1);
3136     NotifyKeyArgs args;
3137     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3138     ASSERT_EQ(AKEYCODE_B, args.keyCode);
3139 
3140     // Key up by scan code.
3141     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_A, 0);
3142     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3143     ASSERT_EQ(AKEYCODE_B, args.keyCode);
3144 }
3145 
3146 /**
3147  * Ensure that the readTime is set to the time when the EV_KEY is received.
3148  */
TEST_F(KeyboardInputMapperTest,Process_SendsReadTime)3149 TEST_F(KeyboardInputMapperTest, Process_SendsReadTime) {
3150     mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, POLICY_FLAG_WAKE);
3151 
3152     KeyboardInputMapper& mapper =
3153             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3154                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3155     NotifyKeyArgs args;
3156 
3157     // Key down
3158     process(mapper, ARBITRARY_TIME, /*readTime=*/12, EV_KEY, KEY_HOME, 1);
3159     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3160     ASSERT_EQ(12, args.readTime);
3161 
3162     // Key up
3163     process(mapper, ARBITRARY_TIME, /*readTime=*/15, EV_KEY, KEY_HOME, 1);
3164     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3165     ASSERT_EQ(15, args.readTime);
3166 }
3167 
TEST_F(KeyboardInputMapperTest,Process_ShouldUpdateMetaState)3168 TEST_F(KeyboardInputMapperTest, Process_ShouldUpdateMetaState) {
3169     mFakeEventHub->addKey(EVENTHUB_ID, KEY_LEFTSHIFT, 0, AKEYCODE_SHIFT_LEFT, 0);
3170     mFakeEventHub->addKey(EVENTHUB_ID, KEY_A, 0, AKEYCODE_A, 0);
3171     mFakeEventHub->addKey(EVENTHUB_ID, 0, KEY_NUMLOCK, AKEYCODE_NUM_LOCK, 0);
3172     mFakeEventHub->addKey(EVENTHUB_ID, 0, KEY_CAPSLOCK, AKEYCODE_CAPS_LOCK, 0);
3173     mFakeEventHub->addKey(EVENTHUB_ID, 0, KEY_SCROLLLOCK, AKEYCODE_SCROLL_LOCK, 0);
3174 
3175     KeyboardInputMapper& mapper =
3176             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3177                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3178 
3179     // Initial metastate is AMETA_NONE.
3180     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3181 
3182     // Metakey down.
3183     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_LEFTSHIFT, 1);
3184     NotifyKeyArgs args;
3185     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3186     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
3187     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, mapper.getMetaState());
3188     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertUpdateGlobalMetaStateWasCalled());
3189 
3190     // Key down.
3191     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_A, 1);
3192     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3193     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
3194     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, mapper.getMetaState());
3195 
3196     // Key up.
3197     process(mapper, ARBITRARY_TIME + 2, READ_TIME, EV_KEY, KEY_A, 0);
3198     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3199     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
3200     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, mapper.getMetaState());
3201 
3202     // Metakey up.
3203     process(mapper, ARBITRARY_TIME + 3, READ_TIME, EV_KEY, KEY_LEFTSHIFT, 0);
3204     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3205     ASSERT_EQ(AMETA_NONE, args.metaState);
3206     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3207     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertUpdateGlobalMetaStateWasCalled());
3208 }
3209 
TEST_F(KeyboardInputMapperTest,Process_WhenNotOrientationAware_ShouldNotRotateDPad)3210 TEST_F(KeyboardInputMapperTest, Process_WhenNotOrientationAware_ShouldNotRotateDPad) {
3211     mFakeEventHub->addKey(EVENTHUB_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0);
3212     mFakeEventHub->addKey(EVENTHUB_ID, KEY_RIGHT, 0, AKEYCODE_DPAD_RIGHT, 0);
3213     mFakeEventHub->addKey(EVENTHUB_ID, KEY_DOWN, 0, AKEYCODE_DPAD_DOWN, 0);
3214     mFakeEventHub->addKey(EVENTHUB_ID, KEY_LEFT, 0, AKEYCODE_DPAD_LEFT, 0);
3215 
3216     KeyboardInputMapper& mapper =
3217             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3218                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3219 
3220     prepareDisplay(ui::ROTATION_90);
3221     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper,
3222             KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_UP));
3223     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper,
3224             KEY_RIGHT, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_RIGHT));
3225     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper,
3226             KEY_DOWN, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_DOWN));
3227     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper,
3228             KEY_LEFT, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_LEFT));
3229 }
3230 
TEST_F(KeyboardInputMapperTest,Process_WhenOrientationAware_ShouldRotateDPad)3231 TEST_F(KeyboardInputMapperTest, Process_WhenOrientationAware_ShouldRotateDPad) {
3232     mFakeEventHub->addKey(EVENTHUB_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0);
3233     mFakeEventHub->addKey(EVENTHUB_ID, KEY_RIGHT, 0, AKEYCODE_DPAD_RIGHT, 0);
3234     mFakeEventHub->addKey(EVENTHUB_ID, KEY_DOWN, 0, AKEYCODE_DPAD_DOWN, 0);
3235     mFakeEventHub->addKey(EVENTHUB_ID, KEY_LEFT, 0, AKEYCODE_DPAD_LEFT, 0);
3236 
3237     addConfigurationProperty("keyboard.orientationAware", "1");
3238     KeyboardInputMapper& mapper =
3239             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3240                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3241 
3242     prepareDisplay(ui::ROTATION_0);
3243     ASSERT_NO_FATAL_FAILURE(
3244             testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_UP, DISPLAY_ID));
3245     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_RIGHT, AKEYCODE_DPAD_RIGHT,
3246                                                 AKEYCODE_DPAD_RIGHT, DISPLAY_ID));
3247     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_DOWN, AKEYCODE_DPAD_DOWN,
3248                                                 AKEYCODE_DPAD_DOWN, DISPLAY_ID));
3249     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT,
3250                                                 AKEYCODE_DPAD_LEFT, DISPLAY_ID));
3251 
3252     clearViewports();
3253     prepareDisplay(ui::ROTATION_90);
3254     ASSERT_NO_FATAL_FAILURE(
3255             testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, DISPLAY_ID));
3256     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_RIGHT, AKEYCODE_DPAD_RIGHT,
3257                                                 AKEYCODE_DPAD_UP, DISPLAY_ID));
3258     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_DOWN, AKEYCODE_DPAD_DOWN,
3259                                                 AKEYCODE_DPAD_RIGHT, DISPLAY_ID));
3260     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT,
3261                                                 AKEYCODE_DPAD_DOWN, DISPLAY_ID));
3262 
3263     clearViewports();
3264     prepareDisplay(ui::ROTATION_180);
3265     ASSERT_NO_FATAL_FAILURE(
3266             testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_DOWN, DISPLAY_ID));
3267     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_RIGHT, AKEYCODE_DPAD_RIGHT,
3268                                                 AKEYCODE_DPAD_LEFT, DISPLAY_ID));
3269     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_DOWN, AKEYCODE_DPAD_DOWN,
3270                                                 AKEYCODE_DPAD_UP, DISPLAY_ID));
3271     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT,
3272                                                 AKEYCODE_DPAD_RIGHT, DISPLAY_ID));
3273 
3274     clearViewports();
3275     prepareDisplay(ui::ROTATION_270);
3276     ASSERT_NO_FATAL_FAILURE(
3277             testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_RIGHT, DISPLAY_ID));
3278     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_RIGHT, AKEYCODE_DPAD_RIGHT,
3279                                                 AKEYCODE_DPAD_DOWN, DISPLAY_ID));
3280     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_DOWN, AKEYCODE_DPAD_DOWN,
3281                                                 AKEYCODE_DPAD_LEFT, DISPLAY_ID));
3282     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT,
3283                                                 AKEYCODE_DPAD_UP, DISPLAY_ID));
3284 
3285     // Special case: if orientation changes while key is down, we still emit the same keycode
3286     // in the key up as we did in the key down.
3287     NotifyKeyArgs args;
3288     clearViewports();
3289     prepareDisplay(ui::ROTATION_270);
3290     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 1);
3291     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3292     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3293     ASSERT_EQ(KEY_UP, args.scanCode);
3294     ASSERT_EQ(AKEYCODE_DPAD_RIGHT, args.keyCode);
3295 
3296     clearViewports();
3297     prepareDisplay(ui::ROTATION_180);
3298     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 0);
3299     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3300     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3301     ASSERT_EQ(KEY_UP, args.scanCode);
3302     ASSERT_EQ(AKEYCODE_DPAD_RIGHT, args.keyCode);
3303 }
3304 
TEST_F(KeyboardInputMapperTest,DisplayIdConfigurationChange_NotOrientationAware)3305 TEST_F(KeyboardInputMapperTest, DisplayIdConfigurationChange_NotOrientationAware) {
3306     // If the keyboard is not orientation aware,
3307     // key events should not be associated with a specific display id
3308     mFakeEventHub->addKey(EVENTHUB_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0);
3309 
3310     KeyboardInputMapper& mapper =
3311             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3312                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3313     NotifyKeyArgs args;
3314 
3315     // Display id should be ADISPLAY_ID_NONE without any display configuration.
3316     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 1);
3317     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3318     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 0);
3319     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3320     ASSERT_EQ(ADISPLAY_ID_NONE, args.displayId);
3321 
3322     prepareDisplay(ui::ROTATION_0);
3323     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 1);
3324     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3325     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 0);
3326     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3327     ASSERT_EQ(ADISPLAY_ID_NONE, args.displayId);
3328 }
3329 
TEST_F(KeyboardInputMapperTest,DisplayIdConfigurationChange_OrientationAware)3330 TEST_F(KeyboardInputMapperTest, DisplayIdConfigurationChange_OrientationAware) {
3331     // If the keyboard is orientation aware,
3332     // key events should be associated with the internal viewport
3333     mFakeEventHub->addKey(EVENTHUB_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0);
3334 
3335     addConfigurationProperty("keyboard.orientationAware", "1");
3336     KeyboardInputMapper& mapper =
3337             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3338                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3339     NotifyKeyArgs args;
3340 
3341     // Display id should be ADISPLAY_ID_NONE without any display configuration.
3342     // ^--- already checked by the previous test
3343 
3344     setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
3345                                  UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
3346     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 1);
3347     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3348     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 0);
3349     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3350     ASSERT_EQ(DISPLAY_ID, args.displayId);
3351 
3352     constexpr int32_t newDisplayId = 2;
3353     clearViewports();
3354     setDisplayInfoAndReconfigure(newDisplayId, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
3355                                  UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
3356     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 1);
3357     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3358     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 0);
3359     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3360     ASSERT_EQ(newDisplayId, args.displayId);
3361 }
3362 
TEST_F(KeyboardInputMapperTest,GetKeyCodeState)3363 TEST_F(KeyboardInputMapperTest, GetKeyCodeState) {
3364     KeyboardInputMapper& mapper =
3365             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3366                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3367 
3368     mFakeEventHub->setKeyCodeState(EVENTHUB_ID, AKEYCODE_A, 1);
3369     ASSERT_EQ(1, mapper.getKeyCodeState(AINPUT_SOURCE_ANY, AKEYCODE_A));
3370 
3371     mFakeEventHub->setKeyCodeState(EVENTHUB_ID, AKEYCODE_A, 0);
3372     ASSERT_EQ(0, mapper.getKeyCodeState(AINPUT_SOURCE_ANY, AKEYCODE_A));
3373 }
3374 
TEST_F(KeyboardInputMapperTest,GetKeyCodeForKeyLocation)3375 TEST_F(KeyboardInputMapperTest, GetKeyCodeForKeyLocation) {
3376     KeyboardInputMapper& mapper =
3377             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3378                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3379 
3380     mFakeEventHub->addKeyCodeMapping(EVENTHUB_ID, AKEYCODE_Y, AKEYCODE_Z);
3381     ASSERT_EQ(AKEYCODE_Z, mapper.getKeyCodeForKeyLocation(AKEYCODE_Y))
3382             << "If a mapping is available, the result is equal to the mapping";
3383 
3384     ASSERT_EQ(AKEYCODE_A, mapper.getKeyCodeForKeyLocation(AKEYCODE_A))
3385             << "If no mapping is available, the result is the key location";
3386 }
3387 
TEST_F(KeyboardInputMapperTest,GetScanCodeState)3388 TEST_F(KeyboardInputMapperTest, GetScanCodeState) {
3389     KeyboardInputMapper& mapper =
3390             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3391                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3392 
3393     mFakeEventHub->setScanCodeState(EVENTHUB_ID, KEY_A, 1);
3394     ASSERT_EQ(1, mapper.getScanCodeState(AINPUT_SOURCE_ANY, KEY_A));
3395 
3396     mFakeEventHub->setScanCodeState(EVENTHUB_ID, KEY_A, 0);
3397     ASSERT_EQ(0, mapper.getScanCodeState(AINPUT_SOURCE_ANY, KEY_A));
3398 }
3399 
TEST_F(KeyboardInputMapperTest,MarkSupportedKeyCodes)3400 TEST_F(KeyboardInputMapperTest, MarkSupportedKeyCodes) {
3401     KeyboardInputMapper& mapper =
3402             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3403                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3404 
3405     mFakeEventHub->addKey(EVENTHUB_ID, KEY_A, 0, AKEYCODE_A, 0);
3406 
3407     uint8_t flags[2] = { 0, 0 };
3408     ASSERT_TRUE(mapper.markSupportedKeyCodes(AINPUT_SOURCE_ANY, {AKEYCODE_A, AKEYCODE_B}, flags));
3409     ASSERT_TRUE(flags[0]);
3410     ASSERT_FALSE(flags[1]);
3411 }
3412 
TEST_F(KeyboardInputMapperTest,Process_LockedKeysShouldToggleMetaStateAndLeds)3413 TEST_F(KeyboardInputMapperTest, Process_LockedKeysShouldToggleMetaStateAndLeds) {
3414     mFakeEventHub->addLed(EVENTHUB_ID, LED_CAPSL, true /*initially on*/);
3415     mFakeEventHub->addLed(EVENTHUB_ID, LED_NUML, false /*initially off*/);
3416     mFakeEventHub->addLed(EVENTHUB_ID, LED_SCROLLL, false /*initially off*/);
3417     mFakeEventHub->addKey(EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
3418     mFakeEventHub->addKey(EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
3419     mFakeEventHub->addKey(EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
3420 
3421     KeyboardInputMapper& mapper =
3422             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3423                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3424     // Initial metastate is AMETA_NONE.
3425     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3426 
3427     // Initialization should have turned all of the lights off.
3428     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3429     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3430     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3431 
3432     // Toggle caps lock on.
3433     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 1);
3434     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 0);
3435     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3436     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3437     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3438     ASSERT_EQ(AMETA_CAPS_LOCK_ON, mapper.getMetaState());
3439 
3440     // Toggle num lock on.
3441     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 1);
3442     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 0);
3443     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3444     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3445     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3446     ASSERT_EQ(AMETA_CAPS_LOCK_ON | AMETA_NUM_LOCK_ON, mapper.getMetaState());
3447 
3448     // Toggle caps lock off.
3449     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 1);
3450     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 0);
3451     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3452     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3453     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3454     ASSERT_EQ(AMETA_NUM_LOCK_ON, mapper.getMetaState());
3455 
3456     // Toggle scroll lock on.
3457     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 1);
3458     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 0);
3459     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3460     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3461     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3462     ASSERT_EQ(AMETA_NUM_LOCK_ON | AMETA_SCROLL_LOCK_ON, mapper.getMetaState());
3463 
3464     // Toggle num lock off.
3465     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 1);
3466     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 0);
3467     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3468     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3469     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3470     ASSERT_EQ(AMETA_SCROLL_LOCK_ON, mapper.getMetaState());
3471 
3472     // Toggle scroll lock off.
3473     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 1);
3474     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 0);
3475     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3476     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3477     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3478     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3479 }
3480 
TEST_F(KeyboardInputMapperTest,NoMetaStateWhenMetaKeysNotPresent)3481 TEST_F(KeyboardInputMapperTest, NoMetaStateWhenMetaKeysNotPresent) {
3482     mFakeEventHub->addKey(EVENTHUB_ID, BTN_A, 0, AKEYCODE_BUTTON_A, 0);
3483     mFakeEventHub->addKey(EVENTHUB_ID, BTN_B, 0, AKEYCODE_BUTTON_B, 0);
3484     mFakeEventHub->addKey(EVENTHUB_ID, BTN_X, 0, AKEYCODE_BUTTON_X, 0);
3485     mFakeEventHub->addKey(EVENTHUB_ID, BTN_Y, 0, AKEYCODE_BUTTON_Y, 0);
3486 
3487     KeyboardInputMapper& mapper =
3488             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3489                                                        AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC);
3490 
3491     // Meta state should be AMETA_NONE after reset
3492     std::list<NotifyArgs> unused = mapper.reset(ARBITRARY_TIME);
3493     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3494     // Meta state should be AMETA_NONE with update, as device doesn't have the keys.
3495     mapper.updateMetaState(AKEYCODE_NUM_LOCK);
3496     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3497 
3498     NotifyKeyArgs args;
3499     // Press button "A"
3500     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_A, 1);
3501     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3502     ASSERT_EQ(AMETA_NONE, args.metaState);
3503     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3504     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3505     ASSERT_EQ(AKEYCODE_BUTTON_A, args.keyCode);
3506 
3507     // Button up.
3508     process(mapper, ARBITRARY_TIME + 2, READ_TIME, EV_KEY, BTN_A, 0);
3509     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3510     ASSERT_EQ(AMETA_NONE, args.metaState);
3511     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3512     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3513     ASSERT_EQ(AKEYCODE_BUTTON_A, args.keyCode);
3514 }
3515 
TEST_F(KeyboardInputMapperTest,Configure_AssignsDisplayPort)3516 TEST_F(KeyboardInputMapperTest, Configure_AssignsDisplayPort) {
3517     // keyboard 1.
3518     mFakeEventHub->addKey(EVENTHUB_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0);
3519     mFakeEventHub->addKey(EVENTHUB_ID, KEY_RIGHT, 0, AKEYCODE_DPAD_RIGHT, 0);
3520     mFakeEventHub->addKey(EVENTHUB_ID, KEY_DOWN, 0, AKEYCODE_DPAD_DOWN, 0);
3521     mFakeEventHub->addKey(EVENTHUB_ID, KEY_LEFT, 0, AKEYCODE_DPAD_LEFT, 0);
3522 
3523     // keyboard 2.
3524     const std::string USB2 = "USB2";
3525     const std::string DEVICE_NAME2 = "KEYBOARD2";
3526     constexpr int32_t SECOND_DEVICE_ID = DEVICE_ID + 1;
3527     constexpr int32_t SECOND_EVENTHUB_ID = EVENTHUB_ID + 1;
3528     std::shared_ptr<InputDevice> device2 =
3529             newDevice(SECOND_DEVICE_ID, DEVICE_NAME2, USB2, SECOND_EVENTHUB_ID,
3530                       ftl::Flags<InputDeviceClass>(0));
3531 
3532     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0);
3533     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_RIGHT, 0, AKEYCODE_DPAD_RIGHT, 0);
3534     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_DOWN, 0, AKEYCODE_DPAD_DOWN, 0);
3535     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_LEFT, 0, AKEYCODE_DPAD_LEFT, 0);
3536 
3537     KeyboardInputMapper& mapper =
3538             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3539                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3540 
3541     device2->addEmptyEventHubDevice(SECOND_EVENTHUB_ID);
3542     KeyboardInputMapper& mapper2 =
3543             device2->constructAndAddMapper<KeyboardInputMapper>(SECOND_EVENTHUB_ID,
3544                                                                 mFakePolicy
3545                                                                         ->getReaderConfiguration(),
3546                                                                 AINPUT_SOURCE_KEYBOARD,
3547                                                                 AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3548     std::list<NotifyArgs> unused =
3549             device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3550                                /*changes=*/{});
3551     unused += device2->reset(ARBITRARY_TIME);
3552 
3553     // Prepared displays and associated info.
3554     constexpr uint8_t hdmi1 = 0;
3555     constexpr uint8_t hdmi2 = 1;
3556     const std::string SECONDARY_UNIQUE_ID = "local:1";
3557 
3558     mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi1);
3559     mFakePolicy->addInputPortAssociation(USB2, hdmi2);
3560 
3561     // No associated display viewport found, should disable the device.
3562     unused += device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3563                                  InputReaderConfiguration::Change::DISPLAY_INFO);
3564     ASSERT_FALSE(device2->isEnabled());
3565 
3566     // Prepare second display.
3567     constexpr int32_t newDisplayId = 2;
3568     setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
3569                                  UNIQUE_ID, hdmi1, ViewportType::INTERNAL);
3570     setDisplayInfoAndReconfigure(newDisplayId, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
3571                                  SECONDARY_UNIQUE_ID, hdmi2, ViewportType::EXTERNAL);
3572     // Default device will reconfigure above, need additional reconfiguration for another device.
3573     unused += device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3574                                  InputReaderConfiguration::Change::DISPLAY_INFO);
3575 
3576     // Device should be enabled after the associated display is found.
3577     ASSERT_TRUE(mDevice->isEnabled());
3578     ASSERT_TRUE(device2->isEnabled());
3579 
3580     // Test pad key events
3581     ASSERT_NO_FATAL_FAILURE(
3582             testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_UP, DISPLAY_ID));
3583     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_RIGHT, AKEYCODE_DPAD_RIGHT,
3584                                                 AKEYCODE_DPAD_RIGHT, DISPLAY_ID));
3585     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_DOWN, AKEYCODE_DPAD_DOWN,
3586                                                 AKEYCODE_DPAD_DOWN, DISPLAY_ID));
3587     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT,
3588                                                 AKEYCODE_DPAD_LEFT, DISPLAY_ID));
3589 
3590     ASSERT_NO_FATAL_FAILURE(
3591             testDPadKeyRotation(mapper2, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_UP, newDisplayId));
3592     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper2, KEY_RIGHT, AKEYCODE_DPAD_RIGHT,
3593                                                 AKEYCODE_DPAD_RIGHT, newDisplayId));
3594     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper2, KEY_DOWN, AKEYCODE_DPAD_DOWN,
3595                                                 AKEYCODE_DPAD_DOWN, newDisplayId));
3596     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper2, KEY_LEFT, AKEYCODE_DPAD_LEFT,
3597                                                 AKEYCODE_DPAD_LEFT, newDisplayId));
3598 }
3599 
TEST_F(KeyboardInputMapperTest,Process_LockedKeysShouldToggleAfterReattach)3600 TEST_F(KeyboardInputMapperTest, Process_LockedKeysShouldToggleAfterReattach) {
3601     mFakeEventHub->addLed(EVENTHUB_ID, LED_CAPSL, true /*initially on*/);
3602     mFakeEventHub->addLed(EVENTHUB_ID, LED_NUML, false /*initially off*/);
3603     mFakeEventHub->addLed(EVENTHUB_ID, LED_SCROLLL, false /*initially off*/);
3604     mFakeEventHub->addKey(EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
3605     mFakeEventHub->addKey(EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
3606     mFakeEventHub->addKey(EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
3607 
3608     KeyboardInputMapper& mapper =
3609             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3610                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3611     // Initial metastate is AMETA_NONE.
3612     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3613 
3614     // Initialization should have turned all of the lights off.
3615     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3616     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3617     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3618 
3619     // Toggle caps lock on.
3620     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 1);
3621     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 0);
3622     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3623     ASSERT_EQ(AMETA_CAPS_LOCK_ON, mapper.getMetaState());
3624 
3625     // Toggle num lock on.
3626     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 1);
3627     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 0);
3628     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3629     ASSERT_EQ(AMETA_CAPS_LOCK_ON | AMETA_NUM_LOCK_ON, mapper.getMetaState());
3630 
3631     // Toggle scroll lock on.
3632     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 1);
3633     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 0);
3634     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3635     ASSERT_EQ(AMETA_CAPS_LOCK_ON | AMETA_NUM_LOCK_ON | AMETA_SCROLL_LOCK_ON, mapper.getMetaState());
3636 
3637     mFakeEventHub->removeDevice(EVENTHUB_ID);
3638     mReader->loopOnce();
3639 
3640     // keyboard 2 should default toggle keys.
3641     const std::string USB2 = "USB2";
3642     const std::string DEVICE_NAME2 = "KEYBOARD2";
3643     constexpr int32_t SECOND_DEVICE_ID = DEVICE_ID + 1;
3644     constexpr int32_t SECOND_EVENTHUB_ID = EVENTHUB_ID + 1;
3645     std::shared_ptr<InputDevice> device2 =
3646             newDevice(SECOND_DEVICE_ID, DEVICE_NAME2, USB2, SECOND_EVENTHUB_ID,
3647                       ftl::Flags<InputDeviceClass>(0));
3648     mFakeEventHub->addLed(SECOND_EVENTHUB_ID, LED_CAPSL, true /*initially on*/);
3649     mFakeEventHub->addLed(SECOND_EVENTHUB_ID, LED_NUML, false /*initially off*/);
3650     mFakeEventHub->addLed(SECOND_EVENTHUB_ID, LED_SCROLLL, false /*initially off*/);
3651     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
3652     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
3653     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
3654 
3655     device2->addEmptyEventHubDevice(SECOND_EVENTHUB_ID);
3656     KeyboardInputMapper& mapper2 =
3657             device2->constructAndAddMapper<KeyboardInputMapper>(SECOND_EVENTHUB_ID,
3658                                                                 mFakePolicy
3659                                                                         ->getReaderConfiguration(),
3660                                                                 AINPUT_SOURCE_KEYBOARD,
3661                                                                 AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3662     std::list<NotifyArgs> unused =
3663             device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3664                                /*changes=*/{});
3665     unused += device2->reset(ARBITRARY_TIME);
3666 
3667     ASSERT_TRUE(mFakeEventHub->getLedState(SECOND_EVENTHUB_ID, LED_CAPSL));
3668     ASSERT_TRUE(mFakeEventHub->getLedState(SECOND_EVENTHUB_ID, LED_NUML));
3669     ASSERT_TRUE(mFakeEventHub->getLedState(SECOND_EVENTHUB_ID, LED_SCROLLL));
3670     ASSERT_EQ(AMETA_CAPS_LOCK_ON | AMETA_NUM_LOCK_ON | AMETA_SCROLL_LOCK_ON,
3671               mapper2.getMetaState());
3672 }
3673 
TEST_F(KeyboardInputMapperTest,Process_toggleCapsLockState)3674 TEST_F(KeyboardInputMapperTest, Process_toggleCapsLockState) {
3675     mFakeEventHub->addKey(EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
3676     mFakeEventHub->addKey(EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
3677     mFakeEventHub->addKey(EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
3678 
3679     // Suppose we have two mappers. (DPAD + KEYBOARD)
3680     constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_DPAD,
3681                                                AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC);
3682     KeyboardInputMapper& mapper =
3683             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3684                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3685     // Initial metastate is AMETA_NONE.
3686     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3687 
3688     mReader->toggleCapsLockState(DEVICE_ID);
3689     ASSERT_EQ(AMETA_CAPS_LOCK_ON, mapper.getMetaState());
3690 }
3691 
TEST_F(KeyboardInputMapperTest,Process_LockedKeysShouldToggleInMultiDevices)3692 TEST_F(KeyboardInputMapperTest, Process_LockedKeysShouldToggleInMultiDevices) {
3693     // keyboard 1.
3694     mFakeEventHub->addLed(EVENTHUB_ID, LED_CAPSL, true /*initially on*/);
3695     mFakeEventHub->addLed(EVENTHUB_ID, LED_NUML, false /*initially off*/);
3696     mFakeEventHub->addLed(EVENTHUB_ID, LED_SCROLLL, false /*initially off*/);
3697     mFakeEventHub->addKey(EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
3698     mFakeEventHub->addKey(EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
3699     mFakeEventHub->addKey(EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
3700 
3701     KeyboardInputMapper& mapper1 =
3702             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3703                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3704 
3705     // keyboard 2.
3706     const std::string USB2 = "USB2";
3707     const std::string DEVICE_NAME2 = "KEYBOARD2";
3708     constexpr int32_t SECOND_DEVICE_ID = DEVICE_ID + 1;
3709     constexpr int32_t SECOND_EVENTHUB_ID = EVENTHUB_ID + 1;
3710     std::shared_ptr<InputDevice> device2 =
3711             newDevice(SECOND_DEVICE_ID, DEVICE_NAME2, USB2, SECOND_EVENTHUB_ID,
3712                       ftl::Flags<InputDeviceClass>(0));
3713     mFakeEventHub->addLed(SECOND_EVENTHUB_ID, LED_CAPSL, true /*initially on*/);
3714     mFakeEventHub->addLed(SECOND_EVENTHUB_ID, LED_NUML, false /*initially off*/);
3715     mFakeEventHub->addLed(SECOND_EVENTHUB_ID, LED_SCROLLL, false /*initially off*/);
3716     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
3717     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
3718     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
3719 
3720     device2->addEmptyEventHubDevice(SECOND_EVENTHUB_ID);
3721     KeyboardInputMapper& mapper2 =
3722             device2->constructAndAddMapper<KeyboardInputMapper>(SECOND_EVENTHUB_ID,
3723                                                                 mFakePolicy
3724                                                                         ->getReaderConfiguration(),
3725                                                                 AINPUT_SOURCE_KEYBOARD,
3726                                                                 AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3727     std::list<NotifyArgs> unused =
3728             device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3729                                /*changes=*/{});
3730     unused += device2->reset(ARBITRARY_TIME);
3731 
3732     // Initial metastate is AMETA_NONE.
3733     ASSERT_EQ(AMETA_NONE, mapper1.getMetaState());
3734     ASSERT_EQ(AMETA_NONE, mapper2.getMetaState());
3735 
3736     // Toggle num lock on and off.
3737     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 1);
3738     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 0);
3739     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3740     ASSERT_EQ(AMETA_NUM_LOCK_ON, mapper1.getMetaState());
3741     ASSERT_EQ(AMETA_NUM_LOCK_ON, mapper2.getMetaState());
3742 
3743     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 1);
3744     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 0);
3745     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3746     ASSERT_EQ(AMETA_NONE, mapper1.getMetaState());
3747     ASSERT_EQ(AMETA_NONE, mapper2.getMetaState());
3748 
3749     // Toggle caps lock on and off.
3750     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 1);
3751     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 0);
3752     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3753     ASSERT_EQ(AMETA_CAPS_LOCK_ON, mapper1.getMetaState());
3754     ASSERT_EQ(AMETA_CAPS_LOCK_ON, mapper2.getMetaState());
3755 
3756     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 1);
3757     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 0);
3758     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3759     ASSERT_EQ(AMETA_NONE, mapper1.getMetaState());
3760     ASSERT_EQ(AMETA_NONE, mapper2.getMetaState());
3761 
3762     // Toggle scroll lock on and off.
3763     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 1);
3764     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 0);
3765     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3766     ASSERT_EQ(AMETA_SCROLL_LOCK_ON, mapper1.getMetaState());
3767     ASSERT_EQ(AMETA_SCROLL_LOCK_ON, mapper2.getMetaState());
3768 
3769     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 1);
3770     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 0);
3771     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3772     ASSERT_EQ(AMETA_NONE, mapper1.getMetaState());
3773     ASSERT_EQ(AMETA_NONE, mapper2.getMetaState());
3774 }
3775 
TEST_F(KeyboardInputMapperTest,Process_DisabledDevice)3776 TEST_F(KeyboardInputMapperTest, Process_DisabledDevice) {
3777     const int32_t USAGE_A = 0x070004;
3778     mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, POLICY_FLAG_WAKE);
3779     mFakeEventHub->addKey(EVENTHUB_ID, 0, USAGE_A, AKEYCODE_A, POLICY_FLAG_WAKE);
3780 
3781     KeyboardInputMapper& mapper =
3782             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3783                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3784     // Key down by scan code.
3785     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_HOME, 1);
3786     NotifyKeyArgs args;
3787     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3788     ASSERT_EQ(DEVICE_ID, args.deviceId);
3789     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3790     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
3791     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3792     ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
3793     ASSERT_EQ(KEY_HOME, args.scanCode);
3794     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3795 
3796     // Disable device, it should synthesize cancellation events for down events.
3797     mFakePolicy->addDisabledDevice(DEVICE_ID);
3798     configureDevice(InputReaderConfiguration::Change::ENABLED_STATE);
3799 
3800     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3801     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3802     ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
3803     ASSERT_EQ(KEY_HOME, args.scanCode);
3804     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_CANCELED, args.flags);
3805 }
3806 
TEST_F(KeyboardInputMapperTest,Configure_AssignKeyboardLayoutInfo)3807 TEST_F(KeyboardInputMapperTest, Configure_AssignKeyboardLayoutInfo) {
3808     constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3809                                                AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3810     std::list<NotifyArgs> unused =
3811             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3812                                /*changes=*/{});
3813 
3814     uint32_t generation = mReader->getContext()->getGeneration();
3815     mFakePolicy->addKeyboardLayoutAssociation(DEVICE_LOCATION, DEVICE_KEYBOARD_LAYOUT_INFO);
3816 
3817     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3818                                  InputReaderConfiguration::Change::KEYBOARD_LAYOUT_ASSOCIATION);
3819 
3820     InputDeviceInfo deviceInfo = mDevice->getDeviceInfo();
3821     ASSERT_EQ(DEVICE_KEYBOARD_LAYOUT_INFO.languageTag,
3822               deviceInfo.getKeyboardLayoutInfo()->languageTag);
3823     ASSERT_EQ(DEVICE_KEYBOARD_LAYOUT_INFO.layoutType,
3824               deviceInfo.getKeyboardLayoutInfo()->layoutType);
3825     ASSERT_TRUE(mReader->getContext()->getGeneration() != generation);
3826 
3827     // Call change layout association with the same values: Generation shouldn't change
3828     generation = mReader->getContext()->getGeneration();
3829     mFakePolicy->addKeyboardLayoutAssociation(DEVICE_LOCATION, DEVICE_KEYBOARD_LAYOUT_INFO);
3830     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3831                                  InputReaderConfiguration::Change::KEYBOARD_LAYOUT_ASSOCIATION);
3832     ASSERT_TRUE(mReader->getContext()->getGeneration() == generation);
3833 }
3834 
TEST_F(KeyboardInputMapperTest,LayoutInfoCorrectlyMapped)3835 TEST_F(KeyboardInputMapperTest, LayoutInfoCorrectlyMapped) {
3836     mFakeEventHub->setRawLayoutInfo(EVENTHUB_ID,
3837                                     RawLayoutInfo{.languageTag = "en", .layoutType = "extended"});
3838 
3839     // Configuration
3840     constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3841                                                AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3842     InputReaderConfiguration config;
3843     std::list<NotifyArgs> unused = mDevice->configure(ARBITRARY_TIME, config, /*changes=*/{});
3844 
3845     ASSERT_EQ("en", mDevice->getDeviceInfo().getKeyboardLayoutInfo()->languageTag);
3846     ASSERT_EQ("extended", mDevice->getDeviceInfo().getKeyboardLayoutInfo()->layoutType);
3847 }
3848 
3849 // --- KeyboardInputMapperTest_ExternalDevice ---
3850 
3851 class KeyboardInputMapperTest_ExternalDevice : public InputMapperTest {
3852 protected:
SetUp()3853     void SetUp() override { InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::EXTERNAL); }
3854 };
3855 
TEST_F(KeyboardInputMapperTest_ExternalDevice,WakeBehavior)3856 TEST_F(KeyboardInputMapperTest_ExternalDevice, WakeBehavior) {
3857     // For external devices, keys will trigger wake on key down. Media keys should also trigger
3858     // wake if triggered from external devices.
3859 
3860     mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, 0);
3861     mFakeEventHub->addKey(EVENTHUB_ID, KEY_PLAY, 0, AKEYCODE_MEDIA_PLAY, 0);
3862     mFakeEventHub->addKey(EVENTHUB_ID, KEY_PLAYPAUSE, 0, AKEYCODE_MEDIA_PLAY_PAUSE,
3863                           POLICY_FLAG_WAKE);
3864 
3865     KeyboardInputMapper& mapper =
3866             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3867                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3868 
3869     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_HOME, 1);
3870     NotifyKeyArgs args;
3871     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3872     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3873 
3874     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_HOME, 0);
3875     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3876     ASSERT_EQ(uint32_t(0), args.policyFlags);
3877 
3878     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_PLAY, 1);
3879     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3880     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3881 
3882     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_PLAY, 0);
3883     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3884     ASSERT_EQ(uint32_t(0), args.policyFlags);
3885 
3886     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_PLAYPAUSE, 1);
3887     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3888     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3889 
3890     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_PLAYPAUSE, 0);
3891     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3892     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3893 }
3894 
TEST_F(KeyboardInputMapperTest_ExternalDevice,DoNotWakeByDefaultBehavior)3895 TEST_F(KeyboardInputMapperTest_ExternalDevice, DoNotWakeByDefaultBehavior) {
3896     // Tv Remote key's wake behavior is prescribed by the keylayout file.
3897 
3898     mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, POLICY_FLAG_WAKE);
3899     mFakeEventHub->addKey(EVENTHUB_ID, KEY_DOWN, 0, AKEYCODE_DPAD_DOWN, 0);
3900     mFakeEventHub->addKey(EVENTHUB_ID, KEY_PLAY, 0, AKEYCODE_MEDIA_PLAY, POLICY_FLAG_WAKE);
3901 
3902     addConfigurationProperty("keyboard.doNotWakeByDefault", "1");
3903     KeyboardInputMapper& mapper =
3904             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
3905                                                        AINPUT_KEYBOARD_TYPE_ALPHABETIC);
3906 
3907     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_HOME, 1);
3908     NotifyKeyArgs args;
3909     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3910     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3911 
3912     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_HOME, 0);
3913     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3914     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3915 
3916     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_DOWN, 1);
3917     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3918     ASSERT_EQ(uint32_t(0), args.policyFlags);
3919 
3920     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_DOWN, 0);
3921     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3922     ASSERT_EQ(uint32_t(0), args.policyFlags);
3923 
3924     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_PLAY, 1);
3925     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3926     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3927 
3928     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_PLAY, 0);
3929     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3930     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3931 }
3932 
3933 // --- CursorInputMapperTest ---
3934 
3935 class CursorInputMapperTest : public InputMapperTest {
3936 protected:
3937     static const int32_t TRACKBALL_MOVEMENT_THRESHOLD;
3938 
3939     std::shared_ptr<FakePointerController> mFakePointerController;
3940 
SetUp()3941     void SetUp() override {
3942         InputMapperTest::SetUp();
3943 
3944         mFakePointerController = std::make_shared<FakePointerController>();
3945         mFakePolicy->setPointerController(mFakePointerController);
3946     }
3947 
3948     void testMotionRotation(CursorInputMapper& mapper, int32_t originalX, int32_t originalY,
3949                             int32_t rotatedX, int32_t rotatedY);
3950 
prepareDisplay(ui::Rotation orientation)3951     void prepareDisplay(ui::Rotation orientation) {
3952         setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, orientation,
3953                                      DISPLAY_UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
3954     }
3955 
prepareSecondaryDisplay()3956     void prepareSecondaryDisplay() {
3957         setDisplayInfoAndReconfigure(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
3958                                      ui::ROTATION_0, SECONDARY_DISPLAY_UNIQUE_ID, NO_PORT,
3959                                      ViewportType::EXTERNAL);
3960     }
3961 
assertCursorPointerCoords(const PointerCoords & coords,float x,float y,float pressure)3962     static void assertCursorPointerCoords(const PointerCoords& coords, float x, float y,
3963                                           float pressure) {
3964         ASSERT_NO_FATAL_FAILURE(assertPointerCoords(coords, x, y, pressure, 0.0f, 0.0f, 0.0f, 0.0f,
3965                                                     0.0f, 0.0f, 0.0f, EPSILON));
3966     }
3967 };
3968 
3969 const int32_t CursorInputMapperTest::TRACKBALL_MOVEMENT_THRESHOLD = 6;
3970 
testMotionRotation(CursorInputMapper & mapper,int32_t originalX,int32_t originalY,int32_t rotatedX,int32_t rotatedY)3971 void CursorInputMapperTest::testMotionRotation(CursorInputMapper& mapper, int32_t originalX,
3972                                                int32_t originalY, int32_t rotatedX,
3973                                                int32_t rotatedY) {
3974     NotifyMotionArgs args;
3975 
3976     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, originalX);
3977     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, originalY);
3978     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
3979     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
3980     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
3981     ASSERT_NO_FATAL_FAILURE(
3982             assertCursorPointerCoords(args.pointerCoords[0],
3983                                       float(rotatedX) / TRACKBALL_MOVEMENT_THRESHOLD,
3984                                       float(rotatedY) / TRACKBALL_MOVEMENT_THRESHOLD, 0.0f));
3985 }
3986 
TEST_F(CursorInputMapperTest,WhenModeIsPointer_GetSources_ReturnsMouse)3987 TEST_F(CursorInputMapperTest, WhenModeIsPointer_GetSources_ReturnsMouse) {
3988     addConfigurationProperty("cursor.mode", "pointer");
3989     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
3990 
3991     ASSERT_EQ(AINPUT_SOURCE_MOUSE, mapper.getSources());
3992 }
3993 
TEST_F(CursorInputMapperTest,WhenModeIsNavigation_GetSources_ReturnsTrackball)3994 TEST_F(CursorInputMapperTest, WhenModeIsNavigation_GetSources_ReturnsTrackball) {
3995     addConfigurationProperty("cursor.mode", "navigation");
3996     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
3997 
3998     ASSERT_EQ(AINPUT_SOURCE_TRACKBALL, mapper.getSources());
3999 }
4000 
TEST_F(CursorInputMapperTest,WhenModeIsPointer_PopulateDeviceInfo_ReturnsRangeFromPointerController)4001 TEST_F(CursorInputMapperTest, WhenModeIsPointer_PopulateDeviceInfo_ReturnsRangeFromPointerController) {
4002     addConfigurationProperty("cursor.mode", "pointer");
4003     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4004 
4005     InputDeviceInfo info;
4006     mapper.populateDeviceInfo(info);
4007 
4008     // Initially there may not be a valid motion range.
4009     ASSERT_EQ(nullptr, info.getMotionRange(AINPUT_MOTION_RANGE_X, AINPUT_SOURCE_MOUSE));
4010     ASSERT_EQ(nullptr, info.getMotionRange(AINPUT_MOTION_RANGE_Y, AINPUT_SOURCE_MOUSE));
4011     ASSERT_NO_FATAL_FAILURE(assertMotionRange(info,
4012             AINPUT_MOTION_RANGE_PRESSURE, AINPUT_SOURCE_MOUSE, 0.0f, 1.0f, 0.0f, 0.0f));
4013 
4014     // When the bounds are set, then there should be a valid motion range.
4015     mFakePointerController->setBounds(1, 2, 800 - 1, 480 - 1);
4016 
4017     InputDeviceInfo info2;
4018     mapper.populateDeviceInfo(info2);
4019 
4020     ASSERT_NO_FATAL_FAILURE(assertMotionRange(info2,
4021             AINPUT_MOTION_RANGE_X, AINPUT_SOURCE_MOUSE,
4022             1, 800 - 1, 0.0f, 0.0f));
4023     ASSERT_NO_FATAL_FAILURE(assertMotionRange(info2,
4024             AINPUT_MOTION_RANGE_Y, AINPUT_SOURCE_MOUSE,
4025             2, 480 - 1, 0.0f, 0.0f));
4026     ASSERT_NO_FATAL_FAILURE(assertMotionRange(info2,
4027             AINPUT_MOTION_RANGE_PRESSURE, AINPUT_SOURCE_MOUSE,
4028             0.0f, 1.0f, 0.0f, 0.0f));
4029 }
4030 
TEST_F(CursorInputMapperTest,WhenModeIsNavigation_PopulateDeviceInfo_ReturnsScaledRange)4031 TEST_F(CursorInputMapperTest, WhenModeIsNavigation_PopulateDeviceInfo_ReturnsScaledRange) {
4032     addConfigurationProperty("cursor.mode", "navigation");
4033     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4034 
4035     InputDeviceInfo info;
4036     mapper.populateDeviceInfo(info);
4037 
4038     ASSERT_NO_FATAL_FAILURE(assertMotionRange(info,
4039             AINPUT_MOTION_RANGE_X, AINPUT_SOURCE_TRACKBALL,
4040             -1.0f, 1.0f, 0.0f, 1.0f / TRACKBALL_MOVEMENT_THRESHOLD));
4041     ASSERT_NO_FATAL_FAILURE(assertMotionRange(info,
4042             AINPUT_MOTION_RANGE_Y, AINPUT_SOURCE_TRACKBALL,
4043             -1.0f, 1.0f, 0.0f, 1.0f / TRACKBALL_MOVEMENT_THRESHOLD));
4044     ASSERT_NO_FATAL_FAILURE(assertMotionRange(info,
4045             AINPUT_MOTION_RANGE_PRESSURE, AINPUT_SOURCE_TRACKBALL,
4046             0.0f, 1.0f, 0.0f, 0.0f));
4047 }
4048 
TEST_F(CursorInputMapperTest,Process_ShouldSetAllFieldsAndIncludeGlobalMetaState)4049 TEST_F(CursorInputMapperTest, Process_ShouldSetAllFieldsAndIncludeGlobalMetaState) {
4050     addConfigurationProperty("cursor.mode", "navigation");
4051     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4052 
4053     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
4054 
4055     NotifyMotionArgs args;
4056 
4057     // Button press.
4058     // Mostly testing non x/y behavior here so we don't need to check again elsewhere.
4059     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_MOUSE, 1);
4060     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4061     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4062     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
4063     ASSERT_EQ(DEVICE_ID, args.deviceId);
4064     ASSERT_EQ(AINPUT_SOURCE_TRACKBALL, args.source);
4065     ASSERT_EQ(uint32_t(0), args.policyFlags);
4066     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
4067     ASSERT_EQ(0, args.flags);
4068     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
4069     ASSERT_EQ(AMOTION_EVENT_BUTTON_PRIMARY, args.buttonState);
4070     ASSERT_EQ(0, args.edgeFlags);
4071     ASSERT_EQ(uint32_t(1), args.getPointerCount());
4072     ASSERT_EQ(0, args.pointerProperties[0].id);
4073     ASSERT_EQ(ToolType::MOUSE, args.pointerProperties[0].toolType);
4074     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0], 0.0f, 0.0f, 1.0f));
4075     ASSERT_EQ(TRACKBALL_MOVEMENT_THRESHOLD, args.xPrecision);
4076     ASSERT_EQ(TRACKBALL_MOVEMENT_THRESHOLD, args.yPrecision);
4077     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
4078 
4079     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4080     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
4081     ASSERT_EQ(DEVICE_ID, args.deviceId);
4082     ASSERT_EQ(AINPUT_SOURCE_TRACKBALL, args.source);
4083     ASSERT_EQ(uint32_t(0), args.policyFlags);
4084     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, args.action);
4085     ASSERT_EQ(0, args.flags);
4086     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
4087     ASSERT_EQ(AMOTION_EVENT_BUTTON_PRIMARY, args.buttonState);
4088     ASSERT_EQ(0, args.edgeFlags);
4089     ASSERT_EQ(uint32_t(1), args.getPointerCount());
4090     ASSERT_EQ(0, args.pointerProperties[0].id);
4091     ASSERT_EQ(ToolType::MOUSE, args.pointerProperties[0].toolType);
4092     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0], 0.0f, 0.0f, 1.0f));
4093     ASSERT_EQ(TRACKBALL_MOVEMENT_THRESHOLD, args.xPrecision);
4094     ASSERT_EQ(TRACKBALL_MOVEMENT_THRESHOLD, args.yPrecision);
4095     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
4096 
4097     // Button release.  Should have same down time.
4098     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, BTN_MOUSE, 0);
4099     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_SYN, SYN_REPORT, 0);
4100     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4101     ASSERT_EQ(ARBITRARY_TIME + 1, args.eventTime);
4102     ASSERT_EQ(DEVICE_ID, args.deviceId);
4103     ASSERT_EQ(AINPUT_SOURCE_TRACKBALL, args.source);
4104     ASSERT_EQ(uint32_t(0), args.policyFlags);
4105     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, args.action);
4106     ASSERT_EQ(0, args.flags);
4107     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
4108     ASSERT_EQ(0, args.buttonState);
4109     ASSERT_EQ(0, args.edgeFlags);
4110     ASSERT_EQ(uint32_t(1), args.getPointerCount());
4111     ASSERT_EQ(0, args.pointerProperties[0].id);
4112     ASSERT_EQ(ToolType::MOUSE, args.pointerProperties[0].toolType);
4113     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0], 0.0f, 0.0f, 0.0f));
4114     ASSERT_EQ(TRACKBALL_MOVEMENT_THRESHOLD, args.xPrecision);
4115     ASSERT_EQ(TRACKBALL_MOVEMENT_THRESHOLD, args.yPrecision);
4116     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
4117 
4118     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4119     ASSERT_EQ(ARBITRARY_TIME + 1, args.eventTime);
4120     ASSERT_EQ(DEVICE_ID, args.deviceId);
4121     ASSERT_EQ(AINPUT_SOURCE_TRACKBALL, args.source);
4122     ASSERT_EQ(uint32_t(0), args.policyFlags);
4123     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
4124     ASSERT_EQ(0, args.flags);
4125     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
4126     ASSERT_EQ(0, args.buttonState);
4127     ASSERT_EQ(0, args.edgeFlags);
4128     ASSERT_EQ(uint32_t(1), args.getPointerCount());
4129     ASSERT_EQ(0, args.pointerProperties[0].id);
4130     ASSERT_EQ(ToolType::MOUSE, args.pointerProperties[0].toolType);
4131     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0], 0.0f, 0.0f, 0.0f));
4132     ASSERT_EQ(TRACKBALL_MOVEMENT_THRESHOLD, args.xPrecision);
4133     ASSERT_EQ(TRACKBALL_MOVEMENT_THRESHOLD, args.yPrecision);
4134     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
4135 }
4136 
TEST_F(CursorInputMapperTest,Process_ShouldHandleIndependentXYUpdates)4137 TEST_F(CursorInputMapperTest, Process_ShouldHandleIndependentXYUpdates) {
4138     addConfigurationProperty("cursor.mode", "navigation");
4139     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4140 
4141     NotifyMotionArgs args;
4142 
4143     // Motion in X but not Y.
4144     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 1);
4145     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4146     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4147     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
4148     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0],
4149                                                       1.0f / TRACKBALL_MOVEMENT_THRESHOLD, 0.0f,
4150                                                       0.0f));
4151 
4152     // Motion in Y but not X.
4153     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, -2);
4154     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4155     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4156     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
4157     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0], 0.0f,
4158                                                       -2.0f / TRACKBALL_MOVEMENT_THRESHOLD, 0.0f));
4159 }
4160 
TEST_F(CursorInputMapperTest,Process_ShouldHandleIndependentButtonUpdates)4161 TEST_F(CursorInputMapperTest, Process_ShouldHandleIndependentButtonUpdates) {
4162     addConfigurationProperty("cursor.mode", "navigation");
4163     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4164 
4165     NotifyMotionArgs args;
4166 
4167     // Button press.
4168     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_MOUSE, 1);
4169     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4170     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4171     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
4172     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0], 0.0f, 0.0f, 1.0f));
4173 
4174     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4175     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, args.action);
4176     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0], 0.0f, 0.0f, 1.0f));
4177 
4178     // Button release.
4179     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_MOUSE, 0);
4180     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4181     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4182     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, args.action);
4183     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0], 0.0f, 0.0f, 0.0f));
4184 
4185     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4186     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
4187     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0], 0.0f, 0.0f, 0.0f));
4188 }
4189 
TEST_F(CursorInputMapperTest,Process_ShouldHandleCombinedXYAndButtonUpdates)4190 TEST_F(CursorInputMapperTest, Process_ShouldHandleCombinedXYAndButtonUpdates) {
4191     addConfigurationProperty("cursor.mode", "navigation");
4192     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4193 
4194     NotifyMotionArgs args;
4195 
4196     // Combined X, Y and Button.
4197     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 1);
4198     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, -2);
4199     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_MOUSE, 1);
4200     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4201     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4202     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
4203     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0],
4204                                                       1.0f / TRACKBALL_MOVEMENT_THRESHOLD,
4205                                                       -2.0f / TRACKBALL_MOVEMENT_THRESHOLD, 1.0f));
4206 
4207     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4208     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, args.action);
4209     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0],
4210                                                       1.0f / TRACKBALL_MOVEMENT_THRESHOLD,
4211                                                       -2.0f / TRACKBALL_MOVEMENT_THRESHOLD, 1.0f));
4212 
4213     // Move X, Y a bit while pressed.
4214     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 2);
4215     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 1);
4216     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4217     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4218     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
4219     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0],
4220                                                       2.0f / TRACKBALL_MOVEMENT_THRESHOLD,
4221                                                       1.0f / TRACKBALL_MOVEMENT_THRESHOLD, 1.0f));
4222 
4223     // Release Button.
4224     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_MOUSE, 0);
4225     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4226     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4227     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, args.action);
4228     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0], 0.0f, 0.0f, 0.0f));
4229 
4230     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4231     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
4232     ASSERT_NO_FATAL_FAILURE(assertCursorPointerCoords(args.pointerCoords[0], 0.0f, 0.0f, 0.0f));
4233 }
4234 
TEST_F(CursorInputMapperTest,Process_WhenOrientationAware_ShouldNotRotateMotions)4235 TEST_F(CursorInputMapperTest, Process_WhenOrientationAware_ShouldNotRotateMotions) {
4236     mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, DISPLAY_UNIQUE_ID);
4237     addConfigurationProperty("cursor.mode", "navigation");
4238     // InputReader works in the un-rotated coordinate space, so orientation-aware devices do not
4239     // need to be rotated.
4240     addConfigurationProperty("cursor.orientationAware", "1");
4241     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4242 
4243     prepareDisplay(ui::ROTATION_90);
4244     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  0,  1,  0,  1));
4245     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1,  1,  1,  1));
4246     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1,  0,  1,  0));
4247     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1, -1,  1, -1));
4248     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  0, -1,  0, -1));
4249     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, -1, -1, -1));
4250     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1,  0, -1,  0));
4251     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1,  1, -1,  1));
4252 }
4253 
TEST_F(CursorInputMapperTest,Process_WhenNotOrientationAware_ShouldRotateMotions)4254 TEST_F(CursorInputMapperTest, Process_WhenNotOrientationAware_ShouldRotateMotions) {
4255     mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, DISPLAY_UNIQUE_ID);
4256     addConfigurationProperty("cursor.mode", "navigation");
4257     // Since InputReader works in the un-rotated coordinate space, only devices that are not
4258     // orientation-aware are affected by display rotation.
4259     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4260 
4261     clearViewports();
4262     prepareDisplay(ui::ROTATION_0);
4263     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  0,  1,  0,  1));
4264     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1,  1,  1,  1));
4265     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1,  0,  1,  0));
4266     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1, -1,  1, -1));
4267     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  0, -1,  0, -1));
4268     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, -1, -1, -1));
4269     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1,  0, -1,  0));
4270     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1,  1, -1,  1));
4271 
4272     clearViewports();
4273     prepareDisplay(ui::ROTATION_90);
4274     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  0,  1, -1,  0));
4275     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1,  1, -1,  1));
4276     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1,  0,  0,  1));
4277     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1, -1,  1,  1));
4278     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  0, -1,  1,  0));
4279     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, -1,  1, -1));
4280     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1,  0,  0, -1));
4281     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1,  1, -1, -1));
4282 
4283     clearViewports();
4284     prepareDisplay(ui::ROTATION_180);
4285     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  0,  1,  0, -1));
4286     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1,  1, -1, -1));
4287     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1,  0, -1,  0));
4288     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1, -1, -1,  1));
4289     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  0, -1,  0,  1));
4290     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, -1,  1,  1));
4291     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1,  0,  1,  0));
4292     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1,  1,  1, -1));
4293 
4294     clearViewports();
4295     prepareDisplay(ui::ROTATION_270);
4296     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  0,  1,  1,  0));
4297     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1,  1,  1, -1));
4298     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1,  0,  0, -1));
4299     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  1, -1, -1, -1));
4300     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper,  0, -1, -1,  0));
4301     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, -1, -1,  1));
4302     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1,  0,  0,  1));
4303     ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1,  1,  1,  1));
4304 }
4305 
TEST_F(CursorInputMapperTest,Process_ShouldHandleAllButtons)4306 TEST_F(CursorInputMapperTest, Process_ShouldHandleAllButtons) {
4307     addConfigurationProperty("cursor.mode", "pointer");
4308     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4309 
4310     mFakePointerController->setBounds(0, 0, 800 - 1, 480 - 1);
4311     mFakePointerController->setPosition(100, 200);
4312 
4313     NotifyMotionArgs motionArgs;
4314     NotifyKeyArgs keyArgs;
4315 
4316     // press BTN_LEFT, release BTN_LEFT
4317     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_LEFT, 1);
4318     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4319     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4320     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
4321     ASSERT_EQ(AMOTION_EVENT_BUTTON_PRIMARY, motionArgs.buttonState);
4322     ASSERT_NO_FATAL_FAILURE(
4323             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 1.0f));
4324 
4325     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4326     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
4327     ASSERT_EQ(AMOTION_EVENT_BUTTON_PRIMARY, motionArgs.buttonState);
4328     ASSERT_NO_FATAL_FAILURE(
4329             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 1.0f));
4330 
4331     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_LEFT, 0);
4332     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4333     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4334     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
4335     ASSERT_EQ(0, motionArgs.buttonState);
4336     ASSERT_NO_FATAL_FAILURE(
4337             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4338 
4339     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4340     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
4341     ASSERT_EQ(0, motionArgs.buttonState);
4342     ASSERT_NO_FATAL_FAILURE(
4343             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4344 
4345     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4346     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
4347     ASSERT_EQ(0, motionArgs.buttonState);
4348     ASSERT_NO_FATAL_FAILURE(
4349             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4350 
4351     // press BTN_RIGHT + BTN_MIDDLE, release BTN_RIGHT, release BTN_MIDDLE
4352     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_RIGHT, 1);
4353     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_MIDDLE, 1);
4354     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4355     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4356     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
4357     ASSERT_EQ(AMOTION_EVENT_BUTTON_SECONDARY | AMOTION_EVENT_BUTTON_TERTIARY,
4358               motionArgs.buttonState);
4359     ASSERT_NO_FATAL_FAILURE(
4360             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 1.0f));
4361 
4362     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4363     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
4364     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
4365     ASSERT_NO_FATAL_FAILURE(
4366             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 1.0f));
4367 
4368     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4369     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
4370     ASSERT_EQ(AMOTION_EVENT_BUTTON_SECONDARY | AMOTION_EVENT_BUTTON_TERTIARY,
4371               motionArgs.buttonState);
4372     ASSERT_NO_FATAL_FAILURE(
4373             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 1.0f));
4374 
4375     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_RIGHT, 0);
4376     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4377     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4378     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
4379     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
4380     ASSERT_NO_FATAL_FAILURE(
4381             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 1.0f));
4382 
4383     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4384     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
4385     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
4386     ASSERT_NO_FATAL_FAILURE(
4387             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 1.0f));
4388 
4389     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_MIDDLE, 0);
4390     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4391     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4392     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
4393     ASSERT_EQ(0, motionArgs.buttonState);
4394     ASSERT_NO_FATAL_FAILURE(
4395             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4396     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_MIDDLE, 0);
4397     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4398 
4399     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4400     ASSERT_EQ(0, motionArgs.buttonState);
4401     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
4402     ASSERT_NO_FATAL_FAILURE(
4403             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4404 
4405     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4406     ASSERT_EQ(0, motionArgs.buttonState);
4407     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
4408     ASSERT_NO_FATAL_FAILURE(
4409             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4410 
4411     // press BTN_BACK, release BTN_BACK
4412     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_BACK, 1);
4413     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4414     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
4415     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
4416     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
4417 
4418     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4419     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
4420     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
4421     ASSERT_NO_FATAL_FAILURE(
4422             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4423 
4424     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4425     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
4426     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
4427     ASSERT_NO_FATAL_FAILURE(
4428             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4429 
4430     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_BACK, 0);
4431     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4432     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4433     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
4434     ASSERT_EQ(0, motionArgs.buttonState);
4435     ASSERT_NO_FATAL_FAILURE(
4436             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4437 
4438     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4439     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
4440     ASSERT_EQ(0, motionArgs.buttonState);
4441 
4442     ASSERT_NO_FATAL_FAILURE(
4443             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4444     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
4445     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
4446     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
4447 
4448     // press BTN_SIDE, release BTN_SIDE
4449     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_SIDE, 1);
4450     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4451     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
4452     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
4453     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
4454 
4455     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4456     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
4457     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
4458     ASSERT_NO_FATAL_FAILURE(
4459             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4460 
4461     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4462     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
4463     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
4464     ASSERT_NO_FATAL_FAILURE(
4465             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4466 
4467     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_SIDE, 0);
4468     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4469     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4470     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
4471     ASSERT_EQ(0, motionArgs.buttonState);
4472     ASSERT_NO_FATAL_FAILURE(
4473             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4474 
4475     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4476     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
4477     ASSERT_EQ(0, motionArgs.buttonState);
4478     ASSERT_NO_FATAL_FAILURE(
4479             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4480 
4481     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
4482     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
4483     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
4484 
4485     // press BTN_FORWARD, release BTN_FORWARD
4486     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_FORWARD, 1);
4487     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4488     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
4489     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
4490     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
4491 
4492     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4493     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
4494     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
4495     ASSERT_NO_FATAL_FAILURE(
4496             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4497 
4498     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4499     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
4500     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
4501     ASSERT_NO_FATAL_FAILURE(
4502             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4503 
4504     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_FORWARD, 0);
4505     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4506     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4507     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
4508     ASSERT_EQ(0, motionArgs.buttonState);
4509     ASSERT_NO_FATAL_FAILURE(
4510             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4511 
4512     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4513     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
4514     ASSERT_EQ(0, motionArgs.buttonState);
4515     ASSERT_NO_FATAL_FAILURE(
4516             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4517 
4518     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
4519     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
4520     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
4521 
4522     // press BTN_EXTRA, release BTN_EXTRA
4523     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_EXTRA, 1);
4524     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4525     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
4526     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
4527     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
4528 
4529     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4530     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
4531     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
4532     ASSERT_NO_FATAL_FAILURE(
4533             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4534 
4535     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4536     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
4537     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
4538     ASSERT_NO_FATAL_FAILURE(
4539             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4540 
4541     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_EXTRA, 0);
4542     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4543     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4544     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
4545     ASSERT_EQ(0, motionArgs.buttonState);
4546     ASSERT_NO_FATAL_FAILURE(
4547             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4548 
4549     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4550     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
4551     ASSERT_EQ(0, motionArgs.buttonState);
4552     ASSERT_NO_FATAL_FAILURE(
4553             assertCursorPointerCoords(motionArgs.pointerCoords[0], 100.0f, 200.0f, 0.0f));
4554 
4555     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
4556     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
4557     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
4558 }
4559 
TEST_F(CursorInputMapperTest,Process_WhenModeIsPointer_ShouldMoveThePointerAround)4560 TEST_F(CursorInputMapperTest, Process_WhenModeIsPointer_ShouldMoveThePointerAround) {
4561     addConfigurationProperty("cursor.mode", "pointer");
4562     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4563 
4564     mFakePointerController->setBounds(0, 0, 800 - 1, 480 - 1);
4565     mFakePointerController->setPosition(100, 200);
4566 
4567     NotifyMotionArgs args;
4568 
4569     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
4570     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
4571     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4572     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4573     ASSERT_EQ(AINPUT_SOURCE_MOUSE, args.source);
4574     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, args.action);
4575     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
4576             110.0f, 220.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f));
4577     ASSERT_NO_FATAL_FAILURE(mFakePointerController->assertPosition(110.0f, 220.0f));
4578 }
4579 
TEST_F(CursorInputMapperTest,Process_PointerCapture)4580 TEST_F(CursorInputMapperTest, Process_PointerCapture) {
4581     addConfigurationProperty("cursor.mode", "pointer");
4582     mFakePolicy->setPointerCapture(true);
4583     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4584 
4585     NotifyDeviceResetArgs resetArgs;
4586     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
4587     ASSERT_EQ(ARBITRARY_TIME, resetArgs.eventTime);
4588     ASSERT_EQ(DEVICE_ID, resetArgs.deviceId);
4589 
4590     mFakePointerController->setBounds(0, 0, 800 - 1, 480 - 1);
4591     mFakePointerController->setPosition(100, 200);
4592 
4593     NotifyMotionArgs args;
4594 
4595     // Move.
4596     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
4597     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
4598     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4599     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4600     ASSERT_EQ(AINPUT_SOURCE_MOUSE_RELATIVE, args.source);
4601     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
4602     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
4603             10.0f, 20.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f));
4604     ASSERT_NO_FATAL_FAILURE(mFakePointerController->assertPosition(100.0f, 200.0f));
4605 
4606     // Button press.
4607     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_MOUSE, 1);
4608     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4609     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4610     ASSERT_EQ(AINPUT_SOURCE_MOUSE_RELATIVE, args.source);
4611     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
4612     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
4613             0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f));
4614     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4615     ASSERT_EQ(AINPUT_SOURCE_MOUSE_RELATIVE, args.source);
4616     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, args.action);
4617     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
4618             0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f));
4619 
4620     // Button release.
4621     process(mapper, ARBITRARY_TIME + 2, READ_TIME, EV_KEY, BTN_MOUSE, 0);
4622     process(mapper, ARBITRARY_TIME + 2, READ_TIME, EV_SYN, SYN_REPORT, 0);
4623     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4624     ASSERT_EQ(AINPUT_SOURCE_MOUSE_RELATIVE, args.source);
4625     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, args.action);
4626     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
4627             0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f));
4628     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4629     ASSERT_EQ(AINPUT_SOURCE_MOUSE_RELATIVE, args.source);
4630     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
4631     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
4632             0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f));
4633 
4634     // Another move.
4635     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 30);
4636     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 40);
4637     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4638     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4639     ASSERT_EQ(AINPUT_SOURCE_MOUSE_RELATIVE, args.source);
4640     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
4641     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
4642             30.0f, 40.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f));
4643     ASSERT_NO_FATAL_FAILURE(mFakePointerController->assertPosition(100.0f, 200.0f));
4644 
4645     // Disable pointer capture and check that the device generation got bumped
4646     // and events are generated the usual way.
4647     const uint32_t generation = mReader->getContext()->getGeneration();
4648     mFakePolicy->setPointerCapture(false);
4649     configureDevice(InputReaderConfiguration::Change::POINTER_CAPTURE);
4650     ASSERT_TRUE(mReader->getContext()->getGeneration() != generation);
4651 
4652     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
4653     ASSERT_EQ(DEVICE_ID, resetArgs.deviceId);
4654 
4655     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
4656     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
4657     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4658     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4659     ASSERT_EQ(AINPUT_SOURCE_MOUSE, args.source);
4660     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, args.action);
4661     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
4662             110.0f, 220.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f));
4663     ASSERT_NO_FATAL_FAILURE(mFakePointerController->assertPosition(110.0f, 220.0f));
4664 }
4665 
4666 /**
4667  * When Pointer Capture is enabled, we expect to report unprocessed relative movements, so any
4668  * pointer acceleration or speed processing should not be applied.
4669  */
TEST_F(CursorInputMapperTest,PointerCaptureDisablesVelocityProcessing)4670 TEST_F(CursorInputMapperTest, PointerCaptureDisablesVelocityProcessing) {
4671     addConfigurationProperty("cursor.mode", "pointer");
4672     const VelocityControlParameters testParams(/*scale=*/5.f, /*low threshold=*/0.f,
4673                                                /*high threshold=*/100.f, /*acceleration=*/10.f);
4674     mFakePolicy->setVelocityControlParams(testParams);
4675     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4676 
4677     NotifyDeviceResetArgs resetArgs;
4678     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
4679     ASSERT_EQ(ARBITRARY_TIME, resetArgs.eventTime);
4680     ASSERT_EQ(DEVICE_ID, resetArgs.deviceId);
4681 
4682     NotifyMotionArgs args;
4683 
4684     // Move and verify scale is applied.
4685     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
4686     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
4687     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4688     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4689     ASSERT_EQ(AINPUT_SOURCE_MOUSE, args.source);
4690     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, args.action);
4691     const float relX = args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X);
4692     const float relY = args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y);
4693     ASSERT_GT(relX, 10);
4694     ASSERT_GT(relY, 20);
4695 
4696     // Enable Pointer Capture
4697     mFakePolicy->setPointerCapture(true);
4698     configureDevice(InputReaderConfiguration::Change::POINTER_CAPTURE);
4699     NotifyPointerCaptureChangedArgs captureArgs;
4700     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyCaptureWasCalled(&captureArgs));
4701     ASSERT_TRUE(captureArgs.request.enable);
4702 
4703     // Move and verify scale is not applied.
4704     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
4705     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
4706     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4707     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4708     ASSERT_EQ(AINPUT_SOURCE_MOUSE_RELATIVE, args.source);
4709     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
4710     ASSERT_EQ(10, args.pointerCoords[0].getX());
4711     ASSERT_EQ(20, args.pointerCoords[0].getY());
4712 }
4713 
TEST_F(CursorInputMapperTest,PointerCaptureDisablesOrientationChanges)4714 TEST_F(CursorInputMapperTest, PointerCaptureDisablesOrientationChanges) {
4715     addConfigurationProperty("cursor.mode", "pointer");
4716     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4717 
4718     NotifyDeviceResetArgs resetArgs;
4719     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
4720     ASSERT_EQ(ARBITRARY_TIME, resetArgs.eventTime);
4721     ASSERT_EQ(DEVICE_ID, resetArgs.deviceId);
4722 
4723     // Ensure the display is rotated.
4724     prepareDisplay(ui::ROTATION_90);
4725 
4726     NotifyMotionArgs args;
4727 
4728     // Verify that the coordinates are rotated.
4729     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
4730     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
4731     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4732     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4733     ASSERT_EQ(AINPUT_SOURCE_MOUSE, args.source);
4734     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, args.action);
4735     ASSERT_EQ(-20, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X));
4736     ASSERT_EQ(10, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y));
4737 
4738     // Enable Pointer Capture.
4739     mFakePolicy->setPointerCapture(true);
4740     configureDevice(InputReaderConfiguration::Change::POINTER_CAPTURE);
4741     NotifyPointerCaptureChangedArgs captureArgs;
4742     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyCaptureWasCalled(&captureArgs));
4743     ASSERT_TRUE(captureArgs.request.enable);
4744 
4745     // Move and verify rotation is not applied.
4746     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
4747     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
4748     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4749     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
4750     ASSERT_EQ(AINPUT_SOURCE_MOUSE_RELATIVE, args.source);
4751     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
4752     ASSERT_EQ(10, args.pointerCoords[0].getX());
4753     ASSERT_EQ(20, args.pointerCoords[0].getY());
4754 }
4755 
TEST_F(CursorInputMapperTest,ConfigureDisplayId_NoAssociatedViewport)4756 TEST_F(CursorInputMapperTest, ConfigureDisplayId_NoAssociatedViewport) {
4757     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4758 
4759     // Set up the default display.
4760     prepareDisplay(ui::ROTATION_90);
4761 
4762     // Set up the secondary display as the display on which the pointer should be shown.
4763     // The InputDevice is not associated with any display.
4764     prepareSecondaryDisplay();
4765     mFakePolicy->setDefaultPointerDisplayId(SECONDARY_DISPLAY_ID);
4766     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
4767 
4768     mFakePointerController->setBounds(0, 0, DISPLAY_WIDTH - 1, DISPLAY_HEIGHT - 1);
4769     mFakePointerController->setPosition(100, 200);
4770 
4771     // Ensure input events are generated for the secondary display.
4772     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
4773     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
4774     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4775     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
4776             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
4777                   WithSource(AINPUT_SOURCE_MOUSE), WithDisplayId(SECONDARY_DISPLAY_ID),
4778                   WithCoords(110.0f, 220.0f))));
4779     ASSERT_NO_FATAL_FAILURE(mFakePointerController->assertPosition(110.0f, 220.0f));
4780 }
4781 
TEST_F(CursorInputMapperTest,ConfigureDisplayId_WithAssociatedViewport)4782 TEST_F(CursorInputMapperTest, ConfigureDisplayId_WithAssociatedViewport) {
4783     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4784 
4785     // Set up the default display.
4786     prepareDisplay(ui::ROTATION_90);
4787 
4788     // Set up the secondary display as the display on which the pointer should be shown,
4789     // and associate the InputDevice with the secondary display.
4790     prepareSecondaryDisplay();
4791     mFakePolicy->setDefaultPointerDisplayId(SECONDARY_DISPLAY_ID);
4792     mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, SECONDARY_DISPLAY_UNIQUE_ID);
4793     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
4794 
4795     mFakePointerController->setBounds(0, 0, DISPLAY_WIDTH - 1, DISPLAY_HEIGHT - 1);
4796     mFakePointerController->setPosition(100, 200);
4797 
4798     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
4799     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
4800     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4801     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
4802             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
4803                   WithSource(AINPUT_SOURCE_MOUSE), WithDisplayId(SECONDARY_DISPLAY_ID),
4804                   WithCoords(110.0f, 220.0f))));
4805     ASSERT_NO_FATAL_FAILURE(mFakePointerController->assertPosition(110.0f, 220.0f));
4806 }
4807 
TEST_F(CursorInputMapperTest,ConfigureDisplayId_IgnoresEventsForMismatchedPointerDisplay)4808 TEST_F(CursorInputMapperTest, ConfigureDisplayId_IgnoresEventsForMismatchedPointerDisplay) {
4809     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4810 
4811     // Set up the default display as the display on which the pointer should be shown.
4812     prepareDisplay(ui::ROTATION_90);
4813     mFakePolicy->setDefaultPointerDisplayId(DISPLAY_ID);
4814 
4815     // Associate the InputDevice with the secondary display.
4816     prepareSecondaryDisplay();
4817     mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, SECONDARY_DISPLAY_UNIQUE_ID);
4818     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
4819 
4820     // The mapper should not generate any events because it is associated with a display that is
4821     // different from the pointer display.
4822     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
4823     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
4824     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4825     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
4826 }
4827 
4828 // --- BluetoothCursorInputMapperTest ---
4829 
4830 class BluetoothCursorInputMapperTest : public CursorInputMapperTest {
4831 protected:
SetUp()4832     void SetUp() override {
4833         InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::EXTERNAL, BUS_BLUETOOTH);
4834 
4835         mFakePointerController = std::make_shared<FakePointerController>();
4836         mFakePolicy->setPointerController(mFakePointerController);
4837     }
4838 };
4839 
TEST_F(BluetoothCursorInputMapperTest,TimestampSmoothening)4840 TEST_F(BluetoothCursorInputMapperTest, TimestampSmoothening) {
4841     addConfigurationProperty("cursor.mode", "pointer");
4842     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4843 
4844     nsecs_t kernelEventTime = ARBITRARY_TIME;
4845     nsecs_t expectedEventTime = ARBITRARY_TIME;
4846     process(mapper, kernelEventTime, READ_TIME, EV_REL, REL_X, 1);
4847     process(mapper, kernelEventTime, READ_TIME, EV_SYN, SYN_REPORT, 0);
4848     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
4849             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
4850                   WithEventTime(expectedEventTime))));
4851 
4852     // Process several events that come in quick succession, according to their timestamps.
4853     for (int i = 0; i < 3; i++) {
4854         constexpr static nsecs_t delta = ms2ns(1);
4855         static_assert(delta < MIN_BLUETOOTH_TIMESTAMP_DELTA);
4856         kernelEventTime += delta;
4857         expectedEventTime += MIN_BLUETOOTH_TIMESTAMP_DELTA;
4858 
4859         process(mapper, kernelEventTime, READ_TIME, EV_REL, REL_X, 1);
4860         process(mapper, kernelEventTime, READ_TIME, EV_SYN, SYN_REPORT, 0);
4861         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
4862                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
4863                       WithEventTime(expectedEventTime))));
4864     }
4865 }
4866 
TEST_F(BluetoothCursorInputMapperTest,TimestampSmootheningIsCapped)4867 TEST_F(BluetoothCursorInputMapperTest, TimestampSmootheningIsCapped) {
4868     addConfigurationProperty("cursor.mode", "pointer");
4869     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4870 
4871     nsecs_t expectedEventTime = ARBITRARY_TIME;
4872     process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 1);
4873     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4874     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
4875             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
4876                   WithEventTime(expectedEventTime))));
4877 
4878     // Process several events with the same timestamp from the kernel.
4879     // Ensure that we do not generate events too far into the future.
4880     constexpr static int32_t numEvents =
4881             MAX_BLUETOOTH_SMOOTHING_DELTA / MIN_BLUETOOTH_TIMESTAMP_DELTA;
4882     for (int i = 0; i < numEvents; i++) {
4883         expectedEventTime += MIN_BLUETOOTH_TIMESTAMP_DELTA;
4884 
4885         process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 1);
4886         process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4887         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
4888                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
4889                       WithEventTime(expectedEventTime))));
4890     }
4891 
4892     // By processing more events with the same timestamp, we should not generate events with a
4893     // timestamp that is more than the specified max time delta from the timestamp at its injection.
4894     const nsecs_t cappedEventTime = ARBITRARY_TIME + MAX_BLUETOOTH_SMOOTHING_DELTA;
4895     for (int i = 0; i < 3; i++) {
4896         process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 1);
4897         process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4898         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
4899                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
4900                       WithEventTime(cappedEventTime))));
4901     }
4902 }
4903 
TEST_F(BluetoothCursorInputMapperTest,TimestampSmootheningNotUsed)4904 TEST_F(BluetoothCursorInputMapperTest, TimestampSmootheningNotUsed) {
4905     addConfigurationProperty("cursor.mode", "pointer");
4906     CursorInputMapper& mapper = constructAndAddMapper<CursorInputMapper>();
4907 
4908     nsecs_t kernelEventTime = ARBITRARY_TIME;
4909     nsecs_t expectedEventTime = ARBITRARY_TIME;
4910     process(mapper, kernelEventTime, READ_TIME, EV_REL, REL_X, 1);
4911     process(mapper, kernelEventTime, READ_TIME, EV_SYN, SYN_REPORT, 0);
4912     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
4913             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
4914                   WithEventTime(expectedEventTime))));
4915 
4916     // If the next event has a timestamp that is sufficiently spaced out so that Bluetooth timestamp
4917     // smoothening is not needed, its timestamp is not affected.
4918     kernelEventTime += MAX_BLUETOOTH_SMOOTHING_DELTA + ms2ns(1);
4919     expectedEventTime = kernelEventTime;
4920 
4921     process(mapper, kernelEventTime, READ_TIME, EV_REL, REL_X, 1);
4922     process(mapper, kernelEventTime, READ_TIME, EV_SYN, SYN_REPORT, 0);
4923     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
4924             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
4925                   WithEventTime(expectedEventTime))));
4926 }
4927 
4928 // --- TouchInputMapperTest ---
4929 
4930 class TouchInputMapperTest : public InputMapperTest {
4931 protected:
4932     static const int32_t RAW_X_MIN;
4933     static const int32_t RAW_X_MAX;
4934     static const int32_t RAW_Y_MIN;
4935     static const int32_t RAW_Y_MAX;
4936     static const int32_t RAW_TOUCH_MIN;
4937     static const int32_t RAW_TOUCH_MAX;
4938     static const int32_t RAW_TOOL_MIN;
4939     static const int32_t RAW_TOOL_MAX;
4940     static const int32_t RAW_PRESSURE_MIN;
4941     static const int32_t RAW_PRESSURE_MAX;
4942     static const int32_t RAW_ORIENTATION_MIN;
4943     static const int32_t RAW_ORIENTATION_MAX;
4944     static const int32_t RAW_DISTANCE_MIN;
4945     static const int32_t RAW_DISTANCE_MAX;
4946     static const int32_t RAW_TILT_MIN;
4947     static const int32_t RAW_TILT_MAX;
4948     static const int32_t RAW_ID_MIN;
4949     static const int32_t RAW_ID_MAX;
4950     static const int32_t RAW_SLOT_MIN;
4951     static const int32_t RAW_SLOT_MAX;
4952     static const float X_PRECISION;
4953     static const float Y_PRECISION;
4954     static const float X_PRECISION_VIRTUAL;
4955     static const float Y_PRECISION_VIRTUAL;
4956 
4957     static const float GEOMETRIC_SCALE;
4958     static const TouchAffineTransformation AFFINE_TRANSFORM;
4959 
4960     static const VirtualKeyDefinition VIRTUAL_KEYS[2];
4961 
4962     const std::string UNIQUE_ID = "local:0";
4963     const std::string SECONDARY_UNIQUE_ID = "local:1";
4964 
4965     enum Axes {
4966         POSITION = 1 << 0,
4967         TOUCH = 1 << 1,
4968         TOOL = 1 << 2,
4969         PRESSURE = 1 << 3,
4970         ORIENTATION = 1 << 4,
4971         MINOR = 1 << 5,
4972         ID = 1 << 6,
4973         DISTANCE = 1 << 7,
4974         TILT = 1 << 8,
4975         SLOT = 1 << 9,
4976         TOOL_TYPE = 1 << 10,
4977     };
4978 
4979     void prepareDisplay(ui::Rotation orientation, std::optional<uint8_t> port = NO_PORT);
4980     void prepareSecondaryDisplay(ViewportType type, std::optional<uint8_t> port = NO_PORT);
4981     void prepareVirtualDisplay(ui::Rotation orientation);
4982     void prepareVirtualKeys();
4983     void prepareLocationCalibration();
4984     int32_t toRawX(float displayX);
4985     int32_t toRawY(float displayY);
4986     int32_t toRotatedRawX(float displayX);
4987     int32_t toRotatedRawY(float displayY);
4988     float toCookedX(float rawX, float rawY);
4989     float toCookedY(float rawX, float rawY);
4990     float toDisplayX(int32_t rawX);
4991     float toDisplayX(int32_t rawX, int32_t displayWidth);
4992     float toDisplayY(int32_t rawY);
4993     float toDisplayY(int32_t rawY, int32_t displayHeight);
4994 
4995 };
4996 
4997 const int32_t TouchInputMapperTest::RAW_X_MIN = 25;
4998 const int32_t TouchInputMapperTest::RAW_X_MAX = 1019;
4999 const int32_t TouchInputMapperTest::RAW_Y_MIN = 30;
5000 const int32_t TouchInputMapperTest::RAW_Y_MAX = 1009;
5001 const int32_t TouchInputMapperTest::RAW_TOUCH_MIN = 0;
5002 const int32_t TouchInputMapperTest::RAW_TOUCH_MAX = 31;
5003 const int32_t TouchInputMapperTest::RAW_TOOL_MIN = 0;
5004 const int32_t TouchInputMapperTest::RAW_TOOL_MAX = 15;
5005 const int32_t TouchInputMapperTest::RAW_PRESSURE_MIN = 0;
5006 const int32_t TouchInputMapperTest::RAW_PRESSURE_MAX = 255;
5007 const int32_t TouchInputMapperTest::RAW_ORIENTATION_MIN = -7;
5008 const int32_t TouchInputMapperTest::RAW_ORIENTATION_MAX = 7;
5009 const int32_t TouchInputMapperTest::RAW_DISTANCE_MIN = 0;
5010 const int32_t TouchInputMapperTest::RAW_DISTANCE_MAX = 7;
5011 const int32_t TouchInputMapperTest::RAW_TILT_MIN = 0;
5012 const int32_t TouchInputMapperTest::RAW_TILT_MAX = 150;
5013 const int32_t TouchInputMapperTest::RAW_ID_MIN = 0;
5014 const int32_t TouchInputMapperTest::RAW_ID_MAX = 9;
5015 const int32_t TouchInputMapperTest::RAW_SLOT_MIN = 0;
5016 const int32_t TouchInputMapperTest::RAW_SLOT_MAX = 9;
5017 const float TouchInputMapperTest::X_PRECISION = float(RAW_X_MAX - RAW_X_MIN + 1) / DISPLAY_WIDTH;
5018 const float TouchInputMapperTest::Y_PRECISION = float(RAW_Y_MAX - RAW_Y_MIN + 1) / DISPLAY_HEIGHT;
5019 const float TouchInputMapperTest::X_PRECISION_VIRTUAL =
5020         float(RAW_X_MAX - RAW_X_MIN + 1) / VIRTUAL_DISPLAY_WIDTH;
5021 const float TouchInputMapperTest::Y_PRECISION_VIRTUAL =
5022         float(RAW_Y_MAX - RAW_Y_MIN + 1) / VIRTUAL_DISPLAY_HEIGHT;
5023 const TouchAffineTransformation TouchInputMapperTest::AFFINE_TRANSFORM =
5024         TouchAffineTransformation(1, -2, 3, -4, 5, -6);
5025 
5026 const float TouchInputMapperTest::GEOMETRIC_SCALE =
5027         avg(float(DISPLAY_WIDTH) / (RAW_X_MAX - RAW_X_MIN + 1),
5028                 float(DISPLAY_HEIGHT) / (RAW_Y_MAX - RAW_Y_MIN + 1));
5029 
5030 const VirtualKeyDefinition TouchInputMapperTest::VIRTUAL_KEYS[2] = {
5031         { KEY_HOME, 60, DISPLAY_HEIGHT + 15, 20, 20 },
5032         { KEY_MENU, DISPLAY_HEIGHT - 60, DISPLAY_WIDTH + 15, 20, 20 },
5033 };
5034 
prepareDisplay(ui::Rotation orientation,std::optional<uint8_t> port)5035 void TouchInputMapperTest::prepareDisplay(ui::Rotation orientation, std::optional<uint8_t> port) {
5036     setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, orientation, UNIQUE_ID,
5037                                  port, ViewportType::INTERNAL);
5038 }
5039 
prepareSecondaryDisplay(ViewportType type,std::optional<uint8_t> port)5040 void TouchInputMapperTest::prepareSecondaryDisplay(ViewportType type, std::optional<uint8_t> port) {
5041     setDisplayInfoAndReconfigure(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
5042                                  ui::ROTATION_0, SECONDARY_UNIQUE_ID, port, type);
5043 }
5044 
prepareVirtualDisplay(ui::Rotation orientation)5045 void TouchInputMapperTest::prepareVirtualDisplay(ui::Rotation orientation) {
5046     setDisplayInfoAndReconfigure(VIRTUAL_DISPLAY_ID, VIRTUAL_DISPLAY_WIDTH, VIRTUAL_DISPLAY_HEIGHT,
5047                                  orientation, VIRTUAL_DISPLAY_UNIQUE_ID, NO_PORT,
5048                                  ViewportType::VIRTUAL);
5049 }
5050 
prepareVirtualKeys()5051 void TouchInputMapperTest::prepareVirtualKeys() {
5052     mFakeEventHub->addVirtualKeyDefinition(EVENTHUB_ID, VIRTUAL_KEYS[0]);
5053     mFakeEventHub->addVirtualKeyDefinition(EVENTHUB_ID, VIRTUAL_KEYS[1]);
5054     mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, POLICY_FLAG_WAKE);
5055     mFakeEventHub->addKey(EVENTHUB_ID, KEY_MENU, 0, AKEYCODE_MENU, POLICY_FLAG_WAKE);
5056 }
5057 
prepareLocationCalibration()5058 void TouchInputMapperTest::prepareLocationCalibration() {
5059     mFakePolicy->setTouchAffineTransformation(AFFINE_TRANSFORM);
5060 }
5061 
toRawX(float displayX)5062 int32_t TouchInputMapperTest::toRawX(float displayX) {
5063     return int32_t(displayX * (RAW_X_MAX - RAW_X_MIN + 1) / DISPLAY_WIDTH + RAW_X_MIN);
5064 }
5065 
toRawY(float displayY)5066 int32_t TouchInputMapperTest::toRawY(float displayY) {
5067     return int32_t(displayY * (RAW_Y_MAX - RAW_Y_MIN + 1) / DISPLAY_HEIGHT + RAW_Y_MIN);
5068 }
5069 
toRotatedRawX(float displayX)5070 int32_t TouchInputMapperTest::toRotatedRawX(float displayX) {
5071     return int32_t(displayX * (RAW_X_MAX - RAW_X_MIN + 1) / DISPLAY_HEIGHT + RAW_X_MIN);
5072 }
5073 
toRotatedRawY(float displayY)5074 int32_t TouchInputMapperTest::toRotatedRawY(float displayY) {
5075     return int32_t(displayY * (RAW_Y_MAX - RAW_Y_MIN + 1) / DISPLAY_WIDTH + RAW_Y_MIN);
5076 }
5077 
toCookedX(float rawX,float rawY)5078 float TouchInputMapperTest::toCookedX(float rawX, float rawY) {
5079     AFFINE_TRANSFORM.applyTo(rawX, rawY);
5080     return rawX;
5081 }
5082 
toCookedY(float rawX,float rawY)5083 float TouchInputMapperTest::toCookedY(float rawX, float rawY) {
5084     AFFINE_TRANSFORM.applyTo(rawX, rawY);
5085     return rawY;
5086 }
5087 
toDisplayX(int32_t rawX)5088 float TouchInputMapperTest::toDisplayX(int32_t rawX) {
5089     return toDisplayX(rawX, DISPLAY_WIDTH);
5090 }
5091 
toDisplayX(int32_t rawX,int32_t displayWidth)5092 float TouchInputMapperTest::toDisplayX(int32_t rawX, int32_t displayWidth) {
5093     return float(rawX - RAW_X_MIN) * displayWidth / (RAW_X_MAX - RAW_X_MIN + 1);
5094 }
5095 
toDisplayY(int32_t rawY)5096 float TouchInputMapperTest::toDisplayY(int32_t rawY) {
5097     return toDisplayY(rawY, DISPLAY_HEIGHT);
5098 }
5099 
toDisplayY(int32_t rawY,int32_t displayHeight)5100 float TouchInputMapperTest::toDisplayY(int32_t rawY, int32_t displayHeight) {
5101     return float(rawY - RAW_Y_MIN) * displayHeight / (RAW_Y_MAX - RAW_Y_MIN + 1);
5102 }
5103 
5104 
5105 // --- SingleTouchInputMapperTest ---
5106 
5107 class SingleTouchInputMapperTest : public TouchInputMapperTest {
5108 protected:
5109     void prepareButtons();
5110     void prepareAxes(int axes);
5111 
5112     void processDown(SingleTouchInputMapper& mapper, int32_t x, int32_t y);
5113     void processMove(SingleTouchInputMapper& mapper, int32_t x, int32_t y);
5114     void processUp(SingleTouchInputMapper& mappery);
5115     void processPressure(SingleTouchInputMapper& mapper, int32_t pressure);
5116     void processToolMajor(SingleTouchInputMapper& mapper, int32_t toolMajor);
5117     void processDistance(SingleTouchInputMapper& mapper, int32_t distance);
5118     void processTilt(SingleTouchInputMapper& mapper, int32_t tiltX, int32_t tiltY);
5119     void processKey(SingleTouchInputMapper& mapper, int32_t code, int32_t value);
5120     void processSync(SingleTouchInputMapper& mapper);
5121 };
5122 
prepareButtons()5123 void SingleTouchInputMapperTest::prepareButtons() {
5124     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOUCH, 0, AKEYCODE_UNKNOWN, 0);
5125 }
5126 
prepareAxes(int axes)5127 void SingleTouchInputMapperTest::prepareAxes(int axes) {
5128     if (axes & POSITION) {
5129         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_X, RAW_X_MIN, RAW_X_MAX, 0, 0);
5130         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_Y, RAW_Y_MIN, RAW_Y_MAX, 0, 0);
5131     }
5132     if (axes & PRESSURE) {
5133         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_PRESSURE, RAW_PRESSURE_MIN,
5134                                        RAW_PRESSURE_MAX, 0, 0);
5135     }
5136     if (axes & TOOL) {
5137         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_TOOL_WIDTH, RAW_TOOL_MIN, RAW_TOOL_MAX, 0,
5138                                        0);
5139     }
5140     if (axes & DISTANCE) {
5141         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_DISTANCE, RAW_DISTANCE_MIN,
5142                                        RAW_DISTANCE_MAX, 0, 0);
5143     }
5144     if (axes & TILT) {
5145         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_TILT_X, RAW_TILT_MIN, RAW_TILT_MAX, 0, 0);
5146         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_TILT_Y, RAW_TILT_MIN, RAW_TILT_MAX, 0, 0);
5147     }
5148 }
5149 
processDown(SingleTouchInputMapper & mapper,int32_t x,int32_t y)5150 void SingleTouchInputMapperTest::processDown(SingleTouchInputMapper& mapper, int32_t x, int32_t y) {
5151     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_TOUCH, 1);
5152     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_X, x);
5153     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_Y, y);
5154 }
5155 
processMove(SingleTouchInputMapper & mapper,int32_t x,int32_t y)5156 void SingleTouchInputMapperTest::processMove(SingleTouchInputMapper& mapper, int32_t x, int32_t y) {
5157     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_X, x);
5158     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_Y, y);
5159 }
5160 
processUp(SingleTouchInputMapper & mapper)5161 void SingleTouchInputMapperTest::processUp(SingleTouchInputMapper& mapper) {
5162     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_TOUCH, 0);
5163 }
5164 
processPressure(SingleTouchInputMapper & mapper,int32_t pressure)5165 void SingleTouchInputMapperTest::processPressure(SingleTouchInputMapper& mapper, int32_t pressure) {
5166     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_PRESSURE, pressure);
5167 }
5168 
processToolMajor(SingleTouchInputMapper & mapper,int32_t toolMajor)5169 void SingleTouchInputMapperTest::processToolMajor(SingleTouchInputMapper& mapper,
5170                                                   int32_t toolMajor) {
5171     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_TOOL_WIDTH, toolMajor);
5172 }
5173 
processDistance(SingleTouchInputMapper & mapper,int32_t distance)5174 void SingleTouchInputMapperTest::processDistance(SingleTouchInputMapper& mapper, int32_t distance) {
5175     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_DISTANCE, distance);
5176 }
5177 
processTilt(SingleTouchInputMapper & mapper,int32_t tiltX,int32_t tiltY)5178 void SingleTouchInputMapperTest::processTilt(SingleTouchInputMapper& mapper, int32_t tiltX,
5179                                              int32_t tiltY) {
5180     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_TILT_X, tiltX);
5181     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_TILT_Y, tiltY);
5182 }
5183 
processKey(SingleTouchInputMapper & mapper,int32_t code,int32_t value)5184 void SingleTouchInputMapperTest::processKey(SingleTouchInputMapper& mapper, int32_t code,
5185                                             int32_t value) {
5186     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, code, value);
5187 }
5188 
processSync(SingleTouchInputMapper & mapper)5189 void SingleTouchInputMapperTest::processSync(SingleTouchInputMapper& mapper) {
5190     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
5191 }
5192 
TEST_F(SingleTouchInputMapperTest,GetSources_WhenDeviceTypeIsNotSpecifiedAndNotACursor_ReturnsPointer)5193 TEST_F(SingleTouchInputMapperTest, GetSources_WhenDeviceTypeIsNotSpecifiedAndNotACursor_ReturnsPointer) {
5194     prepareButtons();
5195     prepareAxes(POSITION);
5196     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5197 
5198     ASSERT_EQ(AINPUT_SOURCE_MOUSE, mapper.getSources());
5199 }
5200 
TEST_F(SingleTouchInputMapperTest,GetSources_WhenDeviceTypeIsTouchScreen_ReturnsTouchScreen)5201 TEST_F(SingleTouchInputMapperTest, GetSources_WhenDeviceTypeIsTouchScreen_ReturnsTouchScreen) {
5202     prepareButtons();
5203     prepareAxes(POSITION);
5204     addConfigurationProperty("touch.deviceType", "touchScreen");
5205     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5206 
5207     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, mapper.getSources());
5208 }
5209 
TEST_F(SingleTouchInputMapperTest,GetKeyCodeState)5210 TEST_F(SingleTouchInputMapperTest, GetKeyCodeState) {
5211     addConfigurationProperty("touch.deviceType", "touchScreen");
5212     prepareDisplay(ui::ROTATION_0);
5213     prepareButtons();
5214     prepareAxes(POSITION);
5215     prepareVirtualKeys();
5216     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5217 
5218     // Unknown key.
5219     ASSERT_EQ(AKEY_STATE_UNKNOWN, mapper.getKeyCodeState(AINPUT_SOURCE_ANY, AKEYCODE_A));
5220 
5221     // Virtual key is down.
5222     int32_t x = toRawX(VIRTUAL_KEYS[0].centerX);
5223     int32_t y = toRawY(VIRTUAL_KEYS[0].centerY);
5224     processDown(mapper, x, y);
5225     processSync(mapper);
5226     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled());
5227 
5228     ASSERT_EQ(AKEY_STATE_VIRTUAL, mapper.getKeyCodeState(AINPUT_SOURCE_ANY, AKEYCODE_HOME));
5229 
5230     // Virtual key is up.
5231     processUp(mapper);
5232     processSync(mapper);
5233     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled());
5234 
5235     ASSERT_EQ(AKEY_STATE_UP, mapper.getKeyCodeState(AINPUT_SOURCE_ANY, AKEYCODE_HOME));
5236 }
5237 
TEST_F(SingleTouchInputMapperTest,GetScanCodeState)5238 TEST_F(SingleTouchInputMapperTest, GetScanCodeState) {
5239     addConfigurationProperty("touch.deviceType", "touchScreen");
5240     prepareDisplay(ui::ROTATION_0);
5241     prepareButtons();
5242     prepareAxes(POSITION);
5243     prepareVirtualKeys();
5244     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5245 
5246     // Unknown key.
5247     ASSERT_EQ(AKEY_STATE_UNKNOWN, mapper.getScanCodeState(AINPUT_SOURCE_ANY, KEY_A));
5248 
5249     // Virtual key is down.
5250     int32_t x = toRawX(VIRTUAL_KEYS[0].centerX);
5251     int32_t y = toRawY(VIRTUAL_KEYS[0].centerY);
5252     processDown(mapper, x, y);
5253     processSync(mapper);
5254     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled());
5255 
5256     ASSERT_EQ(AKEY_STATE_VIRTUAL, mapper.getScanCodeState(AINPUT_SOURCE_ANY, KEY_HOME));
5257 
5258     // Virtual key is up.
5259     processUp(mapper);
5260     processSync(mapper);
5261     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled());
5262 
5263     ASSERT_EQ(AKEY_STATE_UP, mapper.getScanCodeState(AINPUT_SOURCE_ANY, KEY_HOME));
5264 }
5265 
TEST_F(SingleTouchInputMapperTest,MarkSupportedKeyCodes)5266 TEST_F(SingleTouchInputMapperTest, MarkSupportedKeyCodes) {
5267     addConfigurationProperty("touch.deviceType", "touchScreen");
5268     prepareDisplay(ui::ROTATION_0);
5269     prepareButtons();
5270     prepareAxes(POSITION);
5271     prepareVirtualKeys();
5272     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5273 
5274     uint8_t flags[2] = { 0, 0 };
5275     ASSERT_TRUE(
5276             mapper.markSupportedKeyCodes(AINPUT_SOURCE_ANY, {AKEYCODE_HOME, AKEYCODE_A}, flags));
5277     ASSERT_TRUE(flags[0]);
5278     ASSERT_FALSE(flags[1]);
5279 }
5280 
TEST_F(SingleTouchInputMapperTest,Process_WhenVirtualKeyIsPressedAndReleasedNormally_SendsKeyDownAndKeyUp)5281 TEST_F(SingleTouchInputMapperTest, Process_WhenVirtualKeyIsPressedAndReleasedNormally_SendsKeyDownAndKeyUp) {
5282     addConfigurationProperty("touch.deviceType", "touchScreen");
5283     prepareDisplay(ui::ROTATION_0);
5284     prepareButtons();
5285     prepareAxes(POSITION);
5286     prepareVirtualKeys();
5287     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5288 
5289     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
5290 
5291     NotifyKeyArgs args;
5292 
5293     // Press virtual key.
5294     int32_t x = toRawX(VIRTUAL_KEYS[0].centerX);
5295     int32_t y = toRawY(VIRTUAL_KEYS[0].centerY);
5296     processDown(mapper, x, y);
5297     processSync(mapper);
5298 
5299     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
5300     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
5301     ASSERT_EQ(DEVICE_ID, args.deviceId);
5302     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
5303     ASSERT_EQ(POLICY_FLAG_VIRTUAL, args.policyFlags);
5304     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
5305     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY, args.flags);
5306     ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
5307     ASSERT_EQ(KEY_HOME, args.scanCode);
5308     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
5309     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
5310 
5311     // Release virtual key.
5312     processUp(mapper);
5313     processSync(mapper);
5314 
5315     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
5316     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
5317     ASSERT_EQ(DEVICE_ID, args.deviceId);
5318     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
5319     ASSERT_EQ(POLICY_FLAG_VIRTUAL, args.policyFlags);
5320     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
5321     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY, args.flags);
5322     ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
5323     ASSERT_EQ(KEY_HOME, args.scanCode);
5324     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
5325     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
5326 
5327     // Should not have sent any motions.
5328     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
5329 }
5330 
TEST_F(SingleTouchInputMapperTest,Process_WhenVirtualKeyIsPressedAndMovedOutOfBounds_SendsKeyDownAndKeyCancel)5331 TEST_F(SingleTouchInputMapperTest, Process_WhenVirtualKeyIsPressedAndMovedOutOfBounds_SendsKeyDownAndKeyCancel) {
5332     addConfigurationProperty("touch.deviceType", "touchScreen");
5333     prepareDisplay(ui::ROTATION_0);
5334     prepareButtons();
5335     prepareAxes(POSITION);
5336     prepareVirtualKeys();
5337     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5338 
5339     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
5340 
5341     NotifyKeyArgs keyArgs;
5342 
5343     // Press virtual key.
5344     int32_t x = toRawX(VIRTUAL_KEYS[0].centerX);
5345     int32_t y = toRawY(VIRTUAL_KEYS[0].centerY);
5346     processDown(mapper, x, y);
5347     processSync(mapper);
5348 
5349     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
5350     ASSERT_EQ(ARBITRARY_TIME, keyArgs.eventTime);
5351     ASSERT_EQ(DEVICE_ID, keyArgs.deviceId);
5352     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, keyArgs.source);
5353     ASSERT_EQ(POLICY_FLAG_VIRTUAL, keyArgs.policyFlags);
5354     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
5355     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY, keyArgs.flags);
5356     ASSERT_EQ(AKEYCODE_HOME, keyArgs.keyCode);
5357     ASSERT_EQ(KEY_HOME, keyArgs.scanCode);
5358     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, keyArgs.metaState);
5359     ASSERT_EQ(ARBITRARY_TIME, keyArgs.downTime);
5360 
5361     // Move out of bounds.  This should generate a cancel and a pointer down since we moved
5362     // into the display area.
5363     y -= 100;
5364     processMove(mapper, x, y);
5365     processSync(mapper);
5366 
5367     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
5368     ASSERT_EQ(ARBITRARY_TIME, keyArgs.eventTime);
5369     ASSERT_EQ(DEVICE_ID, keyArgs.deviceId);
5370     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, keyArgs.source);
5371     ASSERT_EQ(POLICY_FLAG_VIRTUAL, keyArgs.policyFlags);
5372     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
5373     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
5374             | AKEY_EVENT_FLAG_CANCELED, keyArgs.flags);
5375     ASSERT_EQ(AKEYCODE_HOME, keyArgs.keyCode);
5376     ASSERT_EQ(KEY_HOME, keyArgs.scanCode);
5377     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, keyArgs.metaState);
5378     ASSERT_EQ(ARBITRARY_TIME, keyArgs.downTime);
5379 
5380     NotifyMotionArgs motionArgs;
5381     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5382     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5383     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5384     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5385     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5386     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
5387     ASSERT_EQ(0, motionArgs.flags);
5388     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5389     ASSERT_EQ(0, motionArgs.buttonState);
5390     ASSERT_EQ(0, motionArgs.edgeFlags);
5391     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5392     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5393     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5394     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5395             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
5396     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
5397     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
5398     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5399 
5400     // Keep moving out of bounds.  Should generate a pointer move.
5401     y -= 50;
5402     processMove(mapper, x, y);
5403     processSync(mapper);
5404 
5405     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5406     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5407     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5408     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5409     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5410     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5411     ASSERT_EQ(0, motionArgs.flags);
5412     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5413     ASSERT_EQ(0, motionArgs.buttonState);
5414     ASSERT_EQ(0, motionArgs.edgeFlags);
5415     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5416     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5417     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5418     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5419             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
5420     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
5421     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
5422     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5423 
5424     // Release out of bounds.  Should generate a pointer up.
5425     processUp(mapper);
5426     processSync(mapper);
5427 
5428     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5429     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5430     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5431     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5432     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5433     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
5434     ASSERT_EQ(0, motionArgs.flags);
5435     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5436     ASSERT_EQ(0, motionArgs.buttonState);
5437     ASSERT_EQ(0, motionArgs.edgeFlags);
5438     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5439     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5440     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5441     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5442             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
5443     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
5444     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
5445     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5446 
5447     // Should not have sent any more keys or motions.
5448     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
5449     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
5450 }
5451 
TEST_F(SingleTouchInputMapperTest,Process_WhenTouchStartsOutsideDisplayAndMovesIn_SendsDownAsTouchEntersDisplay)5452 TEST_F(SingleTouchInputMapperTest, Process_WhenTouchStartsOutsideDisplayAndMovesIn_SendsDownAsTouchEntersDisplay) {
5453     addConfigurationProperty("touch.deviceType", "touchScreen");
5454     prepareDisplay(ui::ROTATION_0);
5455     prepareButtons();
5456     prepareAxes(POSITION);
5457     prepareVirtualKeys();
5458     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5459 
5460     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
5461 
5462     NotifyMotionArgs motionArgs;
5463 
5464     // Initially go down out of bounds.
5465     int32_t x = -10;
5466     int32_t y = -10;
5467     processDown(mapper, x, y);
5468     processSync(mapper);
5469 
5470     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
5471 
5472     // Move into the display area.  Should generate a pointer down.
5473     x = 50;
5474     y = 75;
5475     processMove(mapper, x, y);
5476     processSync(mapper);
5477 
5478     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5479     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5480     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5481     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5482     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5483     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
5484     ASSERT_EQ(0, motionArgs.flags);
5485     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5486     ASSERT_EQ(0, motionArgs.buttonState);
5487     ASSERT_EQ(0, motionArgs.edgeFlags);
5488     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5489     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5490     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5491     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5492             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
5493     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
5494     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
5495     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5496 
5497     // Release.  Should generate a pointer up.
5498     processUp(mapper);
5499     processSync(mapper);
5500 
5501     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5502     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5503     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5504     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5505     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5506     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
5507     ASSERT_EQ(0, motionArgs.flags);
5508     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5509     ASSERT_EQ(0, motionArgs.buttonState);
5510     ASSERT_EQ(0, motionArgs.edgeFlags);
5511     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5512     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5513     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5514     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5515             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
5516     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
5517     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
5518     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5519 
5520     // Should not have sent any more keys or motions.
5521     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
5522     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
5523 }
5524 
TEST_F(SingleTouchInputMapperTest,Process_NormalSingleTouchGesture_VirtualDisplay)5525 TEST_F(SingleTouchInputMapperTest, Process_NormalSingleTouchGesture_VirtualDisplay) {
5526     addConfigurationProperty("touch.deviceType", "touchScreen");
5527     addConfigurationProperty("touch.displayId", VIRTUAL_DISPLAY_UNIQUE_ID);
5528 
5529     prepareVirtualDisplay(ui::ROTATION_0);
5530     prepareButtons();
5531     prepareAxes(POSITION);
5532     prepareVirtualKeys();
5533     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5534 
5535     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
5536 
5537     NotifyMotionArgs motionArgs;
5538 
5539     // Down.
5540     int32_t x = 100;
5541     int32_t y = 125;
5542     processDown(mapper, x, y);
5543     processSync(mapper);
5544 
5545     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5546     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5547     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5548     ASSERT_EQ(VIRTUAL_DISPLAY_ID, motionArgs.displayId);
5549     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5550     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5551     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
5552     ASSERT_EQ(0, motionArgs.flags);
5553     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5554     ASSERT_EQ(0, motionArgs.buttonState);
5555     ASSERT_EQ(0, motionArgs.edgeFlags);
5556     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5557     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5558     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5559     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5560             toDisplayX(x, VIRTUAL_DISPLAY_WIDTH), toDisplayY(y, VIRTUAL_DISPLAY_HEIGHT),
5561             1, 0, 0, 0, 0, 0, 0, 0));
5562     ASSERT_NEAR(X_PRECISION_VIRTUAL, motionArgs.xPrecision, EPSILON);
5563     ASSERT_NEAR(Y_PRECISION_VIRTUAL, motionArgs.yPrecision, EPSILON);
5564     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5565 
5566     // Move.
5567     x += 50;
5568     y += 75;
5569     processMove(mapper, x, y);
5570     processSync(mapper);
5571 
5572     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5573     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5574     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5575     ASSERT_EQ(VIRTUAL_DISPLAY_ID, motionArgs.displayId);
5576     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5577     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5578     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5579     ASSERT_EQ(0, motionArgs.flags);
5580     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5581     ASSERT_EQ(0, motionArgs.buttonState);
5582     ASSERT_EQ(0, motionArgs.edgeFlags);
5583     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5584     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5585     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5586     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5587             toDisplayX(x, VIRTUAL_DISPLAY_WIDTH), toDisplayY(y, VIRTUAL_DISPLAY_HEIGHT),
5588             1, 0, 0, 0, 0, 0, 0, 0));
5589     ASSERT_NEAR(X_PRECISION_VIRTUAL, motionArgs.xPrecision, EPSILON);
5590     ASSERT_NEAR(Y_PRECISION_VIRTUAL, motionArgs.yPrecision, EPSILON);
5591     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5592 
5593     // Up.
5594     processUp(mapper);
5595     processSync(mapper);
5596 
5597     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5598     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5599     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5600     ASSERT_EQ(VIRTUAL_DISPLAY_ID, motionArgs.displayId);
5601     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5602     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5603     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
5604     ASSERT_EQ(0, motionArgs.flags);
5605     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5606     ASSERT_EQ(0, motionArgs.buttonState);
5607     ASSERT_EQ(0, motionArgs.edgeFlags);
5608     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5609     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5610     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5611     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5612             toDisplayX(x, VIRTUAL_DISPLAY_WIDTH), toDisplayY(y, VIRTUAL_DISPLAY_HEIGHT),
5613             1, 0, 0, 0, 0, 0, 0, 0));
5614     ASSERT_NEAR(X_PRECISION_VIRTUAL, motionArgs.xPrecision, EPSILON);
5615     ASSERT_NEAR(Y_PRECISION_VIRTUAL, motionArgs.yPrecision, EPSILON);
5616     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5617 
5618     // Should not have sent any more keys or motions.
5619     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
5620     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
5621 }
5622 
TEST_F(SingleTouchInputMapperTest,Process_NormalSingleTouchGesture)5623 TEST_F(SingleTouchInputMapperTest, Process_NormalSingleTouchGesture) {
5624     addConfigurationProperty("touch.deviceType", "touchScreen");
5625     prepareDisplay(ui::ROTATION_0);
5626     prepareButtons();
5627     prepareAxes(POSITION);
5628     prepareVirtualKeys();
5629     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5630 
5631     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
5632 
5633     NotifyMotionArgs motionArgs;
5634 
5635     // Down.
5636     int32_t x = 100;
5637     int32_t y = 125;
5638     processDown(mapper, x, y);
5639     processSync(mapper);
5640 
5641     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5642     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5643     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5644     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5645     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5646     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
5647     ASSERT_EQ(0, motionArgs.flags);
5648     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5649     ASSERT_EQ(0, motionArgs.buttonState);
5650     ASSERT_EQ(0, motionArgs.edgeFlags);
5651     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5652     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5653     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5654     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5655             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
5656     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
5657     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
5658     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5659 
5660     // Move.
5661     x += 50;
5662     y += 75;
5663     processMove(mapper, x, y);
5664     processSync(mapper);
5665 
5666     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5667     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5668     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5669     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5670     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5671     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5672     ASSERT_EQ(0, motionArgs.flags);
5673     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5674     ASSERT_EQ(0, motionArgs.buttonState);
5675     ASSERT_EQ(0, motionArgs.edgeFlags);
5676     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5677     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5678     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5679     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5680             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
5681     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
5682     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
5683     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5684 
5685     // Up.
5686     processUp(mapper);
5687     processSync(mapper);
5688 
5689     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5690     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5691     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5692     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5693     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5694     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
5695     ASSERT_EQ(0, motionArgs.flags);
5696     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5697     ASSERT_EQ(0, motionArgs.buttonState);
5698     ASSERT_EQ(0, motionArgs.edgeFlags);
5699     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5700     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5701     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5702     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5703             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
5704     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
5705     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
5706     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5707 
5708     // Should not have sent any more keys or motions.
5709     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
5710     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
5711 }
5712 
TEST_F(SingleTouchInputMapperTest,Process_WhenOrientationAware_DoesNotRotateMotions)5713 TEST_F(SingleTouchInputMapperTest, Process_WhenOrientationAware_DoesNotRotateMotions) {
5714     addConfigurationProperty("touch.deviceType", "touchScreen");
5715     prepareButtons();
5716     prepareAxes(POSITION);
5717     // InputReader works in the un-rotated coordinate space, so orientation-aware devices do not
5718     // need to be rotated. Touchscreens are orientation-aware by default.
5719     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5720 
5721     NotifyMotionArgs args;
5722 
5723     // Rotation 90.
5724     prepareDisplay(ui::ROTATION_90);
5725     processDown(mapper, toRawX(50), toRawY(75));
5726     processSync(mapper);
5727 
5728     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5729     ASSERT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5730     ASSERT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5731 
5732     processUp(mapper);
5733     processSync(mapper);
5734     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5735 }
5736 
TEST_F(SingleTouchInputMapperTest,Process_WhenNotOrientationAware_RotatesMotions)5737 TEST_F(SingleTouchInputMapperTest, Process_WhenNotOrientationAware_RotatesMotions) {
5738     addConfigurationProperty("touch.deviceType", "touchScreen");
5739     prepareButtons();
5740     prepareAxes(POSITION);
5741     // Since InputReader works in the un-rotated coordinate space, only devices that are not
5742     // orientation-aware are affected by display rotation.
5743     addConfigurationProperty("touch.orientationAware", "0");
5744     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5745 
5746     NotifyMotionArgs args;
5747 
5748     // Rotation 0.
5749     clearViewports();
5750     prepareDisplay(ui::ROTATION_0);
5751     processDown(mapper, toRawX(50), toRawY(75));
5752     processSync(mapper);
5753 
5754     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5755     ASSERT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5756     ASSERT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5757 
5758     processUp(mapper);
5759     processSync(mapper);
5760     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5761 
5762     // Rotation 90.
5763     clearViewports();
5764     prepareDisplay(ui::ROTATION_90);
5765     processDown(mapper, toRotatedRawX(75), RAW_Y_MAX - toRotatedRawY(50) + RAW_Y_MIN);
5766     processSync(mapper);
5767 
5768     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5769     ASSERT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5770     ASSERT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5771 
5772     processUp(mapper);
5773     processSync(mapper);
5774     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5775 
5776     // Rotation 180.
5777     clearViewports();
5778     prepareDisplay(ui::ROTATION_180);
5779     processDown(mapper, RAW_X_MAX - toRawX(50) + RAW_X_MIN, RAW_Y_MAX - toRawY(75) + RAW_Y_MIN);
5780     processSync(mapper);
5781 
5782     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5783     ASSERT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5784     ASSERT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5785 
5786     processUp(mapper);
5787     processSync(mapper);
5788     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5789 
5790     // Rotation 270.
5791     clearViewports();
5792     prepareDisplay(ui::ROTATION_270);
5793     processDown(mapper, RAW_X_MAX - toRotatedRawX(75) + RAW_X_MIN, toRotatedRawY(50));
5794     processSync(mapper);
5795 
5796     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5797     ASSERT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5798     ASSERT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5799 
5800     processUp(mapper);
5801     processSync(mapper);
5802     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5803 }
5804 
TEST_F(SingleTouchInputMapperTest,Process_WhenOrientation0_RotatesMotions)5805 TEST_F(SingleTouchInputMapperTest, Process_WhenOrientation0_RotatesMotions) {
5806     addConfigurationProperty("touch.deviceType", "touchScreen");
5807     prepareButtons();
5808     prepareAxes(POSITION);
5809     addConfigurationProperty("touch.orientationAware", "1");
5810     addConfigurationProperty("touch.orientation", "ORIENTATION_0");
5811     clearViewports();
5812     prepareDisplay(ui::ROTATION_0);
5813     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5814     NotifyMotionArgs args;
5815 
5816     // Orientation 0.
5817     processDown(mapper, toRawX(50), toRawY(75));
5818     processSync(mapper);
5819 
5820     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5821     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5822     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5823 
5824     processUp(mapper);
5825     processSync(mapper);
5826     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5827 }
5828 
TEST_F(SingleTouchInputMapperTest,Process_WhenOrientation90_RotatesMotions)5829 TEST_F(SingleTouchInputMapperTest, Process_WhenOrientation90_RotatesMotions) {
5830     addConfigurationProperty("touch.deviceType", "touchScreen");
5831     prepareButtons();
5832     prepareAxes(POSITION);
5833     addConfigurationProperty("touch.orientationAware", "1");
5834     addConfigurationProperty("touch.orientation", "ORIENTATION_90");
5835     clearViewports();
5836     prepareDisplay(ui::ROTATION_0);
5837     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5838     NotifyMotionArgs args;
5839 
5840     // Orientation 90.
5841     processDown(mapper, RAW_X_MAX - toRotatedRawX(75) + RAW_X_MIN, toRotatedRawY(50));
5842     processSync(mapper);
5843 
5844     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5845     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5846     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5847 
5848     processUp(mapper);
5849     processSync(mapper);
5850     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5851 }
5852 
TEST_F(SingleTouchInputMapperTest,Process_WhenOrientation180_RotatesMotions)5853 TEST_F(SingleTouchInputMapperTest, Process_WhenOrientation180_RotatesMotions) {
5854     addConfigurationProperty("touch.deviceType", "touchScreen");
5855     prepareButtons();
5856     prepareAxes(POSITION);
5857     addConfigurationProperty("touch.orientationAware", "1");
5858     addConfigurationProperty("touch.orientation", "ORIENTATION_180");
5859     clearViewports();
5860     prepareDisplay(ui::ROTATION_0);
5861     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5862     NotifyMotionArgs args;
5863 
5864     // Orientation 180.
5865     processDown(mapper, RAW_X_MAX - toRawX(50) + RAW_X_MIN, RAW_Y_MAX - toRawY(75) + RAW_Y_MIN);
5866     processSync(mapper);
5867 
5868     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5869     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5870     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5871 
5872     processUp(mapper);
5873     processSync(mapper);
5874     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5875 }
5876 
TEST_F(SingleTouchInputMapperTest,Process_WhenOrientation270_RotatesMotions)5877 TEST_F(SingleTouchInputMapperTest, Process_WhenOrientation270_RotatesMotions) {
5878     addConfigurationProperty("touch.deviceType", "touchScreen");
5879     prepareButtons();
5880     prepareAxes(POSITION);
5881     addConfigurationProperty("touch.orientationAware", "1");
5882     addConfigurationProperty("touch.orientation", "ORIENTATION_270");
5883     clearViewports();
5884     prepareDisplay(ui::ROTATION_0);
5885     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5886     NotifyMotionArgs args;
5887 
5888     // Orientation 270.
5889     processDown(mapper, toRotatedRawX(75), RAW_Y_MAX - toRotatedRawY(50) + RAW_Y_MIN);
5890     processSync(mapper);
5891 
5892     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5893     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5894     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5895 
5896     processUp(mapper);
5897     processSync(mapper);
5898     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5899 }
5900 
TEST_F(SingleTouchInputMapperTest,Process_WhenOrientationSpecified_RotatesMotionWithDisplay)5901 TEST_F(SingleTouchInputMapperTest, Process_WhenOrientationSpecified_RotatesMotionWithDisplay) {
5902     addConfigurationProperty("touch.deviceType", "touchScreen");
5903     prepareButtons();
5904     prepareAxes(POSITION);
5905     // Since InputReader works in the un-rotated coordinate space, only devices that are not
5906     // orientation-aware are affected by display rotation.
5907     addConfigurationProperty("touch.orientationAware", "0");
5908     addConfigurationProperty("touch.orientation", "ORIENTATION_90");
5909     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5910 
5911     NotifyMotionArgs args;
5912 
5913     // Orientation 90, Rotation 0.
5914     clearViewports();
5915     prepareDisplay(ui::ROTATION_0);
5916     processDown(mapper, RAW_X_MAX - toRotatedRawX(75) + RAW_X_MIN, toRotatedRawY(50));
5917     processSync(mapper);
5918 
5919     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5920     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5921     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5922 
5923     processUp(mapper);
5924     processSync(mapper);
5925     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5926 
5927     // Orientation 90, Rotation 90.
5928     clearViewports();
5929     prepareDisplay(ui::ROTATION_90);
5930     processDown(mapper, toRawX(50), toRawY(75));
5931     processSync(mapper);
5932 
5933     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5934     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5935     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5936 
5937     processUp(mapper);
5938     processSync(mapper);
5939     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5940 
5941     // Orientation 90, Rotation 180.
5942     clearViewports();
5943     prepareDisplay(ui::ROTATION_180);
5944     processDown(mapper, toRotatedRawX(75), RAW_Y_MAX - toRotatedRawY(50) + RAW_Y_MIN);
5945     processSync(mapper);
5946 
5947     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5948     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5949     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5950 
5951     processUp(mapper);
5952     processSync(mapper);
5953     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5954 
5955     // Orientation 90, Rotation 270.
5956     clearViewports();
5957     prepareDisplay(ui::ROTATION_270);
5958     processDown(mapper, RAW_X_MAX - toRawX(50) + RAW_X_MIN, RAW_Y_MAX - toRawY(75) + RAW_Y_MIN);
5959     processSync(mapper);
5960 
5961     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5962     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5963     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5964 
5965     processUp(mapper);
5966     processSync(mapper);
5967     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5968 }
5969 
TEST_F(SingleTouchInputMapperTest,Process_IgnoresTouchesOutsidePhysicalFrame)5970 TEST_F(SingleTouchInputMapperTest, Process_IgnoresTouchesOutsidePhysicalFrame) {
5971     addConfigurationProperty("touch.deviceType", "touchScreen");
5972     prepareButtons();
5973     prepareAxes(POSITION);
5974     addConfigurationProperty("touch.orientationAware", "1");
5975     prepareDisplay(ui::ROTATION_0);
5976     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5977 
5978     // Set a physical frame in the display viewport.
5979     auto viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
5980     viewport->physicalLeft = 20;
5981     viewport->physicalTop = 600;
5982     viewport->physicalRight = 30;
5983     viewport->physicalBottom = 610;
5984     mFakePolicy->updateViewport(*viewport);
5985     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
5986 
5987     // Start the touch.
5988     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_TOUCH, 1);
5989     processSync(mapper);
5990 
5991     // Expect all input starting outside the physical frame to be ignored.
5992     const std::array<Point, 6> outsidePoints = {
5993             {{0, 0}, {19, 605}, {31, 605}, {25, 599}, {25, 611}, {DISPLAY_WIDTH, DISPLAY_HEIGHT}}};
5994     for (const auto& p : outsidePoints) {
5995         processMove(mapper, toRawX(p.x), toRawY(p.y));
5996         processSync(mapper);
5997         EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
5998     }
5999 
6000     // Move the touch into the physical frame.
6001     processMove(mapper, toRawX(25), toRawY(605));
6002     processSync(mapper);
6003     NotifyMotionArgs args;
6004     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
6005     EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
6006     EXPECT_NEAR(25, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
6007     EXPECT_NEAR(605, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
6008 
6009     // Once the touch down is reported, continue reporting input, even if it is outside the frame.
6010     for (const auto& p : outsidePoints) {
6011         processMove(mapper, toRawX(p.x), toRawY(p.y));
6012         processSync(mapper);
6013         EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
6014         EXPECT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
6015         EXPECT_NEAR(p.x, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
6016         EXPECT_NEAR(p.y, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
6017     }
6018 
6019     processUp(mapper);
6020     processSync(mapper);
6021     EXPECT_NO_FATAL_FAILURE(
6022             mFakeListener->assertNotifyMotionWasCalled(WithMotionAction(AMOTION_EVENT_ACTION_UP)));
6023 }
6024 
TEST_F(SingleTouchInputMapperTest,Process_DoesntCheckPhysicalFrameForTouchpads)6025 TEST_F(SingleTouchInputMapperTest, Process_DoesntCheckPhysicalFrameForTouchpads) {
6026     std::shared_ptr<FakePointerController> fakePointerController =
6027             std::make_shared<FakePointerController>();
6028     mFakePolicy->setPointerController(fakePointerController);
6029 
6030     addConfigurationProperty("touch.deviceType", "pointer");
6031     prepareAxes(POSITION);
6032     prepareDisplay(ui::ROTATION_0);
6033     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6034 
6035     // Set a physical frame in the display viewport.
6036     auto viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
6037     viewport->physicalLeft = 20;
6038     viewport->physicalTop = 600;
6039     viewport->physicalRight = 30;
6040     viewport->physicalBottom = 610;
6041     mFakePolicy->updateViewport(*viewport);
6042     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
6043 
6044     // Start the touch.
6045     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_TOUCH, 1);
6046     processSync(mapper);
6047 
6048     // Expect all input starting outside the physical frame to result in NotifyMotionArgs being
6049     // produced.
6050     const std::array<Point, 6> outsidePoints = {
6051             {{0, 0}, {19, 605}, {31, 605}, {25, 599}, {25, 611}, {DISPLAY_WIDTH, DISPLAY_HEIGHT}}};
6052     for (const auto& p : outsidePoints) {
6053         processMove(mapper, toRawX(p.x), toRawY(p.y));
6054         processSync(mapper);
6055         EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
6056     }
6057 }
6058 
TEST_F(SingleTouchInputMapperTest,Process_AllAxes_DefaultCalibration)6059 TEST_F(SingleTouchInputMapperTest, Process_AllAxes_DefaultCalibration) {
6060     addConfigurationProperty("touch.deviceType", "touchScreen");
6061     prepareDisplay(ui::ROTATION_0);
6062     prepareButtons();
6063     prepareAxes(POSITION | PRESSURE | TOOL | DISTANCE | TILT);
6064     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6065 
6066     // These calculations are based on the input device calibration documentation.
6067     int32_t rawX = 100;
6068     int32_t rawY = 200;
6069     int32_t rawPressure = 10;
6070     int32_t rawToolMajor = 12;
6071     int32_t rawDistance = 2;
6072     int32_t rawTiltX = 30;
6073     int32_t rawTiltY = 110;
6074 
6075     float x = toDisplayX(rawX);
6076     float y = toDisplayY(rawY);
6077     float pressure = float(rawPressure) / RAW_PRESSURE_MAX;
6078     float size = float(rawToolMajor) / RAW_TOOL_MAX;
6079     float tool = float(rawToolMajor) * GEOMETRIC_SCALE;
6080     float distance = float(rawDistance);
6081 
6082     float tiltCenter = (RAW_TILT_MAX + RAW_TILT_MIN) * 0.5f;
6083     float tiltScale = M_PI / 180;
6084     float tiltXAngle = (rawTiltX - tiltCenter) * tiltScale;
6085     float tiltYAngle = (rawTiltY - tiltCenter) * tiltScale;
6086     float orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
6087     float tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
6088 
6089     processDown(mapper, rawX, rawY);
6090     processPressure(mapper, rawPressure);
6091     processToolMajor(mapper, rawToolMajor);
6092     processDistance(mapper, rawDistance);
6093     processTilt(mapper, rawTiltX, rawTiltY);
6094     processSync(mapper);
6095 
6096     NotifyMotionArgs args;
6097     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
6098     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
6099             x, y, pressure, size, tool, tool, tool, tool, orientation, distance));
6100     ASSERT_EQ(tilt, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_TILT));
6101 }
6102 
TEST_F(SingleTouchInputMapperTest,Process_XYAxes_AffineCalibration)6103 TEST_F(SingleTouchInputMapperTest, Process_XYAxes_AffineCalibration) {
6104     addConfigurationProperty("touch.deviceType", "touchScreen");
6105     prepareDisplay(ui::ROTATION_0);
6106     prepareLocationCalibration();
6107     prepareButtons();
6108     prepareAxes(POSITION);
6109     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6110 
6111     int32_t rawX = 100;
6112     int32_t rawY = 200;
6113 
6114     float x = toDisplayX(toCookedX(rawX, rawY));
6115     float y = toDisplayY(toCookedY(rawX, rawY));
6116 
6117     processDown(mapper, rawX, rawY);
6118     processSync(mapper);
6119 
6120     NotifyMotionArgs args;
6121     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
6122     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
6123             x, y, 1, 0, 0, 0, 0, 0, 0, 0));
6124 }
6125 
TEST_F(SingleTouchInputMapperTest,Process_ShouldHandleAllButtons)6126 TEST_F(SingleTouchInputMapperTest, Process_ShouldHandleAllButtons) {
6127     addConfigurationProperty("touch.deviceType", "touchScreen");
6128     prepareDisplay(ui::ROTATION_0);
6129     prepareButtons();
6130     prepareAxes(POSITION);
6131     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6132 
6133     NotifyMotionArgs motionArgs;
6134     NotifyKeyArgs keyArgs;
6135 
6136     processDown(mapper, 100, 200);
6137     processSync(mapper);
6138     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6139     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
6140     ASSERT_EQ(0, motionArgs.buttonState);
6141 
6142     // press BTN_LEFT, release BTN_LEFT
6143     processKey(mapper, BTN_LEFT, 1);
6144     processSync(mapper);
6145     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6146     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6147     ASSERT_EQ(AMOTION_EVENT_BUTTON_PRIMARY, motionArgs.buttonState);
6148 
6149     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6150     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
6151     ASSERT_EQ(AMOTION_EVENT_BUTTON_PRIMARY, motionArgs.buttonState);
6152 
6153     processKey(mapper, BTN_LEFT, 0);
6154     processSync(mapper);
6155     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6156     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
6157     ASSERT_EQ(0, motionArgs.buttonState);
6158 
6159     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6160     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6161     ASSERT_EQ(0, motionArgs.buttonState);
6162 
6163     // press BTN_RIGHT + BTN_MIDDLE, release BTN_RIGHT, release BTN_MIDDLE
6164     processKey(mapper, BTN_RIGHT, 1);
6165     processKey(mapper, BTN_MIDDLE, 1);
6166     processSync(mapper);
6167     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6168     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6169     ASSERT_EQ(AMOTION_EVENT_BUTTON_SECONDARY | AMOTION_EVENT_BUTTON_TERTIARY,
6170             motionArgs.buttonState);
6171 
6172     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6173     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
6174     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
6175 
6176     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6177     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
6178     ASSERT_EQ(AMOTION_EVENT_BUTTON_SECONDARY | AMOTION_EVENT_BUTTON_TERTIARY,
6179             motionArgs.buttonState);
6180 
6181     processKey(mapper, BTN_RIGHT, 0);
6182     processSync(mapper);
6183     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6184     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
6185     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
6186 
6187     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6188     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6189     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
6190 
6191     processKey(mapper, BTN_MIDDLE, 0);
6192     processSync(mapper);
6193     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6194     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
6195     ASSERT_EQ(0, motionArgs.buttonState);
6196 
6197     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6198     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6199     ASSERT_EQ(0, motionArgs.buttonState);
6200 
6201     // press BTN_BACK, release BTN_BACK
6202     processKey(mapper, BTN_BACK, 1);
6203     processSync(mapper);
6204     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
6205     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
6206     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
6207 
6208     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6209     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6210     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
6211 
6212     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6213     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
6214     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
6215 
6216     processKey(mapper, BTN_BACK, 0);
6217     processSync(mapper);
6218     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6219     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
6220     ASSERT_EQ(0, motionArgs.buttonState);
6221 
6222     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6223     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6224     ASSERT_EQ(0, motionArgs.buttonState);
6225 
6226     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
6227     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
6228     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
6229 
6230     // press BTN_SIDE, release BTN_SIDE
6231     processKey(mapper, BTN_SIDE, 1);
6232     processSync(mapper);
6233     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
6234     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
6235     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
6236 
6237     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6238     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6239     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
6240 
6241     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6242     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
6243     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
6244 
6245     processKey(mapper, BTN_SIDE, 0);
6246     processSync(mapper);
6247     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6248     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
6249     ASSERT_EQ(0, motionArgs.buttonState);
6250 
6251     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6252     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6253     ASSERT_EQ(0, motionArgs.buttonState);
6254 
6255     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
6256     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
6257     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
6258 
6259     // press BTN_FORWARD, release BTN_FORWARD
6260     processKey(mapper, BTN_FORWARD, 1);
6261     processSync(mapper);
6262     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
6263     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
6264     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
6265 
6266     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6267     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6268     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
6269 
6270     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6271     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
6272     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
6273 
6274     processKey(mapper, BTN_FORWARD, 0);
6275     processSync(mapper);
6276     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6277     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
6278     ASSERT_EQ(0, motionArgs.buttonState);
6279 
6280     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6281     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6282     ASSERT_EQ(0, motionArgs.buttonState);
6283 
6284     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
6285     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
6286     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
6287 
6288     // press BTN_EXTRA, release BTN_EXTRA
6289     processKey(mapper, BTN_EXTRA, 1);
6290     processSync(mapper);
6291     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
6292     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
6293     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
6294 
6295     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6296     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6297     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
6298 
6299     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6300     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
6301     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
6302 
6303     processKey(mapper, BTN_EXTRA, 0);
6304     processSync(mapper);
6305     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6306     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
6307     ASSERT_EQ(0, motionArgs.buttonState);
6308 
6309     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6310     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6311     ASSERT_EQ(0, motionArgs.buttonState);
6312 
6313     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
6314     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
6315     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
6316 
6317     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
6318 
6319     // press BTN_STYLUS, release BTN_STYLUS
6320     processKey(mapper, BTN_STYLUS, 1);
6321     processSync(mapper);
6322     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6323     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6324     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY, motionArgs.buttonState);
6325 
6326     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6327     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
6328     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY, motionArgs.buttonState);
6329 
6330     processKey(mapper, BTN_STYLUS, 0);
6331     processSync(mapper);
6332     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6333     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
6334     ASSERT_EQ(0, motionArgs.buttonState);
6335 
6336     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6337     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6338     ASSERT_EQ(0, motionArgs.buttonState);
6339 
6340     // press BTN_STYLUS2, release BTN_STYLUS2
6341     processKey(mapper, BTN_STYLUS2, 1);
6342     processSync(mapper);
6343     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6344     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6345     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_SECONDARY, motionArgs.buttonState);
6346 
6347     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6348     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
6349     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_SECONDARY, motionArgs.buttonState);
6350 
6351     processKey(mapper, BTN_STYLUS2, 0);
6352     processSync(mapper);
6353     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6354     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
6355     ASSERT_EQ(0, motionArgs.buttonState);
6356 
6357     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6358     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6359     ASSERT_EQ(0, motionArgs.buttonState);
6360 
6361     // release touch
6362     processUp(mapper);
6363     processSync(mapper);
6364     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6365     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
6366     ASSERT_EQ(0, motionArgs.buttonState);
6367 }
6368 
TEST_F(SingleTouchInputMapperTest,Process_ShouldHandleAllToolTypes)6369 TEST_F(SingleTouchInputMapperTest, Process_ShouldHandleAllToolTypes) {
6370     addConfigurationProperty("touch.deviceType", "touchScreen");
6371     prepareDisplay(ui::ROTATION_0);
6372     prepareButtons();
6373     prepareAxes(POSITION);
6374     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6375 
6376     NotifyMotionArgs motionArgs;
6377 
6378     // default tool type is finger
6379     processDown(mapper, 100, 200);
6380     processSync(mapper);
6381     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6382     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
6383     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
6384 
6385     // eraser
6386     processKey(mapper, BTN_TOOL_RUBBER, 1);
6387     processSync(mapper);
6388     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6389     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6390     ASSERT_EQ(ToolType::ERASER, motionArgs.pointerProperties[0].toolType);
6391 
6392     // stylus
6393     processKey(mapper, BTN_TOOL_RUBBER, 0);
6394     processKey(mapper, BTN_TOOL_PEN, 1);
6395     processSync(mapper);
6396     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6397     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6398     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
6399 
6400     // brush
6401     processKey(mapper, BTN_TOOL_PEN, 0);
6402     processKey(mapper, BTN_TOOL_BRUSH, 1);
6403     processSync(mapper);
6404     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6405     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6406     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
6407 
6408     // pencil
6409     processKey(mapper, BTN_TOOL_BRUSH, 0);
6410     processKey(mapper, BTN_TOOL_PENCIL, 1);
6411     processSync(mapper);
6412     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6413     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6414     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
6415 
6416     // air-brush
6417     processKey(mapper, BTN_TOOL_PENCIL, 0);
6418     processKey(mapper, BTN_TOOL_AIRBRUSH, 1);
6419     processSync(mapper);
6420     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6421     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6422     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
6423 
6424     // mouse
6425     processKey(mapper, BTN_TOOL_AIRBRUSH, 0);
6426     processKey(mapper, BTN_TOOL_MOUSE, 1);
6427     processSync(mapper);
6428     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6429     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6430     ASSERT_EQ(ToolType::MOUSE, motionArgs.pointerProperties[0].toolType);
6431 
6432     // lens
6433     processKey(mapper, BTN_TOOL_MOUSE, 0);
6434     processKey(mapper, BTN_TOOL_LENS, 1);
6435     processSync(mapper);
6436     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6437     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6438     ASSERT_EQ(ToolType::MOUSE, motionArgs.pointerProperties[0].toolType);
6439 
6440     // double-tap
6441     processKey(mapper, BTN_TOOL_LENS, 0);
6442     processKey(mapper, BTN_TOOL_DOUBLETAP, 1);
6443     processSync(mapper);
6444     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6445     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6446     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
6447 
6448     // triple-tap
6449     processKey(mapper, BTN_TOOL_DOUBLETAP, 0);
6450     processKey(mapper, BTN_TOOL_TRIPLETAP, 1);
6451     processSync(mapper);
6452     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6453     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6454     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
6455 
6456     // quad-tap
6457     processKey(mapper, BTN_TOOL_TRIPLETAP, 0);
6458     processKey(mapper, BTN_TOOL_QUADTAP, 1);
6459     processSync(mapper);
6460     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6461     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6462     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
6463 
6464     // finger
6465     processKey(mapper, BTN_TOOL_QUADTAP, 0);
6466     processKey(mapper, BTN_TOOL_FINGER, 1);
6467     processSync(mapper);
6468     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6469     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6470     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
6471 
6472     // stylus trumps finger
6473     processKey(mapper, BTN_TOOL_PEN, 1);
6474     processSync(mapper);
6475     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6476     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6477     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
6478 
6479     // eraser trumps stylus
6480     processKey(mapper, BTN_TOOL_RUBBER, 1);
6481     processSync(mapper);
6482     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6483     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6484     ASSERT_EQ(ToolType::ERASER, motionArgs.pointerProperties[0].toolType);
6485 
6486     // mouse trumps eraser
6487     processKey(mapper, BTN_TOOL_MOUSE, 1);
6488     processSync(mapper);
6489     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6490     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6491     ASSERT_EQ(ToolType::MOUSE, motionArgs.pointerProperties[0].toolType);
6492 
6493     // back to default tool type
6494     processKey(mapper, BTN_TOOL_MOUSE, 0);
6495     processKey(mapper, BTN_TOOL_RUBBER, 0);
6496     processKey(mapper, BTN_TOOL_PEN, 0);
6497     processKey(mapper, BTN_TOOL_FINGER, 0);
6498     processSync(mapper);
6499     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6500     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6501     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
6502 }
6503 
TEST_F(SingleTouchInputMapperTest,Process_WhenBtnTouchPresent_HoversIfItsValueIsZero)6504 TEST_F(SingleTouchInputMapperTest, Process_WhenBtnTouchPresent_HoversIfItsValueIsZero) {
6505     addConfigurationProperty("touch.deviceType", "touchScreen");
6506     prepareDisplay(ui::ROTATION_0);
6507     prepareButtons();
6508     prepareAxes(POSITION);
6509     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOOL_FINGER, 0, AKEYCODE_UNKNOWN, 0);
6510     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6511 
6512     NotifyMotionArgs motionArgs;
6513 
6514     // initially hovering because BTN_TOUCH not sent yet, pressure defaults to 0
6515     processKey(mapper, BTN_TOOL_FINGER, 1);
6516     processMove(mapper, 100, 200);
6517     processSync(mapper);
6518     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6519     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
6520     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6521             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
6522 
6523     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6524     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
6525     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6526             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
6527 
6528     // move a little
6529     processMove(mapper, 150, 250);
6530     processSync(mapper);
6531     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6532     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
6533     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6534             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6535 
6536     // down when BTN_TOUCH is pressed, pressure defaults to 1
6537     processKey(mapper, BTN_TOUCH, 1);
6538     processSync(mapper);
6539     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6540     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
6541     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6542             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6543 
6544     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6545     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
6546     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6547             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
6548 
6549     // up when BTN_TOUCH is released, hover restored
6550     processKey(mapper, BTN_TOUCH, 0);
6551     processSync(mapper);
6552     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6553     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
6554     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6555             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
6556 
6557     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6558     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
6559     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6560             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6561 
6562     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6563     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
6564     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6565             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6566 
6567     // exit hover when pointer goes away
6568     processKey(mapper, BTN_TOOL_FINGER, 0);
6569     processSync(mapper);
6570     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6571     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
6572     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6573             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6574 }
6575 
TEST_F(SingleTouchInputMapperTest,Process_WhenAbsPressureIsPresent_HoversIfItsValueIsZero)6576 TEST_F(SingleTouchInputMapperTest, Process_WhenAbsPressureIsPresent_HoversIfItsValueIsZero) {
6577     addConfigurationProperty("touch.deviceType", "touchScreen");
6578     prepareDisplay(ui::ROTATION_0);
6579     prepareButtons();
6580     prepareAxes(POSITION | PRESSURE);
6581     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6582 
6583     NotifyMotionArgs motionArgs;
6584 
6585     // initially hovering because pressure is 0
6586     processDown(mapper, 100, 200);
6587     processPressure(mapper, 0);
6588     processSync(mapper);
6589     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6590     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
6591     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6592             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
6593 
6594     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6595     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
6596     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6597             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
6598 
6599     // move a little
6600     processMove(mapper, 150, 250);
6601     processSync(mapper);
6602     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6603     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
6604     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6605             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6606 
6607     // down when pressure is non-zero
6608     processPressure(mapper, RAW_PRESSURE_MAX);
6609     processSync(mapper);
6610     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6611     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
6612     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6613             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6614 
6615     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6616     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
6617     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6618             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
6619 
6620     // up when pressure becomes 0, hover restored
6621     processPressure(mapper, 0);
6622     processSync(mapper);
6623     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6624     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
6625     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6626             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
6627 
6628     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6629     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
6630     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6631             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6632 
6633     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6634     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
6635     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6636             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6637 
6638     // exit hover when pointer goes away
6639     processUp(mapper);
6640     processSync(mapper);
6641     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6642     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
6643     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6644             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6645 }
6646 
TEST_F(SingleTouchInputMapperTest,Reset_CancelsOngoingGesture)6647 TEST_F(SingleTouchInputMapperTest, Reset_CancelsOngoingGesture) {
6648     addConfigurationProperty("touch.deviceType", "touchScreen");
6649     prepareDisplay(ui::ROTATION_0);
6650     prepareButtons();
6651     prepareAxes(POSITION | PRESSURE);
6652     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6653 
6654     // Touch down.
6655     processDown(mapper, 100, 200);
6656     processPressure(mapper, 1);
6657     processSync(mapper);
6658     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6659             WithMotionAction(AMOTION_EVENT_ACTION_DOWN)));
6660 
6661     // Reset the mapper. This should cancel the ongoing gesture.
6662     resetMapper(mapper, ARBITRARY_TIME);
6663     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6664             WithMotionAction(AMOTION_EVENT_ACTION_CANCEL)));
6665 
6666     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6667 }
6668 
TEST_F(SingleTouchInputMapperTest,Reset_RecreatesTouchState)6669 TEST_F(SingleTouchInputMapperTest, Reset_RecreatesTouchState) {
6670     addConfigurationProperty("touch.deviceType", "touchScreen");
6671     prepareDisplay(ui::ROTATION_0);
6672     prepareButtons();
6673     prepareAxes(POSITION | PRESSURE);
6674     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6675 
6676     // Set the initial state for the touch pointer.
6677     mFakeEventHub->setAbsoluteAxisValue(EVENTHUB_ID, ABS_X, 100);
6678     mFakeEventHub->setAbsoluteAxisValue(EVENTHUB_ID, ABS_Y, 200);
6679     mFakeEventHub->setAbsoluteAxisValue(EVENTHUB_ID, ABS_PRESSURE, RAW_PRESSURE_MAX);
6680     mFakeEventHub->setScanCodeState(EVENTHUB_ID, BTN_TOUCH, 1);
6681 
6682     // Reset the mapper. When the mapper is reset, we expect it to attempt to recreate the touch
6683     // state by reading the current axis values. Since there was no ongoing gesture, calling reset
6684     // does not generate any events.
6685     resetMapper(mapper, ARBITRARY_TIME);
6686 
6687     // Send a sync to simulate an empty touch frame where nothing changes. The mapper should use
6688     // the recreated touch state to generate a down event.
6689     processSync(mapper);
6690     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6691             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithPressure(1.f))));
6692 
6693     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6694 }
6695 
TEST_F(SingleTouchInputMapperTest,Process_WhenViewportDisplayIdChanged_TouchIsCanceledAndDeviceIsReset)6696 TEST_F(SingleTouchInputMapperTest,
6697        Process_WhenViewportDisplayIdChanged_TouchIsCanceledAndDeviceIsReset) {
6698     addConfigurationProperty("touch.deviceType", "touchScreen");
6699     prepareDisplay(ui::ROTATION_0);
6700     prepareButtons();
6701     prepareAxes(POSITION);
6702     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6703     NotifyMotionArgs motionArgs;
6704 
6705     // Down.
6706     processDown(mapper, 100, 200);
6707     processSync(mapper);
6708 
6709     // We should receive a down event
6710     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6711     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
6712 
6713     // Change display id
6714     clearViewports();
6715     prepareSecondaryDisplay(ViewportType::INTERNAL);
6716 
6717     // We should receive a cancel event
6718     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6719     ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionArgs.action);
6720     // Then receive reset called
6721     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6722 }
6723 
TEST_F(SingleTouchInputMapperTest,Process_WhenViewportActiveStatusChanged_TouchIsCanceledAndDeviceIsReset)6724 TEST_F(SingleTouchInputMapperTest,
6725        Process_WhenViewportActiveStatusChanged_TouchIsCanceledAndDeviceIsReset) {
6726     addConfigurationProperty("touch.deviceType", "touchScreen");
6727     prepareDisplay(ui::ROTATION_0);
6728     prepareButtons();
6729     prepareAxes(POSITION);
6730     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6731     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6732     NotifyMotionArgs motionArgs;
6733 
6734     // Start a new gesture.
6735     processDown(mapper, 100, 200);
6736     processSync(mapper);
6737     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6738     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
6739 
6740     // Make the viewport inactive. This will put the device in disabled mode.
6741     auto viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
6742     viewport->isActive = false;
6743     mFakePolicy->updateViewport(*viewport);
6744     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
6745 
6746     // We should receive a cancel event for the ongoing gesture.
6747     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6748     ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionArgs.action);
6749     // Then we should be notified that the device was reset.
6750     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6751 
6752     // No events are generated while the viewport is inactive.
6753     processMove(mapper, 101, 201);
6754     processSync(mapper);
6755     processUp(mapper);
6756     processSync(mapper);
6757     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6758 
6759     // Start a new gesture while the viewport is still inactive.
6760     processDown(mapper, 300, 400);
6761     mFakeEventHub->setAbsoluteAxisValue(EVENTHUB_ID, ABS_X, 300);
6762     mFakeEventHub->setAbsoluteAxisValue(EVENTHUB_ID, ABS_Y, 400);
6763     mFakeEventHub->setScanCodeState(EVENTHUB_ID, BTN_TOUCH, 1);
6764     processSync(mapper);
6765 
6766     // Make the viewport active again. The device should resume processing events.
6767     viewport->isActive = true;
6768     mFakePolicy->updateViewport(*viewport);
6769     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
6770 
6771     // The device is reset because it changes back to direct mode, without generating any events.
6772     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6773     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6774 
6775     // In the next sync, the touch state that was recreated when the device was reset is reported.
6776     processSync(mapper);
6777     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6778             WithMotionAction(AMOTION_EVENT_ACTION_DOWN)));
6779 
6780     // No more events.
6781     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6782     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasNotCalled());
6783 }
6784 
TEST_F(SingleTouchInputMapperTest,ButtonIsReleasedOnTouchUp)6785 TEST_F(SingleTouchInputMapperTest, ButtonIsReleasedOnTouchUp) {
6786     addConfigurationProperty("touch.deviceType", "touchScreen");
6787     prepareDisplay(ui::ROTATION_0);
6788     prepareButtons();
6789     prepareAxes(POSITION);
6790     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6791     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6792 
6793     // Press a stylus button.
6794     processKey(mapper, BTN_STYLUS, 1);
6795     processSync(mapper);
6796 
6797     // Start a touch gesture and ensure the BUTTON_PRESS event is generated.
6798     processDown(mapper, 100, 200);
6799     processSync(mapper);
6800     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6801             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
6802                   WithCoords(toDisplayX(100), toDisplayY(200)),
6803                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
6804     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6805             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
6806                   WithCoords(toDisplayX(100), toDisplayY(200)),
6807                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
6808 
6809     // Release the touch gesture. Ensure that the BUTTON_RELEASE event is generated even though
6810     // the button has not actually been released, since there will be no pointers through which the
6811     // button state can be reported. The event is generated at the location of the pointer before
6812     // it went up.
6813     processUp(mapper);
6814     processSync(mapper);
6815     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6816             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
6817                   WithCoords(toDisplayX(100), toDisplayY(200)), WithButtonState(0))));
6818     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6819             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
6820                   WithCoords(toDisplayX(100), toDisplayY(200)), WithButtonState(0))));
6821 }
6822 
TEST_F(SingleTouchInputMapperTest,StylusButtonMotionEventsDisabled)6823 TEST_F(SingleTouchInputMapperTest, StylusButtonMotionEventsDisabled) {
6824     addConfigurationProperty("touch.deviceType", "touchScreen");
6825     prepareDisplay(ui::ROTATION_0);
6826     prepareButtons();
6827     prepareAxes(POSITION);
6828 
6829     mFakePolicy->setStylusButtonMotionEventsEnabled(false);
6830 
6831     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6832     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6833 
6834     // Press a stylus button.
6835     processKey(mapper, BTN_STYLUS, 1);
6836     processSync(mapper);
6837 
6838     // Start a touch gesture and ensure that the stylus button is not reported.
6839     processDown(mapper, 100, 200);
6840     processSync(mapper);
6841     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6842             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithButtonState(0))));
6843 
6844     // Release and press the stylus button again.
6845     processKey(mapper, BTN_STYLUS, 0);
6846     processSync(mapper);
6847     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6848             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE), WithButtonState(0))));
6849     processKey(mapper, BTN_STYLUS, 1);
6850     processSync(mapper);
6851     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6852             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE), WithButtonState(0))));
6853 
6854     // Release the touch gesture.
6855     processUp(mapper);
6856     processSync(mapper);
6857     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6858             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP), WithButtonState(0))));
6859 
6860     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6861 }
6862 
TEST_F(SingleTouchInputMapperTest,WhenDeviceTypeIsSetToTouchNavigation_setsCorrectType)6863 TEST_F(SingleTouchInputMapperTest, WhenDeviceTypeIsSetToTouchNavigation_setsCorrectType) {
6864     mFakePolicy->addDeviceTypeAssociation(DEVICE_LOCATION, "touchNavigation");
6865     prepareDisplay(ui::ROTATION_0);
6866     prepareButtons();
6867     prepareAxes(POSITION);
6868     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6869     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6870 
6871     ASSERT_EQ(AINPUT_SOURCE_TOUCH_NAVIGATION, mapper.getSources());
6872 }
6873 
TEST_F(SingleTouchInputMapperTest,Process_WhenConfigEnabled_ShouldShowDirectStylusPointer)6874 TEST_F(SingleTouchInputMapperTest, Process_WhenConfigEnabled_ShouldShowDirectStylusPointer) {
6875     std::shared_ptr<FakePointerController> fakePointerController =
6876             std::make_shared<FakePointerController>();
6877     addConfigurationProperty("touch.deviceType", "touchScreen");
6878     prepareDisplay(ui::ROTATION_0);
6879     prepareButtons();
6880     prepareAxes(POSITION);
6881     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOOL_PEN, 0, AKEYCODE_UNKNOWN, 0);
6882     mFakePolicy->setPointerController(fakePointerController);
6883     mFakePolicy->setStylusPointerIconEnabled(true);
6884     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6885 
6886     processKey(mapper, BTN_TOOL_PEN, 1);
6887     processMove(mapper, 100, 200);
6888     processSync(mapper);
6889     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6890             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
6891                   WithToolType(ToolType::STYLUS),
6892                   WithPointerCoords(0, toDisplayX(100), toDisplayY(200)))));
6893     ASSERT_TRUE(fakePointerController->isPointerShown());
6894     ASSERT_NO_FATAL_FAILURE(
6895             fakePointerController->assertPosition(toDisplayX(100), toDisplayY(200)));
6896 }
6897 
TEST_F(SingleTouchInputMapperTest,Process_WhenConfigDisabled_ShouldNotShowDirectStylusPointer)6898 TEST_F(SingleTouchInputMapperTest, Process_WhenConfigDisabled_ShouldNotShowDirectStylusPointer) {
6899     std::shared_ptr<FakePointerController> fakePointerController =
6900             std::make_shared<FakePointerController>();
6901     addConfigurationProperty("touch.deviceType", "touchScreen");
6902     prepareDisplay(ui::ROTATION_0);
6903     prepareButtons();
6904     prepareAxes(POSITION);
6905     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOOL_PEN, 0, AKEYCODE_UNKNOWN, 0);
6906     mFakePolicy->setPointerController(fakePointerController);
6907     mFakePolicy->setStylusPointerIconEnabled(false);
6908     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6909 
6910     processKey(mapper, BTN_TOOL_PEN, 1);
6911     processMove(mapper, 100, 200);
6912     processSync(mapper);
6913     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6914             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
6915                   WithToolType(ToolType::STYLUS),
6916                   WithPointerCoords(0, toDisplayX(100), toDisplayY(200)))));
6917     ASSERT_FALSE(fakePointerController->isPointerShown());
6918 }
6919 
TEST_F(SingleTouchInputMapperTest,WhenDeviceTypeIsChangedToTouchNavigation_updatesDeviceType)6920 TEST_F(SingleTouchInputMapperTest, WhenDeviceTypeIsChangedToTouchNavigation_updatesDeviceType) {
6921     // Initialize the device without setting device source to touch navigation.
6922     addConfigurationProperty("touch.deviceType", "touchScreen");
6923     prepareDisplay(ui::ROTATION_0);
6924     prepareButtons();
6925     prepareAxes(POSITION);
6926     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6927 
6928     // Ensure that the device is created as a touchscreen, not touch navigation.
6929     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, mapper.getSources());
6930 
6931     // Add device type association after the device was created.
6932     mFakePolicy->addDeviceTypeAssociation(DEVICE_LOCATION, "touchNavigation");
6933 
6934     // Send update to the mapper.
6935     std::list<NotifyArgs> unused2 =
6936             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
6937                                InputReaderConfiguration::Change::DEVICE_TYPE /*changes*/);
6938 
6939     // Check whether device type update was successful.
6940     ASSERT_EQ(AINPUT_SOURCE_TOUCH_NAVIGATION, mDevice->getSources());
6941 }
6942 
TEST_F(SingleTouchInputMapperTest,HoverEventsOutsidePhysicalFrameAreIgnored)6943 TEST_F(SingleTouchInputMapperTest, HoverEventsOutsidePhysicalFrameAreIgnored) {
6944     // Initialize the device without setting device source to touch navigation.
6945     addConfigurationProperty("touch.deviceType", "touchScreen");
6946     prepareDisplay(ui::ROTATION_0);
6947     prepareButtons();
6948     prepareAxes(POSITION);
6949     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOOL_PEN, 0, AKEYCODE_UNKNOWN, 0);
6950 
6951     // Set a physical frame in the display viewport.
6952     auto viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
6953     viewport->physicalLeft = 0;
6954     viewport->physicalTop = 0;
6955     viewport->physicalRight = DISPLAY_WIDTH / 2;
6956     viewport->physicalBottom = DISPLAY_HEIGHT / 2;
6957     mFakePolicy->updateViewport(*viewport);
6958     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
6959 
6960     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6961 
6962     // Hovering inside the physical frame produces events.
6963     processKey(mapper, BTN_TOOL_PEN, 1);
6964     processMove(mapper, RAW_X_MIN + 1, RAW_Y_MIN + 1);
6965     processSync(mapper);
6966     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6967             WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER)));
6968     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6969             WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE)));
6970 
6971     // Leaving the physical frame ends the hovering gesture.
6972     processMove(mapper, RAW_X_MAX - 1, RAW_Y_MAX - 1);
6973     processSync(mapper);
6974     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6975             WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT)));
6976 
6977     // Moving outside the physical frame does not produce events.
6978     processMove(mapper, RAW_X_MAX - 2, RAW_Y_MAX - 2);
6979     processSync(mapper);
6980     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6981 
6982     // Re-entering the physical frame produces events.
6983     processMove(mapper, RAW_X_MIN, RAW_Y_MIN);
6984     processSync(mapper);
6985     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6986             WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER)));
6987     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6988             WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE)));
6989 }
6990 
6991 // --- TouchDisplayProjectionTest ---
6992 
6993 class TouchDisplayProjectionTest : public SingleTouchInputMapperTest {
6994 public:
6995     // The values inside DisplayViewport are expected to be pre-rotated. This updates the current
6996     // DisplayViewport to pre-rotate the values. The viewport's physical display will be set to the
6997     // rotated equivalent of the given un-rotated physical display bounds.
configurePhysicalDisplay(ui::Rotation orientation,Rect naturalPhysicalDisplay,int32_t naturalDisplayWidth=DISPLAY_WIDTH,int32_t naturalDisplayHeight=DISPLAY_HEIGHT)6998     void configurePhysicalDisplay(ui::Rotation orientation, Rect naturalPhysicalDisplay,
6999                                   int32_t naturalDisplayWidth = DISPLAY_WIDTH,
7000                                   int32_t naturalDisplayHeight = DISPLAY_HEIGHT) {
7001         uint32_t inverseRotationFlags;
7002         auto rotatedWidth = naturalDisplayWidth;
7003         auto rotatedHeight = naturalDisplayHeight;
7004         switch (orientation) {
7005             case ui::ROTATION_90:
7006                 inverseRotationFlags = ui::Transform::ROT_270;
7007                 std::swap(rotatedWidth, rotatedHeight);
7008                 break;
7009             case ui::ROTATION_180:
7010                 inverseRotationFlags = ui::Transform::ROT_180;
7011                 break;
7012             case ui::ROTATION_270:
7013                 inverseRotationFlags = ui::Transform::ROT_90;
7014                 std::swap(rotatedWidth, rotatedHeight);
7015                 break;
7016             case ui::ROTATION_0:
7017                 inverseRotationFlags = ui::Transform::ROT_0;
7018                 break;
7019         }
7020 
7021         const ui::Transform rotation(inverseRotationFlags, rotatedWidth, rotatedHeight);
7022         const Rect rotatedPhysicalDisplay = rotation.transform(naturalPhysicalDisplay);
7023 
7024         std::optional<DisplayViewport> internalViewport =
7025                 *mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
7026         DisplayViewport& v = *internalViewport;
7027         v.displayId = DISPLAY_ID;
7028         v.orientation = orientation;
7029 
7030         v.logicalLeft = 0;
7031         v.logicalTop = 0;
7032         v.logicalRight = 100;
7033         v.logicalBottom = 100;
7034 
7035         v.physicalLeft = rotatedPhysicalDisplay.left;
7036         v.physicalTop = rotatedPhysicalDisplay.top;
7037         v.physicalRight = rotatedPhysicalDisplay.right;
7038         v.physicalBottom = rotatedPhysicalDisplay.bottom;
7039 
7040         v.deviceWidth = rotatedWidth;
7041         v.deviceHeight = rotatedHeight;
7042 
7043         v.isActive = true;
7044         v.uniqueId = UNIQUE_ID;
7045         v.type = ViewportType::INTERNAL;
7046         mFakePolicy->updateViewport(v);
7047         configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
7048     }
7049 
assertReceivedMove(const Point & point)7050     void assertReceivedMove(const Point& point) {
7051         NotifyMotionArgs motionArgs;
7052         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7053         ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7054         ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7055         ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0], point.x, point.y,
7056                                                     1, 0, 0, 0, 0, 0, 0, 0));
7057     }
7058 };
7059 
TEST_F(TouchDisplayProjectionTest,IgnoresTouchesOutsidePhysicalDisplay)7060 TEST_F(TouchDisplayProjectionTest, IgnoresTouchesOutsidePhysicalDisplay) {
7061     addConfigurationProperty("touch.deviceType", "touchScreen");
7062     prepareDisplay(ui::ROTATION_0);
7063 
7064     prepareButtons();
7065     prepareAxes(POSITION);
7066     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
7067 
7068     NotifyMotionArgs motionArgs;
7069 
7070     // Configure the DisplayViewport such that the logical display maps to a subsection of
7071     // the display panel called the physical display. Here, the physical display is bounded by the
7072     // points (10, 20) and (70, 160) inside the display space, which is of the size 400 x 800.
7073     static const Rect kPhysicalDisplay{10, 20, 70, 160};
7074     static const std::array<Point, 6> kPointsOutsidePhysicalDisplay{
7075             {{-10, -10}, {0, 0}, {5, 100}, {50, 15}, {75, 100}, {50, 165}}};
7076 
7077     for (auto orientation : {ui::ROTATION_0, ui::ROTATION_90, ui::ROTATION_180, ui::ROTATION_270}) {
7078         configurePhysicalDisplay(orientation, kPhysicalDisplay);
7079 
7080         // Touches outside the physical display should be ignored, and should not generate any
7081         // events. Ensure touches at the following points that lie outside of the physical display
7082         // area do not generate any events.
7083         for (const auto& point : kPointsOutsidePhysicalDisplay) {
7084             processDown(mapper, toRawX(point.x), toRawY(point.y));
7085             processSync(mapper);
7086             processUp(mapper);
7087             processSync(mapper);
7088             ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled())
7089                     << "Unexpected event generated for touch outside physical display at point: "
7090                     << point.x << ", " << point.y;
7091         }
7092     }
7093 }
7094 
TEST_F(TouchDisplayProjectionTest,EmitsTouchDownAfterEnteringPhysicalDisplay)7095 TEST_F(TouchDisplayProjectionTest, EmitsTouchDownAfterEnteringPhysicalDisplay) {
7096     addConfigurationProperty("touch.deviceType", "touchScreen");
7097     prepareDisplay(ui::ROTATION_0);
7098 
7099     prepareButtons();
7100     prepareAxes(POSITION);
7101     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
7102 
7103     NotifyMotionArgs motionArgs;
7104 
7105     // Configure the DisplayViewport such that the logical display maps to a subsection of
7106     // the display panel called the physical display. Here, the physical display is bounded by the
7107     // points (10, 20) and (70, 160) inside the display space, which is of the size 400 x 800.
7108     static const Rect kPhysicalDisplay{10, 20, 70, 160};
7109 
7110     for (auto orientation : {ui::ROTATION_0, ui::ROTATION_90, ui::ROTATION_180, ui::ROTATION_270}) {
7111         configurePhysicalDisplay(orientation, kPhysicalDisplay);
7112 
7113         // Touches that start outside the physical display should be ignored until it enters the
7114         // physical display bounds, at which point it should generate a down event. Start a touch at
7115         // the point (5, 100), which is outside the physical display bounds.
7116         static const Point kOutsidePoint{5, 100};
7117         processDown(mapper, toRawX(kOutsidePoint.x), toRawY(kOutsidePoint.y));
7118         processSync(mapper);
7119         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7120 
7121         // Move the touch into the physical display area. This should generate a pointer down.
7122         processMove(mapper, toRawX(11), toRawY(21));
7123         processSync(mapper);
7124         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7125         ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
7126         ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7127         ASSERT_NO_FATAL_FAILURE(
7128                 assertPointerCoords(motionArgs.pointerCoords[0], 11, 21, 1, 0, 0, 0, 0, 0, 0, 0));
7129 
7130         // Move the touch inside the physical display area. This should generate a pointer move.
7131         processMove(mapper, toRawX(69), toRawY(159));
7132         processSync(mapper);
7133         assertReceivedMove({69, 159});
7134 
7135         // Move outside the physical display area. Since the pointer is already down, this should
7136         // now continue generating events.
7137         processMove(mapper, toRawX(kOutsidePoint.x), toRawY(kOutsidePoint.y));
7138         processSync(mapper);
7139         assertReceivedMove(kOutsidePoint);
7140 
7141         // Release. This should generate a pointer up.
7142         processUp(mapper);
7143         processSync(mapper);
7144         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7145         ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
7146         ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0], kOutsidePoint.x,
7147                                                     kOutsidePoint.y, 1, 0, 0, 0, 0, 0, 0, 0));
7148 
7149         // Ensure no more events were generated.
7150         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
7151         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7152     }
7153 }
7154 
7155 // --- TouchscreenPrecisionTests ---
7156 
7157 // This test suite is used to ensure that touchscreen devices are scaled and configured correctly
7158 // in various orientations and with different display rotations. We configure the touchscreen to
7159 // have a higher resolution than that of the display by an integer scale factor in each axis so that
7160 // we can enforce that coordinates match precisely as expected.
7161 class TouchscreenPrecisionTestsFixture : public TouchDisplayProjectionTest,
7162                                          public ::testing::WithParamInterface<ui::Rotation> {
7163 public:
SetUp()7164     void SetUp() override {
7165         SingleTouchInputMapperTest::SetUp();
7166 
7167         // Prepare the raw axes to have twice the resolution of the display in the X axis and
7168         // four times the resolution of the display in the Y axis.
7169         prepareButtons();
7170         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_X, PRECISION_RAW_X_MIN, PRECISION_RAW_X_MAX,
7171                                        PRECISION_RAW_X_FLAT, PRECISION_RAW_X_FUZZ,
7172                                        PRECISION_RAW_X_RES);
7173         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_Y, PRECISION_RAW_Y_MIN, PRECISION_RAW_Y_MAX,
7174                                        PRECISION_RAW_Y_FLAT, PRECISION_RAW_Y_FUZZ,
7175                                        PRECISION_RAW_Y_RES);
7176     }
7177 
7178     static const int32_t PRECISION_RAW_X_MIN = TouchInputMapperTest::RAW_X_MIN;
7179     static const int32_t PRECISION_RAW_X_MAX = PRECISION_RAW_X_MIN + DISPLAY_WIDTH * 2 - 1;
7180     static const int32_t PRECISION_RAW_Y_MIN = TouchInputMapperTest::RAW_Y_MIN;
7181     static const int32_t PRECISION_RAW_Y_MAX = PRECISION_RAW_Y_MIN + DISPLAY_HEIGHT * 4 - 1;
7182 
7183     static const int32_t PRECISION_RAW_X_RES = 50;  // units per millimeter
7184     static const int32_t PRECISION_RAW_Y_RES = 100; // units per millimeter
7185 
7186     static const int32_t PRECISION_RAW_X_FLAT = 16;
7187     static const int32_t PRECISION_RAW_Y_FLAT = 32;
7188 
7189     static const int32_t PRECISION_RAW_X_FUZZ = 4;
7190     static const int32_t PRECISION_RAW_Y_FUZZ = 8;
7191 
7192     static const std::array<Point, 4> kRawCorners;
7193 };
7194 
7195 const std::array<Point, 4> TouchscreenPrecisionTestsFixture::kRawCorners = {{
7196         {PRECISION_RAW_X_MIN, PRECISION_RAW_Y_MIN}, // left-top
7197         {PRECISION_RAW_X_MAX, PRECISION_RAW_Y_MIN}, // right-top
7198         {PRECISION_RAW_X_MAX, PRECISION_RAW_Y_MAX}, // right-bottom
7199         {PRECISION_RAW_X_MIN, PRECISION_RAW_Y_MAX}, // left-bottom
7200 }};
7201 
7202 // Tests for how the touchscreen is oriented relative to the natural orientation of the display.
7203 // For example, if a touchscreen is configured with an orientation of 90 degrees, it is a portrait
7204 // touchscreen panel that is used on a device whose natural display orientation is in landscape.
TEST_P(TouchscreenPrecisionTestsFixture,OrientationPrecision)7205 TEST_P(TouchscreenPrecisionTestsFixture, OrientationPrecision) {
7206     enum class Orientation {
7207         ORIENTATION_0 = ui::toRotationInt(ui::ROTATION_0),
7208         ORIENTATION_90 = ui::toRotationInt(ui::ROTATION_90),
7209         ORIENTATION_180 = ui::toRotationInt(ui::ROTATION_180),
7210         ORIENTATION_270 = ui::toRotationInt(ui::ROTATION_270),
7211         ftl_last = ORIENTATION_270,
7212     };
7213     using Orientation::ORIENTATION_0, Orientation::ORIENTATION_90, Orientation::ORIENTATION_180,
7214             Orientation::ORIENTATION_270;
7215     static const std::map<Orientation, std::array<vec2, 4> /*mappedCorners*/> kMappedCorners = {
7216             {ORIENTATION_0, {{{0, 0}, {479.5, 0}, {479.5, 799.75}, {0, 799.75}}}},
7217             {ORIENTATION_90, {{{0, 479.5}, {0, 0}, {799.75, 0}, {799.75, 479.5}}}},
7218             {ORIENTATION_180, {{{479.5, 799.75}, {0, 799.75}, {0, 0}, {479.5, 0}}}},
7219             {ORIENTATION_270, {{{799.75, 0}, {799.75, 479.5}, {0, 479.5}, {0, 0}}}},
7220     };
7221 
7222     const auto touchscreenOrientation = static_cast<Orientation>(ui::toRotationInt(GetParam()));
7223 
7224     // Configure the touchscreen as being installed in the one of the four different orientations
7225     // relative to the display.
7226     addConfigurationProperty("touch.deviceType", "touchScreen");
7227     addConfigurationProperty("touch.orientation", ftl::enum_string(touchscreenOrientation).c_str());
7228     prepareDisplay(ui::ROTATION_0);
7229 
7230     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
7231 
7232     // If the touchscreen is installed in a rotated orientation relative to the display (i.e. in
7233     // orientations of either 90 or 270) this means the display's natural resolution will be
7234     // flipped.
7235     const bool displayRotated =
7236             touchscreenOrientation == ORIENTATION_90 || touchscreenOrientation == ORIENTATION_270;
7237     const int32_t width = displayRotated ? DISPLAY_HEIGHT : DISPLAY_WIDTH;
7238     const int32_t height = displayRotated ? DISPLAY_WIDTH : DISPLAY_HEIGHT;
7239     const Rect physicalFrame{0, 0, width, height};
7240     configurePhysicalDisplay(ui::ROTATION_0, physicalFrame, width, height);
7241 
7242     const auto& expectedPoints = kMappedCorners.at(touchscreenOrientation);
7243     const float expectedPrecisionX = displayRotated ? 4 : 2;
7244     const float expectedPrecisionY = displayRotated ? 2 : 4;
7245 
7246     // Test all four corners.
7247     for (int i = 0; i < 4; i++) {
7248         const auto& raw = kRawCorners[i];
7249         processDown(mapper, raw.x, raw.y);
7250         processSync(mapper);
7251         const auto& expected = expectedPoints[i];
7252         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7253                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
7254                       WithCoords(expected.x, expected.y),
7255                       WithPrecision(expectedPrecisionX, expectedPrecisionY))))
7256                 << "Failed to process raw point (" << raw.x << ", " << raw.y << ") "
7257                 << "with touchscreen orientation "
7258                 << ftl::enum_string(touchscreenOrientation).c_str() << ", expected point ("
7259                 << expected.x << ", " << expected.y << ").";
7260         processUp(mapper);
7261         processSync(mapper);
7262         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7263                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
7264                       WithCoords(expected.x, expected.y))));
7265     }
7266 }
7267 
TEST_P(TouchscreenPrecisionTestsFixture,RotationPrecisionWhenOrientationAware)7268 TEST_P(TouchscreenPrecisionTestsFixture, RotationPrecisionWhenOrientationAware) {
7269     static const std::map<ui::Rotation /*rotation*/, std::array<vec2, 4> /*mappedCorners*/>
7270             kMappedCorners = {
7271                     {ui::ROTATION_0, {{{0, 0}, {479.5, 0}, {479.5, 799.75}, {0, 799.75}}}},
7272                     {ui::ROTATION_90, {{{0.5, 0}, {480, 0}, {480, 799.75}, {0.5, 799.75}}}},
7273                     {ui::ROTATION_180, {{{0.5, 0.25}, {480, 0.25}, {480, 800}, {0.5, 800}}}},
7274                     {ui::ROTATION_270, {{{0, 0.25}, {479.5, 0.25}, {479.5, 800}, {0, 800}}}},
7275             };
7276 
7277     const ui::Rotation displayRotation = GetParam();
7278 
7279     addConfigurationProperty("touch.deviceType", "touchScreen");
7280     prepareDisplay(displayRotation);
7281 
7282     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
7283 
7284     const auto& expectedPoints = kMappedCorners.at(displayRotation);
7285 
7286     // Test all four corners.
7287     for (int i = 0; i < 4; i++) {
7288         const auto& expected = expectedPoints[i];
7289         const auto& raw = kRawCorners[i];
7290         processDown(mapper, raw.x, raw.y);
7291         processSync(mapper);
7292         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7293                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
7294                       WithCoords(expected.x, expected.y), WithPrecision(2, 4))))
7295                 << "Failed to process raw point (" << raw.x << ", " << raw.y << ") "
7296                 << "with display rotation " << ui::toCString(displayRotation)
7297                 << ", expected point (" << expected.x << ", " << expected.y << ").";
7298         processUp(mapper);
7299         processSync(mapper);
7300         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7301                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
7302                       WithCoords(expected.x, expected.y))));
7303     }
7304 }
7305 
TEST_P(TouchscreenPrecisionTestsFixture,RotationPrecisionOrientationAwareInOri270)7306 TEST_P(TouchscreenPrecisionTestsFixture, RotationPrecisionOrientationAwareInOri270) {
7307     static const std::map<ui::Rotation /*orientation*/, std::array<vec2, 4> /*mappedCorners*/>
7308             kMappedCorners = {
7309                     {ui::ROTATION_0, {{{799.75, 0}, {799.75, 479.5}, {0, 479.5}, {0, 0}}}},
7310                     {ui::ROTATION_90, {{{800, 0}, {800, 479.5}, {0.25, 479.5}, {0.25, 0}}}},
7311                     {ui::ROTATION_180, {{{800, 0.5}, {800, 480}, {0.25, 480}, {0.25, 0.5}}}},
7312                     {ui::ROTATION_270, {{{799.75, 0.5}, {799.75, 480}, {0, 480}, {0, 0.5}}}},
7313             };
7314 
7315     const ui::Rotation displayRotation = GetParam();
7316 
7317     addConfigurationProperty("touch.deviceType", "touchScreen");
7318     addConfigurationProperty("touch.orientation", "ORIENTATION_270");
7319 
7320     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
7321 
7322     // Ori 270, so width and height swapped
7323     const Rect physicalFrame{0, 0, DISPLAY_HEIGHT, DISPLAY_WIDTH};
7324     prepareDisplay(displayRotation);
7325     configurePhysicalDisplay(displayRotation, physicalFrame, DISPLAY_HEIGHT, DISPLAY_WIDTH);
7326 
7327     const auto& expectedPoints = kMappedCorners.at(displayRotation);
7328 
7329     // Test all four corners.
7330     for (int i = 0; i < 4; i++) {
7331         const auto& expected = expectedPoints[i];
7332         const auto& raw = kRawCorners[i];
7333         processDown(mapper, raw.x, raw.y);
7334         processSync(mapper);
7335         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7336                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
7337                       WithCoords(expected.x, expected.y), WithPrecision(4, 2))))
7338                 << "Failed to process raw point (" << raw.x << ", " << raw.y << ") "
7339                 << "with display rotation " << ui::toCString(displayRotation)
7340                 << ", expected point (" << expected.x << ", " << expected.y << ").";
7341         processUp(mapper);
7342         processSync(mapper);
7343         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7344                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
7345                       WithCoords(expected.x, expected.y))));
7346     }
7347 }
7348 
TEST_P(TouchscreenPrecisionTestsFixture,MotionRangesAreOrientedInRotatedDisplay)7349 TEST_P(TouchscreenPrecisionTestsFixture, MotionRangesAreOrientedInRotatedDisplay) {
7350     const ui::Rotation displayRotation = GetParam();
7351 
7352     addConfigurationProperty("touch.deviceType", "touchScreen");
7353     prepareDisplay(displayRotation);
7354 
7355     __attribute__((unused)) SingleTouchInputMapper& mapper =
7356             constructAndAddMapper<SingleTouchInputMapper>();
7357 
7358     const InputDeviceInfo deviceInfo = mDevice->getDeviceInfo();
7359     // MotionRanges use display pixels as their units
7360     const auto* xRange = deviceInfo.getMotionRange(AMOTION_EVENT_AXIS_X, AINPUT_SOURCE_TOUCHSCREEN);
7361     const auto* yRange = deviceInfo.getMotionRange(AMOTION_EVENT_AXIS_Y, AINPUT_SOURCE_TOUCHSCREEN);
7362 
7363     // The MotionRanges should be oriented in the rotated display's coordinate space
7364     const bool displayRotated =
7365             displayRotation == ui::ROTATION_90 || displayRotation == ui::ROTATION_270;
7366 
7367     constexpr float MAX_X = 479.5;
7368     constexpr float MAX_Y = 799.75;
7369     EXPECT_EQ(xRange->min, 0.f);
7370     EXPECT_EQ(yRange->min, 0.f);
7371     EXPECT_EQ(xRange->max, displayRotated ? MAX_Y : MAX_X);
7372     EXPECT_EQ(yRange->max, displayRotated ? MAX_X : MAX_Y);
7373 
7374     EXPECT_EQ(xRange->flat, 8.f);
7375     EXPECT_EQ(yRange->flat, 8.f);
7376 
7377     EXPECT_EQ(xRange->fuzz, 2.f);
7378     EXPECT_EQ(yRange->fuzz, 2.f);
7379 
7380     EXPECT_EQ(xRange->resolution, 25.f); // pixels per millimeter
7381     EXPECT_EQ(yRange->resolution, 25.f); // pixels per millimeter
7382 }
7383 
7384 // Run the precision tests for all rotations.
7385 INSTANTIATE_TEST_SUITE_P(TouchscreenPrecisionTests, TouchscreenPrecisionTestsFixture,
7386                          ::testing::Values(ui::ROTATION_0, ui::ROTATION_90, ui::ROTATION_180,
7387                                            ui::ROTATION_270),
__anone2377bd80202(const testing::TestParamInfo<ui::Rotation>& testParamInfo) 7388                          [](const testing::TestParamInfo<ui::Rotation>& testParamInfo) {
7389                              return ftl::enum_string(testParamInfo.param);
7390                          });
7391 
7392 // --- ExternalStylusFusionTest ---
7393 
7394 class ExternalStylusFusionTest : public SingleTouchInputMapperTest {
7395 public:
initializeInputMapperWithExternalStylus()7396     SingleTouchInputMapper& initializeInputMapperWithExternalStylus() {
7397         addConfigurationProperty("touch.deviceType", "touchScreen");
7398         prepareDisplay(ui::ROTATION_0);
7399         prepareButtons();
7400         prepareAxes(POSITION);
7401         auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
7402 
7403         mStylusState.when = ARBITRARY_TIME;
7404         mStylusState.pressure = 0.f;
7405         mStylusState.toolType = ToolType::STYLUS;
7406         mReader->getContext()->setExternalStylusDevices({mExternalStylusDeviceInfo});
7407         configureDevice(InputReaderConfiguration::Change::EXTERNAL_STYLUS_PRESENCE);
7408         processExternalStylusState(mapper);
7409         return mapper;
7410     }
7411 
processExternalStylusState(InputMapper & mapper)7412     std::list<NotifyArgs> processExternalStylusState(InputMapper& mapper) {
7413         std::list<NotifyArgs> generatedArgs = mapper.updateExternalStylusState(mStylusState);
7414         for (const NotifyArgs& args : generatedArgs) {
7415             mFakeListener->notify(args);
7416         }
7417         // Loop the reader to flush the input listener queue.
7418         mReader->loopOnce();
7419         return generatedArgs;
7420     }
7421 
7422 protected:
7423     StylusState mStylusState{};
7424 
testStartFusedStylusGesture(SingleTouchInputMapper & mapper)7425     void testStartFusedStylusGesture(SingleTouchInputMapper& mapper) {
7426         auto toolTypeSource =
7427                 AllOf(WithSource(STYLUS_FUSION_SOURCE), WithToolType(ToolType::STYLUS));
7428 
7429         // The first pointer is withheld.
7430         processDown(mapper, 100, 200);
7431         processSync(mapper);
7432         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7433         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasRequested(
7434                 ARBITRARY_TIME + EXTERNAL_STYLUS_DATA_TIMEOUT));
7435 
7436         // The external stylus reports pressure. The withheld finger pointer is released as a
7437         // stylus.
7438         mStylusState.pressure = 1.f;
7439         processExternalStylusState(mapper);
7440         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7441                 AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_DOWN))));
7442         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7443 
7444         // Subsequent pointer events are not withheld.
7445         processMove(mapper, 101, 201);
7446         processSync(mapper);
7447         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7448                 AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE))));
7449 
7450         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7451         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7452     }
7453 
testSuccessfulFusionGesture(SingleTouchInputMapper & mapper)7454     void testSuccessfulFusionGesture(SingleTouchInputMapper& mapper) {
7455         ASSERT_NO_FATAL_FAILURE(testStartFusedStylusGesture(mapper));
7456 
7457         // Releasing the touch pointer ends the gesture.
7458         processUp(mapper);
7459         processSync(mapper);
7460         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7461                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP), WithSource(STYLUS_FUSION_SOURCE),
7462                       WithToolType(ToolType::STYLUS))));
7463 
7464         mStylusState.pressure = 0.f;
7465         processExternalStylusState(mapper);
7466         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7467         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7468     }
7469 
testUnsuccessfulFusionGesture(SingleTouchInputMapper & mapper)7470     void testUnsuccessfulFusionGesture(SingleTouchInputMapper& mapper) {
7471         // When stylus fusion is not successful, events should be reported with the original source.
7472         // In this case, it is from a touchscreen.
7473         auto toolTypeSource =
7474                 AllOf(WithSource(AINPUT_SOURCE_TOUCHSCREEN), WithToolType(ToolType::FINGER));
7475 
7476         // The first pointer is withheld when an external stylus is connected,
7477         // and a timeout is requested.
7478         processDown(mapper, 100, 200);
7479         processSync(mapper);
7480         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7481         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasRequested(
7482                 ARBITRARY_TIME + EXTERNAL_STYLUS_DATA_TIMEOUT));
7483 
7484         // If the timeout expires early, it is requested again.
7485         handleTimeout(mapper, ARBITRARY_TIME + 1);
7486         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasRequested(
7487                 ARBITRARY_TIME + EXTERNAL_STYLUS_DATA_TIMEOUT));
7488 
7489         // When the timeout expires, the withheld touch is released as a finger pointer.
7490         handleTimeout(mapper, ARBITRARY_TIME + EXTERNAL_STYLUS_DATA_TIMEOUT);
7491         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7492                 AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_DOWN))));
7493 
7494         // Subsequent pointer events are not withheld.
7495         processMove(mapper, 101, 201);
7496         processSync(mapper);
7497         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7498                 AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE))));
7499         processUp(mapper);
7500         processSync(mapper);
7501         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7502                 AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_UP))));
7503 
7504         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7505         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7506     }
7507 
7508 private:
7509     InputDeviceInfo mExternalStylusDeviceInfo{};
7510 };
7511 
TEST_F(ExternalStylusFusionTest,UsesBluetoothStylusSource)7512 TEST_F(ExternalStylusFusionTest, UsesBluetoothStylusSource) {
7513     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
7514     ASSERT_EQ(STYLUS_FUSION_SOURCE, mapper.getSources());
7515 }
7516 
TEST_F(ExternalStylusFusionTest,UnsuccessfulFusion)7517 TEST_F(ExternalStylusFusionTest, UnsuccessfulFusion) {
7518     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
7519     ASSERT_NO_FATAL_FAILURE(testUnsuccessfulFusionGesture(mapper));
7520 }
7521 
TEST_F(ExternalStylusFusionTest,SuccessfulFusion_TouchFirst)7522 TEST_F(ExternalStylusFusionTest, SuccessfulFusion_TouchFirst) {
7523     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
7524     ASSERT_NO_FATAL_FAILURE(testSuccessfulFusionGesture(mapper));
7525 }
7526 
7527 // Test a successful stylus fusion gesture where the pressure is reported by the external
7528 // before the touch is reported by the touchscreen.
TEST_F(ExternalStylusFusionTest,SuccessfulFusion_PressureFirst)7529 TEST_F(ExternalStylusFusionTest, SuccessfulFusion_PressureFirst) {
7530     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
7531     auto toolTypeSource = AllOf(WithSource(STYLUS_FUSION_SOURCE), WithToolType(ToolType::STYLUS));
7532 
7533     // The external stylus reports pressure first. It is ignored for now.
7534     mStylusState.pressure = 1.f;
7535     processExternalStylusState(mapper);
7536     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7537     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7538 
7539     // When the touch goes down afterwards, it is reported as a stylus pointer.
7540     processDown(mapper, 100, 200);
7541     processSync(mapper);
7542     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7543             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_DOWN))));
7544     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7545 
7546     processMove(mapper, 101, 201);
7547     processSync(mapper);
7548     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7549             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE))));
7550     processUp(mapper);
7551     processSync(mapper);
7552     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7553             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_UP))));
7554 
7555     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7556     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7557 }
7558 
TEST_F(ExternalStylusFusionTest,FusionIsRepeatedForEachNewGesture)7559 TEST_F(ExternalStylusFusionTest, FusionIsRepeatedForEachNewGesture) {
7560     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
7561 
7562     ASSERT_NO_FATAL_FAILURE(testSuccessfulFusionGesture(mapper));
7563     ASSERT_NO_FATAL_FAILURE(testUnsuccessfulFusionGesture(mapper));
7564 
7565     ASSERT_NO_FATAL_FAILURE(testSuccessfulFusionGesture(mapper));
7566     ASSERT_NO_FATAL_FAILURE(testSuccessfulFusionGesture(mapper));
7567     ASSERT_NO_FATAL_FAILURE(testUnsuccessfulFusionGesture(mapper));
7568     ASSERT_NO_FATAL_FAILURE(testUnsuccessfulFusionGesture(mapper));
7569 }
7570 
TEST_F(ExternalStylusFusionTest,FusedPointerReportsPressureChanges)7571 TEST_F(ExternalStylusFusionTest, FusedPointerReportsPressureChanges) {
7572     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
7573     auto toolTypeSource = AllOf(WithSource(STYLUS_FUSION_SOURCE), WithToolType(ToolType::STYLUS));
7574 
7575     mStylusState.pressure = 0.8f;
7576     processExternalStylusState(mapper);
7577     processDown(mapper, 100, 200);
7578     processSync(mapper);
7579     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7580             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
7581                   WithPressure(0.8f))));
7582     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7583 
7584     // The external stylus reports a pressure change. We wait for some time for a touch event.
7585     mStylusState.pressure = 0.6f;
7586     processExternalStylusState(mapper);
7587     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7588     ASSERT_NO_FATAL_FAILURE(
7589             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
7590 
7591     // If a touch is reported within the timeout, it reports the updated pressure.
7592     processMove(mapper, 101, 201);
7593     processSync(mapper);
7594     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7595             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
7596                   WithPressure(0.6f))));
7597     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7598 
7599     // There is another pressure change.
7600     mStylusState.pressure = 0.5f;
7601     processExternalStylusState(mapper);
7602     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7603     ASSERT_NO_FATAL_FAILURE(
7604             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
7605 
7606     // If a touch is not reported within the timeout, a move event is generated to report
7607     // the new pressure.
7608     handleTimeout(mapper, ARBITRARY_TIME + TOUCH_DATA_TIMEOUT);
7609     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7610             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
7611                   WithPressure(0.5f))));
7612 
7613     // If a zero pressure is reported before the touch goes up, the previous pressure value is
7614     // repeated indefinitely.
7615     mStylusState.pressure = 0.0f;
7616     processExternalStylusState(mapper);
7617     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7618     ASSERT_NO_FATAL_FAILURE(
7619             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
7620     processMove(mapper, 102, 202);
7621     processSync(mapper);
7622     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7623             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
7624                   WithPressure(0.5f))));
7625     processMove(mapper, 103, 203);
7626     processSync(mapper);
7627     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7628             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
7629                   WithPressure(0.5f))));
7630 
7631     processUp(mapper);
7632     processSync(mapper);
7633     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7634             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP), WithSource(STYLUS_FUSION_SOURCE),
7635                   WithToolType(ToolType::STYLUS))));
7636 
7637     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7638     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7639 }
7640 
TEST_F(ExternalStylusFusionTest,FusedPointerReportsToolTypeChanges)7641 TEST_F(ExternalStylusFusionTest, FusedPointerReportsToolTypeChanges) {
7642     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
7643     auto source = WithSource(STYLUS_FUSION_SOURCE);
7644 
7645     mStylusState.pressure = 1.f;
7646     mStylusState.toolType = ToolType::ERASER;
7647     processExternalStylusState(mapper);
7648     processDown(mapper, 100, 200);
7649     processSync(mapper);
7650     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7651             AllOf(source, WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
7652                   WithToolType(ToolType::ERASER))));
7653     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7654 
7655     // The external stylus reports a tool change. We wait for some time for a touch event.
7656     mStylusState.toolType = ToolType::STYLUS;
7657     processExternalStylusState(mapper);
7658     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7659     ASSERT_NO_FATAL_FAILURE(
7660             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
7661 
7662     // If a touch is reported within the timeout, it reports the updated pressure.
7663     processMove(mapper, 101, 201);
7664     processSync(mapper);
7665     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7666             AllOf(source, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
7667                   WithToolType(ToolType::STYLUS))));
7668     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7669 
7670     // There is another tool type change.
7671     mStylusState.toolType = ToolType::FINGER;
7672     processExternalStylusState(mapper);
7673     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7674     ASSERT_NO_FATAL_FAILURE(
7675             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
7676 
7677     // If a touch is not reported within the timeout, a move event is generated to report
7678     // the new tool type.
7679     handleTimeout(mapper, ARBITRARY_TIME + TOUCH_DATA_TIMEOUT);
7680     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7681             AllOf(source, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
7682                   WithToolType(ToolType::FINGER))));
7683 
7684     processUp(mapper);
7685     processSync(mapper);
7686     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7687             AllOf(source, WithMotionAction(AMOTION_EVENT_ACTION_UP),
7688                   WithToolType(ToolType::FINGER))));
7689 
7690     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7691     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7692 }
7693 
TEST_F(ExternalStylusFusionTest,FusedPointerReportsButtons)7694 TEST_F(ExternalStylusFusionTest, FusedPointerReportsButtons) {
7695     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
7696     auto toolTypeSource = AllOf(WithSource(STYLUS_FUSION_SOURCE), WithToolType(ToolType::STYLUS));
7697 
7698     ASSERT_NO_FATAL_FAILURE(testStartFusedStylusGesture(mapper));
7699 
7700     // The external stylus reports a button change. We wait for some time for a touch event.
7701     mStylusState.buttons = AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
7702     processExternalStylusState(mapper);
7703     ASSERT_NO_FATAL_FAILURE(
7704             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
7705 
7706     // If a touch is reported within the timeout, it reports the updated button state.
7707     processMove(mapper, 101, 201);
7708     processSync(mapper);
7709     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7710             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
7711                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
7712     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7713             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
7714                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
7715     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7716 
7717     // The button is now released.
7718     mStylusState.buttons = 0;
7719     processExternalStylusState(mapper);
7720     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7721     ASSERT_NO_FATAL_FAILURE(
7722             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
7723 
7724     // If a touch is not reported within the timeout, a move event is generated to report
7725     // the new button state.
7726     handleTimeout(mapper, ARBITRARY_TIME + TOUCH_DATA_TIMEOUT);
7727     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7728             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
7729                   WithButtonState(0))));
7730     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7731             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
7732                   WithButtonState(0))));
7733 
7734     processUp(mapper);
7735     processSync(mapper);
7736     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7737             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_UP), WithButtonState(0))));
7738 
7739     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7740     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7741 }
7742 
7743 // --- MultiTouchInputMapperTest ---
7744 
7745 class MultiTouchInputMapperTest : public TouchInputMapperTest {
7746 protected:
7747     void prepareAxes(int axes);
7748 
7749     void processPosition(MultiTouchInputMapper& mapper, int32_t x, int32_t y);
7750     void processTouchMajor(MultiTouchInputMapper& mapper, int32_t touchMajor);
7751     void processTouchMinor(MultiTouchInputMapper& mapper, int32_t touchMinor);
7752     void processToolMajor(MultiTouchInputMapper& mapper, int32_t toolMajor);
7753     void processToolMinor(MultiTouchInputMapper& mapper, int32_t toolMinor);
7754     void processOrientation(MultiTouchInputMapper& mapper, int32_t orientation);
7755     void processPressure(MultiTouchInputMapper& mapper, int32_t pressure);
7756     void processDistance(MultiTouchInputMapper& mapper, int32_t distance);
7757     void processId(MultiTouchInputMapper& mapper, int32_t id);
7758     void processSlot(MultiTouchInputMapper& mapper, int32_t slot);
7759     void processToolType(MultiTouchInputMapper& mapper, int32_t toolType);
7760     void processKey(MultiTouchInputMapper& mapper, int32_t code, int32_t value);
7761     void processHidUsage(MultiTouchInputMapper& mapper, int32_t usageCode, int32_t value);
7762     void processMTSync(MultiTouchInputMapper& mapper);
7763     void processSync(MultiTouchInputMapper& mapper, nsecs_t eventTime = ARBITRARY_TIME,
7764                      nsecs_t readTime = READ_TIME);
7765 };
7766 
prepareAxes(int axes)7767 void MultiTouchInputMapperTest::prepareAxes(int axes) {
7768     if (axes & POSITION) {
7769         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_X, RAW_X_MIN, RAW_X_MAX, 0, 0);
7770         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_Y, RAW_Y_MIN, RAW_Y_MAX, 0, 0);
7771     }
7772     if (axes & TOUCH) {
7773         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_TOUCH_MAJOR, RAW_TOUCH_MIN,
7774                                        RAW_TOUCH_MAX, 0, 0);
7775         if (axes & MINOR) {
7776             mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_TOUCH_MINOR, RAW_TOUCH_MIN,
7777                                            RAW_TOUCH_MAX, 0, 0);
7778         }
7779     }
7780     if (axes & TOOL) {
7781         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_WIDTH_MAJOR, RAW_TOOL_MIN, RAW_TOOL_MAX,
7782                                        0, 0);
7783         if (axes & MINOR) {
7784             mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_WIDTH_MINOR, RAW_TOOL_MIN,
7785                                            RAW_TOOL_MAX, 0, 0);
7786         }
7787     }
7788     if (axes & ORIENTATION) {
7789         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_ORIENTATION, RAW_ORIENTATION_MIN,
7790                                        RAW_ORIENTATION_MAX, 0, 0);
7791     }
7792     if (axes & PRESSURE) {
7793         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_PRESSURE, RAW_PRESSURE_MIN,
7794                                        RAW_PRESSURE_MAX, 0, 0);
7795     }
7796     if (axes & DISTANCE) {
7797         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_DISTANCE, RAW_DISTANCE_MIN,
7798                                        RAW_DISTANCE_MAX, 0, 0);
7799     }
7800     if (axes & ID) {
7801         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_TRACKING_ID, RAW_ID_MIN, RAW_ID_MAX, 0,
7802                                        0);
7803     }
7804     if (axes & SLOT) {
7805         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_SLOT, RAW_SLOT_MIN, RAW_SLOT_MAX, 0, 0);
7806         mFakeEventHub->setAbsoluteAxisValue(EVENTHUB_ID, ABS_MT_SLOT, 0);
7807     }
7808     if (axes & TOOL_TYPE) {
7809         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_TOOL_TYPE, 0, MT_TOOL_MAX, 0, 0);
7810     }
7811 }
7812 
processPosition(MultiTouchInputMapper & mapper,int32_t x,int32_t y)7813 void MultiTouchInputMapperTest::processPosition(MultiTouchInputMapper& mapper, int32_t x,
7814                                                 int32_t y) {
7815     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_POSITION_X, x);
7816     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_POSITION_Y, y);
7817 }
7818 
processTouchMajor(MultiTouchInputMapper & mapper,int32_t touchMajor)7819 void MultiTouchInputMapperTest::processTouchMajor(MultiTouchInputMapper& mapper,
7820                                                   int32_t touchMajor) {
7821     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_TOUCH_MAJOR, touchMajor);
7822 }
7823 
processTouchMinor(MultiTouchInputMapper & mapper,int32_t touchMinor)7824 void MultiTouchInputMapperTest::processTouchMinor(MultiTouchInputMapper& mapper,
7825                                                   int32_t touchMinor) {
7826     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_TOUCH_MINOR, touchMinor);
7827 }
7828 
processToolMajor(MultiTouchInputMapper & mapper,int32_t toolMajor)7829 void MultiTouchInputMapperTest::processToolMajor(MultiTouchInputMapper& mapper, int32_t toolMajor) {
7830     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_WIDTH_MAJOR, toolMajor);
7831 }
7832 
processToolMinor(MultiTouchInputMapper & mapper,int32_t toolMinor)7833 void MultiTouchInputMapperTest::processToolMinor(MultiTouchInputMapper& mapper, int32_t toolMinor) {
7834     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_WIDTH_MINOR, toolMinor);
7835 }
7836 
processOrientation(MultiTouchInputMapper & mapper,int32_t orientation)7837 void MultiTouchInputMapperTest::processOrientation(MultiTouchInputMapper& mapper,
7838                                                    int32_t orientation) {
7839     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_ORIENTATION, orientation);
7840 }
7841 
processPressure(MultiTouchInputMapper & mapper,int32_t pressure)7842 void MultiTouchInputMapperTest::processPressure(MultiTouchInputMapper& mapper, int32_t pressure) {
7843     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_PRESSURE, pressure);
7844 }
7845 
processDistance(MultiTouchInputMapper & mapper,int32_t distance)7846 void MultiTouchInputMapperTest::processDistance(MultiTouchInputMapper& mapper, int32_t distance) {
7847     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_DISTANCE, distance);
7848 }
7849 
processId(MultiTouchInputMapper & mapper,int32_t id)7850 void MultiTouchInputMapperTest::processId(MultiTouchInputMapper& mapper, int32_t id) {
7851     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_TRACKING_ID, id);
7852 }
7853 
processSlot(MultiTouchInputMapper & mapper,int32_t slot)7854 void MultiTouchInputMapperTest::processSlot(MultiTouchInputMapper& mapper, int32_t slot) {
7855     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_SLOT, slot);
7856 }
7857 
processToolType(MultiTouchInputMapper & mapper,int32_t toolType)7858 void MultiTouchInputMapperTest::processToolType(MultiTouchInputMapper& mapper, int32_t toolType) {
7859     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_TOOL_TYPE, toolType);
7860 }
7861 
processKey(MultiTouchInputMapper & mapper,int32_t code,int32_t value)7862 void MultiTouchInputMapperTest::processKey(MultiTouchInputMapper& mapper, int32_t code,
7863                                            int32_t value) {
7864     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, code, value);
7865 }
7866 
processHidUsage(MultiTouchInputMapper & mapper,int32_t usageCode,int32_t value)7867 void MultiTouchInputMapperTest::processHidUsage(MultiTouchInputMapper& mapper, int32_t usageCode,
7868                                                 int32_t value) {
7869     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_SCAN, usageCode);
7870     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UNKNOWN, value);
7871 }
7872 
processMTSync(MultiTouchInputMapper & mapper)7873 void MultiTouchInputMapperTest::processMTSync(MultiTouchInputMapper& mapper) {
7874     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_MT_REPORT, 0);
7875 }
7876 
processSync(MultiTouchInputMapper & mapper,nsecs_t eventTime,nsecs_t readTime)7877 void MultiTouchInputMapperTest::processSync(MultiTouchInputMapper& mapper, nsecs_t eventTime,
7878                                             nsecs_t readTime) {
7879     process(mapper, eventTime, readTime, EV_SYN, SYN_REPORT, 0);
7880 }
7881 
TEST_F(MultiTouchInputMapperTest,Process_NormalMultiTouchGesture_WithoutTrackingIds)7882 TEST_F(MultiTouchInputMapperTest, Process_NormalMultiTouchGesture_WithoutTrackingIds) {
7883     addConfigurationProperty("touch.deviceType", "touchScreen");
7884     prepareDisplay(ui::ROTATION_0);
7885     prepareAxes(POSITION);
7886     prepareVirtualKeys();
7887     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
7888 
7889     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
7890 
7891     NotifyMotionArgs motionArgs;
7892 
7893     // Two fingers down at once.
7894     int32_t x1 = 100, y1 = 125, x2 = 300, y2 = 500;
7895     processPosition(mapper, x1, y1);
7896     processMTSync(mapper);
7897     processPosition(mapper, x2, y2);
7898     processMTSync(mapper);
7899     processSync(mapper);
7900 
7901     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7902     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7903     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7904     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7905     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7906     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
7907     ASSERT_EQ(0, motionArgs.flags);
7908     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7909     ASSERT_EQ(0, motionArgs.buttonState);
7910     ASSERT_EQ(0, motionArgs.edgeFlags);
7911     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7912     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7913     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7914     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7915             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7916     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7917     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7918     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7919 
7920     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7921     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7922     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7923     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7924     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7925     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
7926     ASSERT_EQ(0, motionArgs.flags);
7927     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7928     ASSERT_EQ(0, motionArgs.buttonState);
7929     ASSERT_EQ(0, motionArgs.edgeFlags);
7930     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7931     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7932     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7933     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7934     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7935     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7936             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7937     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7938             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7939     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7940     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7941     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7942 
7943     // Move.
7944     x1 += 10; y1 += 15; x2 += 5; y2 -= 10;
7945     processPosition(mapper, x1, y1);
7946     processMTSync(mapper);
7947     processPosition(mapper, x2, y2);
7948     processMTSync(mapper);
7949     processSync(mapper);
7950 
7951     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7952     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7953     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7954     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7955     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7956     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7957     ASSERT_EQ(0, motionArgs.flags);
7958     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7959     ASSERT_EQ(0, motionArgs.buttonState);
7960     ASSERT_EQ(0, motionArgs.edgeFlags);
7961     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7962     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7963     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7964     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7965     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7966     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7967             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7968     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7969             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7970     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7971     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7972     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7973 
7974     // First finger up.
7975     x2 += 15; y2 -= 20;
7976     processPosition(mapper, x2, y2);
7977     processMTSync(mapper);
7978     processSync(mapper);
7979 
7980     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7981     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7982     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7983     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7984     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7985     ASSERT_EQ(ACTION_POINTER_0_UP, motionArgs.action);
7986     ASSERT_EQ(0, motionArgs.flags);
7987     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7988     ASSERT_EQ(0, motionArgs.buttonState);
7989     ASSERT_EQ(0, motionArgs.edgeFlags);
7990     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7991     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7992     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7993     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7994     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7995     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7996             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7997     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7998             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7999     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
8000     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
8001     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
8002 
8003     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8004     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
8005     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
8006     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
8007     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
8008     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8009     ASSERT_EQ(0, motionArgs.flags);
8010     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
8011     ASSERT_EQ(0, motionArgs.buttonState);
8012     ASSERT_EQ(0, motionArgs.edgeFlags);
8013     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8014     ASSERT_EQ(1, motionArgs.pointerProperties[0].id);
8015     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8016     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8017             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8018     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
8019     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
8020     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
8021 
8022     // Move.
8023     x2 += 20; y2 -= 25;
8024     processPosition(mapper, x2, y2);
8025     processMTSync(mapper);
8026     processSync(mapper);
8027 
8028     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8029     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
8030     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
8031     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
8032     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
8033     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8034     ASSERT_EQ(0, motionArgs.flags);
8035     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
8036     ASSERT_EQ(0, motionArgs.buttonState);
8037     ASSERT_EQ(0, motionArgs.edgeFlags);
8038     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8039     ASSERT_EQ(1, motionArgs.pointerProperties[0].id);
8040     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8041     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8042             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8043     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
8044     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
8045     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
8046 
8047     // New finger down.
8048     int32_t x3 = 700, y3 = 300;
8049     processPosition(mapper, x2, y2);
8050     processMTSync(mapper);
8051     processPosition(mapper, x3, y3);
8052     processMTSync(mapper);
8053     processSync(mapper);
8054 
8055     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8056     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
8057     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
8058     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
8059     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
8060     ASSERT_EQ(ACTION_POINTER_0_DOWN, motionArgs.action);
8061     ASSERT_EQ(0, motionArgs.flags);
8062     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
8063     ASSERT_EQ(0, motionArgs.buttonState);
8064     ASSERT_EQ(0, motionArgs.edgeFlags);
8065     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
8066     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8067     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8068     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
8069     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
8070     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8071             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
8072     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
8073             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8074     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
8075     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
8076     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
8077 
8078     // Second finger up.
8079     x3 += 30; y3 -= 20;
8080     processPosition(mapper, x3, y3);
8081     processMTSync(mapper);
8082     processSync(mapper);
8083 
8084     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8085     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
8086     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
8087     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
8088     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
8089     ASSERT_EQ(ACTION_POINTER_1_UP, motionArgs.action);
8090     ASSERT_EQ(0, motionArgs.flags);
8091     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
8092     ASSERT_EQ(0, motionArgs.buttonState);
8093     ASSERT_EQ(0, motionArgs.edgeFlags);
8094     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
8095     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8096     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8097     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
8098     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
8099     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8100             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
8101     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
8102             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8103     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
8104     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
8105     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
8106 
8107     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8108     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
8109     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
8110     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
8111     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
8112     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8113     ASSERT_EQ(0, motionArgs.flags);
8114     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
8115     ASSERT_EQ(0, motionArgs.buttonState);
8116     ASSERT_EQ(0, motionArgs.edgeFlags);
8117     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8118     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8119     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8120     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8121             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
8122     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
8123     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
8124     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
8125 
8126     // Last finger up.
8127     processMTSync(mapper);
8128     processSync(mapper);
8129 
8130     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8131     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
8132     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
8133     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
8134     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
8135     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
8136     ASSERT_EQ(0, motionArgs.flags);
8137     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
8138     ASSERT_EQ(0, motionArgs.buttonState);
8139     ASSERT_EQ(0, motionArgs.edgeFlags);
8140     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8141     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8142     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8143     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8144             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
8145     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
8146     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
8147     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
8148 
8149     // Should not have sent any more keys or motions.
8150     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
8151     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
8152 }
8153 
TEST_F(MultiTouchInputMapperTest,AxisResolution_IsPopulated)8154 TEST_F(MultiTouchInputMapperTest, AxisResolution_IsPopulated) {
8155     addConfigurationProperty("touch.deviceType", "touchScreen");
8156     prepareDisplay(ui::ROTATION_0);
8157 
8158     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_X, RAW_X_MIN, RAW_X_MAX, /*flat*/ 0,
8159                                    /*fuzz*/ 0, /*resolution*/ 10);
8160     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_Y, RAW_Y_MIN, RAW_Y_MAX, /*flat*/ 0,
8161                                    /*fuzz*/ 0, /*resolution*/ 11);
8162     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_TOUCH_MAJOR, RAW_TOUCH_MIN, RAW_TOUCH_MAX,
8163                                    /*flat*/ 0, /*fuzz*/ 0, /*resolution*/ 12);
8164     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_TOUCH_MINOR, RAW_TOUCH_MIN, RAW_TOUCH_MAX,
8165                                    /*flat*/ 0, /*fuzz*/ 0, /*resolution*/ 13);
8166     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_WIDTH_MAJOR, RAW_TOOL_MIN, RAW_TOOL_MAX,
8167                                    /*flat*/ 0, /*flat*/ 0, /*resolution*/ 14);
8168     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_WIDTH_MINOR, RAW_TOOL_MIN, RAW_TOOL_MAX,
8169                                    /*flat*/ 0, /*flat*/ 0, /*resolution*/ 15);
8170 
8171     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8172 
8173     // X and Y axes
8174     assertAxisResolution(mapper, AMOTION_EVENT_AXIS_X, 10 / X_PRECISION);
8175     assertAxisResolution(mapper, AMOTION_EVENT_AXIS_Y, 11 / Y_PRECISION);
8176     // Touch major and minor
8177     assertAxisResolution(mapper, AMOTION_EVENT_AXIS_TOUCH_MAJOR, 12 * GEOMETRIC_SCALE);
8178     assertAxisResolution(mapper, AMOTION_EVENT_AXIS_TOUCH_MINOR, 13 * GEOMETRIC_SCALE);
8179     // Tool major and minor
8180     assertAxisResolution(mapper, AMOTION_EVENT_AXIS_TOOL_MAJOR, 14 * GEOMETRIC_SCALE);
8181     assertAxisResolution(mapper, AMOTION_EVENT_AXIS_TOOL_MINOR, 15 * GEOMETRIC_SCALE);
8182 }
8183 
TEST_F(MultiTouchInputMapperTest,TouchMajorAndMinorAxes_DoNotAppearIfNotSupported)8184 TEST_F(MultiTouchInputMapperTest, TouchMajorAndMinorAxes_DoNotAppearIfNotSupported) {
8185     addConfigurationProperty("touch.deviceType", "touchScreen");
8186     prepareDisplay(ui::ROTATION_0);
8187 
8188     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_X, RAW_X_MIN, RAW_X_MAX, /*flat*/ 0,
8189                                    /*fuzz*/ 0, /*resolution*/ 10);
8190     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_Y, RAW_Y_MIN, RAW_Y_MAX, /*flat*/ 0,
8191                                    /*fuzz*/ 0, /*resolution*/ 11);
8192 
8193     // We do not add ABS_MT_TOUCH_MAJOR / MINOR or ABS_MT_WIDTH_MAJOR / MINOR axes
8194 
8195     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8196 
8197     // Touch major and minor
8198     assertAxisNotPresent(mapper, AMOTION_EVENT_AXIS_TOUCH_MAJOR);
8199     assertAxisNotPresent(mapper, AMOTION_EVENT_AXIS_TOUCH_MINOR);
8200     // Tool major and minor
8201     assertAxisNotPresent(mapper, AMOTION_EVENT_AXIS_TOOL_MAJOR);
8202     assertAxisNotPresent(mapper, AMOTION_EVENT_AXIS_TOOL_MINOR);
8203 }
8204 
TEST_F(MultiTouchInputMapperTest,Process_NormalMultiTouchGesture_WithTrackingIds)8205 TEST_F(MultiTouchInputMapperTest, Process_NormalMultiTouchGesture_WithTrackingIds) {
8206     addConfigurationProperty("touch.deviceType", "touchScreen");
8207     prepareDisplay(ui::ROTATION_0);
8208     prepareAxes(POSITION | ID);
8209     prepareVirtualKeys();
8210     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8211 
8212     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
8213 
8214     NotifyMotionArgs motionArgs;
8215 
8216     // Two fingers down at once.
8217     int32_t x1 = 100, y1 = 125, x2 = 300, y2 = 500;
8218     processPosition(mapper, x1, y1);
8219     processId(mapper, 1);
8220     processMTSync(mapper);
8221     processPosition(mapper, x2, y2);
8222     processId(mapper, 2);
8223     processMTSync(mapper);
8224     processSync(mapper);
8225 
8226     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8227     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
8228     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8229     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8230     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8231     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8232             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
8233 
8234     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8235     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
8236     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
8237     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8238     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8239     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
8240     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
8241     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8242             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
8243     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
8244             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8245 
8246     // Move.
8247     x1 += 10; y1 += 15; x2 += 5; y2 -= 10;
8248     processPosition(mapper, x1, y1);
8249     processId(mapper, 1);
8250     processMTSync(mapper);
8251     processPosition(mapper, x2, y2);
8252     processId(mapper, 2);
8253     processMTSync(mapper);
8254     processSync(mapper);
8255 
8256     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8257     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8258     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
8259     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8260     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8261     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
8262     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
8263     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8264             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
8265     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
8266             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8267 
8268     // First finger up.
8269     x2 += 15; y2 -= 20;
8270     processPosition(mapper, x2, y2);
8271     processId(mapper, 2);
8272     processMTSync(mapper);
8273     processSync(mapper);
8274 
8275     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8276     ASSERT_EQ(ACTION_POINTER_0_UP, motionArgs.action);
8277     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
8278     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8279     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8280     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
8281     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
8282     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8283             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
8284     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
8285             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8286 
8287     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8288     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8289     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8290     ASSERT_EQ(1, motionArgs.pointerProperties[0].id);
8291     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8292     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8293             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8294 
8295     // Move.
8296     x2 += 20; y2 -= 25;
8297     processPosition(mapper, x2, y2);
8298     processId(mapper, 2);
8299     processMTSync(mapper);
8300     processSync(mapper);
8301 
8302     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8303     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8304     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8305     ASSERT_EQ(1, motionArgs.pointerProperties[0].id);
8306     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8307     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8308             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8309 
8310     // New finger down.
8311     int32_t x3 = 700, y3 = 300;
8312     processPosition(mapper, x2, y2);
8313     processId(mapper, 2);
8314     processMTSync(mapper);
8315     processPosition(mapper, x3, y3);
8316     processId(mapper, 3);
8317     processMTSync(mapper);
8318     processSync(mapper);
8319 
8320     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8321     ASSERT_EQ(ACTION_POINTER_0_DOWN, motionArgs.action);
8322     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
8323     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8324     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8325     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
8326     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
8327     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8328             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
8329     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
8330             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8331 
8332     // Second finger up.
8333     x3 += 30; y3 -= 20;
8334     processPosition(mapper, x3, y3);
8335     processId(mapper, 3);
8336     processMTSync(mapper);
8337     processSync(mapper);
8338 
8339     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8340     ASSERT_EQ(ACTION_POINTER_1_UP, motionArgs.action);
8341     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
8342     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8343     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8344     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
8345     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
8346     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8347             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
8348     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
8349             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8350 
8351     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8352     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8353     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8354     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8355     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8356     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8357             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
8358 
8359     // Last finger up.
8360     processMTSync(mapper);
8361     processSync(mapper);
8362 
8363     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8364     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
8365     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8366     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8367     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8368     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8369             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
8370 
8371     // Should not have sent any more keys or motions.
8372     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
8373     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
8374 }
8375 
TEST_F(MultiTouchInputMapperTest,Process_NormalMultiTouchGesture_WithSlots)8376 TEST_F(MultiTouchInputMapperTest, Process_NormalMultiTouchGesture_WithSlots) {
8377     addConfigurationProperty("touch.deviceType", "touchScreen");
8378     prepareDisplay(ui::ROTATION_0);
8379     prepareAxes(POSITION | ID | SLOT);
8380     prepareVirtualKeys();
8381     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8382 
8383     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
8384 
8385     NotifyMotionArgs motionArgs;
8386 
8387     // Two fingers down at once.
8388     int32_t x1 = 100, y1 = 125, x2 = 300, y2 = 500;
8389     processPosition(mapper, x1, y1);
8390     processId(mapper, 1);
8391     processSlot(mapper, 1);
8392     processPosition(mapper, x2, y2);
8393     processId(mapper, 2);
8394     processSync(mapper);
8395 
8396     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8397     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
8398     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8399     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8400     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8401     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8402             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
8403 
8404     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8405     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
8406     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
8407     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8408     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8409     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
8410     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
8411     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8412             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
8413     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
8414             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8415 
8416     // Move.
8417     x1 += 10; y1 += 15; x2 += 5; y2 -= 10;
8418     processSlot(mapper, 0);
8419     processPosition(mapper, x1, y1);
8420     processSlot(mapper, 1);
8421     processPosition(mapper, x2, y2);
8422     processSync(mapper);
8423 
8424     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8425     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8426     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
8427     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8428     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8429     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
8430     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
8431     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8432             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
8433     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
8434             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8435 
8436     // First finger up.
8437     x2 += 15; y2 -= 20;
8438     processSlot(mapper, 0);
8439     processId(mapper, -1);
8440     processSlot(mapper, 1);
8441     processPosition(mapper, x2, y2);
8442     processSync(mapper);
8443 
8444     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8445     ASSERT_EQ(ACTION_POINTER_0_UP, motionArgs.action);
8446     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
8447     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8448     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8449     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
8450     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
8451     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8452             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
8453     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
8454             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8455 
8456     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8457     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8458     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8459     ASSERT_EQ(1, motionArgs.pointerProperties[0].id);
8460     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8461     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8462             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8463 
8464     // Move.
8465     x2 += 20; y2 -= 25;
8466     processPosition(mapper, x2, y2);
8467     processSync(mapper);
8468 
8469     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8470     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8471     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8472     ASSERT_EQ(1, motionArgs.pointerProperties[0].id);
8473     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8474     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8475             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8476 
8477     // New finger down.
8478     int32_t x3 = 700, y3 = 300;
8479     processPosition(mapper, x2, y2);
8480     processSlot(mapper, 0);
8481     processId(mapper, 3);
8482     processPosition(mapper, x3, y3);
8483     processSync(mapper);
8484 
8485     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8486     ASSERT_EQ(ACTION_POINTER_0_DOWN, motionArgs.action);
8487     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
8488     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8489     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8490     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
8491     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
8492     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8493             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
8494     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
8495             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8496 
8497     // Second finger up.
8498     x3 += 30; y3 -= 20;
8499     processSlot(mapper, 1);
8500     processId(mapper, -1);
8501     processSlot(mapper, 0);
8502     processPosition(mapper, x3, y3);
8503     processSync(mapper);
8504 
8505     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8506     ASSERT_EQ(ACTION_POINTER_1_UP, motionArgs.action);
8507     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
8508     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8509     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8510     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
8511     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
8512     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8513             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
8514     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
8515             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
8516 
8517     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8518     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8519     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8520     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8521     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8522     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8523             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
8524 
8525     // Last finger up.
8526     processId(mapper, -1);
8527     processSync(mapper);
8528 
8529     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8530     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
8531     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
8532     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
8533     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8534     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8535             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
8536 
8537     // Should not have sent any more keys or motions.
8538     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
8539     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
8540 }
8541 
TEST_F(MultiTouchInputMapperTest,Process_AllAxes_WithDefaultCalibration)8542 TEST_F(MultiTouchInputMapperTest, Process_AllAxes_WithDefaultCalibration) {
8543     addConfigurationProperty("touch.deviceType", "touchScreen");
8544     prepareDisplay(ui::ROTATION_0);
8545     prepareAxes(POSITION | TOUCH | TOOL | PRESSURE | ORIENTATION | ID | MINOR | DISTANCE);
8546     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8547 
8548     // These calculations are based on the input device calibration documentation.
8549     int32_t rawX = 100;
8550     int32_t rawY = 200;
8551     int32_t rawTouchMajor = 7;
8552     int32_t rawTouchMinor = 6;
8553     int32_t rawToolMajor = 9;
8554     int32_t rawToolMinor = 8;
8555     int32_t rawPressure = 11;
8556     int32_t rawDistance = 0;
8557     int32_t rawOrientation = 3;
8558     int32_t id = 5;
8559 
8560     float x = toDisplayX(rawX);
8561     float y = toDisplayY(rawY);
8562     float pressure = float(rawPressure) / RAW_PRESSURE_MAX;
8563     float size = avg(rawTouchMajor, rawTouchMinor) / RAW_TOUCH_MAX;
8564     float toolMajor = float(rawToolMajor) * GEOMETRIC_SCALE;
8565     float toolMinor = float(rawToolMinor) * GEOMETRIC_SCALE;
8566     float touchMajor = float(rawTouchMajor) * GEOMETRIC_SCALE;
8567     float touchMinor = float(rawTouchMinor) * GEOMETRIC_SCALE;
8568     float orientation = float(rawOrientation) / RAW_ORIENTATION_MAX * M_PI_2;
8569     float distance = float(rawDistance);
8570 
8571     processPosition(mapper, rawX, rawY);
8572     processTouchMajor(mapper, rawTouchMajor);
8573     processTouchMinor(mapper, rawTouchMinor);
8574     processToolMajor(mapper, rawToolMajor);
8575     processToolMinor(mapper, rawToolMinor);
8576     processPressure(mapper, rawPressure);
8577     processOrientation(mapper, rawOrientation);
8578     processDistance(mapper, rawDistance);
8579     processId(mapper, id);
8580     processMTSync(mapper);
8581     processSync(mapper);
8582 
8583     NotifyMotionArgs args;
8584     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8585     ASSERT_EQ(0, args.pointerProperties[0].id);
8586     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
8587             x, y, pressure, size, touchMajor, touchMinor, toolMajor, toolMinor,
8588             orientation, distance));
8589 }
8590 
TEST_F(MultiTouchInputMapperTest,Process_TouchAndToolAxes_GeometricCalibration)8591 TEST_F(MultiTouchInputMapperTest, Process_TouchAndToolAxes_GeometricCalibration) {
8592     addConfigurationProperty("touch.deviceType", "touchScreen");
8593     prepareDisplay(ui::ROTATION_0);
8594     prepareAxes(POSITION | TOUCH | TOOL | MINOR);
8595     addConfigurationProperty("touch.size.calibration", "geometric");
8596     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8597 
8598     // These calculations are based on the input device calibration documentation.
8599     int32_t rawX = 100;
8600     int32_t rawY = 200;
8601     int32_t rawTouchMajor = 140;
8602     int32_t rawTouchMinor = 120;
8603     int32_t rawToolMajor = 180;
8604     int32_t rawToolMinor = 160;
8605 
8606     float x = toDisplayX(rawX);
8607     float y = toDisplayY(rawY);
8608     float size = avg(rawTouchMajor, rawTouchMinor) / RAW_TOUCH_MAX;
8609     float toolMajor = float(rawToolMajor) * GEOMETRIC_SCALE;
8610     float toolMinor = float(rawToolMinor) * GEOMETRIC_SCALE;
8611     float touchMajor = float(rawTouchMajor) * GEOMETRIC_SCALE;
8612     float touchMinor = float(rawTouchMinor) * GEOMETRIC_SCALE;
8613 
8614     processPosition(mapper, rawX, rawY);
8615     processTouchMajor(mapper, rawTouchMajor);
8616     processTouchMinor(mapper, rawTouchMinor);
8617     processToolMajor(mapper, rawToolMajor);
8618     processToolMinor(mapper, rawToolMinor);
8619     processMTSync(mapper);
8620     processSync(mapper);
8621 
8622     NotifyMotionArgs args;
8623     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8624     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
8625             x, y, 1.0f, size, touchMajor, touchMinor, toolMajor, toolMinor, 0, 0));
8626 }
8627 
TEST_F(MultiTouchInputMapperTest,Process_TouchAndToolAxes_SummedLinearCalibration)8628 TEST_F(MultiTouchInputMapperTest, Process_TouchAndToolAxes_SummedLinearCalibration) {
8629     addConfigurationProperty("touch.deviceType", "touchScreen");
8630     prepareDisplay(ui::ROTATION_0);
8631     prepareAxes(POSITION | TOUCH | TOOL);
8632     addConfigurationProperty("touch.size.calibration", "diameter");
8633     addConfigurationProperty("touch.size.scale", "10");
8634     addConfigurationProperty("touch.size.bias", "160");
8635     addConfigurationProperty("touch.size.isSummed", "1");
8636     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8637 
8638     // These calculations are based on the input device calibration documentation.
8639     // Note: We only provide a single common touch/tool value because the device is assumed
8640     //       not to emit separate values for each pointer (isSummed = 1).
8641     int32_t rawX = 100;
8642     int32_t rawY = 200;
8643     int32_t rawX2 = 150;
8644     int32_t rawY2 = 250;
8645     int32_t rawTouchMajor = 5;
8646     int32_t rawToolMajor = 8;
8647 
8648     float x = toDisplayX(rawX);
8649     float y = toDisplayY(rawY);
8650     float x2 = toDisplayX(rawX2);
8651     float y2 = toDisplayY(rawY2);
8652     float size = float(rawTouchMajor) / 2 / RAW_TOUCH_MAX;
8653     float touch = float(rawTouchMajor) / 2 * 10.0f + 160.0f;
8654     float tool = float(rawToolMajor) / 2 * 10.0f + 160.0f;
8655 
8656     processPosition(mapper, rawX, rawY);
8657     processTouchMajor(mapper, rawTouchMajor);
8658     processToolMajor(mapper, rawToolMajor);
8659     processMTSync(mapper);
8660     processPosition(mapper, rawX2, rawY2);
8661     processTouchMajor(mapper, rawTouchMajor);
8662     processToolMajor(mapper, rawToolMajor);
8663     processMTSync(mapper);
8664     processSync(mapper);
8665 
8666     NotifyMotionArgs args;
8667     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8668     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
8669 
8670     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8671     ASSERT_EQ(ACTION_POINTER_1_DOWN, args.action);
8672     ASSERT_EQ(size_t(2), args.getPointerCount());
8673     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
8674             x, y, 1.0f, size, touch, touch, tool, tool, 0, 0));
8675     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[1],
8676             x2, y2, 1.0f, size, touch, touch, tool, tool, 0, 0));
8677 }
8678 
TEST_F(MultiTouchInputMapperTest,Process_TouchAndToolAxes_AreaCalibration)8679 TEST_F(MultiTouchInputMapperTest, Process_TouchAndToolAxes_AreaCalibration) {
8680     addConfigurationProperty("touch.deviceType", "touchScreen");
8681     prepareDisplay(ui::ROTATION_0);
8682     prepareAxes(POSITION | TOUCH | TOOL);
8683     addConfigurationProperty("touch.size.calibration", "area");
8684     addConfigurationProperty("touch.size.scale", "43");
8685     addConfigurationProperty("touch.size.bias", "3");
8686     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8687 
8688     // These calculations are based on the input device calibration documentation.
8689     int32_t rawX = 100;
8690     int32_t rawY = 200;
8691     int32_t rawTouchMajor = 5;
8692     int32_t rawToolMajor = 8;
8693 
8694     float x = toDisplayX(rawX);
8695     float y = toDisplayY(rawY);
8696     float size = float(rawTouchMajor) / RAW_TOUCH_MAX;
8697     float touch = sqrtf(rawTouchMajor) * 43.0f + 3.0f;
8698     float tool = sqrtf(rawToolMajor) * 43.0f + 3.0f;
8699 
8700     processPosition(mapper, rawX, rawY);
8701     processTouchMajor(mapper, rawTouchMajor);
8702     processToolMajor(mapper, rawToolMajor);
8703     processMTSync(mapper);
8704     processSync(mapper);
8705 
8706     NotifyMotionArgs args;
8707     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8708     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
8709             x, y, 1.0f, size, touch, touch, tool, tool, 0, 0));
8710 }
8711 
TEST_F(MultiTouchInputMapperTest,Process_PressureAxis_AmplitudeCalibration)8712 TEST_F(MultiTouchInputMapperTest, Process_PressureAxis_AmplitudeCalibration) {
8713     addConfigurationProperty("touch.deviceType", "touchScreen");
8714     prepareDisplay(ui::ROTATION_0);
8715     prepareAxes(POSITION | PRESSURE);
8716     addConfigurationProperty("touch.pressure.calibration", "amplitude");
8717     addConfigurationProperty("touch.pressure.scale", "0.01");
8718     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8719 
8720     InputDeviceInfo info;
8721     mapper.populateDeviceInfo(info);
8722     ASSERT_NO_FATAL_FAILURE(assertMotionRange(info,
8723             AINPUT_MOTION_RANGE_PRESSURE, AINPUT_SOURCE_TOUCHSCREEN,
8724             0.0f, RAW_PRESSURE_MAX * 0.01, 0.0f, 0.0f));
8725 
8726     // These calculations are based on the input device calibration documentation.
8727     int32_t rawX = 100;
8728     int32_t rawY = 200;
8729     int32_t rawPressure = 60;
8730 
8731     float x = toDisplayX(rawX);
8732     float y = toDisplayY(rawY);
8733     float pressure = float(rawPressure) * 0.01f;
8734 
8735     processPosition(mapper, rawX, rawY);
8736     processPressure(mapper, rawPressure);
8737     processMTSync(mapper);
8738     processSync(mapper);
8739 
8740     NotifyMotionArgs args;
8741     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8742     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
8743             x, y, pressure, 0, 0, 0, 0, 0, 0, 0));
8744 }
8745 
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandleAllButtons)8746 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandleAllButtons) {
8747     addConfigurationProperty("touch.deviceType", "touchScreen");
8748     prepareDisplay(ui::ROTATION_0);
8749     prepareAxes(POSITION | ID | SLOT);
8750     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8751 
8752     NotifyMotionArgs motionArgs;
8753     NotifyKeyArgs keyArgs;
8754 
8755     processId(mapper, 1);
8756     processPosition(mapper, 100, 200);
8757     processSync(mapper);
8758     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8759     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
8760     ASSERT_EQ(0, motionArgs.buttonState);
8761 
8762     // press BTN_LEFT, release BTN_LEFT
8763     processKey(mapper, BTN_LEFT, 1);
8764     processSync(mapper);
8765     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8766     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8767     ASSERT_EQ(AMOTION_EVENT_BUTTON_PRIMARY, motionArgs.buttonState);
8768 
8769     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8770     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8771     ASSERT_EQ(AMOTION_EVENT_BUTTON_PRIMARY, motionArgs.buttonState);
8772 
8773     processKey(mapper, BTN_LEFT, 0);
8774     processSync(mapper);
8775     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8776     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8777     ASSERT_EQ(0, motionArgs.buttonState);
8778 
8779     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8780     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8781     ASSERT_EQ(0, motionArgs.buttonState);
8782 
8783     // press BTN_RIGHT + BTN_MIDDLE, release BTN_RIGHT, release BTN_MIDDLE
8784     processKey(mapper, BTN_RIGHT, 1);
8785     processKey(mapper, BTN_MIDDLE, 1);
8786     processSync(mapper);
8787     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8788     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8789     ASSERT_EQ(AMOTION_EVENT_BUTTON_SECONDARY | AMOTION_EVENT_BUTTON_TERTIARY,
8790             motionArgs.buttonState);
8791 
8792     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8793     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8794     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
8795 
8796     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8797     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8798     ASSERT_EQ(AMOTION_EVENT_BUTTON_SECONDARY | AMOTION_EVENT_BUTTON_TERTIARY,
8799             motionArgs.buttonState);
8800 
8801     processKey(mapper, BTN_RIGHT, 0);
8802     processSync(mapper);
8803     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8804     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8805     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
8806 
8807     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8808     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8809     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
8810 
8811     processKey(mapper, BTN_MIDDLE, 0);
8812     processSync(mapper);
8813     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8814     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8815     ASSERT_EQ(0, motionArgs.buttonState);
8816 
8817     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8818     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8819     ASSERT_EQ(0, motionArgs.buttonState);
8820 
8821     // press BTN_BACK, release BTN_BACK
8822     processKey(mapper, BTN_BACK, 1);
8823     processSync(mapper);
8824     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8825     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
8826     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
8827 
8828     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8829     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8830     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
8831 
8832     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8833     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8834     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
8835 
8836     processKey(mapper, BTN_BACK, 0);
8837     processSync(mapper);
8838     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8839     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8840     ASSERT_EQ(0, motionArgs.buttonState);
8841 
8842     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8843     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8844     ASSERT_EQ(0, motionArgs.buttonState);
8845 
8846     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8847     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
8848     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
8849 
8850     // press BTN_SIDE, release BTN_SIDE
8851     processKey(mapper, BTN_SIDE, 1);
8852     processSync(mapper);
8853     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8854     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
8855     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
8856 
8857     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8858     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8859     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
8860 
8861     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8862     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8863     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
8864 
8865     processKey(mapper, BTN_SIDE, 0);
8866     processSync(mapper);
8867     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8868     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8869     ASSERT_EQ(0, motionArgs.buttonState);
8870 
8871     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8872     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8873     ASSERT_EQ(0, motionArgs.buttonState);
8874 
8875     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8876     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
8877     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
8878 
8879     // press BTN_FORWARD, release BTN_FORWARD
8880     processKey(mapper, BTN_FORWARD, 1);
8881     processSync(mapper);
8882     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8883     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
8884     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
8885 
8886     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8887     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8888     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
8889 
8890     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8891     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8892     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
8893 
8894     processKey(mapper, BTN_FORWARD, 0);
8895     processSync(mapper);
8896     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8897     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8898     ASSERT_EQ(0, motionArgs.buttonState);
8899 
8900     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8901     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8902     ASSERT_EQ(0, motionArgs.buttonState);
8903 
8904     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8905     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
8906     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
8907 
8908     // press BTN_EXTRA, release BTN_EXTRA
8909     processKey(mapper, BTN_EXTRA, 1);
8910     processSync(mapper);
8911     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8912     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
8913     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
8914 
8915     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8916     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8917     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
8918 
8919     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8920     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8921     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
8922 
8923     processKey(mapper, BTN_EXTRA, 0);
8924     processSync(mapper);
8925     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8926     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8927     ASSERT_EQ(0, motionArgs.buttonState);
8928 
8929     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8930     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8931     ASSERT_EQ(0, motionArgs.buttonState);
8932 
8933     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8934     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
8935     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
8936 
8937     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
8938 
8939     // press BTN_STYLUS, release BTN_STYLUS
8940     processKey(mapper, BTN_STYLUS, 1);
8941     processSync(mapper);
8942     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8943     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8944     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY, motionArgs.buttonState);
8945 
8946     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8947     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8948     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY, motionArgs.buttonState);
8949 
8950     processKey(mapper, BTN_STYLUS, 0);
8951     processSync(mapper);
8952     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8953     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8954     ASSERT_EQ(0, motionArgs.buttonState);
8955 
8956     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8957     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8958     ASSERT_EQ(0, motionArgs.buttonState);
8959 
8960     // press BTN_STYLUS2, release BTN_STYLUS2
8961     processKey(mapper, BTN_STYLUS2, 1);
8962     processSync(mapper);
8963     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8964     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8965     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_SECONDARY, motionArgs.buttonState);
8966 
8967     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8968     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8969     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_SECONDARY, motionArgs.buttonState);
8970 
8971     processKey(mapper, BTN_STYLUS2, 0);
8972     processSync(mapper);
8973     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8974     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8975     ASSERT_EQ(0, motionArgs.buttonState);
8976 
8977     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8978     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8979     ASSERT_EQ(0, motionArgs.buttonState);
8980 
8981     // release touch
8982     processId(mapper, -1);
8983     processSync(mapper);
8984     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8985     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
8986     ASSERT_EQ(0, motionArgs.buttonState);
8987 }
8988 
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandleMappedStylusButtons)8989 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandleMappedStylusButtons) {
8990     addConfigurationProperty("touch.deviceType", "touchScreen");
8991     prepareDisplay(ui::ROTATION_0);
8992     prepareAxes(POSITION | ID | SLOT);
8993     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8994 
8995     mFakeEventHub->addKey(EVENTHUB_ID, BTN_A, 0, AKEYCODE_STYLUS_BUTTON_PRIMARY, 0);
8996     mFakeEventHub->addKey(EVENTHUB_ID, 0, 0xabcd, AKEYCODE_STYLUS_BUTTON_SECONDARY, 0);
8997 
8998     // Touch down.
8999     processId(mapper, 1);
9000     processPosition(mapper, 100, 200);
9001     processSync(mapper);
9002     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9003             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithButtonState(0))));
9004 
9005     // Press and release button mapped to the primary stylus button.
9006     processKey(mapper, BTN_A, 1);
9007     processSync(mapper);
9008     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9009             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
9010                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
9011     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9012             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
9013                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
9014 
9015     processKey(mapper, BTN_A, 0);
9016     processSync(mapper);
9017     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9018             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE), WithButtonState(0))));
9019     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9020             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE), WithButtonState(0))));
9021 
9022     // Press and release the HID usage mapped to the secondary stylus button.
9023     processHidUsage(mapper, 0xabcd, 1);
9024     processSync(mapper);
9025     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9026             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
9027                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_SECONDARY))));
9028     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9029             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
9030                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_SECONDARY))));
9031 
9032     processHidUsage(mapper, 0xabcd, 0);
9033     processSync(mapper);
9034     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9035             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE), WithButtonState(0))));
9036     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9037             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE), WithButtonState(0))));
9038 
9039     // Release touch.
9040     processId(mapper, -1);
9041     processSync(mapper);
9042     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9043             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP), WithButtonState(0))));
9044 }
9045 
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandleAllToolTypes)9046 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandleAllToolTypes) {
9047     addConfigurationProperty("touch.deviceType", "touchScreen");
9048     prepareDisplay(ui::ROTATION_0);
9049     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE);
9050     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9051 
9052     NotifyMotionArgs motionArgs;
9053 
9054     // default tool type is finger
9055     processId(mapper, 1);
9056     processPosition(mapper, 100, 200);
9057     processSync(mapper);
9058     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9059     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9060     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9061 
9062     // eraser
9063     processKey(mapper, BTN_TOOL_RUBBER, 1);
9064     processSync(mapper);
9065     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9066     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9067     ASSERT_EQ(ToolType::ERASER, motionArgs.pointerProperties[0].toolType);
9068 
9069     // stylus
9070     processKey(mapper, BTN_TOOL_RUBBER, 0);
9071     processKey(mapper, BTN_TOOL_PEN, 1);
9072     processSync(mapper);
9073     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9074     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9075     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
9076 
9077     // brush
9078     processKey(mapper, BTN_TOOL_PEN, 0);
9079     processKey(mapper, BTN_TOOL_BRUSH, 1);
9080     processSync(mapper);
9081     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9082     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9083     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
9084 
9085     // pencil
9086     processKey(mapper, BTN_TOOL_BRUSH, 0);
9087     processKey(mapper, BTN_TOOL_PENCIL, 1);
9088     processSync(mapper);
9089     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9090     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9091     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
9092 
9093     // air-brush
9094     processKey(mapper, BTN_TOOL_PENCIL, 0);
9095     processKey(mapper, BTN_TOOL_AIRBRUSH, 1);
9096     processSync(mapper);
9097     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9098     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9099     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
9100 
9101     // mouse
9102     processKey(mapper, BTN_TOOL_AIRBRUSH, 0);
9103     processKey(mapper, BTN_TOOL_MOUSE, 1);
9104     processSync(mapper);
9105     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9106     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9107     ASSERT_EQ(ToolType::MOUSE, motionArgs.pointerProperties[0].toolType);
9108 
9109     // lens
9110     processKey(mapper, BTN_TOOL_MOUSE, 0);
9111     processKey(mapper, BTN_TOOL_LENS, 1);
9112     processSync(mapper);
9113     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9114     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9115     ASSERT_EQ(ToolType::MOUSE, motionArgs.pointerProperties[0].toolType);
9116 
9117     // double-tap
9118     processKey(mapper, BTN_TOOL_LENS, 0);
9119     processKey(mapper, BTN_TOOL_DOUBLETAP, 1);
9120     processSync(mapper);
9121     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9122     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9123     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9124 
9125     // triple-tap
9126     processKey(mapper, BTN_TOOL_DOUBLETAP, 0);
9127     processKey(mapper, BTN_TOOL_TRIPLETAP, 1);
9128     processSync(mapper);
9129     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9130     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9131     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9132 
9133     // quad-tap
9134     processKey(mapper, BTN_TOOL_TRIPLETAP, 0);
9135     processKey(mapper, BTN_TOOL_QUADTAP, 1);
9136     processSync(mapper);
9137     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9138     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9139     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9140 
9141     // finger
9142     processKey(mapper, BTN_TOOL_QUADTAP, 0);
9143     processKey(mapper, BTN_TOOL_FINGER, 1);
9144     processSync(mapper);
9145     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9146     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9147     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9148 
9149     // stylus trumps finger
9150     processKey(mapper, BTN_TOOL_PEN, 1);
9151     processSync(mapper);
9152     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9153     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9154     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
9155 
9156     // eraser trumps stylus
9157     processKey(mapper, BTN_TOOL_RUBBER, 1);
9158     processSync(mapper);
9159     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9160     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9161     ASSERT_EQ(ToolType::ERASER, motionArgs.pointerProperties[0].toolType);
9162 
9163     // mouse trumps eraser
9164     processKey(mapper, BTN_TOOL_MOUSE, 1);
9165     processSync(mapper);
9166     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9167     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9168     ASSERT_EQ(ToolType::MOUSE, motionArgs.pointerProperties[0].toolType);
9169 
9170     // MT tool type trumps BTN tool types: MT_TOOL_FINGER
9171     processToolType(mapper, MT_TOOL_FINGER); // this is the first time we send MT_TOOL_TYPE
9172     processSync(mapper);
9173     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9174     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9175     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9176 
9177     // MT tool type trumps BTN tool types: MT_TOOL_PEN
9178     processToolType(mapper, MT_TOOL_PEN);
9179     processSync(mapper);
9180     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9181     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9182     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
9183 
9184     // back to default tool type
9185     processToolType(mapper, -1); // use a deliberately undefined tool type, for testing
9186     processKey(mapper, BTN_TOOL_MOUSE, 0);
9187     processKey(mapper, BTN_TOOL_RUBBER, 0);
9188     processKey(mapper, BTN_TOOL_PEN, 0);
9189     processKey(mapper, BTN_TOOL_FINGER, 0);
9190     processSync(mapper);
9191     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9192     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9193     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9194 }
9195 
TEST_F(MultiTouchInputMapperTest,Process_WhenBtnTouchPresent_HoversIfItsValueIsZero)9196 TEST_F(MultiTouchInputMapperTest, Process_WhenBtnTouchPresent_HoversIfItsValueIsZero) {
9197     addConfigurationProperty("touch.deviceType", "touchScreen");
9198     prepareDisplay(ui::ROTATION_0);
9199     prepareAxes(POSITION | ID | SLOT);
9200     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOUCH, 0, AKEYCODE_UNKNOWN, 0);
9201     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9202 
9203     NotifyMotionArgs motionArgs;
9204 
9205     // initially hovering because BTN_TOUCH not sent yet, pressure defaults to 0
9206     processId(mapper, 1);
9207     processPosition(mapper, 100, 200);
9208     processSync(mapper);
9209     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9210     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
9211     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9212             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
9213 
9214     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9215     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
9216     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9217             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
9218 
9219     // move a little
9220     processPosition(mapper, 150, 250);
9221     processSync(mapper);
9222     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9223     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
9224     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9225             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
9226 
9227     // down when BTN_TOUCH is pressed, pressure defaults to 1
9228     processKey(mapper, BTN_TOUCH, 1);
9229     processSync(mapper);
9230     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9231     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
9232     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9233             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
9234 
9235     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9236     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9237     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9238             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
9239 
9240     // up when BTN_TOUCH is released, hover restored
9241     processKey(mapper, BTN_TOUCH, 0);
9242     processSync(mapper);
9243     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9244     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
9245     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9246             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
9247 
9248     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9249     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
9250     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9251             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
9252 
9253     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9254     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
9255     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9256             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
9257 
9258     // exit hover when pointer goes away
9259     processId(mapper, -1);
9260     processSync(mapper);
9261     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9262     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
9263     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9264             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
9265 }
9266 
TEST_F(MultiTouchInputMapperTest,Process_WhenAbsMTPressureIsPresent_HoversIfItsValueIsZero)9267 TEST_F(MultiTouchInputMapperTest, Process_WhenAbsMTPressureIsPresent_HoversIfItsValueIsZero) {
9268     addConfigurationProperty("touch.deviceType", "touchScreen");
9269     prepareDisplay(ui::ROTATION_0);
9270     prepareAxes(POSITION | ID | SLOT | PRESSURE);
9271     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9272 
9273     NotifyMotionArgs motionArgs;
9274 
9275     // initially hovering because pressure is 0
9276     processId(mapper, 1);
9277     processPosition(mapper, 100, 200);
9278     processPressure(mapper, 0);
9279     processSync(mapper);
9280     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9281     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
9282     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9283             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
9284 
9285     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9286     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
9287     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9288             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
9289 
9290     // move a little
9291     processPosition(mapper, 150, 250);
9292     processSync(mapper);
9293     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9294     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
9295     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9296             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
9297 
9298     // down when pressure becomes non-zero
9299     processPressure(mapper, RAW_PRESSURE_MAX);
9300     processSync(mapper);
9301     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9302     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
9303     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9304             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
9305 
9306     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9307     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9308     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9309             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
9310 
9311     // up when pressure becomes 0, hover restored
9312     processPressure(mapper, 0);
9313     processSync(mapper);
9314     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9315     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
9316     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9317             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
9318 
9319     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9320     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
9321     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9322             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
9323 
9324     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9325     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
9326     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9327             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
9328 
9329     // exit hover when pointer goes away
9330     processId(mapper, -1);
9331     processSync(mapper);
9332     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9333     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
9334     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
9335             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
9336 }
9337 
9338 /**
9339  * Set the input device port <--> display port associations, and check that the
9340  * events are routed to the display that matches the display port.
9341  * This can be checked by looking at the displayId of the resulting NotifyMotionArgs.
9342  */
TEST_F(MultiTouchInputMapperTest,Configure_AssignsDisplayPort)9343 TEST_F(MultiTouchInputMapperTest, Configure_AssignsDisplayPort) {
9344     const std::string usb2 = "USB2";
9345     const uint8_t hdmi1 = 0;
9346     const uint8_t hdmi2 = 1;
9347     const std::string secondaryUniqueId = "uniqueId2";
9348     constexpr ViewportType type = ViewportType::EXTERNAL;
9349 
9350     addConfigurationProperty("touch.deviceType", "touchScreen");
9351     prepareAxes(POSITION);
9352     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9353 
9354     mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi1);
9355     mFakePolicy->addInputPortAssociation(usb2, hdmi2);
9356 
9357     // We are intentionally not adding the viewport for display 1 yet. Since the port association
9358     // for this input device is specified, and the matching viewport is not present,
9359     // the input device should be disabled (at the mapper level).
9360 
9361     // Add viewport for display 2 on hdmi2
9362     prepareSecondaryDisplay(type, hdmi2);
9363     // Send a touch event
9364     processPosition(mapper, 100, 100);
9365     processSync(mapper);
9366     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
9367 
9368     // Add viewport for display 1 on hdmi1
9369     prepareDisplay(ui::ROTATION_0, hdmi1);
9370     // Send a touch event again
9371     processPosition(mapper, 100, 100);
9372     processSync(mapper);
9373 
9374     NotifyMotionArgs args;
9375     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
9376     ASSERT_EQ(DISPLAY_ID, args.displayId);
9377 }
9378 
TEST_F(MultiTouchInputMapperTest,Configure_AssignsDisplayUniqueId)9379 TEST_F(MultiTouchInputMapperTest, Configure_AssignsDisplayUniqueId) {
9380     addConfigurationProperty("touch.deviceType", "touchScreen");
9381     prepareAxes(POSITION);
9382     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9383 
9384     mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, VIRTUAL_DISPLAY_UNIQUE_ID);
9385 
9386     prepareDisplay(ui::ROTATION_0);
9387     prepareVirtualDisplay(ui::ROTATION_0);
9388 
9389     // Send a touch event
9390     processPosition(mapper, 100, 100);
9391     processSync(mapper);
9392 
9393     NotifyMotionArgs args;
9394     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
9395     ASSERT_EQ(VIRTUAL_DISPLAY_ID, args.displayId);
9396 }
9397 
TEST_F(MultiTouchInputMapperTest,Process_Pointer_ShouldHandleDisplayId)9398 TEST_F(MultiTouchInputMapperTest, Process_Pointer_ShouldHandleDisplayId) {
9399     // Setup for second display.
9400     std::shared_ptr<FakePointerController> fakePointerController =
9401             std::make_shared<FakePointerController>();
9402     fakePointerController->setBounds(0, 0, DISPLAY_WIDTH - 1, DISPLAY_HEIGHT - 1);
9403     fakePointerController->setPosition(100, 200);
9404     mFakePolicy->setPointerController(fakePointerController);
9405 
9406     mFakePolicy->setDefaultPointerDisplayId(SECONDARY_DISPLAY_ID);
9407     prepareSecondaryDisplay(ViewportType::EXTERNAL);
9408 
9409     prepareDisplay(ui::ROTATION_0);
9410     prepareAxes(POSITION);
9411     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9412 
9413     // Check source is mouse that would obtain the PointerController.
9414     ASSERT_EQ(AINPUT_SOURCE_MOUSE, mapper.getSources());
9415 
9416     NotifyMotionArgs motionArgs;
9417     processPosition(mapper, 100, 100);
9418     processSync(mapper);
9419 
9420     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9421     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
9422     ASSERT_EQ(SECONDARY_DISPLAY_ID, motionArgs.displayId);
9423 }
9424 
9425 /**
9426  * Ensure that the readTime is set to the SYN_REPORT value when processing touch events.
9427  */
TEST_F(MultiTouchInputMapperTest,Process_SendsReadTime)9428 TEST_F(MultiTouchInputMapperTest, Process_SendsReadTime) {
9429     addConfigurationProperty("touch.deviceType", "touchScreen");
9430     prepareAxes(POSITION);
9431     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9432 
9433     prepareDisplay(ui::ROTATION_0);
9434     process(mapper, 10, /*readTime=*/11, EV_ABS, ABS_MT_TRACKING_ID, 1);
9435     process(mapper, 15, /*readTime=*/16, EV_ABS, ABS_MT_POSITION_X, 100);
9436     process(mapper, 20, /*readTime=*/21, EV_ABS, ABS_MT_POSITION_Y, 100);
9437     process(mapper, 25, /*readTime=*/26, EV_SYN, SYN_REPORT, 0);
9438 
9439     NotifyMotionArgs args;
9440     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
9441     ASSERT_EQ(26, args.readTime);
9442 
9443     process(mapper, 30, /*readTime=*/31, EV_ABS, ABS_MT_POSITION_X, 110);
9444     process(mapper, 30, /*readTime=*/32, EV_ABS, ABS_MT_POSITION_Y, 220);
9445     process(mapper, 30, /*readTime=*/33, EV_SYN, SYN_REPORT, 0);
9446 
9447     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
9448     ASSERT_EQ(33, args.readTime);
9449 }
9450 
9451 /**
9452  * When the viewport is not active (isActive=false), the touch mapper should be disabled and the
9453  * events should not be delivered to the listener.
9454  */
TEST_F(MultiTouchInputMapperTest,WhenViewportIsNotActive_TouchesAreDropped)9455 TEST_F(MultiTouchInputMapperTest, WhenViewportIsNotActive_TouchesAreDropped) {
9456     addConfigurationProperty("touch.deviceType", "touchScreen");
9457     // Don't set touch.enableForInactiveViewport to verify the default behavior.
9458     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
9459                                     /*isActive=*/false, UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
9460     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
9461     prepareAxes(POSITION);
9462     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9463 
9464     NotifyMotionArgs motionArgs;
9465     processPosition(mapper, 100, 100);
9466     processSync(mapper);
9467 
9468     mFakeListener->assertNotifyMotionWasNotCalled();
9469 }
9470 
9471 /**
9472  * When the viewport is not active (isActive=false) and touch.enableForInactiveViewport is true,
9473  * the touch mapper can process the events and the events can be delivered to the listener.
9474  */
TEST_F(MultiTouchInputMapperTest,WhenViewportIsNotActive_TouchesAreProcessed)9475 TEST_F(MultiTouchInputMapperTest, WhenViewportIsNotActive_TouchesAreProcessed) {
9476     addConfigurationProperty("touch.deviceType", "touchScreen");
9477     addConfigurationProperty("touch.enableForInactiveViewport", "1");
9478     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
9479                                     /*isActive=*/false, UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
9480     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
9481     prepareAxes(POSITION);
9482     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9483 
9484     NotifyMotionArgs motionArgs;
9485     processPosition(mapper, 100, 100);
9486     processSync(mapper);
9487 
9488     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9489     EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9490 }
9491 
TEST_F(MultiTouchInputMapperTest,Process_DeactivateViewport_AbortTouches)9492 TEST_F(MultiTouchInputMapperTest, Process_DeactivateViewport_AbortTouches) {
9493     addConfigurationProperty("touch.deviceType", "touchScreen");
9494     addConfigurationProperty("touch.enableForInactiveViewport", "0");
9495     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
9496                                     /*isActive=*/true, UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
9497     std::optional<DisplayViewport> optionalDisplayViewport =
9498             mFakePolicy->getDisplayViewportByUniqueId(UNIQUE_ID);
9499     ASSERT_TRUE(optionalDisplayViewport.has_value());
9500     DisplayViewport displayViewport = *optionalDisplayViewport;
9501 
9502     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
9503     prepareAxes(POSITION);
9504     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9505 
9506     // Finger down
9507     int32_t x = 100, y = 100;
9508     processPosition(mapper, x, y);
9509     processSync(mapper);
9510 
9511     NotifyMotionArgs motionArgs;
9512     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9513     EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9514 
9515     // Deactivate display viewport
9516     displayViewport.isActive = false;
9517     ASSERT_TRUE(mFakePolicy->updateViewport(displayViewport));
9518     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
9519 
9520     // The ongoing touch should be canceled immediately
9521     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9522     EXPECT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionArgs.action);
9523 
9524     // Finger move is ignored
9525     x += 10, y += 10;
9526     processPosition(mapper, x, y);
9527     processSync(mapper);
9528     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
9529 
9530     // Reactivate display viewport
9531     displayViewport.isActive = true;
9532     ASSERT_TRUE(mFakePolicy->updateViewport(displayViewport));
9533     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
9534 
9535     // Finger move again starts new gesture
9536     x += 10, y += 10;
9537     processPosition(mapper, x, y);
9538     processSync(mapper);
9539     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9540     EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9541 }
9542 
TEST_F(MultiTouchInputMapperTest,Process_Pointer_ShowTouches)9543 TEST_F(MultiTouchInputMapperTest, Process_Pointer_ShowTouches) {
9544     // Setup the first touch screen device.
9545     prepareAxes(POSITION | ID | SLOT);
9546     addConfigurationProperty("touch.deviceType", "touchScreen");
9547     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9548 
9549     // Create the second touch screen device, and enable multi fingers.
9550     const std::string USB2 = "USB2";
9551     const std::string DEVICE_NAME2 = "TOUCHSCREEN2";
9552     constexpr int32_t SECOND_DEVICE_ID = DEVICE_ID + 1;
9553     constexpr int32_t SECOND_EVENTHUB_ID = EVENTHUB_ID + 1;
9554     std::shared_ptr<InputDevice> device2 =
9555             newDevice(SECOND_DEVICE_ID, DEVICE_NAME2, USB2, SECOND_EVENTHUB_ID,
9556                       ftl::Flags<InputDeviceClass>(0));
9557 
9558     mFakeEventHub->addAbsoluteAxis(SECOND_EVENTHUB_ID, ABS_MT_POSITION_X, RAW_X_MIN, RAW_X_MAX,
9559                                    /*flat=*/0, /*fuzz=*/0);
9560     mFakeEventHub->addAbsoluteAxis(SECOND_EVENTHUB_ID, ABS_MT_POSITION_Y, RAW_Y_MIN, RAW_Y_MAX,
9561                                    /*flat=*/0, /*fuzz=*/0);
9562     mFakeEventHub->addAbsoluteAxis(SECOND_EVENTHUB_ID, ABS_MT_TRACKING_ID, RAW_ID_MIN, RAW_ID_MAX,
9563                                    /*flat=*/0, /*fuzz=*/0);
9564     mFakeEventHub->addAbsoluteAxis(SECOND_EVENTHUB_ID, ABS_MT_SLOT, RAW_SLOT_MIN, RAW_SLOT_MAX,
9565                                    /*flat=*/0, /*fuzz=*/0);
9566     mFakeEventHub->setAbsoluteAxisValue(SECOND_EVENTHUB_ID, ABS_MT_SLOT, /*value=*/0);
9567     mFakeEventHub->addConfigurationProperty(SECOND_EVENTHUB_ID, String8("touch.deviceType"),
9568                                             String8("touchScreen"));
9569 
9570     // Setup the second touch screen device.
9571     device2->addEmptyEventHubDevice(SECOND_EVENTHUB_ID);
9572     MultiTouchInputMapper& mapper2 = device2->constructAndAddMapper<
9573             MultiTouchInputMapper>(SECOND_EVENTHUB_ID, mFakePolicy->getReaderConfiguration());
9574     std::list<NotifyArgs> unused =
9575             device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
9576                                /*changes=*/{});
9577     unused += device2->reset(ARBITRARY_TIME);
9578 
9579     // Setup PointerController.
9580     std::shared_ptr<FakePointerController> fakePointerController =
9581             std::make_shared<FakePointerController>();
9582     mFakePolicy->setPointerController(fakePointerController);
9583 
9584     // Setup policy for associated displays and show touches.
9585     const uint8_t hdmi1 = 0;
9586     const uint8_t hdmi2 = 1;
9587     mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi1);
9588     mFakePolicy->addInputPortAssociation(USB2, hdmi2);
9589     mFakePolicy->setShowTouches(true);
9590 
9591     // Create displays.
9592     prepareDisplay(ui::ROTATION_0, hdmi1);
9593     prepareSecondaryDisplay(ViewportType::EXTERNAL, hdmi2);
9594 
9595     // Default device will reconfigure above, need additional reconfiguration for another device.
9596     unused += device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
9597                                  InputReaderConfiguration::Change::DISPLAY_INFO |
9598                                          InputReaderConfiguration::Change::SHOW_TOUCHES);
9599 
9600     // Two fingers down at default display.
9601     int32_t x1 = 100, y1 = 125, x2 = 300, y2 = 500;
9602     processPosition(mapper, x1, y1);
9603     processId(mapper, 1);
9604     processSlot(mapper, 1);
9605     processPosition(mapper, x2, y2);
9606     processId(mapper, 2);
9607     processSync(mapper);
9608 
9609     std::map<int32_t, std::vector<int32_t>>::const_iterator iter =
9610             fakePointerController->getSpots().find(DISPLAY_ID);
9611     ASSERT_TRUE(iter != fakePointerController->getSpots().end());
9612     ASSERT_EQ(size_t(2), iter->second.size());
9613 
9614     // Two fingers down at second display.
9615     processPosition(mapper2, x1, y1);
9616     processId(mapper2, 1);
9617     processSlot(mapper2, 1);
9618     processPosition(mapper2, x2, y2);
9619     processId(mapper2, 2);
9620     processSync(mapper2);
9621 
9622     iter = fakePointerController->getSpots().find(SECONDARY_DISPLAY_ID);
9623     ASSERT_TRUE(iter != fakePointerController->getSpots().end());
9624     ASSERT_EQ(size_t(2), iter->second.size());
9625 
9626     // Disable the show touches configuration and ensure the spots are cleared.
9627     mFakePolicy->setShowTouches(false);
9628     unused += device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
9629                                  InputReaderConfiguration::Change::SHOW_TOUCHES);
9630 
9631     ASSERT_TRUE(fakePointerController->getSpots().empty());
9632 }
9633 
TEST_F(MultiTouchInputMapperTest,VideoFrames_ReceivedByListener)9634 TEST_F(MultiTouchInputMapperTest, VideoFrames_ReceivedByListener) {
9635     prepareAxes(POSITION);
9636     addConfigurationProperty("touch.deviceType", "touchScreen");
9637     prepareDisplay(ui::ROTATION_0);
9638     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9639 
9640     NotifyMotionArgs motionArgs;
9641     // Unrotated video frame
9642     TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, {1, 2});
9643     std::vector<TouchVideoFrame> frames{frame};
9644     mFakeEventHub->setVideoFrames({{EVENTHUB_ID, frames}});
9645     processPosition(mapper, 100, 200);
9646     processSync(mapper);
9647     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9648     ASSERT_EQ(frames, motionArgs.videoFrames);
9649 
9650     // Subsequent touch events should not have any videoframes
9651     // This is implemented separately in FakeEventHub,
9652     // but that should match the behaviour of TouchVideoDevice.
9653     processPosition(mapper, 200, 200);
9654     processSync(mapper);
9655     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9656     ASSERT_EQ(std::vector<TouchVideoFrame>(), motionArgs.videoFrames);
9657 }
9658 
TEST_F(MultiTouchInputMapperTest,VideoFrames_AreNotRotated)9659 TEST_F(MultiTouchInputMapperTest, VideoFrames_AreNotRotated) {
9660     prepareAxes(POSITION);
9661     addConfigurationProperty("touch.deviceType", "touchScreen");
9662     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9663     // Unrotated video frame
9664     TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, {1, 2});
9665     NotifyMotionArgs motionArgs;
9666 
9667     // Test all 4 orientations
9668     for (ui::Rotation orientation : ftl::enum_range<ui::Rotation>()) {
9669         SCOPED_TRACE("Orientation " + StringPrintf("%i", orientation));
9670         clearViewports();
9671         prepareDisplay(orientation);
9672         std::vector<TouchVideoFrame> frames{frame};
9673         mFakeEventHub->setVideoFrames({{EVENTHUB_ID, frames}});
9674         processPosition(mapper, 100, 200);
9675         processSync(mapper);
9676         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9677         ASSERT_EQ(frames, motionArgs.videoFrames);
9678     }
9679 }
9680 
TEST_F(MultiTouchInputMapperTest,VideoFrames_WhenNotOrientationAware_AreRotated)9681 TEST_F(MultiTouchInputMapperTest, VideoFrames_WhenNotOrientationAware_AreRotated) {
9682     prepareAxes(POSITION);
9683     addConfigurationProperty("touch.deviceType", "touchScreen");
9684     // Since InputReader works in the un-rotated coordinate space, only devices that are not
9685     // orientation-aware are affected by display rotation.
9686     addConfigurationProperty("touch.orientationAware", "0");
9687     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9688     // Unrotated video frame
9689     TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, {1, 2});
9690     NotifyMotionArgs motionArgs;
9691 
9692     // Test all 4 orientations
9693     for (ui::Rotation orientation : ftl::enum_range<ui::Rotation>()) {
9694         SCOPED_TRACE("Orientation " + StringPrintf("%i", orientation));
9695         clearViewports();
9696         prepareDisplay(orientation);
9697         std::vector<TouchVideoFrame> frames{frame};
9698         mFakeEventHub->setVideoFrames({{EVENTHUB_ID, frames}});
9699         processPosition(mapper, 100, 200);
9700         processSync(mapper);
9701         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9702         // We expect the raw coordinates of the MotionEvent to be rotated in the inverse direction
9703         // compared to the display. This is so that when the window transform (which contains the
9704         // display rotation) is applied later by InputDispatcher, the coordinates end up in the
9705         // window's coordinate space.
9706         frames[0].rotate(getInverseRotation(orientation));
9707         ASSERT_EQ(frames, motionArgs.videoFrames);
9708 
9709         // Release finger.
9710         processSync(mapper);
9711         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9712     }
9713 }
9714 
TEST_F(MultiTouchInputMapperTest,VideoFrames_MultipleFramesAreNotRotated)9715 TEST_F(MultiTouchInputMapperTest, VideoFrames_MultipleFramesAreNotRotated) {
9716     prepareAxes(POSITION);
9717     addConfigurationProperty("touch.deviceType", "touchScreen");
9718     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9719     // Unrotated video frames. There's no rule that they must all have the same dimensions,
9720     // so mix these.
9721     TouchVideoFrame frame1(3, 2, {1, 2, 3, 4, 5, 6}, {1, 2});
9722     TouchVideoFrame frame2(3, 3, {0, 1, 2, 3, 4, 5, 6, 7, 8}, {1, 3});
9723     TouchVideoFrame frame3(2, 2, {10, 20, 10, 0}, {1, 4});
9724     std::vector<TouchVideoFrame> frames{frame1, frame2, frame3};
9725     NotifyMotionArgs motionArgs;
9726 
9727     prepareDisplay(ui::ROTATION_90);
9728     mFakeEventHub->setVideoFrames({{EVENTHUB_ID, frames}});
9729     processPosition(mapper, 100, 200);
9730     processSync(mapper);
9731     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9732     ASSERT_EQ(frames, motionArgs.videoFrames);
9733 }
9734 
TEST_F(MultiTouchInputMapperTest,VideoFrames_WhenNotOrientationAware_MultipleFramesAreRotated)9735 TEST_F(MultiTouchInputMapperTest, VideoFrames_WhenNotOrientationAware_MultipleFramesAreRotated) {
9736     prepareAxes(POSITION);
9737     addConfigurationProperty("touch.deviceType", "touchScreen");
9738     // Since InputReader works in the un-rotated coordinate space, only devices that are not
9739     // orientation-aware are affected by display rotation.
9740     addConfigurationProperty("touch.orientationAware", "0");
9741     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9742     // Unrotated video frames. There's no rule that they must all have the same dimensions,
9743     // so mix these.
9744     TouchVideoFrame frame1(3, 2, {1, 2, 3, 4, 5, 6}, {1, 2});
9745     TouchVideoFrame frame2(3, 3, {0, 1, 2, 3, 4, 5, 6, 7, 8}, {1, 3});
9746     TouchVideoFrame frame3(2, 2, {10, 20, 10, 0}, {1, 4});
9747     std::vector<TouchVideoFrame> frames{frame1, frame2, frame3};
9748     NotifyMotionArgs motionArgs;
9749 
9750     prepareDisplay(ui::ROTATION_90);
9751     mFakeEventHub->setVideoFrames({{EVENTHUB_ID, frames}});
9752     processPosition(mapper, 100, 200);
9753     processSync(mapper);
9754     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9755     std::for_each(frames.begin(), frames.end(), [](TouchVideoFrame& frame) {
9756         // We expect the raw coordinates of the MotionEvent to be rotated in the inverse direction
9757         // compared to the display. This is so that when the window transform (which contains the
9758         // display rotation) is applied later by InputDispatcher, the coordinates end up in the
9759         // window's coordinate space.
9760         frame.rotate(getInverseRotation(ui::ROTATION_90));
9761     });
9762     ASSERT_EQ(frames, motionArgs.videoFrames);
9763 }
9764 
9765 /**
9766  * If we had defined port associations, but the viewport is not ready, the touch device would be
9767  * expected to be disabled, and it should be enabled after the viewport has found.
9768  */
TEST_F(MultiTouchInputMapperTest,Configure_EnabledForAssociatedDisplay)9769 TEST_F(MultiTouchInputMapperTest, Configure_EnabledForAssociatedDisplay) {
9770     constexpr uint8_t hdmi2 = 1;
9771     const std::string secondaryUniqueId = "uniqueId2";
9772     constexpr ViewportType type = ViewportType::EXTERNAL;
9773 
9774     mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi2);
9775 
9776     addConfigurationProperty("touch.deviceType", "touchScreen");
9777     prepareAxes(POSITION);
9778     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9779 
9780     ASSERT_EQ(mDevice->isEnabled(), false);
9781 
9782     // Add display on hdmi2, the device should be enabled and can receive touch event.
9783     prepareSecondaryDisplay(type, hdmi2);
9784     ASSERT_EQ(mDevice->isEnabled(), true);
9785 
9786     // Send a touch event.
9787     processPosition(mapper, 100, 100);
9788     processSync(mapper);
9789 
9790     NotifyMotionArgs args;
9791     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
9792     ASSERT_EQ(SECONDARY_DISPLAY_ID, args.displayId);
9793 }
9794 
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandleSingleTouch)9795 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandleSingleTouch) {
9796     addConfigurationProperty("touch.deviceType", "touchScreen");
9797     prepareDisplay(ui::ROTATION_0);
9798     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE);
9799     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9800 
9801     NotifyMotionArgs motionArgs;
9802 
9803     constexpr int32_t x1 = 100, y1 = 200, x2 = 120, y2 = 220, x3 = 140, y3 = 240;
9804     // finger down
9805     processId(mapper, 1);
9806     processPosition(mapper, x1, y1);
9807     processSync(mapper);
9808     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9809     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9810     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9811 
9812     // finger move
9813     processId(mapper, 1);
9814     processPosition(mapper, x2, y2);
9815     processSync(mapper);
9816     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9817     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9818     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9819 
9820     // finger up.
9821     processId(mapper, -1);
9822     processSync(mapper);
9823     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9824     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
9825     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9826 
9827     // new finger down
9828     processId(mapper, 1);
9829     processPosition(mapper, x3, y3);
9830     processSync(mapper);
9831     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9832     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9833     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9834 }
9835 
9836 /**
9837  * Test single touch should be canceled when received the MT_TOOL_PALM event, and the following
9838  * MOVE and UP events should be ignored.
9839  */
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandlePalmToolType_SinglePointer)9840 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandlePalmToolType_SinglePointer) {
9841     addConfigurationProperty("touch.deviceType", "touchScreen");
9842     prepareDisplay(ui::ROTATION_0);
9843     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE);
9844     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9845 
9846     NotifyMotionArgs motionArgs;
9847 
9848     // default tool type is finger
9849     constexpr int32_t x1 = 100, y1 = 200, x2 = 120, y2 = 220, x3 = 140, y3 = 240;
9850     processId(mapper, FIRST_TRACKING_ID);
9851     processPosition(mapper, x1, y1);
9852     processSync(mapper);
9853     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9854     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9855     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9856 
9857     // Tool changed to MT_TOOL_PALM expect sending the cancel event.
9858     processToolType(mapper, MT_TOOL_PALM);
9859     processSync(mapper);
9860     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9861     ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionArgs.action);
9862 
9863     // Ignore the following MOVE and UP events if had detect a palm event.
9864     processId(mapper, FIRST_TRACKING_ID);
9865     processPosition(mapper, x2, y2);
9866     processSync(mapper);
9867     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
9868 
9869     // finger up.
9870     processId(mapper, INVALID_TRACKING_ID);
9871     processSync(mapper);
9872     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
9873 
9874     // new finger down
9875     processId(mapper, FIRST_TRACKING_ID);
9876     processToolType(mapper, MT_TOOL_FINGER);
9877     processPosition(mapper, x3, y3);
9878     processSync(mapper);
9879     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9880     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9881     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9882 }
9883 
9884 /**
9885  * Test multi-touch should sent POINTER_UP when received the MT_TOOL_PALM event from some finger,
9886  * and the rest active fingers could still be allowed to receive the events
9887  */
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandlePalmToolType_TwoPointers)9888 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandlePalmToolType_TwoPointers) {
9889     addConfigurationProperty("touch.deviceType", "touchScreen");
9890     prepareDisplay(ui::ROTATION_0);
9891     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE);
9892     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9893 
9894     NotifyMotionArgs motionArgs;
9895 
9896     // default tool type is finger
9897     constexpr int32_t x1 = 100, y1 = 200, x2 = 120, y2 = 220;
9898     processId(mapper, FIRST_TRACKING_ID);
9899     processPosition(mapper, x1, y1);
9900     processSync(mapper);
9901     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9902     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9903     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9904 
9905     // Second finger down.
9906     processSlot(mapper, SECOND_SLOT);
9907     processId(mapper, SECOND_TRACKING_ID);
9908     processPosition(mapper, x2, y2);
9909     processSync(mapper);
9910     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9911     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
9912     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
9913 
9914     // If the tool type of the first finger changes to MT_TOOL_PALM,
9915     // we expect to receive ACTION_POINTER_UP with cancel flag.
9916     processSlot(mapper, FIRST_SLOT);
9917     processId(mapper, FIRST_TRACKING_ID);
9918     processToolType(mapper, MT_TOOL_PALM);
9919     processSync(mapper);
9920     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9921     ASSERT_EQ(ACTION_POINTER_0_UP, motionArgs.action);
9922     ASSERT_EQ(AMOTION_EVENT_FLAG_CANCELED, motionArgs.flags);
9923 
9924     // The following MOVE events of second finger should be processed.
9925     processSlot(mapper, SECOND_SLOT);
9926     processId(mapper, SECOND_TRACKING_ID);
9927     processPosition(mapper, x2 + 1, y2 + 1);
9928     processSync(mapper);
9929     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9930     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9931     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9932 
9933     // First finger up. It used to be in palm mode, and we already generated ACTION_POINTER_UP for
9934     // it. Second finger receive move.
9935     processSlot(mapper, FIRST_SLOT);
9936     processId(mapper, INVALID_TRACKING_ID);
9937     processSync(mapper);
9938     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9939     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9940     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9941 
9942     // Second finger keeps moving.
9943     processSlot(mapper, SECOND_SLOT);
9944     processId(mapper, SECOND_TRACKING_ID);
9945     processPosition(mapper, x2 + 2, y2 + 2);
9946     processSync(mapper);
9947     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9948     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9949     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9950 
9951     // Second finger up.
9952     processId(mapper, INVALID_TRACKING_ID);
9953     processSync(mapper);
9954     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9955     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
9956     ASSERT_NE(AMOTION_EVENT_FLAG_CANCELED, motionArgs.flags);
9957 }
9958 
9959 /**
9960  * Test multi-touch should sent POINTER_UP when received the MT_TOOL_PALM event, if only 1 finger
9961  * is active, it should send CANCEL after receiving the MT_TOOL_PALM event.
9962  */
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandlePalmToolType_ShouldCancelWhenAllTouchIsPalm)9963 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandlePalmToolType_ShouldCancelWhenAllTouchIsPalm) {
9964     addConfigurationProperty("touch.deviceType", "touchScreen");
9965     prepareDisplay(ui::ROTATION_0);
9966     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE);
9967     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9968 
9969     NotifyMotionArgs motionArgs;
9970 
9971     constexpr int32_t x1 = 100, y1 = 200, x2 = 120, y2 = 220, x3 = 140, y3 = 240;
9972     // First finger down.
9973     processId(mapper, FIRST_TRACKING_ID);
9974     processPosition(mapper, x1, y1);
9975     processSync(mapper);
9976     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9977     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9978     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9979 
9980     // Second finger down.
9981     processSlot(mapper, SECOND_SLOT);
9982     processId(mapper, SECOND_TRACKING_ID);
9983     processPosition(mapper, x2, y2);
9984     processSync(mapper);
9985     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9986     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
9987     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9988 
9989     // If the tool type of the first finger changes to MT_TOOL_PALM,
9990     // we expect to receive ACTION_POINTER_UP with cancel flag.
9991     processSlot(mapper, FIRST_SLOT);
9992     processId(mapper, FIRST_TRACKING_ID);
9993     processToolType(mapper, MT_TOOL_PALM);
9994     processSync(mapper);
9995     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9996     ASSERT_EQ(ACTION_POINTER_0_UP, motionArgs.action);
9997     ASSERT_EQ(AMOTION_EVENT_FLAG_CANCELED, motionArgs.flags);
9998 
9999     // Second finger keeps moving.
10000     processSlot(mapper, SECOND_SLOT);
10001     processId(mapper, SECOND_TRACKING_ID);
10002     processPosition(mapper, x2 + 1, y2 + 1);
10003     processSync(mapper);
10004     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10005     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10006 
10007     // second finger becomes palm, receive cancel due to only 1 finger is active.
10008     processId(mapper, SECOND_TRACKING_ID);
10009     processToolType(mapper, MT_TOOL_PALM);
10010     processSync(mapper);
10011     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10012     ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionArgs.action);
10013 
10014     // third finger down.
10015     processSlot(mapper, THIRD_SLOT);
10016     processId(mapper, THIRD_TRACKING_ID);
10017     processToolType(mapper, MT_TOOL_FINGER);
10018     processPosition(mapper, x3, y3);
10019     processSync(mapper);
10020     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10021     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
10022     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10023     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
10024 
10025     // third finger move
10026     processId(mapper, THIRD_TRACKING_ID);
10027     processPosition(mapper, x3 + 1, y3 + 1);
10028     processSync(mapper);
10029     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10030     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10031 
10032     // first finger up, third finger receive move.
10033     processSlot(mapper, FIRST_SLOT);
10034     processId(mapper, INVALID_TRACKING_ID);
10035     processSync(mapper);
10036     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10037     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10038     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
10039 
10040     // second finger up, third finger receive move.
10041     processSlot(mapper, SECOND_SLOT);
10042     processId(mapper, INVALID_TRACKING_ID);
10043     processSync(mapper);
10044     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10045     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10046     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
10047 
10048     // third finger up.
10049     processSlot(mapper, THIRD_SLOT);
10050     processId(mapper, INVALID_TRACKING_ID);
10051     processSync(mapper);
10052     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10053     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
10054     ASSERT_NE(AMOTION_EVENT_FLAG_CANCELED, motionArgs.flags);
10055 }
10056 
10057 /**
10058  * Test multi-touch should sent POINTER_UP when received the MT_TOOL_PALM event from some finger,
10059  * and the active finger could still be allowed to receive the events
10060  */
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandlePalmToolType_KeepFirstPointer)10061 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandlePalmToolType_KeepFirstPointer) {
10062     addConfigurationProperty("touch.deviceType", "touchScreen");
10063     prepareDisplay(ui::ROTATION_0);
10064     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE);
10065     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10066 
10067     NotifyMotionArgs motionArgs;
10068 
10069     // default tool type is finger
10070     constexpr int32_t x1 = 100, y1 = 200, x2 = 120, y2 = 220;
10071     processId(mapper, FIRST_TRACKING_ID);
10072     processPosition(mapper, x1, y1);
10073     processSync(mapper);
10074     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10075     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
10076     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10077 
10078     // Second finger down.
10079     processSlot(mapper, SECOND_SLOT);
10080     processId(mapper, SECOND_TRACKING_ID);
10081     processPosition(mapper, x2, y2);
10082     processSync(mapper);
10083     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10084     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
10085     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10086 
10087     // If the tool type of the second finger changes to MT_TOOL_PALM,
10088     // we expect to receive ACTION_POINTER_UP with cancel flag.
10089     processId(mapper, SECOND_TRACKING_ID);
10090     processToolType(mapper, MT_TOOL_PALM);
10091     processSync(mapper);
10092     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10093     ASSERT_EQ(ACTION_POINTER_1_UP, motionArgs.action);
10094     ASSERT_EQ(AMOTION_EVENT_FLAG_CANCELED, motionArgs.flags);
10095 
10096     // The following MOVE event should be processed.
10097     processSlot(mapper, FIRST_SLOT);
10098     processId(mapper, FIRST_TRACKING_ID);
10099     processPosition(mapper, x1 + 1, y1 + 1);
10100     processSync(mapper);
10101     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10102     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10103     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
10104 
10105     // second finger up.
10106     processSlot(mapper, SECOND_SLOT);
10107     processId(mapper, INVALID_TRACKING_ID);
10108     processSync(mapper);
10109     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10110     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10111 
10112     // first finger keep moving
10113     processSlot(mapper, FIRST_SLOT);
10114     processId(mapper, FIRST_TRACKING_ID);
10115     processPosition(mapper, x1 + 2, y1 + 2);
10116     processSync(mapper);
10117     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10118     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10119 
10120     // first finger up.
10121     processId(mapper, INVALID_TRACKING_ID);
10122     processSync(mapper);
10123     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10124     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
10125     ASSERT_NE(AMOTION_EVENT_FLAG_CANCELED, motionArgs.flags);
10126 }
10127 
10128 /**
10129  * Test multi-touch should sent ACTION_POINTER_UP/ACTION_UP when received the INVALID_TRACKING_ID,
10130  * to prevent the driver side may send unexpected data after set tracking id as INVALID_TRACKING_ID
10131  * cause slot be valid again.
10132  */
TEST_F(MultiTouchInputMapperTest,Process_MultiTouch_WithInvalidTrackingId)10133 TEST_F(MultiTouchInputMapperTest, Process_MultiTouch_WithInvalidTrackingId) {
10134     addConfigurationProperty("touch.deviceType", "touchScreen");
10135     prepareDisplay(ui::ROTATION_0);
10136     prepareAxes(POSITION | ID | SLOT | PRESSURE);
10137     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10138 
10139     NotifyMotionArgs motionArgs;
10140 
10141     constexpr int32_t x1 = 100, y1 = 200, x2 = 0, y2 = 0;
10142     // First finger down.
10143     processId(mapper, FIRST_TRACKING_ID);
10144     processPosition(mapper, x1, y1);
10145     processPressure(mapper, RAW_PRESSURE_MAX);
10146     processSync(mapper);
10147     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10148     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
10149     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
10150 
10151     // First finger move.
10152     processId(mapper, FIRST_TRACKING_ID);
10153     processPosition(mapper, x1 + 1, y1 + 1);
10154     processPressure(mapper, RAW_PRESSURE_MAX);
10155     processSync(mapper);
10156     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10157     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10158     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
10159 
10160     // Second finger down.
10161     processSlot(mapper, SECOND_SLOT);
10162     processId(mapper, SECOND_TRACKING_ID);
10163     processPosition(mapper, x2, y2);
10164     processPressure(mapper, RAW_PRESSURE_MAX);
10165     processSync(mapper);
10166     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10167     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
10168     ASSERT_EQ(uint32_t(2), motionArgs.getPointerCount());
10169 
10170     // second finger up with some unexpected data.
10171     processSlot(mapper, SECOND_SLOT);
10172     processId(mapper, INVALID_TRACKING_ID);
10173     processPosition(mapper, x2, y2);
10174     processSync(mapper);
10175     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10176     ASSERT_EQ(ACTION_POINTER_1_UP, motionArgs.action);
10177     ASSERT_EQ(uint32_t(2), motionArgs.getPointerCount());
10178 
10179     // first finger up with some unexpected data.
10180     processSlot(mapper, FIRST_SLOT);
10181     processId(mapper, INVALID_TRACKING_ID);
10182     processPosition(mapper, x2, y2);
10183     processPressure(mapper, RAW_PRESSURE_MAX);
10184     processSync(mapper);
10185     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10186     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
10187     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
10188 }
10189 
TEST_F(MultiTouchInputMapperTest,Reset_PreservesLastTouchState)10190 TEST_F(MultiTouchInputMapperTest, Reset_PreservesLastTouchState) {
10191     addConfigurationProperty("touch.deviceType", "touchScreen");
10192     prepareDisplay(ui::ROTATION_0);
10193     prepareAxes(POSITION | ID | SLOT | PRESSURE);
10194     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10195 
10196     // First finger down.
10197     processId(mapper, FIRST_TRACKING_ID);
10198     processPosition(mapper, 100, 200);
10199     processPressure(mapper, RAW_PRESSURE_MAX);
10200     processSync(mapper);
10201     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10202             WithMotionAction(AMOTION_EVENT_ACTION_DOWN)));
10203 
10204     // Second finger down.
10205     processSlot(mapper, SECOND_SLOT);
10206     processId(mapper, SECOND_TRACKING_ID);
10207     processPosition(mapper, 300, 400);
10208     processPressure(mapper, RAW_PRESSURE_MAX);
10209     processSync(mapper);
10210     ASSERT_NO_FATAL_FAILURE(
10211             mFakeListener->assertNotifyMotionWasCalled(WithMotionAction(ACTION_POINTER_1_DOWN)));
10212 
10213     // Reset the mapper. When the mapper is reset, we expect the current multi-touch state to be
10214     // preserved. Resetting should cancel the ongoing gesture.
10215     resetMapper(mapper, ARBITRARY_TIME);
10216     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10217             WithMotionAction(AMOTION_EVENT_ACTION_CANCEL)));
10218 
10219     // Send a sync to simulate an empty touch frame where nothing changes. The mapper should use
10220     // the existing touch state to generate a down event.
10221     processPosition(mapper, 301, 302);
10222     processSync(mapper);
10223     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10224             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithPressure(1.f))));
10225     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10226             AllOf(WithMotionAction(ACTION_POINTER_1_DOWN), WithPressure(1.f))));
10227 
10228     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
10229 }
10230 
TEST_F(MultiTouchInputMapperTest,Reset_PreservesLastTouchState_NoPointersDown)10231 TEST_F(MultiTouchInputMapperTest, Reset_PreservesLastTouchState_NoPointersDown) {
10232     addConfigurationProperty("touch.deviceType", "touchScreen");
10233     prepareDisplay(ui::ROTATION_0);
10234     prepareAxes(POSITION | ID | SLOT | PRESSURE);
10235     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10236 
10237     // First finger touches down and releases.
10238     processId(mapper, FIRST_TRACKING_ID);
10239     processPosition(mapper, 100, 200);
10240     processPressure(mapper, RAW_PRESSURE_MAX);
10241     processSync(mapper);
10242     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10243             WithMotionAction(AMOTION_EVENT_ACTION_DOWN)));
10244     processId(mapper, INVALID_TRACKING_ID);
10245     processSync(mapper);
10246     ASSERT_NO_FATAL_FAILURE(
10247             mFakeListener->assertNotifyMotionWasCalled(WithMotionAction(AMOTION_EVENT_ACTION_UP)));
10248 
10249     // Reset the mapper. When the mapper is reset, we expect it to restore the latest
10250     // raw state where no pointers are down.
10251     resetMapper(mapper, ARBITRARY_TIME);
10252     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
10253 
10254     // Send an empty sync frame. Since there are no pointers, no events are generated.
10255     processSync(mapper);
10256     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
10257 }
10258 
TEST_F(MultiTouchInputMapperTest,StylusSourceIsAddedDynamicallyFromToolType)10259 TEST_F(MultiTouchInputMapperTest, StylusSourceIsAddedDynamicallyFromToolType) {
10260     addConfigurationProperty("touch.deviceType", "touchScreen");
10261     prepareDisplay(ui::ROTATION_0);
10262     prepareAxes(POSITION | ID | SLOT | PRESSURE | TOOL_TYPE);
10263     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10264     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
10265 
10266     // Even if the device supports reporting the ABS_MT_TOOL_TYPE axis, which could give it the
10267     // ability to report MT_TOOL_PEN, we do not report the device as coming from a stylus source.
10268     // Due to limitations in the evdev protocol, we cannot say for certain that a device is capable
10269     // of reporting stylus events just because it supports ABS_MT_TOOL_TYPE.
10270     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, mapper.getSources());
10271 
10272     // However, if the device ever ends up reporting an event with MT_TOOL_PEN, it should be
10273     // reported with the stylus source.
10274     processId(mapper, FIRST_TRACKING_ID);
10275     processToolType(mapper, MT_TOOL_PEN);
10276     processPosition(mapper, 100, 200);
10277     processPressure(mapper, RAW_PRESSURE_MAX);
10278     processSync(mapper);
10279     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10280             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
10281                   WithSource(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS),
10282                   WithToolType(ToolType::STYLUS))));
10283 
10284     // Now that we know the device supports styluses, ensure that the device is re-configured with
10285     // the stylus source.
10286     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS, mapper.getSources());
10287     {
10288         const auto& devices = mReader->getInputDevices();
10289         auto deviceInfo =
10290                 std::find_if(devices.begin(), devices.end(),
10291                              [](const InputDeviceInfo& info) { return info.getId() == DEVICE_ID; });
10292         LOG_ALWAYS_FATAL_IF(deviceInfo == devices.end(), "Cannot find InputDevice");
10293         ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS, deviceInfo->getSources());
10294     }
10295 
10296     // Ensure the device was not reset to prevent interruptions of any ongoing gestures.
10297     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasNotCalled());
10298 
10299     processId(mapper, INVALID_TRACKING_ID);
10300     processSync(mapper);
10301     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10302             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
10303                   WithSource(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS),
10304                   WithToolType(ToolType::STYLUS))));
10305 }
10306 
TEST_F(MultiTouchInputMapperTest,Process_WhenConfigEnabled_ShouldShowDirectStylusPointer)10307 TEST_F(MultiTouchInputMapperTest, Process_WhenConfigEnabled_ShouldShowDirectStylusPointer) {
10308     addConfigurationProperty("touch.deviceType", "touchScreen");
10309     prepareDisplay(ui::ROTATION_0);
10310     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE | PRESSURE);
10311     // Add BTN_TOOL_PEN to statically show stylus support, since using ABS_MT_TOOL_TYPE can only
10312     // indicate stylus presence dynamically.
10313     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOOL_PEN, 0, AKEYCODE_UNKNOWN, 0);
10314     std::shared_ptr<FakePointerController> fakePointerController =
10315             std::make_shared<FakePointerController>();
10316     mFakePolicy->setPointerController(fakePointerController);
10317     mFakePolicy->setStylusPointerIconEnabled(true);
10318     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10319 
10320     processId(mapper, FIRST_TRACKING_ID);
10321     processPressure(mapper, RAW_PRESSURE_MIN);
10322     processPosition(mapper, 100, 200);
10323     processToolType(mapper, MT_TOOL_PEN);
10324     processSync(mapper);
10325     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10326             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
10327                   WithToolType(ToolType::STYLUS),
10328                   WithPointerCoords(0, toDisplayX(100), toDisplayY(200)))));
10329     ASSERT_TRUE(fakePointerController->isPointerShown());
10330     ASSERT_NO_FATAL_FAILURE(
10331             fakePointerController->assertPosition(toDisplayX(100), toDisplayY(200)));
10332 }
10333 
TEST_F(MultiTouchInputMapperTest,Process_WhenConfigDisabled_ShouldNotShowDirectStylusPointer)10334 TEST_F(MultiTouchInputMapperTest, Process_WhenConfigDisabled_ShouldNotShowDirectStylusPointer) {
10335     addConfigurationProperty("touch.deviceType", "touchScreen");
10336     prepareDisplay(ui::ROTATION_0);
10337     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE | PRESSURE);
10338     // Add BTN_TOOL_PEN to statically show stylus support, since using ABS_MT_TOOL_TYPE can only
10339     // indicate stylus presence dynamically.
10340     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOOL_PEN, 0, AKEYCODE_UNKNOWN, 0);
10341     std::shared_ptr<FakePointerController> fakePointerController =
10342             std::make_shared<FakePointerController>();
10343     mFakePolicy->setPointerController(fakePointerController);
10344     mFakePolicy->setStylusPointerIconEnabled(false);
10345     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10346 
10347     processId(mapper, FIRST_TRACKING_ID);
10348     processPressure(mapper, RAW_PRESSURE_MIN);
10349     processPosition(mapper, 100, 200);
10350     processToolType(mapper, MT_TOOL_PEN);
10351     processSync(mapper);
10352     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10353             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
10354                   WithToolType(ToolType::STYLUS),
10355                   WithPointerCoords(0, toDisplayX(100), toDisplayY(200)))));
10356     ASSERT_FALSE(fakePointerController->isPointerShown());
10357 }
10358 
10359 // --- MultiTouchInputMapperTest_ExternalDevice ---
10360 
10361 class MultiTouchInputMapperTest_ExternalDevice : public MultiTouchInputMapperTest {
10362 protected:
SetUp()10363     void SetUp() override { InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::EXTERNAL); }
10364 };
10365 
10366 /**
10367  * Expect fallback to internal viewport if device is external and external viewport is not present.
10368  */
TEST_F(MultiTouchInputMapperTest_ExternalDevice,Viewports_Fallback)10369 TEST_F(MultiTouchInputMapperTest_ExternalDevice, Viewports_Fallback) {
10370     prepareAxes(POSITION);
10371     addConfigurationProperty("touch.deviceType", "touchScreen");
10372     prepareDisplay(ui::ROTATION_0);
10373     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10374 
10375     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, mapper.getSources());
10376 
10377     NotifyMotionArgs motionArgs;
10378 
10379     // Expect the event to be sent to the internal viewport,
10380     // because an external viewport is not present.
10381     processPosition(mapper, 100, 100);
10382     processSync(mapper);
10383     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10384     ASSERT_EQ(ADISPLAY_ID_DEFAULT, motionArgs.displayId);
10385 
10386     // Expect the event to be sent to the external viewport if it is present.
10387     prepareSecondaryDisplay(ViewportType::EXTERNAL);
10388     processPosition(mapper, 100, 100);
10389     processSync(mapper);
10390     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10391     ASSERT_EQ(SECONDARY_DISPLAY_ID, motionArgs.displayId);
10392 }
10393 
TEST_F(MultiTouchInputMapperTest,Process_TouchpadCapture)10394 TEST_F(MultiTouchInputMapperTest, Process_TouchpadCapture) {
10395     // we need a pointer controller for mouse mode of touchpad (start pointer at 0,0)
10396     std::shared_ptr<FakePointerController> fakePointerController =
10397             std::make_shared<FakePointerController>();
10398     fakePointerController->setBounds(0, 0, DISPLAY_WIDTH - 1, DISPLAY_HEIGHT - 1);
10399     fakePointerController->setPosition(0, 0);
10400 
10401     // prepare device and capture
10402     prepareDisplay(ui::ROTATION_0);
10403     prepareAxes(POSITION | ID | SLOT);
10404     mFakeEventHub->addKey(EVENTHUB_ID, BTN_LEFT, 0, AKEYCODE_UNKNOWN, 0);
10405     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOUCH, 0, AKEYCODE_UNKNOWN, 0);
10406     mFakePolicy->setPointerCapture(true);
10407     mFakePolicy->setPointerController(fakePointerController);
10408     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10409 
10410     // captured touchpad should be a touchpad source
10411     NotifyDeviceResetArgs resetArgs;
10412     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
10413     ASSERT_EQ(AINPUT_SOURCE_TOUCHPAD, mapper.getSources());
10414 
10415     InputDeviceInfo deviceInfo = mDevice->getDeviceInfo();
10416 
10417     const InputDeviceInfo::MotionRange* relRangeX =
10418             deviceInfo.getMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, AINPUT_SOURCE_TOUCHPAD);
10419     ASSERT_NE(relRangeX, nullptr);
10420     ASSERT_EQ(relRangeX->min, -(RAW_X_MAX - RAW_X_MIN));
10421     ASSERT_EQ(relRangeX->max, RAW_X_MAX - RAW_X_MIN);
10422     const InputDeviceInfo::MotionRange* relRangeY =
10423             deviceInfo.getMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, AINPUT_SOURCE_TOUCHPAD);
10424     ASSERT_NE(relRangeY, nullptr);
10425     ASSERT_EQ(relRangeY->min, -(RAW_Y_MAX - RAW_Y_MIN));
10426     ASSERT_EQ(relRangeY->max, RAW_Y_MAX - RAW_Y_MIN);
10427 
10428     // run captured pointer tests - note that this is unscaled, so input listener events should be
10429     //                              identical to what the hardware sends (accounting for any
10430     //                              calibration).
10431     // FINGER 0 DOWN
10432     processSlot(mapper, 0);
10433     processId(mapper, 1);
10434     processPosition(mapper, 100 + RAW_X_MIN, 100 + RAW_Y_MIN);
10435     processKey(mapper, BTN_TOUCH, 1);
10436     processSync(mapper);
10437 
10438     // expect coord[0] to contain initial location of touch 0
10439     NotifyMotionArgs args;
10440     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10441     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
10442     ASSERT_EQ(1U, args.getPointerCount());
10443     ASSERT_EQ(0, args.pointerProperties[0].id);
10444     ASSERT_EQ(AINPUT_SOURCE_TOUCHPAD, args.source);
10445     ASSERT_NO_FATAL_FAILURE(
10446             assertPointerCoords(args.pointerCoords[0], 100, 100, 1, 0, 0, 0, 0, 0, 0, 0));
10447 
10448     // FINGER 1 DOWN
10449     processSlot(mapper, 1);
10450     processId(mapper, 2);
10451     processPosition(mapper, 560 + RAW_X_MIN, 154 + RAW_Y_MIN);
10452     processSync(mapper);
10453 
10454     // expect coord[0] to contain previous location, coord[1] to contain new touch 1 location
10455     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10456     ASSERT_EQ(ACTION_POINTER_1_DOWN, args.action);
10457     ASSERT_EQ(2U, args.getPointerCount());
10458     ASSERT_EQ(0, args.pointerProperties[0].id);
10459     ASSERT_EQ(1, args.pointerProperties[1].id);
10460     ASSERT_NO_FATAL_FAILURE(
10461             assertPointerCoords(args.pointerCoords[0], 100, 100, 1, 0, 0, 0, 0, 0, 0, 0));
10462     ASSERT_NO_FATAL_FAILURE(
10463             assertPointerCoords(args.pointerCoords[1], 560, 154, 1, 0, 0, 0, 0, 0, 0, 0));
10464 
10465     // FINGER 1 MOVE
10466     processPosition(mapper, 540 + RAW_X_MIN, 690 + RAW_Y_MIN);
10467     processSync(mapper);
10468 
10469     // expect coord[0] to contain previous location, coord[1] to contain new touch 1 location
10470     // from move
10471     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10472     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
10473     ASSERT_NO_FATAL_FAILURE(
10474             assertPointerCoords(args.pointerCoords[0], 100, 100, 1, 0, 0, 0, 0, 0, 0, 0));
10475     ASSERT_NO_FATAL_FAILURE(
10476             assertPointerCoords(args.pointerCoords[1], 540, 690, 1, 0, 0, 0, 0, 0, 0, 0));
10477 
10478     // FINGER 0 MOVE
10479     processSlot(mapper, 0);
10480     processPosition(mapper, 50 + RAW_X_MIN, 800 + RAW_Y_MIN);
10481     processSync(mapper);
10482 
10483     // expect coord[0] to contain new touch 0 location, coord[1] to contain previous location
10484     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10485     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
10486     ASSERT_NO_FATAL_FAILURE(
10487             assertPointerCoords(args.pointerCoords[0], 50, 800, 1, 0, 0, 0, 0, 0, 0, 0));
10488     ASSERT_NO_FATAL_FAILURE(
10489             assertPointerCoords(args.pointerCoords[1], 540, 690, 1, 0, 0, 0, 0, 0, 0, 0));
10490 
10491     // BUTTON DOWN
10492     processKey(mapper, BTN_LEFT, 1);
10493     processSync(mapper);
10494 
10495     // touchinputmapper design sends a move before button press
10496     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10497     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
10498     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10499     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, args.action);
10500 
10501     // BUTTON UP
10502     processKey(mapper, BTN_LEFT, 0);
10503     processSync(mapper);
10504 
10505     // touchinputmapper design sends a move after button release
10506     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10507     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, args.action);
10508     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10509     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
10510 
10511     // FINGER 0 UP
10512     processId(mapper, -1);
10513     processSync(mapper);
10514     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10515     ASSERT_EQ(AMOTION_EVENT_ACTION_POINTER_UP | 0x0000, args.action);
10516 
10517     // FINGER 1 MOVE
10518     processSlot(mapper, 1);
10519     processPosition(mapper, 320 + RAW_X_MIN, 900 + RAW_Y_MIN);
10520     processSync(mapper);
10521 
10522     // expect coord[0] to contain new location of touch 1, and properties[0].id to contain 1
10523     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10524     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
10525     ASSERT_EQ(1U, args.getPointerCount());
10526     ASSERT_EQ(1, args.pointerProperties[0].id);
10527     ASSERT_NO_FATAL_FAILURE(
10528             assertPointerCoords(args.pointerCoords[0], 320, 900, 1, 0, 0, 0, 0, 0, 0, 0));
10529 
10530     // FINGER 1 UP
10531     processId(mapper, -1);
10532     processKey(mapper, BTN_TOUCH, 0);
10533     processSync(mapper);
10534     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10535     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
10536 
10537     // non captured touchpad should be a mouse source
10538     mFakePolicy->setPointerCapture(false);
10539     configureDevice(InputReaderConfiguration::Change::POINTER_CAPTURE);
10540     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
10541     ASSERT_EQ(AINPUT_SOURCE_MOUSE, mapper.getSources());
10542 }
10543 
TEST_F(MultiTouchInputMapperTest,Process_UnCapturedTouchpadPointer)10544 TEST_F(MultiTouchInputMapperTest, Process_UnCapturedTouchpadPointer) {
10545     std::shared_ptr<FakePointerController> fakePointerController =
10546             std::make_shared<FakePointerController>();
10547     fakePointerController->setBounds(0, 0, DISPLAY_WIDTH - 1, DISPLAY_HEIGHT - 1);
10548     fakePointerController->setPosition(0, 0);
10549 
10550     // prepare device and capture
10551     prepareDisplay(ui::ROTATION_0);
10552     prepareAxes(POSITION | ID | SLOT);
10553     mFakeEventHub->addKey(EVENTHUB_ID, BTN_LEFT, 0, AKEYCODE_UNKNOWN, 0);
10554     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOUCH, 0, AKEYCODE_UNKNOWN, 0);
10555     mFakePolicy->setPointerController(fakePointerController);
10556     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10557     // run uncaptured pointer tests - pushes out generic events
10558     // FINGER 0 DOWN
10559     processId(mapper, 3);
10560     processPosition(mapper, 100, 100);
10561     processKey(mapper, BTN_TOUCH, 1);
10562     processSync(mapper);
10563 
10564     // start at (100,100), cursor should be at (0,0) * scale
10565     NotifyMotionArgs args;
10566     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10567     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, args.action);
10568     ASSERT_NO_FATAL_FAILURE(
10569             assertPointerCoords(args.pointerCoords[0], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
10570 
10571     // FINGER 0 MOVE
10572     processPosition(mapper, 200, 200);
10573     processSync(mapper);
10574 
10575     // compute scaling to help with touch position checking
10576     float rawDiagonal = hypotf(RAW_X_MAX - RAW_X_MIN, RAW_Y_MAX - RAW_Y_MIN);
10577     float displayDiagonal = hypotf(DISPLAY_WIDTH, DISPLAY_HEIGHT);
10578     float scale =
10579             mFakePolicy->getPointerGestureMovementSpeedRatio() * displayDiagonal / rawDiagonal;
10580 
10581     // translate from (100,100) -> (200,200), cursor should have changed to (100,100) * scale)
10582     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10583     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, args.action);
10584     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0], 100 * scale, 100 * scale, 0,
10585                                                 0, 0, 0, 0, 0, 0, 0));
10586 
10587     // BUTTON DOWN
10588     processKey(mapper, BTN_LEFT, 1);
10589     processSync(mapper);
10590 
10591     // touchinputmapper design sends a move before button press
10592     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10593     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
10594     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10595     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, args.action);
10596 
10597     // BUTTON UP
10598     processKey(mapper, BTN_LEFT, 0);
10599     processSync(mapper);
10600 
10601     // touchinputmapper design sends a move after button release
10602     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10603     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, args.action);
10604     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10605     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
10606 }
10607 
TEST_F(MultiTouchInputMapperTest,WhenCapturedAndNotCaptured_GetSources)10608 TEST_F(MultiTouchInputMapperTest, WhenCapturedAndNotCaptured_GetSources) {
10609     std::shared_ptr<FakePointerController> fakePointerController =
10610             std::make_shared<FakePointerController>();
10611 
10612     prepareDisplay(ui::ROTATION_0);
10613     prepareAxes(POSITION | ID | SLOT);
10614     mFakeEventHub->addKey(EVENTHUB_ID, BTN_LEFT, 0, AKEYCODE_UNKNOWN, 0);
10615     mFakePolicy->setPointerController(fakePointerController);
10616     mFakePolicy->setPointerCapture(false);
10617     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10618 
10619     // uncaptured touchpad should be a pointer device
10620     ASSERT_EQ(AINPUT_SOURCE_MOUSE, mapper.getSources());
10621 
10622     // captured touchpad should be a touchpad device
10623     mFakePolicy->setPointerCapture(true);
10624     configureDevice(InputReaderConfiguration::Change::POINTER_CAPTURE);
10625     ASSERT_EQ(AINPUT_SOURCE_TOUCHPAD, mapper.getSources());
10626 }
10627 
10628 // --- BluetoothMultiTouchInputMapperTest ---
10629 
10630 class BluetoothMultiTouchInputMapperTest : public MultiTouchInputMapperTest {
10631 protected:
SetUp()10632     void SetUp() override {
10633         InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::EXTERNAL, BUS_BLUETOOTH);
10634     }
10635 };
10636 
TEST_F(BluetoothMultiTouchInputMapperTest,TimestampSmoothening)10637 TEST_F(BluetoothMultiTouchInputMapperTest, TimestampSmoothening) {
10638     addConfigurationProperty("touch.deviceType", "touchScreen");
10639     prepareDisplay(ui::ROTATION_0);
10640     prepareAxes(POSITION | ID | SLOT | PRESSURE);
10641     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10642 
10643     nsecs_t kernelEventTime = ARBITRARY_TIME;
10644     nsecs_t expectedEventTime = ARBITRARY_TIME;
10645     // Touch down.
10646     processId(mapper, FIRST_TRACKING_ID);
10647     processPosition(mapper, 100, 200);
10648     processPressure(mapper, RAW_PRESSURE_MAX);
10649     processSync(mapper, ARBITRARY_TIME);
10650     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10651             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithEventTime(ARBITRARY_TIME))));
10652 
10653     // Process several events that come in quick succession, according to their timestamps.
10654     for (int i = 0; i < 3; i++) {
10655         constexpr static nsecs_t delta = ms2ns(1);
10656         static_assert(delta < MIN_BLUETOOTH_TIMESTAMP_DELTA);
10657         kernelEventTime += delta;
10658         expectedEventTime += MIN_BLUETOOTH_TIMESTAMP_DELTA;
10659 
10660         processPosition(mapper, 101 + i, 201 + i);
10661         processSync(mapper, kernelEventTime);
10662         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10663                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
10664                       WithEventTime(expectedEventTime))));
10665     }
10666 
10667     // Release the touch.
10668     processId(mapper, INVALID_TRACKING_ID);
10669     processPressure(mapper, RAW_PRESSURE_MIN);
10670     processSync(mapper, ARBITRARY_TIME + ms2ns(50));
10671     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10672             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
10673                   WithEventTime(ARBITRARY_TIME + ms2ns(50)))));
10674 }
10675 
10676 // --- MultiTouchPointerModeTest ---
10677 
10678 class MultiTouchPointerModeTest : public MultiTouchInputMapperTest {
10679 protected:
10680     float mPointerMovementScale;
10681     float mPointerXZoomScale;
preparePointerMode(int xAxisResolution,int yAxisResolution)10682     void preparePointerMode(int xAxisResolution, int yAxisResolution) {
10683         addConfigurationProperty("touch.deviceType", "pointer");
10684         std::shared_ptr<FakePointerController> fakePointerController =
10685                 std::make_shared<FakePointerController>();
10686         fakePointerController->setBounds(0, 0, DISPLAY_WIDTH - 1, DISPLAY_HEIGHT - 1);
10687         fakePointerController->setPosition(0, 0);
10688         prepareDisplay(ui::ROTATION_0);
10689 
10690         prepareAxes(POSITION);
10691         prepareAbsoluteAxisResolution(xAxisResolution, yAxisResolution);
10692         // In order to enable swipe and freeform gesture in pointer mode, pointer capture
10693         // needs to be disabled, and the pointer gesture needs to be enabled.
10694         mFakePolicy->setPointerCapture(false);
10695         mFakePolicy->setPointerGestureEnabled(true);
10696         mFakePolicy->setPointerController(fakePointerController);
10697 
10698         float rawDiagonal = hypotf(RAW_X_MAX - RAW_X_MIN, RAW_Y_MAX - RAW_Y_MIN);
10699         float displayDiagonal = hypotf(DISPLAY_WIDTH, DISPLAY_HEIGHT);
10700         mPointerMovementScale =
10701                 mFakePolicy->getPointerGestureMovementSpeedRatio() * displayDiagonal / rawDiagonal;
10702         mPointerXZoomScale =
10703                 mFakePolicy->getPointerGestureZoomSpeedRatio() * displayDiagonal / rawDiagonal;
10704     }
10705 
prepareAbsoluteAxisResolution(int xAxisResolution,int yAxisResolution)10706     void prepareAbsoluteAxisResolution(int xAxisResolution, int yAxisResolution) {
10707         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_X, RAW_X_MIN, RAW_X_MAX,
10708                                        /*flat*/ 0,
10709                                        /*fuzz*/ 0, /*resolution*/ xAxisResolution);
10710         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_Y, RAW_Y_MIN, RAW_Y_MAX,
10711                                        /*flat*/ 0,
10712                                        /*fuzz*/ 0, /*resolution*/ yAxisResolution);
10713     }
10714 };
10715 
10716 /**
10717  * Two fingers down on a pointer mode touch pad. The width
10718  * of the two finger is larger than 1/4 of the touch pack diagnal length. However, it
10719  * is smaller than the fixed min physical length 30mm. Two fingers' distance must
10720  * be greater than the both value to be freeform gesture, so that after two
10721  * fingers start to move downwards, the gesture should be swipe.
10722  */
TEST_F(MultiTouchPointerModeTest,PointerGestureMaxSwipeWidthSwipe)10723 TEST_F(MultiTouchPointerModeTest, PointerGestureMaxSwipeWidthSwipe) {
10724     // The min freeform gesture width is 25units/mm x 30mm = 750
10725     // which is greater than fraction of the diagnal length of the touchpad (349).
10726     // Thus, MaxSwipWidth is 750.
10727     preparePointerMode(/*xResolution=*/25, /*yResolution=*/25);
10728     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10729     NotifyMotionArgs motionArgs;
10730 
10731     // Two fingers down at once.
10732     // The two fingers are 450 units apart, expects the current gesture to be PRESS
10733     // Pointer's initial position is used the [0,0] coordinate.
10734     int32_t x1 = 100, y1 = 125, x2 = 550, y2 = 125;
10735 
10736     processId(mapper, FIRST_TRACKING_ID);
10737     processPosition(mapper, x1, y1);
10738     processMTSync(mapper);
10739     processId(mapper, SECOND_TRACKING_ID);
10740     processPosition(mapper, x2, y2);
10741     processMTSync(mapper);
10742     processSync(mapper);
10743 
10744     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10745     ASSERT_EQ(1U, motionArgs.getPointerCount());
10746     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
10747     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10748     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
10749     ASSERT_NO_FATAL_FAILURE(
10750             assertPointerCoords(motionArgs.pointerCoords[0], 0, 0, 1, 0, 0, 0, 0, 0, 0, 0));
10751 
10752     // It should be recognized as a SWIPE gesture when two fingers start to move down,
10753     // that there should be 1 pointer.
10754     int32_t movingDistance = 200;
10755     y1 += movingDistance;
10756     y2 += movingDistance;
10757 
10758     processId(mapper, FIRST_TRACKING_ID);
10759     processPosition(mapper, x1, y1);
10760     processMTSync(mapper);
10761     processId(mapper, SECOND_TRACKING_ID);
10762     processPosition(mapper, x2, y2);
10763     processMTSync(mapper);
10764     processSync(mapper);
10765 
10766     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10767     ASSERT_EQ(1U, motionArgs.getPointerCount());
10768     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10769     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10770     ASSERT_EQ(MotionClassification::TWO_FINGER_SWIPE, motionArgs.classification);
10771     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0], 0,
10772                                                 movingDistance * mPointerMovementScale, 1, 0, 0, 0,
10773                                                 0, 0, 0, 0));
10774 }
10775 
10776 /**
10777  * Two fingers down on a pointer mode touch pad. The width of the two finger is larger
10778  * than the minimum freeform gesture width, 30mm. However, it is smaller than 1/4 of
10779  * the touch pack diagnal length. Two fingers' distance must be greater than the both
10780  * value to be freeform gesture, so that after two fingers start to move downwards,
10781  * the gesture should be swipe.
10782  */
TEST_F(MultiTouchPointerModeTest,PointerGestureMaxSwipeWidthLowResolutionSwipe)10783 TEST_F(MultiTouchPointerModeTest, PointerGestureMaxSwipeWidthLowResolutionSwipe) {
10784     // The min freeform gesture width is 5units/mm x 30mm = 150
10785     // which is greater than fraction of the diagnal length of the touchpad (349).
10786     // Thus, MaxSwipWidth is the fraction of the diagnal length, 349.
10787     preparePointerMode(/*xResolution=*/5, /*yResolution=*/5);
10788     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10789     NotifyMotionArgs motionArgs;
10790 
10791     // Two fingers down at once.
10792     // The two fingers are 250 units apart, expects the current gesture to be PRESS
10793     // Pointer's initial position is used the [0,0] coordinate.
10794     int32_t x1 = 100, y1 = 125, x2 = 350, y2 = 125;
10795 
10796     processId(mapper, FIRST_TRACKING_ID);
10797     processPosition(mapper, x1, y1);
10798     processMTSync(mapper);
10799     processId(mapper, SECOND_TRACKING_ID);
10800     processPosition(mapper, x2, y2);
10801     processMTSync(mapper);
10802     processSync(mapper);
10803 
10804     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10805     ASSERT_EQ(1U, motionArgs.getPointerCount());
10806     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
10807     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10808     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
10809     ASSERT_NO_FATAL_FAILURE(
10810             assertPointerCoords(motionArgs.pointerCoords[0], 0, 0, 1, 0, 0, 0, 0, 0, 0, 0));
10811 
10812     // It should be recognized as a SWIPE gesture when two fingers start to move down,
10813     // and there should be 1 pointer.
10814     int32_t movingDistance = 200;
10815     y1 += movingDistance;
10816     y2 += movingDistance;
10817 
10818     processId(mapper, FIRST_TRACKING_ID);
10819     processPosition(mapper, x1, y1);
10820     processMTSync(mapper);
10821     processId(mapper, SECOND_TRACKING_ID);
10822     processPosition(mapper, x2, y2);
10823     processMTSync(mapper);
10824     processSync(mapper);
10825 
10826     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10827     ASSERT_EQ(1U, motionArgs.getPointerCount());
10828     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10829     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10830     ASSERT_EQ(MotionClassification::TWO_FINGER_SWIPE, motionArgs.classification);
10831     // New coordinate is the scaled relative coordinate from the initial coordinate.
10832     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0], 0,
10833                                                 movingDistance * mPointerMovementScale, 1, 0, 0, 0,
10834                                                 0, 0, 0, 0));
10835 }
10836 
10837 /**
10838  * Touch the touch pad with two fingers with a distance wider than the minimum freeform
10839  * gesture width and 1/4 of the diagnal length of the touchpad. Expect to receive
10840  * freeform gestures after two fingers start to move downwards.
10841  */
TEST_F(MultiTouchPointerModeTest,PointerGestureMaxSwipeWidthFreeform)10842 TEST_F(MultiTouchPointerModeTest, PointerGestureMaxSwipeWidthFreeform) {
10843     preparePointerMode(/*xResolution=*/25, /*yResolution=*/25);
10844     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10845 
10846     NotifyMotionArgs motionArgs;
10847 
10848     // Two fingers down at once. Wider than the max swipe width.
10849     // The gesture is expected to be PRESS, then transformed to FREEFORM
10850     int32_t x1 = 100, y1 = 125, x2 = 900, y2 = 125;
10851 
10852     processId(mapper, FIRST_TRACKING_ID);
10853     processPosition(mapper, x1, y1);
10854     processMTSync(mapper);
10855     processId(mapper, SECOND_TRACKING_ID);
10856     processPosition(mapper, x2, y2);
10857     processMTSync(mapper);
10858     processSync(mapper);
10859 
10860     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10861     ASSERT_EQ(1U, motionArgs.getPointerCount());
10862     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
10863     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10864     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
10865     // One pointer for PRESS, and its coordinate is used as the origin for pointer coordinates.
10866     ASSERT_NO_FATAL_FAILURE(
10867             assertPointerCoords(motionArgs.pointerCoords[0], 0, 0, 1, 0, 0, 0, 0, 0, 0, 0));
10868 
10869     int32_t movingDistance = 200;
10870 
10871     // Move two fingers down, expect a cancel event because gesture is changing to freeform,
10872     // then two down events for two pointers.
10873     y1 += movingDistance;
10874     y2 += movingDistance;
10875 
10876     processId(mapper, FIRST_TRACKING_ID);
10877     processPosition(mapper, x1, y1);
10878     processMTSync(mapper);
10879     processId(mapper, SECOND_TRACKING_ID);
10880     processPosition(mapper, x2, y2);
10881     processMTSync(mapper);
10882     processSync(mapper);
10883 
10884     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10885     // The previous PRESS gesture is cancelled, because it is transformed to freeform
10886     ASSERT_EQ(1U, motionArgs.getPointerCount());
10887     ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionArgs.action);
10888     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10889     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10890     ASSERT_EQ(1U, motionArgs.getPointerCount());
10891     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
10892     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10893     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10894     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
10895     ASSERT_EQ(2U, motionArgs.getPointerCount());
10896     ASSERT_EQ(AMOTION_EVENT_ACTION_POINTER_DOWN, motionArgs.action & AMOTION_EVENT_ACTION_MASK);
10897     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10898     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
10899     // Two pointers' scaled relative coordinates from their initial centroid.
10900     // Initial y coordinates are 0 as y1 and y2 have the same value.
10901     float cookedX1 = (x1 - x2) / 2 * mPointerXZoomScale;
10902     float cookedX2 = (x2 - x1) / 2 * mPointerXZoomScale;
10903     // When pointers move,  the new coordinates equal to the initial coordinates plus
10904     // scaled moving distance.
10905     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0], cookedX1,
10906                                                 movingDistance * mPointerMovementScale, 1, 0, 0, 0,
10907                                                 0, 0, 0, 0));
10908     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1], cookedX2,
10909                                                 movingDistance * mPointerMovementScale, 1, 0, 0, 0,
10910                                                 0, 0, 0, 0));
10911 
10912     // Move two fingers down again, expect one MOVE motion event.
10913     y1 += movingDistance;
10914     y2 += movingDistance;
10915 
10916     processId(mapper, FIRST_TRACKING_ID);
10917     processPosition(mapper, x1, y1);
10918     processMTSync(mapper);
10919     processId(mapper, SECOND_TRACKING_ID);
10920     processPosition(mapper, x2, y2);
10921     processMTSync(mapper);
10922     processSync(mapper);
10923 
10924     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10925     ASSERT_EQ(2U, motionArgs.getPointerCount());
10926     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10927     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10928     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
10929     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0], cookedX1,
10930                                                 movingDistance * 2 * mPointerMovementScale, 1, 0, 0,
10931                                                 0, 0, 0, 0, 0));
10932     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1], cookedX2,
10933                                                 movingDistance * 2 * mPointerMovementScale, 1, 0, 0,
10934                                                 0, 0, 0, 0, 0));
10935 }
10936 
TEST_F(MultiTouchPointerModeTest,TwoFingerSwipeOffsets)10937 TEST_F(MultiTouchPointerModeTest, TwoFingerSwipeOffsets) {
10938     preparePointerMode(/*xResolution=*/25, /*yResolution=*/25);
10939     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10940     NotifyMotionArgs motionArgs;
10941 
10942     // Place two fingers down.
10943     int32_t x1 = 100, y1 = 125, x2 = 550, y2 = 125;
10944 
10945     processId(mapper, FIRST_TRACKING_ID);
10946     processPosition(mapper, x1, y1);
10947     processMTSync(mapper);
10948     processId(mapper, SECOND_TRACKING_ID);
10949     processPosition(mapper, x2, y2);
10950     processMTSync(mapper);
10951     processSync(mapper);
10952 
10953     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10954     ASSERT_EQ(1U, motionArgs.getPointerCount());
10955     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
10956     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
10957     ASSERT_EQ(0, motionArgs.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET));
10958     ASSERT_EQ(0, motionArgs.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET));
10959 
10960     // Move the two fingers down and to the left.
10961     int32_t movingDistance = 200;
10962     x1 -= movingDistance;
10963     y1 += movingDistance;
10964     x2 -= movingDistance;
10965     y2 += movingDistance;
10966 
10967     processId(mapper, FIRST_TRACKING_ID);
10968     processPosition(mapper, x1, y1);
10969     processMTSync(mapper);
10970     processId(mapper, SECOND_TRACKING_ID);
10971     processPosition(mapper, x2, y2);
10972     processMTSync(mapper);
10973     processSync(mapper);
10974 
10975     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10976     ASSERT_EQ(1U, motionArgs.getPointerCount());
10977     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10978     ASSERT_EQ(MotionClassification::TWO_FINGER_SWIPE, motionArgs.classification);
10979     ASSERT_LT(motionArgs.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET), 0);
10980     ASSERT_GT(motionArgs.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET), 0);
10981 }
10982 
TEST_F(MultiTouchPointerModeTest,WhenViewportActiveStatusChanged_PointerGestureIsReset)10983 TEST_F(MultiTouchPointerModeTest, WhenViewportActiveStatusChanged_PointerGestureIsReset) {
10984     preparePointerMode(/*xResolution=*/25, /*yResolution=*/25);
10985     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOOL_PEN, 0, AKEYCODE_UNKNOWN, 0);
10986     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10987     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
10988 
10989     // Start a stylus gesture.
10990     processKey(mapper, BTN_TOOL_PEN, 1);
10991     processId(mapper, FIRST_TRACKING_ID);
10992     processPosition(mapper, 100, 200);
10993     processSync(mapper);
10994     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10995             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
10996                   WithSource(AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_STYLUS),
10997                   WithToolType(ToolType::STYLUS))));
10998     // TODO(b/257078296): Pointer mode generates extra event.
10999     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
11000             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
11001                   WithSource(AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_STYLUS),
11002                   WithToolType(ToolType::STYLUS))));
11003     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
11004 
11005     // Make the viewport inactive. This will put the device in disabled mode, and the ongoing stylus
11006     // gesture should be disabled.
11007     auto viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
11008     viewport->isActive = false;
11009     mFakePolicy->updateViewport(*viewport);
11010     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
11011     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
11012             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
11013                   WithSource(AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_STYLUS),
11014                   WithToolType(ToolType::STYLUS))));
11015     // TODO(b/257078296): Pointer mode generates extra event.
11016     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
11017             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
11018                   WithSource(AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_STYLUS),
11019                   WithToolType(ToolType::STYLUS))));
11020     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
11021 }
11022 
11023 // --- JoystickInputMapperTest ---
11024 
11025 class JoystickInputMapperTest : public InputMapperTest {
11026 protected:
11027     static const int32_t RAW_X_MIN;
11028     static const int32_t RAW_X_MAX;
11029     static const int32_t RAW_Y_MIN;
11030     static const int32_t RAW_Y_MAX;
11031 
SetUp()11032     void SetUp() override {
11033         InputMapperTest::SetUp(InputDeviceClass::JOYSTICK | InputDeviceClass::EXTERNAL);
11034     }
prepareAxes()11035     void prepareAxes() {
11036         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_X, RAW_X_MIN, RAW_X_MAX, 0, 0);
11037         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_Y, RAW_Y_MIN, RAW_Y_MAX, 0, 0);
11038     }
11039 
processAxis(JoystickInputMapper & mapper,int32_t axis,int32_t value)11040     void processAxis(JoystickInputMapper& mapper, int32_t axis, int32_t value) {
11041         process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, axis, value);
11042     }
11043 
processSync(JoystickInputMapper & mapper)11044     void processSync(JoystickInputMapper& mapper) {
11045         process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
11046     }
11047 
prepareVirtualDisplay(ui::Rotation orientation)11048     void prepareVirtualDisplay(ui::Rotation orientation) {
11049         setDisplayInfoAndReconfigure(VIRTUAL_DISPLAY_ID, VIRTUAL_DISPLAY_WIDTH,
11050                                      VIRTUAL_DISPLAY_HEIGHT, orientation, VIRTUAL_DISPLAY_UNIQUE_ID,
11051                                      NO_PORT, ViewportType::VIRTUAL);
11052     }
11053 };
11054 
11055 const int32_t JoystickInputMapperTest::RAW_X_MIN = -32767;
11056 const int32_t JoystickInputMapperTest::RAW_X_MAX = 32767;
11057 const int32_t JoystickInputMapperTest::RAW_Y_MIN = -32767;
11058 const int32_t JoystickInputMapperTest::RAW_Y_MAX = 32767;
11059 
TEST_F(JoystickInputMapperTest,Configure_AssignsDisplayUniqueId)11060 TEST_F(JoystickInputMapperTest, Configure_AssignsDisplayUniqueId) {
11061     prepareAxes();
11062     JoystickInputMapper& mapper = constructAndAddMapper<JoystickInputMapper>();
11063 
11064     mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, VIRTUAL_DISPLAY_UNIQUE_ID);
11065 
11066     prepareVirtualDisplay(ui::ROTATION_0);
11067 
11068     // Send an axis event
11069     processAxis(mapper, ABS_X, 100);
11070     processSync(mapper);
11071 
11072     NotifyMotionArgs args;
11073     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
11074     ASSERT_EQ(VIRTUAL_DISPLAY_ID, args.displayId);
11075 
11076     // Send another axis event
11077     processAxis(mapper, ABS_Y, 100);
11078     processSync(mapper);
11079 
11080     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
11081     ASSERT_EQ(VIRTUAL_DISPLAY_ID, args.displayId);
11082 }
11083 
11084 // --- PeripheralControllerTest ---
11085 
11086 class PeripheralControllerTest : public testing::Test {
11087 protected:
11088     static const char* DEVICE_NAME;
11089     static const char* DEVICE_LOCATION;
11090     static const int32_t DEVICE_ID;
11091     static const int32_t DEVICE_GENERATION;
11092     static const int32_t DEVICE_CONTROLLER_NUMBER;
11093     static const ftl::Flags<InputDeviceClass> DEVICE_CLASSES;
11094     static const int32_t EVENTHUB_ID;
11095 
11096     std::shared_ptr<FakeEventHub> mFakeEventHub;
11097     sp<FakeInputReaderPolicy> mFakePolicy;
11098     std::unique_ptr<TestInputListener> mFakeListener;
11099     std::unique_ptr<InstrumentedInputReader> mReader;
11100     std::shared_ptr<InputDevice> mDevice;
11101 
SetUp(ftl::Flags<InputDeviceClass> classes)11102     virtual void SetUp(ftl::Flags<InputDeviceClass> classes) {
11103         mFakeEventHub = std::make_unique<FakeEventHub>();
11104         mFakePolicy = sp<FakeInputReaderPolicy>::make();
11105         mFakeListener = std::make_unique<TestInputListener>();
11106         mReader = std::make_unique<InstrumentedInputReader>(mFakeEventHub, mFakePolicy,
11107                                                             *mFakeListener);
11108         mDevice = newDevice(DEVICE_ID, DEVICE_NAME, DEVICE_LOCATION, EVENTHUB_ID, classes);
11109     }
11110 
SetUp()11111     void SetUp() override { SetUp(DEVICE_CLASSES); }
11112 
TearDown()11113     void TearDown() override {
11114         mFakeListener.reset();
11115         mFakePolicy.clear();
11116     }
11117 
newDevice(int32_t deviceId,const std::string & name,const std::string & location,int32_t eventHubId,ftl::Flags<InputDeviceClass> classes)11118     std::shared_ptr<InputDevice> newDevice(int32_t deviceId, const std::string& name,
11119                                            const std::string& location, int32_t eventHubId,
11120                                            ftl::Flags<InputDeviceClass> classes) {
11121         InputDeviceIdentifier identifier;
11122         identifier.name = name;
11123         identifier.location = location;
11124         std::shared_ptr<InputDevice> device =
11125                 std::make_shared<InputDevice>(mReader->getContext(), deviceId, DEVICE_GENERATION,
11126                                               identifier);
11127         mReader->pushNextDevice(device);
11128         mFakeEventHub->addDevice(eventHubId, name, classes);
11129         mReader->loopOnce();
11130         return device;
11131     }
11132 
11133     template <class T, typename... Args>
addControllerAndConfigure(Args...args)11134     T& addControllerAndConfigure(Args... args) {
11135         T& controller = mDevice->addController<T>(EVENTHUB_ID, args...);
11136 
11137         return controller;
11138     }
11139 };
11140 
11141 const char* PeripheralControllerTest::DEVICE_NAME = "device";
11142 const char* PeripheralControllerTest::DEVICE_LOCATION = "BLUETOOTH";
11143 const int32_t PeripheralControllerTest::DEVICE_ID = END_RESERVED_ID + 1000;
11144 const int32_t PeripheralControllerTest::DEVICE_GENERATION = 2;
11145 const int32_t PeripheralControllerTest::DEVICE_CONTROLLER_NUMBER = 0;
11146 const ftl::Flags<InputDeviceClass> PeripheralControllerTest::DEVICE_CLASSES =
11147         ftl::Flags<InputDeviceClass>(0); // not needed for current tests
11148 const int32_t PeripheralControllerTest::EVENTHUB_ID = 1;
11149 
11150 // --- BatteryControllerTest ---
11151 class BatteryControllerTest : public PeripheralControllerTest {
11152 protected:
SetUp()11153     void SetUp() override {
11154         PeripheralControllerTest::SetUp(DEVICE_CLASSES | InputDeviceClass::BATTERY);
11155     }
11156 };
11157 
TEST_F(BatteryControllerTest,GetBatteryCapacity)11158 TEST_F(BatteryControllerTest, GetBatteryCapacity) {
11159     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11160 
11161     ASSERT_TRUE(controller.getBatteryCapacity(FakeEventHub::DEFAULT_BATTERY));
11162     ASSERT_EQ(controller.getBatteryCapacity(FakeEventHub::DEFAULT_BATTERY).value_or(-1),
11163               FakeEventHub::BATTERY_CAPACITY);
11164 }
11165 
TEST_F(BatteryControllerTest,GetBatteryStatus)11166 TEST_F(BatteryControllerTest, GetBatteryStatus) {
11167     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11168 
11169     ASSERT_TRUE(controller.getBatteryStatus(FakeEventHub::DEFAULT_BATTERY));
11170     ASSERT_EQ(controller.getBatteryStatus(FakeEventHub::DEFAULT_BATTERY).value_or(-1),
11171               FakeEventHub::BATTERY_STATUS);
11172 }
11173 
11174 // --- LightControllerTest ---
11175 class LightControllerTest : public PeripheralControllerTest {
11176 protected:
SetUp()11177     void SetUp() override {
11178         PeripheralControllerTest::SetUp(DEVICE_CLASSES | InputDeviceClass::LIGHT);
11179     }
11180 };
11181 
TEST_F(LightControllerTest,MonoLight)11182 TEST_F(LightControllerTest, MonoLight) {
11183     RawLightInfo infoMono = {.id = 1,
11184                              .name = "mono_light",
11185                              .maxBrightness = 255,
11186                              .flags = InputLightClass::BRIGHTNESS,
11187                              .path = ""};
11188     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
11189 
11190     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11191     InputDeviceInfo info;
11192     controller.populateDeviceInfo(&info);
11193     std::vector<InputDeviceLightInfo> lights = info.getLights();
11194     ASSERT_EQ(1U, lights.size());
11195     ASSERT_EQ(InputDeviceLightType::INPUT, lights[0].type);
11196     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
11197 
11198     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_BRIGHTNESS));
11199     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_BRIGHTNESS);
11200 }
11201 
TEST_F(LightControllerTest,MonoKeyboardBacklight)11202 TEST_F(LightControllerTest, MonoKeyboardBacklight) {
11203     RawLightInfo infoMono = {.id = 1,
11204                              .name = "mono_keyboard_backlight",
11205                              .maxBrightness = 255,
11206                              .flags = InputLightClass::BRIGHTNESS |
11207                                      InputLightClass::KEYBOARD_BACKLIGHT,
11208                              .path = ""};
11209     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
11210 
11211     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11212     InputDeviceInfo info;
11213     controller.populateDeviceInfo(&info);
11214     std::vector<InputDeviceLightInfo> lights = info.getLights();
11215     ASSERT_EQ(1U, lights.size());
11216     ASSERT_EQ(InputDeviceLightType::KEYBOARD_BACKLIGHT, lights[0].type);
11217     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
11218 
11219     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_BRIGHTNESS));
11220     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_BRIGHTNESS);
11221 }
11222 
TEST_F(LightControllerTest,Ignore_MonoLight_WithPreferredBacklightLevels)11223 TEST_F(LightControllerTest, Ignore_MonoLight_WithPreferredBacklightLevels) {
11224     RawLightInfo infoMono = {.id = 1,
11225                              .name = "mono_light",
11226                              .maxBrightness = 255,
11227                              .flags = InputLightClass::BRIGHTNESS,
11228                              .path = ""};
11229     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
11230     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "keyboard.backlight.brightnessLevels",
11231                                             "0,100,200");
11232 
11233     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11234     std::list<NotifyArgs> unused =
11235             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
11236                                /*changes=*/{});
11237 
11238     InputDeviceInfo info;
11239     controller.populateDeviceInfo(&info);
11240     std::vector<InputDeviceLightInfo> lights = info.getLights();
11241     ASSERT_EQ(1U, lights.size());
11242     ASSERT_EQ(0U, lights[0].preferredBrightnessLevels.size());
11243 }
11244 
TEST_F(LightControllerTest,KeyboardBacklight_WithNoPreferredBacklightLevels)11245 TEST_F(LightControllerTest, KeyboardBacklight_WithNoPreferredBacklightLevels) {
11246     RawLightInfo infoMono = {.id = 1,
11247                              .name = "mono_keyboard_backlight",
11248                              .maxBrightness = 255,
11249                              .flags = InputLightClass::BRIGHTNESS |
11250                                      InputLightClass::KEYBOARD_BACKLIGHT,
11251                              .path = ""};
11252     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
11253 
11254     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11255     std::list<NotifyArgs> unused =
11256             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
11257                                /*changes=*/{});
11258 
11259     InputDeviceInfo info;
11260     controller.populateDeviceInfo(&info);
11261     std::vector<InputDeviceLightInfo> lights = info.getLights();
11262     ASSERT_EQ(1U, lights.size());
11263     ASSERT_EQ(0U, lights[0].preferredBrightnessLevels.size());
11264 }
11265 
TEST_F(LightControllerTest,KeyboardBacklight_WithPreferredBacklightLevels)11266 TEST_F(LightControllerTest, KeyboardBacklight_WithPreferredBacklightLevels) {
11267     RawLightInfo infoMono = {.id = 1,
11268                              .name = "mono_keyboard_backlight",
11269                              .maxBrightness = 255,
11270                              .flags = InputLightClass::BRIGHTNESS |
11271                                      InputLightClass::KEYBOARD_BACKLIGHT,
11272                              .path = ""};
11273     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
11274     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "keyboard.backlight.brightnessLevels",
11275                                             "0,100,200");
11276 
11277     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11278     std::list<NotifyArgs> unused =
11279             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
11280                                /*changes=*/{});
11281 
11282     InputDeviceInfo info;
11283     controller.populateDeviceInfo(&info);
11284     std::vector<InputDeviceLightInfo> lights = info.getLights();
11285     ASSERT_EQ(1U, lights.size());
11286     ASSERT_EQ(3U, lights[0].preferredBrightnessLevels.size());
11287     std::set<BrightnessLevel>::iterator it = lights[0].preferredBrightnessLevels.begin();
11288     ASSERT_EQ(BrightnessLevel(0), *it);
11289     std::advance(it, 1);
11290     ASSERT_EQ(BrightnessLevel(100), *it);
11291     std::advance(it, 1);
11292     ASSERT_EQ(BrightnessLevel(200), *it);
11293 }
11294 
TEST_F(LightControllerTest,KeyboardBacklight_WithWrongPreferredBacklightLevels)11295 TEST_F(LightControllerTest, KeyboardBacklight_WithWrongPreferredBacklightLevels) {
11296     RawLightInfo infoMono = {.id = 1,
11297                              .name = "mono_keyboard_backlight",
11298                              .maxBrightness = 255,
11299                              .flags = InputLightClass::BRIGHTNESS |
11300                                      InputLightClass::KEYBOARD_BACKLIGHT,
11301                              .path = ""};
11302     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
11303     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "keyboard.backlight.brightnessLevels",
11304                                             "0,100,200,300,400,500");
11305 
11306     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11307     std::list<NotifyArgs> unused =
11308             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
11309                                /*changes=*/{});
11310 
11311     InputDeviceInfo info;
11312     controller.populateDeviceInfo(&info);
11313     std::vector<InputDeviceLightInfo> lights = info.getLights();
11314     ASSERT_EQ(1U, lights.size());
11315     ASSERT_EQ(0U, lights[0].preferredBrightnessLevels.size());
11316 }
11317 
TEST_F(LightControllerTest,RGBLight)11318 TEST_F(LightControllerTest, RGBLight) {
11319     RawLightInfo infoRed = {.id = 1,
11320                             .name = "red",
11321                             .maxBrightness = 255,
11322                             .flags = InputLightClass::BRIGHTNESS | InputLightClass::RED,
11323                             .path = ""};
11324     RawLightInfo infoGreen = {.id = 2,
11325                               .name = "green",
11326                               .maxBrightness = 255,
11327                               .flags = InputLightClass::BRIGHTNESS | InputLightClass::GREEN,
11328                               .path = ""};
11329     RawLightInfo infoBlue = {.id = 3,
11330                              .name = "blue",
11331                              .maxBrightness = 255,
11332                              .flags = InputLightClass::BRIGHTNESS | InputLightClass::BLUE,
11333                              .path = ""};
11334     mFakeEventHub->addRawLightInfo(infoRed.id, std::move(infoRed));
11335     mFakeEventHub->addRawLightInfo(infoGreen.id, std::move(infoGreen));
11336     mFakeEventHub->addRawLightInfo(infoBlue.id, std::move(infoBlue));
11337 
11338     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11339     InputDeviceInfo info;
11340     controller.populateDeviceInfo(&info);
11341     std::vector<InputDeviceLightInfo> lights = info.getLights();
11342     ASSERT_EQ(1U, lights.size());
11343     ASSERT_EQ(InputDeviceLightType::INPUT, lights[0].type);
11344     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
11345     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
11346 
11347     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
11348     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_COLOR);
11349 }
11350 
TEST_F(LightControllerTest,CorrectRGBKeyboardBacklight)11351 TEST_F(LightControllerTest, CorrectRGBKeyboardBacklight) {
11352     RawLightInfo infoRed = {.id = 1,
11353                             .name = "red_keyboard_backlight",
11354                             .maxBrightness = 255,
11355                             .flags = InputLightClass::BRIGHTNESS | InputLightClass::RED |
11356                                     InputLightClass::KEYBOARD_BACKLIGHT,
11357                             .path = ""};
11358     RawLightInfo infoGreen = {.id = 2,
11359                               .name = "green_keyboard_backlight",
11360                               .maxBrightness = 255,
11361                               .flags = InputLightClass::BRIGHTNESS | InputLightClass::GREEN |
11362                                       InputLightClass::KEYBOARD_BACKLIGHT,
11363                               .path = ""};
11364     RawLightInfo infoBlue = {.id = 3,
11365                              .name = "blue_keyboard_backlight",
11366                              .maxBrightness = 255,
11367                              .flags = InputLightClass::BRIGHTNESS | InputLightClass::BLUE |
11368                                      InputLightClass::KEYBOARD_BACKLIGHT,
11369                              .path = ""};
11370     mFakeEventHub->addRawLightInfo(infoRed.id, std::move(infoRed));
11371     mFakeEventHub->addRawLightInfo(infoGreen.id, std::move(infoGreen));
11372     mFakeEventHub->addRawLightInfo(infoBlue.id, std::move(infoBlue));
11373 
11374     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11375     InputDeviceInfo info;
11376     controller.populateDeviceInfo(&info);
11377     std::vector<InputDeviceLightInfo> lights = info.getLights();
11378     ASSERT_EQ(1U, lights.size());
11379     ASSERT_EQ(InputDeviceLightType::KEYBOARD_BACKLIGHT, lights[0].type);
11380     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
11381     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
11382 
11383     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
11384     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_COLOR);
11385 }
11386 
TEST_F(LightControllerTest,IncorrectRGBKeyboardBacklight)11387 TEST_F(LightControllerTest, IncorrectRGBKeyboardBacklight) {
11388     RawLightInfo infoRed = {.id = 1,
11389                             .name = "red",
11390                             .maxBrightness = 255,
11391                             .flags = InputLightClass::BRIGHTNESS | InputLightClass::RED,
11392                             .path = ""};
11393     RawLightInfo infoGreen = {.id = 2,
11394                               .name = "green",
11395                               .maxBrightness = 255,
11396                               .flags = InputLightClass::BRIGHTNESS | InputLightClass::GREEN,
11397                               .path = ""};
11398     RawLightInfo infoBlue = {.id = 3,
11399                              .name = "blue",
11400                              .maxBrightness = 255,
11401                              .flags = InputLightClass::BRIGHTNESS | InputLightClass::BLUE,
11402                              .path = ""};
11403     RawLightInfo infoGlobal = {.id = 3,
11404                                .name = "global_keyboard_backlight",
11405                                .maxBrightness = 255,
11406                                .flags = InputLightClass::BRIGHTNESS | InputLightClass::GLOBAL |
11407                                        InputLightClass::KEYBOARD_BACKLIGHT,
11408                                .path = ""};
11409     mFakeEventHub->addRawLightInfo(infoRed.id, std::move(infoRed));
11410     mFakeEventHub->addRawLightInfo(infoGreen.id, std::move(infoGreen));
11411     mFakeEventHub->addRawLightInfo(infoBlue.id, std::move(infoBlue));
11412     mFakeEventHub->addRawLightInfo(infoBlue.id, std::move(infoGlobal));
11413 
11414     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11415     InputDeviceInfo info;
11416     controller.populateDeviceInfo(&info);
11417     std::vector<InputDeviceLightInfo> lights = info.getLights();
11418     ASSERT_EQ(1U, lights.size());
11419     ASSERT_EQ(InputDeviceLightType::INPUT, lights[0].type);
11420     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
11421     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
11422 
11423     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
11424     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_COLOR);
11425 }
11426 
TEST_F(LightControllerTest,MultiColorRGBLight)11427 TEST_F(LightControllerTest, MultiColorRGBLight) {
11428     RawLightInfo infoColor = {.id = 1,
11429                               .name = "multi_color",
11430                               .maxBrightness = 255,
11431                               .flags = InputLightClass::BRIGHTNESS |
11432                                       InputLightClass::MULTI_INTENSITY |
11433                                       InputLightClass::MULTI_INDEX,
11434                               .path = ""};
11435 
11436     mFakeEventHub->addRawLightInfo(infoColor.id, std::move(infoColor));
11437 
11438     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11439     InputDeviceInfo info;
11440     controller.populateDeviceInfo(&info);
11441     std::vector<InputDeviceLightInfo> lights = info.getLights();
11442     ASSERT_EQ(1U, lights.size());
11443     ASSERT_EQ(InputDeviceLightType::INPUT, lights[0].type);
11444     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
11445     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
11446 
11447     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
11448     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_COLOR);
11449 }
11450 
TEST_F(LightControllerTest,MultiColorRGBKeyboardBacklight)11451 TEST_F(LightControllerTest, MultiColorRGBKeyboardBacklight) {
11452     RawLightInfo infoColor = {.id = 1,
11453                               .name = "multi_color_keyboard_backlight",
11454                               .maxBrightness = 255,
11455                               .flags = InputLightClass::BRIGHTNESS |
11456                                       InputLightClass::MULTI_INTENSITY |
11457                                       InputLightClass::MULTI_INDEX |
11458                                       InputLightClass::KEYBOARD_BACKLIGHT,
11459                               .path = ""};
11460 
11461     mFakeEventHub->addRawLightInfo(infoColor.id, std::move(infoColor));
11462 
11463     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11464     InputDeviceInfo info;
11465     controller.populateDeviceInfo(&info);
11466     std::vector<InputDeviceLightInfo> lights = info.getLights();
11467     ASSERT_EQ(1U, lights.size());
11468     ASSERT_EQ(InputDeviceLightType::KEYBOARD_BACKLIGHT, lights[0].type);
11469     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
11470     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
11471 
11472     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
11473     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_COLOR);
11474 }
11475 
TEST_F(LightControllerTest,PlayerIdLight)11476 TEST_F(LightControllerTest, PlayerIdLight) {
11477     RawLightInfo info1 = {.id = 1,
11478                           .name = "player1",
11479                           .maxBrightness = 255,
11480                           .flags = InputLightClass::BRIGHTNESS,
11481                           .path = ""};
11482     RawLightInfo info2 = {.id = 2,
11483                           .name = "player2",
11484                           .maxBrightness = 255,
11485                           .flags = InputLightClass::BRIGHTNESS,
11486                           .path = ""};
11487     RawLightInfo info3 = {.id = 3,
11488                           .name = "player3",
11489                           .maxBrightness = 255,
11490                           .flags = InputLightClass::BRIGHTNESS,
11491                           .path = ""};
11492     RawLightInfo info4 = {.id = 4,
11493                           .name = "player4",
11494                           .maxBrightness = 255,
11495                           .flags = InputLightClass::BRIGHTNESS,
11496                           .path = ""};
11497     mFakeEventHub->addRawLightInfo(info1.id, std::move(info1));
11498     mFakeEventHub->addRawLightInfo(info2.id, std::move(info2));
11499     mFakeEventHub->addRawLightInfo(info3.id, std::move(info3));
11500     mFakeEventHub->addRawLightInfo(info4.id, std::move(info4));
11501 
11502     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
11503     InputDeviceInfo info;
11504     controller.populateDeviceInfo(&info);
11505     std::vector<InputDeviceLightInfo> lights = info.getLights();
11506     ASSERT_EQ(1U, lights.size());
11507     ASSERT_EQ(InputDeviceLightType::PLAYER_ID, lights[0].type);
11508     ASSERT_FALSE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
11509     ASSERT_FALSE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
11510 
11511     ASSERT_FALSE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
11512     ASSERT_TRUE(controller.setLightPlayerId(lights[0].id, LIGHT_PLAYER_ID));
11513     ASSERT_EQ(controller.getLightPlayerId(lights[0].id).value_or(-1), LIGHT_PLAYER_ID);
11514 }
11515 
11516 } // namespace android
11517