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 <NotifyArgsBuilders.h>
31 #include <PeripheralController.h>
32 #include <SensorInputMapper.h>
33 #include <SingleTouchInputMapper.h>
34 #include <SwitchInputMapper.h>
35 #include <TestEventMatchers.h>
36 #include <TestInputListener.h>
37 #include <TouchInputMapper.h>
38 #include <UinputDevice.h>
39 #include <VibratorInputMapper.h>
40 #include <android-base/thread_annotations.h>
41 #include <com_android_input_flags.h>
42 #include <ftl/enum.h>
43 #include <gtest/gtest.h>
44 #include <ui/Rotation.h>
45 
46 #include <thread>
47 #include "FakeEventHub.h"
48 #include "FakeInputReaderPolicy.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 using std::chrono_literals::operator""s;
61 
62 // Arbitrary display properties.
63 static constexpr ui::LogicalDisplayId DISPLAY_ID = ui::LogicalDisplayId::DEFAULT;
64 static const std::string DISPLAY_UNIQUE_ID = "local:1";
65 static constexpr ui::LogicalDisplayId SECONDARY_DISPLAY_ID =
66         ui::LogicalDisplayId{DISPLAY_ID.val() + 1};
67 static constexpr int32_t DISPLAY_WIDTH = 480;
68 static constexpr int32_t DISPLAY_HEIGHT = 800;
69 static constexpr ui::LogicalDisplayId VIRTUAL_DISPLAY_ID = ui::LogicalDisplayId{1};
70 static constexpr int32_t VIRTUAL_DISPLAY_WIDTH = 400;
71 static constexpr int32_t VIRTUAL_DISPLAY_HEIGHT = 500;
72 static const char* VIRTUAL_DISPLAY_UNIQUE_ID = "virtual:1";
73 static constexpr std::optional<uint8_t> NO_PORT = std::nullopt; // no physical port is specified
74 
75 static constexpr int32_t FIRST_SLOT = 0;
76 static constexpr int32_t SECOND_SLOT = 1;
77 static constexpr int32_t THIRD_SLOT = 2;
78 static constexpr int32_t INVALID_TRACKING_ID = -1;
79 static constexpr int32_t FIRST_TRACKING_ID = 0;
80 static constexpr int32_t SECOND_TRACKING_ID = 1;
81 static constexpr int32_t THIRD_TRACKING_ID = 2;
82 static constexpr int32_t LIGHT_BRIGHTNESS = 0x55000000;
83 static constexpr int32_t LIGHT_COLOR = 0x7F448866;
84 static constexpr int32_t LIGHT_PLAYER_ID = 2;
85 
86 static constexpr int32_t ACTION_POINTER_0_DOWN =
87         AMOTION_EVENT_ACTION_POINTER_DOWN | (0 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
88 static constexpr int32_t ACTION_POINTER_0_UP =
89         AMOTION_EVENT_ACTION_POINTER_UP | (0 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
90 static constexpr int32_t ACTION_POINTER_1_DOWN =
91         AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
92 static constexpr int32_t ACTION_POINTER_1_UP =
93         AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
94 
95 static constexpr uint32_t STYLUS_FUSION_SOURCE =
96         AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_BLUETOOTH_STYLUS;
97 
98 // Minimum timestamp separation between subsequent input events from a Bluetooth device.
99 static constexpr nsecs_t MIN_BLUETOOTH_TIMESTAMP_DELTA = ms2ns(4);
100 
101 namespace input_flags = com::android::input::flags;
102 
103 template<typename T>
min(T a,T b)104 static inline T min(T a, T b) {
105     return a < b ? a : b;
106 }
107 
avg(float x,float y)108 static inline float avg(float x, float y) {
109     return (x + y) / 2;
110 }
111 
112 // Mapping for light color name and the light color
113 const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
114                                                                   {"green", LightColor::GREEN},
115                                                                   {"blue", LightColor::BLUE}};
116 
getInverseRotation(ui::Rotation orientation)117 static ui::Rotation getInverseRotation(ui::Rotation orientation) {
118     switch (orientation) {
119         case ui::ROTATION_90:
120             return ui::ROTATION_270;
121         case ui::ROTATION_270:
122             return ui::ROTATION_90;
123         default:
124             return orientation;
125     }
126 }
127 
assertAxisResolution(MultiTouchInputMapper & mapper,int axis,float resolution)128 static void assertAxisResolution(MultiTouchInputMapper& mapper, int axis, float resolution) {
129     InputDeviceInfo info;
130     mapper.populateDeviceInfo(info);
131 
132     const InputDeviceInfo::MotionRange* motionRange =
133             info.getMotionRange(axis, AINPUT_SOURCE_TOUCHSCREEN);
134     ASSERT_NEAR(motionRange->resolution, resolution, EPSILON);
135 }
136 
assertAxisNotPresent(MultiTouchInputMapper & mapper,int axis)137 static void assertAxisNotPresent(MultiTouchInputMapper& mapper, int axis) {
138     InputDeviceInfo info;
139     mapper.populateDeviceInfo(info);
140 
141     const InputDeviceInfo::MotionRange* motionRange =
142             info.getMotionRange(axis, AINPUT_SOURCE_TOUCHSCREEN);
143     ASSERT_EQ(nullptr, motionRange);
144 }
145 
dumpReader(InputReader & reader)146 [[maybe_unused]] static void dumpReader(InputReader& reader) {
147     std::string dump;
148     reader.dump(dump);
149     std::istringstream iss(dump);
150     for (std::string line; std::getline(iss, line);) {
151         ALOGE("%s", line.c_str());
152         std::this_thread::sleep_for(1ms);
153     }
154 }
155 
156 // --- FakeInputMapper ---
157 
158 class FakeInputMapper : public InputMapper {
159     uint32_t mSources;
160     int32_t mKeyboardType;
161     int32_t mMetaState;
162     KeyedVector<int32_t, int32_t> mKeyCodeStates;
163     KeyedVector<int32_t, int32_t> mScanCodeStates;
164     KeyedVector<int32_t, int32_t> mSwitchStates;
165     // fake mapping which would normally come from keyCharacterMap
166     std::unordered_map<int32_t, int32_t> mKeyCodeMapping;
167     std::vector<int32_t> mSupportedKeyCodes;
168     std::list<NotifyArgs> mProcessResult;
169 
170     std::mutex mLock;
171     std::condition_variable mStateChangedCondition;
172     bool mConfigureWasCalled GUARDED_BY(mLock);
173     bool mResetWasCalled GUARDED_BY(mLock);
174     bool mProcessWasCalled GUARDED_BY(mLock);
175     RawEvent mLastEvent GUARDED_BY(mLock);
176 
177     std::optional<DisplayViewport> mViewport;
178 public:
FakeInputMapper(InputDeviceContext & deviceContext,const InputReaderConfiguration & readerConfig,uint32_t sources)179     FakeInputMapper(InputDeviceContext& deviceContext, const InputReaderConfiguration& readerConfig,
180                     uint32_t sources)
181           : InputMapper(deviceContext, readerConfig),
182             mSources(sources),
183             mKeyboardType(AINPUT_KEYBOARD_TYPE_NONE),
184             mMetaState(0),
185             mConfigureWasCalled(false),
186             mResetWasCalled(false),
187             mProcessWasCalled(false) {}
188 
~FakeInputMapper()189     virtual ~FakeInputMapper() {}
190 
setKeyboardType(int32_t keyboardType)191     void setKeyboardType(int32_t keyboardType) {
192         mKeyboardType = keyboardType;
193     }
194 
setMetaState(int32_t metaState)195     void setMetaState(int32_t metaState) {
196         mMetaState = metaState;
197     }
198 
199     // Sets the return value for the `process` call.
setProcessResult(std::list<NotifyArgs> notifyArgs)200     void setProcessResult(std::list<NotifyArgs> notifyArgs) {
201         mProcessResult.clear();
202         for (auto notifyArg : notifyArgs) {
203             mProcessResult.push_back(notifyArg);
204         }
205     }
206 
assertConfigureWasCalled()207     void assertConfigureWasCalled() {
208         std::unique_lock<std::mutex> lock(mLock);
209         base::ScopedLockAssertion assumeLocked(mLock);
210         const bool configureCalled =
211                 mStateChangedCondition.wait_for(lock, WAIT_TIMEOUT, [this]() REQUIRES(mLock) {
212                     return mConfigureWasCalled;
213                 });
214         if (!configureCalled) {
215             FAIL() << "Expected configure() to have been called.";
216         }
217         mConfigureWasCalled = false;
218     }
219 
assertResetWasCalled()220     void assertResetWasCalled() {
221         std::unique_lock<std::mutex> lock(mLock);
222         base::ScopedLockAssertion assumeLocked(mLock);
223         const bool resetCalled =
224                 mStateChangedCondition.wait_for(lock, WAIT_TIMEOUT, [this]() REQUIRES(mLock) {
225                     return mResetWasCalled;
226                 });
227         if (!resetCalled) {
228             FAIL() << "Expected reset() to have been called.";
229         }
230         mResetWasCalled = false;
231     }
232 
assertResetWasNotCalled()233     void assertResetWasNotCalled() {
234         std::scoped_lock lock(mLock);
235         ASSERT_FALSE(mResetWasCalled) << "Expected reset to not have been called.";
236     }
237 
assertProcessWasCalled(RawEvent * outLastEvent=nullptr)238     void assertProcessWasCalled(RawEvent* outLastEvent = nullptr) {
239         std::unique_lock<std::mutex> lock(mLock);
240         base::ScopedLockAssertion assumeLocked(mLock);
241         const bool processCalled =
242                 mStateChangedCondition.wait_for(lock, WAIT_TIMEOUT, [this]() REQUIRES(mLock) {
243                     return mProcessWasCalled;
244                 });
245         if (!processCalled) {
246             FAIL() << "Expected process() to have been called.";
247         }
248         if (outLastEvent) {
249             *outLastEvent = mLastEvent;
250         }
251         mProcessWasCalled = false;
252     }
253 
assertProcessWasNotCalled()254     void assertProcessWasNotCalled() {
255         std::scoped_lock lock(mLock);
256         ASSERT_FALSE(mProcessWasCalled) << "Expected process to not have been called.";
257     }
258 
setKeyCodeState(int32_t keyCode,int32_t state)259     void setKeyCodeState(int32_t keyCode, int32_t state) {
260         mKeyCodeStates.replaceValueFor(keyCode, state);
261     }
262 
setScanCodeState(int32_t scanCode,int32_t state)263     void setScanCodeState(int32_t scanCode, int32_t state) {
264         mScanCodeStates.replaceValueFor(scanCode, state);
265     }
266 
setSwitchState(int32_t switchCode,int32_t state)267     void setSwitchState(int32_t switchCode, int32_t state) {
268         mSwitchStates.replaceValueFor(switchCode, state);
269     }
270 
addSupportedKeyCode(int32_t keyCode)271     void addSupportedKeyCode(int32_t keyCode) {
272         mSupportedKeyCodes.push_back(keyCode);
273     }
274 
addKeyCodeMapping(int32_t fromKeyCode,int32_t toKeyCode)275     void addKeyCodeMapping(int32_t fromKeyCode, int32_t toKeyCode) {
276         mKeyCodeMapping.insert_or_assign(fromKeyCode, toKeyCode);
277     }
278 
279 private:
getSources() const280     uint32_t getSources() const override { return mSources; }
281 
populateDeviceInfo(InputDeviceInfo & deviceInfo)282     void populateDeviceInfo(InputDeviceInfo& deviceInfo) override {
283         InputMapper::populateDeviceInfo(deviceInfo);
284 
285         if (mKeyboardType != AINPUT_KEYBOARD_TYPE_NONE) {
286             deviceInfo.setKeyboardType(mKeyboardType);
287         }
288     }
289 
reconfigure(nsecs_t,const InputReaderConfiguration & config,ConfigurationChanges changes)290     std::list<NotifyArgs> reconfigure(nsecs_t, const InputReaderConfiguration& config,
291                                       ConfigurationChanges changes) override {
292         std::scoped_lock<std::mutex> lock(mLock);
293         mConfigureWasCalled = true;
294 
295         // Find the associated viewport if exist.
296         const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
297         if (displayPort && changes.test(InputReaderConfiguration::Change::DISPLAY_INFO)) {
298             mViewport = config.getDisplayViewportByPort(*displayPort);
299         }
300 
301         mStateChangedCondition.notify_all();
302         return {};
303     }
304 
reset(nsecs_t)305     std::list<NotifyArgs> reset(nsecs_t) override {
306         std::scoped_lock<std::mutex> lock(mLock);
307         mResetWasCalled = true;
308         mStateChangedCondition.notify_all();
309         return {};
310     }
311 
process(const RawEvent & rawEvent)312     std::list<NotifyArgs> process(const RawEvent& rawEvent) override {
313         std::scoped_lock<std::mutex> lock(mLock);
314         mLastEvent = rawEvent;
315         mProcessWasCalled = true;
316         mStateChangedCondition.notify_all();
317         return mProcessResult;
318     }
319 
getKeyCodeState(uint32_t,int32_t keyCode)320     int32_t getKeyCodeState(uint32_t, int32_t keyCode) override {
321         ssize_t index = mKeyCodeStates.indexOfKey(keyCode);
322         return index >= 0 ? mKeyCodeStates.valueAt(index) : AKEY_STATE_UNKNOWN;
323     }
324 
getKeyCodeForKeyLocation(int32_t locationKeyCode) const325     int32_t getKeyCodeForKeyLocation(int32_t locationKeyCode) const override {
326         auto it = mKeyCodeMapping.find(locationKeyCode);
327         return it != mKeyCodeMapping.end() ? it->second : locationKeyCode;
328     }
329 
getScanCodeState(uint32_t,int32_t scanCode)330     int32_t getScanCodeState(uint32_t, int32_t scanCode) override {
331         ssize_t index = mScanCodeStates.indexOfKey(scanCode);
332         return index >= 0 ? mScanCodeStates.valueAt(index) : AKEY_STATE_UNKNOWN;
333     }
334 
getSwitchState(uint32_t,int32_t switchCode)335     int32_t getSwitchState(uint32_t, int32_t switchCode) override {
336         ssize_t index = mSwitchStates.indexOfKey(switchCode);
337         return index >= 0 ? mSwitchStates.valueAt(index) : AKEY_STATE_UNKNOWN;
338     }
339 
340     // Return true if the device has non-empty key layout.
markSupportedKeyCodes(uint32_t,const std::vector<int32_t> & keyCodes,uint8_t * outFlags)341     bool markSupportedKeyCodes(uint32_t, const std::vector<int32_t>& keyCodes,
342                                uint8_t* outFlags) override {
343         for (size_t i = 0; i < keyCodes.size(); i++) {
344             for (size_t j = 0; j < mSupportedKeyCodes.size(); j++) {
345                 if (keyCodes[i] == mSupportedKeyCodes[j]) {
346                     outFlags[i] = 1;
347                 }
348             }
349         }
350         bool result = mSupportedKeyCodes.size() > 0;
351         return result;
352     }
353 
getMetaState()354     virtual int32_t getMetaState() {
355         return mMetaState;
356     }
357 
fadePointer()358     virtual void fadePointer() {
359     }
360 
getAssociatedDisplay()361     virtual std::optional<ui::LogicalDisplayId> getAssociatedDisplay() {
362         if (mViewport) {
363             return std::make_optional(mViewport->displayId);
364         }
365         return std::nullopt;
366     }
367 };
368 
369 // --- InputReaderPolicyTest ---
370 class InputReaderPolicyTest : public testing::Test {
371 protected:
372     sp<FakeInputReaderPolicy> mFakePolicy;
373 
SetUp()374     void SetUp() override { mFakePolicy = sp<FakeInputReaderPolicy>::make(); }
TearDown()375     void TearDown() override { mFakePolicy.clear(); }
376 };
377 
378 /**
379  * Check that empty set of viewports is an acceptable configuration.
380  * Also try to get internal viewport two different ways - by type and by uniqueId.
381  *
382  * There will be confusion if two viewports with empty uniqueId and identical type are present.
383  * Such configuration is not currently allowed.
384  */
TEST_F(InputReaderPolicyTest,Viewports_GetCleared)385 TEST_F(InputReaderPolicyTest, Viewports_GetCleared) {
386     static const std::string uniqueId = "local:0";
387 
388     // We didn't add any viewports yet, so there shouldn't be any.
389     std::optional<DisplayViewport> internalViewport =
390             mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
391     ASSERT_FALSE(internalViewport);
392 
393     // Add an internal viewport, then clear it
394     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
395                                     /*isActive=*/true, uniqueId, NO_PORT, ViewportType::INTERNAL);
396 
397     // Check matching by uniqueId
398     internalViewport = mFakePolicy->getDisplayViewportByUniqueId(uniqueId);
399     ASSERT_TRUE(internalViewport);
400     ASSERT_EQ(ViewportType::INTERNAL, internalViewport->type);
401 
402     // Check matching by viewport type
403     internalViewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
404     ASSERT_TRUE(internalViewport);
405     ASSERT_EQ(uniqueId, internalViewport->uniqueId);
406 
407     mFakePolicy->clearViewports();
408     // Make sure nothing is found after clear
409     internalViewport = mFakePolicy->getDisplayViewportByUniqueId(uniqueId);
410     ASSERT_FALSE(internalViewport);
411     internalViewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
412     ASSERT_FALSE(internalViewport);
413 }
414 
TEST_F(InputReaderPolicyTest,Viewports_GetByType)415 TEST_F(InputReaderPolicyTest, Viewports_GetByType) {
416     const std::string internalUniqueId = "local:0";
417     const std::string externalUniqueId = "local:1";
418     const std::string virtualUniqueId1 = "virtual:2";
419     const std::string virtualUniqueId2 = "virtual:3";
420     constexpr ui::LogicalDisplayId virtualDisplayId1 = ui::LogicalDisplayId{2};
421     constexpr ui::LogicalDisplayId virtualDisplayId2 = ui::LogicalDisplayId{3};
422 
423     // Add an internal viewport
424     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
425                                     /*isActive=*/true, internalUniqueId, NO_PORT,
426                                     ViewportType::INTERNAL);
427     // Add an external viewport
428     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
429                                     /*isActive=*/true, externalUniqueId, NO_PORT,
430                                     ViewportType::EXTERNAL);
431     // Add an virtual viewport
432     mFakePolicy->addDisplayViewport(virtualDisplayId1, DISPLAY_WIDTH, DISPLAY_HEIGHT,
433                                     ui::ROTATION_0, /*isActive=*/true, virtualUniqueId1, NO_PORT,
434                                     ViewportType::VIRTUAL);
435     // Add another virtual viewport
436     mFakePolicy->addDisplayViewport(virtualDisplayId2, DISPLAY_WIDTH, DISPLAY_HEIGHT,
437                                     ui::ROTATION_0, /*isActive=*/true, virtualUniqueId2, NO_PORT,
438                                     ViewportType::VIRTUAL);
439 
440     // Check matching by type for internal
441     std::optional<DisplayViewport> internalViewport =
442             mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
443     ASSERT_TRUE(internalViewport);
444     ASSERT_EQ(internalUniqueId, internalViewport->uniqueId);
445 
446     // Check matching by type for external
447     std::optional<DisplayViewport> externalViewport =
448             mFakePolicy->getDisplayViewportByType(ViewportType::EXTERNAL);
449     ASSERT_TRUE(externalViewport);
450     ASSERT_EQ(externalUniqueId, externalViewport->uniqueId);
451 
452     // Check matching by uniqueId for virtual viewport #1
453     std::optional<DisplayViewport> virtualViewport1 =
454             mFakePolicy->getDisplayViewportByUniqueId(virtualUniqueId1);
455     ASSERT_TRUE(virtualViewport1);
456     ASSERT_EQ(ViewportType::VIRTUAL, virtualViewport1->type);
457     ASSERT_EQ(virtualUniqueId1, virtualViewport1->uniqueId);
458     ASSERT_EQ(virtualDisplayId1, virtualViewport1->displayId);
459 
460     // Check matching by uniqueId for virtual viewport #2
461     std::optional<DisplayViewport> virtualViewport2 =
462             mFakePolicy->getDisplayViewportByUniqueId(virtualUniqueId2);
463     ASSERT_TRUE(virtualViewport2);
464     ASSERT_EQ(ViewportType::VIRTUAL, virtualViewport2->type);
465     ASSERT_EQ(virtualUniqueId2, virtualViewport2->uniqueId);
466     ASSERT_EQ(virtualDisplayId2, virtualViewport2->displayId);
467 }
468 
469 
470 /**
471  * We can have 2 viewports of the same kind. We can distinguish them by uniqueId, and confirm
472  * that lookup works by checking display id.
473  * Check that 2 viewports of each kind is possible, for all existing viewport types.
474  */
TEST_F(InputReaderPolicyTest,Viewports_TwoOfSameType)475 TEST_F(InputReaderPolicyTest, Viewports_TwoOfSameType) {
476     const std::string uniqueId1 = "uniqueId1";
477     const std::string uniqueId2 = "uniqueId2";
478     constexpr ui::LogicalDisplayId displayId1 = ui::LogicalDisplayId{2};
479     constexpr ui::LogicalDisplayId displayId2 = ui::LogicalDisplayId{3};
480 
481     std::vector<ViewportType> types = {ViewportType::INTERNAL, ViewportType::EXTERNAL,
482                                        ViewportType::VIRTUAL};
483     for (const ViewportType& type : types) {
484         mFakePolicy->clearViewports();
485         // Add a viewport
486         mFakePolicy->addDisplayViewport(displayId1, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
487                                         /*isActive=*/true, uniqueId1, NO_PORT, type);
488         // Add another viewport
489         mFakePolicy->addDisplayViewport(displayId2, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
490                                         /*isActive=*/true, uniqueId2, NO_PORT, type);
491 
492         // Check that correct display viewport was returned by comparing the display IDs.
493         std::optional<DisplayViewport> viewport1 =
494                 mFakePolicy->getDisplayViewportByUniqueId(uniqueId1);
495         ASSERT_TRUE(viewport1);
496         ASSERT_EQ(displayId1, viewport1->displayId);
497         ASSERT_EQ(type, viewport1->type);
498 
499         std::optional<DisplayViewport> viewport2 =
500                 mFakePolicy->getDisplayViewportByUniqueId(uniqueId2);
501         ASSERT_TRUE(viewport2);
502         ASSERT_EQ(displayId2, viewport2->displayId);
503         ASSERT_EQ(type, viewport2->type);
504 
505         // When there are multiple viewports of the same kind, and uniqueId is not specified
506         // in the call to getDisplayViewport, then that situation is not supported.
507         // The viewports can be stored in any order, so we cannot rely on the order, since that
508         // is just implementation detail.
509         // However, we can check that it still returns *a* viewport, we just cannot assert
510         // which one specifically is returned.
511         std::optional<DisplayViewport> someViewport = mFakePolicy->getDisplayViewportByType(type);
512         ASSERT_TRUE(someViewport);
513     }
514 }
515 
516 /**
517  * When we have multiple internal displays make sure we always return the default display when
518  * querying by type.
519  */
TEST_F(InputReaderPolicyTest,Viewports_ByTypeReturnsDefaultForInternal)520 TEST_F(InputReaderPolicyTest, Viewports_ByTypeReturnsDefaultForInternal) {
521     const std::string uniqueId1 = "uniqueId1";
522     const std::string uniqueId2 = "uniqueId2";
523     constexpr ui::LogicalDisplayId nonDefaultDisplayId = ui::LogicalDisplayId{2};
524     ASSERT_NE(nonDefaultDisplayId, ui::LogicalDisplayId::DEFAULT)
525             << "Test display ID should not be ui::LogicalDisplayId::DEFAULT ";
526 
527     // Add the default display first and ensure it gets returned.
528     mFakePolicy->clearViewports();
529     mFakePolicy->addDisplayViewport(ui::LogicalDisplayId::DEFAULT, DISPLAY_WIDTH, DISPLAY_HEIGHT,
530                                     ui::ROTATION_0, /*isActive=*/true, uniqueId1, NO_PORT,
531                                     ViewportType::INTERNAL);
532     mFakePolicy->addDisplayViewport(nonDefaultDisplayId, DISPLAY_WIDTH, DISPLAY_HEIGHT,
533                                     ui::ROTATION_0, /*isActive=*/true, uniqueId2, NO_PORT,
534                                     ViewportType::INTERNAL);
535 
536     std::optional<DisplayViewport> viewport =
537             mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
538     ASSERT_TRUE(viewport);
539     ASSERT_EQ(ui::LogicalDisplayId::DEFAULT, viewport->displayId);
540     ASSERT_EQ(ViewportType::INTERNAL, viewport->type);
541 
542     // Add the default display second to make sure order doesn't matter.
543     mFakePolicy->clearViewports();
544     mFakePolicy->addDisplayViewport(nonDefaultDisplayId, DISPLAY_WIDTH, DISPLAY_HEIGHT,
545                                     ui::ROTATION_0, /*isActive=*/true, uniqueId2, NO_PORT,
546                                     ViewportType::INTERNAL);
547     mFakePolicy->addDisplayViewport(ui::LogicalDisplayId::DEFAULT, DISPLAY_WIDTH, DISPLAY_HEIGHT,
548                                     ui::ROTATION_0, /*isActive=*/true, uniqueId1, NO_PORT,
549                                     ViewportType::INTERNAL);
550 
551     viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
552     ASSERT_TRUE(viewport);
553     ASSERT_EQ(ui::LogicalDisplayId::DEFAULT, viewport->displayId);
554     ASSERT_EQ(ViewportType::INTERNAL, viewport->type);
555 }
556 
557 /**
558  * Check getDisplayViewportByPort
559  */
TEST_F(InputReaderPolicyTest,Viewports_GetByPort)560 TEST_F(InputReaderPolicyTest, Viewports_GetByPort) {
561     constexpr ViewportType type = ViewportType::EXTERNAL;
562     const std::string uniqueId1 = "uniqueId1";
563     const std::string uniqueId2 = "uniqueId2";
564     constexpr ui::LogicalDisplayId displayId1 = ui::LogicalDisplayId{1};
565     constexpr ui::LogicalDisplayId displayId2 = ui::LogicalDisplayId{2};
566     const uint8_t hdmi1 = 0;
567     const uint8_t hdmi2 = 1;
568     const uint8_t hdmi3 = 2;
569 
570     mFakePolicy->clearViewports();
571     // Add a viewport that's associated with some display port that's not of interest.
572     mFakePolicy->addDisplayViewport(displayId1, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
573                                     /*isActive=*/true, uniqueId1, hdmi3, type);
574     // Add another viewport, connected to HDMI1 port
575     mFakePolicy->addDisplayViewport(displayId2, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
576                                     /*isActive=*/true, uniqueId2, hdmi1, type);
577 
578     // Check that correct display viewport was returned by comparing the display ports.
579     std::optional<DisplayViewport> hdmi1Viewport = mFakePolicy->getDisplayViewportByPort(hdmi1);
580     ASSERT_TRUE(hdmi1Viewport);
581     ASSERT_EQ(displayId2, hdmi1Viewport->displayId);
582     ASSERT_EQ(uniqueId2, hdmi1Viewport->uniqueId);
583 
584     // Check that we can still get the same viewport using the uniqueId
585     hdmi1Viewport = mFakePolicy->getDisplayViewportByUniqueId(uniqueId2);
586     ASSERT_TRUE(hdmi1Viewport);
587     ASSERT_EQ(displayId2, hdmi1Viewport->displayId);
588     ASSERT_EQ(uniqueId2, hdmi1Viewport->uniqueId);
589     ASSERT_EQ(type, hdmi1Viewport->type);
590 
591     // Check that we cannot find a port with "HDMI2", because we never added one
592     std::optional<DisplayViewport> hdmi2Viewport = mFakePolicy->getDisplayViewportByPort(hdmi2);
593     ASSERT_FALSE(hdmi2Viewport);
594 }
595 
596 // --- InputReaderTest ---
597 
598 class InputReaderTest : public testing::Test {
599 protected:
600     std::unique_ptr<TestInputListener> mFakeListener;
601     sp<FakeInputReaderPolicy> mFakePolicy;
602     std::shared_ptr<FakeEventHub> mFakeEventHub;
603     std::unique_ptr<InstrumentedInputReader> mReader;
604 
SetUp()605     void SetUp() override {
606         mFakeEventHub = std::make_unique<FakeEventHub>();
607         mFakePolicy = sp<FakeInputReaderPolicy>::make();
608         mFakeListener = std::make_unique<TestInputListener>();
609 
610         mReader = std::make_unique<InstrumentedInputReader>(mFakeEventHub, mFakePolicy,
611                                                             *mFakeListener);
612     }
613 
TearDown()614     void TearDown() override {
615         mFakeListener.reset();
616         mFakePolicy.clear();
617     }
618 
addDevice(int32_t eventHubId,const std::string & name,ftl::Flags<InputDeviceClass> classes,const PropertyMap * configuration)619     void addDevice(int32_t eventHubId, const std::string& name,
620                    ftl::Flags<InputDeviceClass> classes, const PropertyMap* configuration) {
621         mFakeEventHub->addDevice(eventHubId, name, classes);
622 
623         if (configuration) {
624             mFakeEventHub->addConfigurationMap(eventHubId, configuration);
625         }
626         mFakeEventHub->finishDeviceScan();
627         mReader->loopOnce();
628         mReader->loopOnce();
629         ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
630         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyInputDevicesChangedWasCalled());
631         ASSERT_NO_FATAL_FAILURE(mFakeEventHub->assertQueueIsEmpty());
632     }
633 
disableDevice(int32_t deviceId)634     void disableDevice(int32_t deviceId) {
635         mFakePolicy->addDisabledDevice(deviceId);
636         mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::ENABLED_STATE);
637     }
638 
enableDevice(int32_t deviceId)639     void enableDevice(int32_t deviceId) {
640         mFakePolicy->removeDisabledDevice(deviceId);
641         mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::ENABLED_STATE);
642     }
643 
addDeviceWithFakeInputMapper(int32_t deviceId,int32_t eventHubId,const std::string & name,ftl::Flags<InputDeviceClass> classes,uint32_t sources,const PropertyMap * configuration)644     FakeInputMapper& addDeviceWithFakeInputMapper(int32_t deviceId, int32_t eventHubId,
645                                                   const std::string& name,
646                                                   ftl::Flags<InputDeviceClass> classes,
647                                                   uint32_t sources,
648                                                   const PropertyMap* configuration) {
649         std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, name);
650         FakeInputMapper& mapper =
651                 device->addMapper<FakeInputMapper>(eventHubId,
652                                                    mFakePolicy->getReaderConfiguration(), sources);
653         mReader->pushNextDevice(device);
654         addDevice(eventHubId, name, classes, configuration);
655         return mapper;
656     }
657 };
658 
TEST_F(InputReaderTest,PolicyGetInputDevices)659 TEST_F(InputReaderTest, PolicyGetInputDevices) {
660     ASSERT_NO_FATAL_FAILURE(addDevice(1, "keyboard", InputDeviceClass::KEYBOARD, nullptr));
661     ASSERT_NO_FATAL_FAILURE(addDevice(2, "ignored", ftl::Flags<InputDeviceClass>(0),
662                                       nullptr)); // no classes so device will be ignored
663 
664     // Should also have received a notification describing the new input devices.
665     const std::vector<InputDeviceInfo>& inputDevices = mFakePolicy->getInputDevices();
666     ASSERT_EQ(1U, inputDevices.size());
667     ASSERT_EQ(END_RESERVED_ID + 1, inputDevices[0].getId());
668     ASSERT_STREQ("keyboard", inputDevices[0].getIdentifier().name.c_str());
669     ASSERT_EQ(AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC, inputDevices[0].getKeyboardType());
670     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, inputDevices[0].getSources());
671     ASSERT_EQ(0U, inputDevices[0].getMotionRanges().size());
672 }
673 
TEST_F(InputReaderTest,InputDeviceRecreatedOnSysfsNodeChanged)674 TEST_F(InputReaderTest, InputDeviceRecreatedOnSysfsNodeChanged) {
675     ASSERT_NO_FATAL_FAILURE(addDevice(1, "keyboard", InputDeviceClass::KEYBOARD, nullptr));
676     mFakeEventHub->setSysfsRootPath(1, "xyz");
677 
678     // Should also have received a notification describing the new input device.
679     ASSERT_EQ(1U, mFakePolicy->getInputDevices().size());
680     InputDeviceInfo inputDevice = mFakePolicy->getInputDevices()[0];
681     ASSERT_EQ(0U, inputDevice.getLights().size());
682 
683     RawLightInfo infoMonolight = {.id = 123,
684                                   .name = "mono_keyboard_backlight",
685                                   .maxBrightness = 255,
686                                   .flags = InputLightClass::BRIGHTNESS,
687                                   .path = ""};
688     mFakeEventHub->addRawLightInfo(/*rawId=*/123, std::move(infoMonolight));
689     mReader->sysfsNodeChanged("xyz");
690     mReader->loopOnce();
691 
692     // Should also have received a notification describing the new recreated input device.
693     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
694     inputDevice = mFakePolicy->getInputDevices()[0];
695     ASSERT_EQ(1U, inputDevice.getLights().size());
696 }
697 
TEST_F(InputReaderTest,GetMergedInputDevices)698 TEST_F(InputReaderTest, GetMergedInputDevices) {
699     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
700     constexpr int32_t eventHubIds[2] = {END_RESERVED_ID, END_RESERVED_ID + 1};
701     // Add two subdevices to device
702     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
703     // Must add at least one mapper or the device will be ignored!
704     device->addMapper<FakeInputMapper>(eventHubIds[0], mFakePolicy->getReaderConfiguration(),
705                                        AINPUT_SOURCE_KEYBOARD);
706     device->addMapper<FakeInputMapper>(eventHubIds[1], mFakePolicy->getReaderConfiguration(),
707                                        AINPUT_SOURCE_KEYBOARD);
708 
709     // Push same device instance for next device to be added, so they'll have same identifier.
710     mReader->pushNextDevice(device);
711     mReader->pushNextDevice(device);
712     ASSERT_NO_FATAL_FAILURE(
713             addDevice(eventHubIds[0], "fake1", InputDeviceClass::KEYBOARD, nullptr));
714     ASSERT_NO_FATAL_FAILURE(
715             addDevice(eventHubIds[1], "fake2", InputDeviceClass::KEYBOARD, nullptr));
716 
717     // Two devices will be merged to one input device as they have same identifier
718     ASSERT_EQ(1U, mFakePolicy->getInputDevices().size());
719 }
720 
TEST_F(InputReaderTest,GetMergedInputDevicesEnabled)721 TEST_F(InputReaderTest, GetMergedInputDevicesEnabled) {
722     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
723     constexpr int32_t eventHubIds[2] = {END_RESERVED_ID, END_RESERVED_ID + 1};
724     // Add two subdevices to device
725     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
726     // Must add at least one mapper or the device will be ignored!
727     device->addMapper<FakeInputMapper>(eventHubIds[0], mFakePolicy->getReaderConfiguration(),
728                                        AINPUT_SOURCE_KEYBOARD);
729     device->addMapper<FakeInputMapper>(eventHubIds[1], mFakePolicy->getReaderConfiguration(),
730                                        AINPUT_SOURCE_KEYBOARD);
731 
732     // Push same device instance for next device to be added, so they'll have same identifier.
733     mReader->pushNextDevice(device);
734     mReader->pushNextDevice(device);
735     // Sensor device is initially disabled
736     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubIds[0], "fake1",
737                                       InputDeviceClass::KEYBOARD | InputDeviceClass::SENSOR,
738                                       nullptr));
739     // Device is disabled because the only sub device is a sensor device and disabled initially.
740     ASSERT_FALSE(mFakeEventHub->isDeviceEnabled(eventHubIds[0]));
741     ASSERT_FALSE(device->isEnabled());
742     ASSERT_NO_FATAL_FAILURE(
743             addDevice(eventHubIds[1], "fake2", InputDeviceClass::KEYBOARD, nullptr));
744     // The merged device is enabled if any sub device is enabled
745     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(eventHubIds[1]));
746     ASSERT_TRUE(device->isEnabled());
747 }
748 
TEST_F(InputReaderTest,WhenEnabledChanges_SendsDeviceResetNotification)749 TEST_F(InputReaderTest, WhenEnabledChanges_SendsDeviceResetNotification) {
750     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
751     constexpr ftl::Flags<InputDeviceClass> deviceClass(InputDeviceClass::KEYBOARD);
752     constexpr int32_t eventHubId = 1;
753     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
754     // Must add at least one mapper or the device will be ignored!
755     device->addMapper<FakeInputMapper>(eventHubId, mFakePolicy->getReaderConfiguration(),
756                                        AINPUT_SOURCE_KEYBOARD);
757     mReader->pushNextDevice(device);
758     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
759 
760     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasCalled(nullptr));
761 
762     NotifyDeviceResetArgs resetArgs;
763     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
764     ASSERT_EQ(deviceId, resetArgs.deviceId);
765 
766     ASSERT_EQ(device->isEnabled(), true);
767     disableDevice(deviceId);
768     mReader->loopOnce();
769 
770     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
771     ASSERT_EQ(deviceId, resetArgs.deviceId);
772     ASSERT_EQ(device->isEnabled(), false);
773 
774     disableDevice(deviceId);
775     mReader->loopOnce();
776     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasNotCalled());
777     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasNotCalled());
778     ASSERT_EQ(device->isEnabled(), false);
779 
780     enableDevice(deviceId);
781     mReader->loopOnce();
782     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
783     ASSERT_EQ(deviceId, resetArgs.deviceId);
784     ASSERT_EQ(device->isEnabled(), true);
785 }
786 
TEST_F(InputReaderTest,GetKeyCodeState_ForwardsRequestsToMappers)787 TEST_F(InputReaderTest, GetKeyCodeState_ForwardsRequestsToMappers) {
788     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
789     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
790     constexpr int32_t eventHubId = 1;
791     FakeInputMapper& mapper =
792             addDeviceWithFakeInputMapper(deviceId, eventHubId, "fake", deviceClass,
793                                          AINPUT_SOURCE_KEYBOARD, nullptr);
794     mapper.setKeyCodeState(AKEYCODE_A, AKEY_STATE_DOWN);
795 
796     ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getKeyCodeState(0,
797             AINPUT_SOURCE_ANY, AKEYCODE_A))
798             << "Should return unknown when the device id is >= 0 but unknown.";
799 
800     ASSERT_EQ(AKEY_STATE_UNKNOWN,
801               mReader->getKeyCodeState(deviceId, AINPUT_SOURCE_TRACKBALL, AKEYCODE_A))
802             << "Should return unknown when the device id is valid but the sources are not "
803                "supported by the device.";
804 
805     ASSERT_EQ(AKEY_STATE_DOWN,
806               mReader->getKeyCodeState(deviceId, AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL,
807                                        AKEYCODE_A))
808             << "Should return value provided by mapper when device id is valid and the device "
809                "supports some of the sources.";
810 
811     ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getKeyCodeState(-1,
812             AINPUT_SOURCE_TRACKBALL, AKEYCODE_A))
813             << "Should return unknown when the device id is < 0 but the sources are not supported by any device.";
814 
815     ASSERT_EQ(AKEY_STATE_DOWN, mReader->getKeyCodeState(-1,
816             AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL, AKEYCODE_A))
817             << "Should return value provided by mapper when device id is < 0 and one of the devices supports some of the sources.";
818 }
819 
TEST_F(InputReaderTest,GetKeyCodeForKeyLocation_ForwardsRequestsToMappers)820 TEST_F(InputReaderTest, GetKeyCodeForKeyLocation_ForwardsRequestsToMappers) {
821     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
822     constexpr int32_t eventHubId = 1;
823     FakeInputMapper& mapper = addDeviceWithFakeInputMapper(deviceId, eventHubId, "keyboard",
824                                                            InputDeviceClass::KEYBOARD,
825                                                            AINPUT_SOURCE_KEYBOARD, nullptr);
826     mapper.addKeyCodeMapping(AKEYCODE_Y, AKEYCODE_Z);
827 
828     ASSERT_EQ(AKEYCODE_UNKNOWN, mReader->getKeyCodeForKeyLocation(0, AKEYCODE_Y))
829             << "Should return unknown when the device with the specified id is not found.";
830 
831     ASSERT_EQ(AKEYCODE_Z, mReader->getKeyCodeForKeyLocation(deviceId, AKEYCODE_Y))
832             << "Should return correct mapping when device id is valid and mapping exists.";
833 
834     ASSERT_EQ(AKEYCODE_A, mReader->getKeyCodeForKeyLocation(deviceId, AKEYCODE_A))
835             << "Should return the location key code when device id is valid and there's no "
836                "mapping.";
837 }
838 
TEST_F(InputReaderTest,GetKeyCodeForKeyLocation_NoKeyboardMapper)839 TEST_F(InputReaderTest, GetKeyCodeForKeyLocation_NoKeyboardMapper) {
840     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
841     constexpr int32_t eventHubId = 1;
842     FakeInputMapper& mapper = addDeviceWithFakeInputMapper(deviceId, eventHubId, "joystick",
843                                                            InputDeviceClass::JOYSTICK,
844                                                            AINPUT_SOURCE_GAMEPAD, nullptr);
845     mapper.addKeyCodeMapping(AKEYCODE_Y, AKEYCODE_Z);
846 
847     ASSERT_EQ(AKEYCODE_UNKNOWN, mReader->getKeyCodeForKeyLocation(deviceId, AKEYCODE_Y))
848             << "Should return unknown when the device id is valid but there is no keyboard mapper";
849 }
850 
TEST_F(InputReaderTest,GetScanCodeState_ForwardsRequestsToMappers)851 TEST_F(InputReaderTest, GetScanCodeState_ForwardsRequestsToMappers) {
852     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
853     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
854     constexpr int32_t eventHubId = 1;
855     FakeInputMapper& mapper =
856             addDeviceWithFakeInputMapper(deviceId, eventHubId, "fake", deviceClass,
857                                          AINPUT_SOURCE_KEYBOARD, nullptr);
858     mapper.setScanCodeState(KEY_A, AKEY_STATE_DOWN);
859 
860     ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getScanCodeState(0,
861             AINPUT_SOURCE_ANY, KEY_A))
862             << "Should return unknown when the device id is >= 0 but unknown.";
863 
864     ASSERT_EQ(AKEY_STATE_UNKNOWN,
865               mReader->getScanCodeState(deviceId, AINPUT_SOURCE_TRACKBALL, KEY_A))
866             << "Should return unknown when the device id is valid but the sources are not "
867                "supported by the device.";
868 
869     ASSERT_EQ(AKEY_STATE_DOWN,
870               mReader->getScanCodeState(deviceId, AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL,
871                                         KEY_A))
872             << "Should return value provided by mapper when device id is valid and the device "
873                "supports some of the sources.";
874 
875     ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getScanCodeState(-1,
876             AINPUT_SOURCE_TRACKBALL, KEY_A))
877             << "Should return unknown when the device id is < 0 but the sources are not supported by any device.";
878 
879     ASSERT_EQ(AKEY_STATE_DOWN, mReader->getScanCodeState(-1,
880             AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL, KEY_A))
881             << "Should return value provided by mapper when device id is < 0 and one of the devices supports some of the sources.";
882 }
883 
TEST_F(InputReaderTest,GetSwitchState_ForwardsRequestsToMappers)884 TEST_F(InputReaderTest, GetSwitchState_ForwardsRequestsToMappers) {
885     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
886     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
887     constexpr int32_t eventHubId = 1;
888     FakeInputMapper& mapper =
889             addDeviceWithFakeInputMapper(deviceId, eventHubId, "fake", deviceClass,
890                                          AINPUT_SOURCE_KEYBOARD, nullptr);
891     mapper.setSwitchState(SW_LID, AKEY_STATE_DOWN);
892 
893     ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getSwitchState(0,
894             AINPUT_SOURCE_ANY, SW_LID))
895             << "Should return unknown when the device id is >= 0 but unknown.";
896 
897     ASSERT_EQ(AKEY_STATE_UNKNOWN,
898               mReader->getSwitchState(deviceId, AINPUT_SOURCE_TRACKBALL, SW_LID))
899             << "Should return unknown when the device id is valid but the sources are not "
900                "supported by the device.";
901 
902     ASSERT_EQ(AKEY_STATE_DOWN,
903               mReader->getSwitchState(deviceId, AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL,
904                                       SW_LID))
905             << "Should return value provided by mapper when device id is valid and the device "
906                "supports some of the sources.";
907 
908     ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getSwitchState(-1,
909             AINPUT_SOURCE_TRACKBALL, SW_LID))
910             << "Should return unknown when the device id is < 0 but the sources are not supported by any device.";
911 
912     ASSERT_EQ(AKEY_STATE_DOWN, mReader->getSwitchState(-1,
913             AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL, SW_LID))
914             << "Should return value provided by mapper when device id is < 0 and one of the devices supports some of the sources.";
915 }
916 
TEST_F(InputReaderTest,MarkSupportedKeyCodes_ForwardsRequestsToMappers)917 TEST_F(InputReaderTest, MarkSupportedKeyCodes_ForwardsRequestsToMappers) {
918     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
919     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
920     constexpr int32_t eventHubId = 1;
921     FakeInputMapper& mapper =
922             addDeviceWithFakeInputMapper(deviceId, eventHubId, "fake", deviceClass,
923                                          AINPUT_SOURCE_KEYBOARD, nullptr);
924 
925     mapper.addSupportedKeyCode(AKEYCODE_A);
926     mapper.addSupportedKeyCode(AKEYCODE_B);
927 
928     const std::vector<int32_t> keyCodes{AKEYCODE_A, AKEYCODE_B, AKEYCODE_1, AKEYCODE_2};
929     uint8_t flags[4] = { 0, 0, 0, 1 };
930 
931     ASSERT_FALSE(mReader->hasKeys(0, AINPUT_SOURCE_ANY, keyCodes, flags))
932             << "Should return false when device id is >= 0 but unknown.";
933     ASSERT_TRUE(!flags[0] && !flags[1] && !flags[2] && !flags[3]);
934 
935     flags[3] = 1;
936     ASSERT_FALSE(mReader->hasKeys(deviceId, AINPUT_SOURCE_TRACKBALL, keyCodes, flags))
937             << "Should return false when device id is valid but the sources are not supported by "
938                "the device.";
939     ASSERT_TRUE(!flags[0] && !flags[1] && !flags[2] && !flags[3]);
940 
941     flags[3] = 1;
942     ASSERT_TRUE(mReader->hasKeys(deviceId, AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL,
943                                  keyCodes, flags))
944             << "Should return value provided by mapper when device id is valid and the device "
945                "supports some of the sources.";
946     ASSERT_TRUE(flags[0] && flags[1] && !flags[2] && !flags[3]);
947 
948     flags[3] = 1;
949     ASSERT_FALSE(mReader->hasKeys(-1, AINPUT_SOURCE_TRACKBALL, keyCodes, flags))
950             << "Should return false when the device id is < 0 but the sources are not supported by "
951                "any device.";
952     ASSERT_TRUE(!flags[0] && !flags[1] && !flags[2] && !flags[3]);
953 
954     flags[3] = 1;
955     ASSERT_TRUE(
956             mReader->hasKeys(-1, AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TRACKBALL, keyCodes, flags))
957             << "Should return value provided by mapper when device id is < 0 and one of the "
958                "devices supports some of the sources.";
959     ASSERT_TRUE(flags[0] && flags[1] && !flags[2] && !flags[3]);
960 }
961 
TEST_F(InputReaderTest,LoopOnce_WhenDeviceScanFinished_SendsConfigurationChanged)962 TEST_F(InputReaderTest, LoopOnce_WhenDeviceScanFinished_SendsConfigurationChanged) {
963     constexpr int32_t eventHubId = 1;
964     addDevice(eventHubId, "ignored", InputDeviceClass::KEYBOARD, nullptr);
965 
966     NotifyConfigurationChangedArgs args;
967 
968     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasCalled(&args));
969     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
970 }
971 
TEST_F(InputReaderTest,LoopOnce_ForwardsRawEventsToMappers)972 TEST_F(InputReaderTest, LoopOnce_ForwardsRawEventsToMappers) {
973     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
974     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
975     constexpr nsecs_t when = 0;
976     constexpr int32_t eventHubId = 1;
977     constexpr nsecs_t readTime = 2;
978     FakeInputMapper& mapper =
979             addDeviceWithFakeInputMapper(deviceId, eventHubId, "fake", deviceClass,
980                                          AINPUT_SOURCE_KEYBOARD, nullptr);
981 
982     mFakeEventHub->enqueueEvent(when, readTime, eventHubId, EV_KEY, KEY_A, 1);
983     mReader->loopOnce();
984     ASSERT_NO_FATAL_FAILURE(mFakeEventHub->assertQueueIsEmpty());
985 
986     RawEvent event;
987     ASSERT_NO_FATAL_FAILURE(mapper.assertProcessWasCalled(&event));
988     ASSERT_EQ(when, event.when);
989     ASSERT_EQ(readTime, event.readTime);
990     ASSERT_EQ(eventHubId, event.deviceId);
991     ASSERT_EQ(EV_KEY, event.type);
992     ASSERT_EQ(KEY_A, event.code);
993     ASSERT_EQ(1, event.value);
994 }
995 
TEST_F(InputReaderTest,DeviceReset_RandomId)996 TEST_F(InputReaderTest, DeviceReset_RandomId) {
997     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
998     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
999     constexpr int32_t eventHubId = 1;
1000     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
1001     // Must add at least one mapper or the device will be ignored!
1002     device->addMapper<FakeInputMapper>(eventHubId, mFakePolicy->getReaderConfiguration(),
1003                                        AINPUT_SOURCE_KEYBOARD);
1004     mReader->pushNextDevice(device);
1005     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1006 
1007     NotifyDeviceResetArgs resetArgs;
1008     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1009     int32_t prevId = resetArgs.id;
1010 
1011     disableDevice(deviceId);
1012     mReader->loopOnce();
1013     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1014     ASSERT_NE(prevId, resetArgs.id);
1015     prevId = resetArgs.id;
1016 
1017     enableDevice(deviceId);
1018     mReader->loopOnce();
1019     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1020     ASSERT_NE(prevId, resetArgs.id);
1021     prevId = resetArgs.id;
1022 
1023     disableDevice(deviceId);
1024     mReader->loopOnce();
1025     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1026     ASSERT_NE(prevId, resetArgs.id);
1027     prevId = resetArgs.id;
1028 }
1029 
TEST_F(InputReaderTest,DeviceReset_GenerateIdWithInputReaderSource)1030 TEST_F(InputReaderTest, DeviceReset_GenerateIdWithInputReaderSource) {
1031     constexpr int32_t deviceId = 1;
1032     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
1033     constexpr int32_t eventHubId = 1;
1034     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
1035     // Must add at least one mapper or the device will be ignored!
1036     device->addMapper<FakeInputMapper>(eventHubId, mFakePolicy->getReaderConfiguration(),
1037                                        AINPUT_SOURCE_KEYBOARD);
1038     mReader->pushNextDevice(device);
1039     ASSERT_NO_FATAL_FAILURE(addDevice(deviceId, "fake", deviceClass, nullptr));
1040 
1041     NotifyDeviceResetArgs resetArgs;
1042     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1043     ASSERT_EQ(IdGenerator::Source::INPUT_READER, IdGenerator::getSource(resetArgs.id));
1044 }
1045 
TEST_F(InputReaderTest,Device_CanDispatchToDisplay)1046 TEST_F(InputReaderTest, Device_CanDispatchToDisplay) {
1047     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1048     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
1049     constexpr int32_t eventHubId = 1;
1050     const char* DEVICE_LOCATION = "USB1";
1051     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
1052     FakeInputMapper& mapper =
1053             device->addMapper<FakeInputMapper>(eventHubId, mFakePolicy->getReaderConfiguration(),
1054                                                AINPUT_SOURCE_TOUCHSCREEN);
1055     mReader->pushNextDevice(device);
1056 
1057     const uint8_t hdmi1 = 1;
1058 
1059     // Associated touch screen with second display.
1060     mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi1);
1061 
1062     // Add default and second display.
1063     mFakePolicy->clearViewports();
1064     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
1065                                     /*isActive=*/true, "local:0", NO_PORT, ViewportType::INTERNAL);
1066     mFakePolicy->addDisplayViewport(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
1067                                     ui::ROTATION_0, /*isActive=*/true, "local:1", hdmi1,
1068                                     ViewportType::EXTERNAL);
1069     mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::DISPLAY_INFO);
1070     mReader->loopOnce();
1071 
1072     // Add the device, and make sure all of the callbacks are triggered.
1073     // The device is added after the input port associations are processed since
1074     // we do not yet support dynamic device-to-display associations.
1075     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1076     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasCalled());
1077     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
1078     ASSERT_NO_FATAL_FAILURE(mapper.assertConfigureWasCalled());
1079 
1080     // Device should only dispatch to the specified display.
1081     ASSERT_EQ(deviceId, device->getId());
1082     ASSERT_FALSE(mReader->canDispatchToDisplay(deviceId, DISPLAY_ID));
1083     ASSERT_TRUE(mReader->canDispatchToDisplay(deviceId, SECONDARY_DISPLAY_ID));
1084 
1085     // Can't dispatch event from a disabled device.
1086     disableDevice(deviceId);
1087     mReader->loopOnce();
1088     ASSERT_FALSE(mReader->canDispatchToDisplay(deviceId, SECONDARY_DISPLAY_ID));
1089 }
1090 
TEST_F(InputReaderTest,WhenEnabledChanges_AllSubdevicesAreUpdated)1091 TEST_F(InputReaderTest, WhenEnabledChanges_AllSubdevicesAreUpdated) {
1092     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1093     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
1094     constexpr int32_t eventHubIds[2] = {END_RESERVED_ID, END_RESERVED_ID + 1};
1095     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
1096     // Must add at least one mapper or the device will be ignored!
1097     device->addMapper<FakeInputMapper>(eventHubIds[0], mFakePolicy->getReaderConfiguration(),
1098                                        AINPUT_SOURCE_KEYBOARD);
1099     device->addMapper<FakeInputMapper>(eventHubIds[1], mFakePolicy->getReaderConfiguration(),
1100                                        AINPUT_SOURCE_KEYBOARD);
1101     mReader->pushNextDevice(device);
1102     mReader->pushNextDevice(device);
1103     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubIds[0], "fake1", deviceClass, nullptr));
1104     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubIds[1], "fake2", deviceClass, nullptr));
1105 
1106     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasCalled(nullptr));
1107 
1108     NotifyDeviceResetArgs resetArgs;
1109     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1110     ASSERT_EQ(deviceId, resetArgs.deviceId);
1111     ASSERT_TRUE(device->isEnabled());
1112     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(eventHubIds[0]));
1113     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(eventHubIds[1]));
1114 
1115     disableDevice(deviceId);
1116     mReader->loopOnce();
1117 
1118     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1119     ASSERT_EQ(deviceId, resetArgs.deviceId);
1120     ASSERT_FALSE(device->isEnabled());
1121     ASSERT_FALSE(mFakeEventHub->isDeviceEnabled(eventHubIds[0]));
1122     ASSERT_FALSE(mFakeEventHub->isDeviceEnabled(eventHubIds[1]));
1123 
1124     enableDevice(deviceId);
1125     mReader->loopOnce();
1126 
1127     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
1128     ASSERT_EQ(deviceId, resetArgs.deviceId);
1129     ASSERT_TRUE(device->isEnabled());
1130     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(eventHubIds[0]));
1131     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(eventHubIds[1]));
1132 }
1133 
TEST_F(InputReaderTest,GetKeyCodeState_ForwardsRequestsToSubdeviceMappers)1134 TEST_F(InputReaderTest, GetKeyCodeState_ForwardsRequestsToSubdeviceMappers) {
1135     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1136     constexpr ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD;
1137     constexpr int32_t eventHubIds[2] = {END_RESERVED_ID, END_RESERVED_ID + 1};
1138     // Add two subdevices to device
1139     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake");
1140     FakeInputMapper& mapperDevice1 =
1141             device->addMapper<FakeInputMapper>(eventHubIds[0],
1142                                                mFakePolicy->getReaderConfiguration(),
1143                                                AINPUT_SOURCE_KEYBOARD);
1144     FakeInputMapper& mapperDevice2 =
1145             device->addMapper<FakeInputMapper>(eventHubIds[1],
1146                                                mFakePolicy->getReaderConfiguration(),
1147                                                AINPUT_SOURCE_KEYBOARD);
1148     mReader->pushNextDevice(device);
1149     mReader->pushNextDevice(device);
1150     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubIds[0], "fake1", deviceClass, nullptr));
1151     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubIds[1], "fake2", deviceClass, nullptr));
1152 
1153     mapperDevice1.setKeyCodeState(AKEYCODE_A, AKEY_STATE_DOWN);
1154     mapperDevice2.setKeyCodeState(AKEYCODE_B, AKEY_STATE_DOWN);
1155 
1156     ASSERT_EQ(AKEY_STATE_DOWN,
1157               mReader->getKeyCodeState(deviceId, AINPUT_SOURCE_KEYBOARD, AKEYCODE_A));
1158     ASSERT_EQ(AKEY_STATE_DOWN,
1159               mReader->getKeyCodeState(deviceId, AINPUT_SOURCE_KEYBOARD, AKEYCODE_B));
1160     ASSERT_EQ(AKEY_STATE_UNKNOWN,
1161               mReader->getKeyCodeState(deviceId, AINPUT_SOURCE_KEYBOARD, AKEYCODE_C));
1162 }
1163 
TEST_F(InputReaderTest,ChangingPointerCaptureNotifiesInputListener)1164 TEST_F(InputReaderTest, ChangingPointerCaptureNotifiesInputListener) {
1165     NotifyPointerCaptureChangedArgs args;
1166 
1167     auto request = mFakePolicy->setPointerCapture(/*window=*/sp<BBinder>::make());
1168     mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::POINTER_CAPTURE);
1169     mReader->loopOnce();
1170     mFakeListener->assertNotifyCaptureWasCalled(&args);
1171     ASSERT_TRUE(args.request.isEnable()) << "Pointer Capture should be enabled.";
1172     ASSERT_EQ(args.request, request) << "Pointer Capture sequence number should match.";
1173 
1174     mFakePolicy->setPointerCapture(/*window=*/nullptr);
1175     mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::POINTER_CAPTURE);
1176     mReader->loopOnce();
1177     mFakeListener->assertNotifyCaptureWasCalled(&args);
1178     ASSERT_FALSE(args.request.isEnable()) << "Pointer Capture should be disabled.";
1179 
1180     // Verify that the Pointer Capture state is not updated when the configuration value
1181     // does not change.
1182     mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::POINTER_CAPTURE);
1183     mReader->loopOnce();
1184     mFakeListener->assertNotifyCaptureWasNotCalled();
1185 }
1186 
TEST_F(InputReaderTest,GetLastUsedInputDeviceId)1187 TEST_F(InputReaderTest, GetLastUsedInputDeviceId) {
1188     constexpr int32_t FIRST_DEVICE_ID = END_RESERVED_ID + 1000;
1189     constexpr int32_t SECOND_DEVICE_ID = FIRST_DEVICE_ID + 1;
1190     FakeInputMapper& firstMapper =
1191             addDeviceWithFakeInputMapper(FIRST_DEVICE_ID, FIRST_DEVICE_ID, "first",
1192                                          InputDeviceClass::KEYBOARD, AINPUT_SOURCE_KEYBOARD,
1193                                          /*configuration=*/nullptr);
1194     FakeInputMapper& secondMapper =
1195             addDeviceWithFakeInputMapper(SECOND_DEVICE_ID, SECOND_DEVICE_ID, "second",
1196                                          InputDeviceClass::TOUCH_MT, AINPUT_SOURCE_STYLUS,
1197                                          /*configuration=*/nullptr);
1198 
1199     ASSERT_EQ(ReservedInputDeviceId::INVALID_INPUT_DEVICE_ID, mReader->getLastUsedInputDeviceId());
1200 
1201     // Start a new key gesture from the first device
1202     firstMapper.setProcessResult({KeyArgsBuilder(AKEY_EVENT_ACTION_DOWN, AINPUT_SOURCE_KEYBOARD)
1203                                           .deviceId(FIRST_DEVICE_ID)
1204                                           .build()});
1205     mFakeEventHub->enqueueEvent(ARBITRARY_TIME, ARBITRARY_TIME, FIRST_DEVICE_ID, 0, 0, 0);
1206     mReader->loopOnce();
1207     ASSERT_EQ(firstMapper.getDeviceId(), mReader->getLastUsedInputDeviceId());
1208 
1209     // Start a new touch gesture from the second device
1210     secondMapper.setProcessResult(
1211             {MotionArgsBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_STYLUS)
1212                      .deviceId(SECOND_DEVICE_ID)
1213                      .pointer(PointerBuilder(/*id=*/0, ToolType::FINGER))
1214                      .build()});
1215     mFakeEventHub->enqueueEvent(ARBITRARY_TIME, ARBITRARY_TIME, SECOND_DEVICE_ID, 0, 0, 0);
1216     mReader->loopOnce();
1217     ASSERT_EQ(SECOND_DEVICE_ID, mReader->getLastUsedInputDeviceId());
1218 
1219     // Releasing the key is not a new gesture, so it does not update the last used device
1220     firstMapper.setProcessResult({KeyArgsBuilder(AKEY_EVENT_ACTION_UP, AINPUT_SOURCE_KEYBOARD)
1221                                           .deviceId(FIRST_DEVICE_ID)
1222                                           .build()});
1223     mFakeEventHub->enqueueEvent(ARBITRARY_TIME, ARBITRARY_TIME, FIRST_DEVICE_ID, 0, 0, 0);
1224     mReader->loopOnce();
1225     ASSERT_EQ(SECOND_DEVICE_ID, mReader->getLastUsedInputDeviceId());
1226 
1227     // But pressing a new key does start a new gesture
1228     firstMapper.setProcessResult({KeyArgsBuilder(AKEY_EVENT_ACTION_DOWN, AINPUT_SOURCE_KEYBOARD)
1229                                           .deviceId(FIRST_DEVICE_ID)
1230                                           .build()});
1231     mFakeEventHub->enqueueEvent(ARBITRARY_TIME, ARBITRARY_TIME, FIRST_DEVICE_ID, 0, 0, 0);
1232     mReader->loopOnce();
1233     ASSERT_EQ(FIRST_DEVICE_ID, mReader->getLastUsedInputDeviceId());
1234 
1235     // Moving or ending a touch gesture does not update the last used device
1236     secondMapper.setProcessResult(
1237             {MotionArgsBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
1238                      .deviceId(SECOND_DEVICE_ID)
1239                      .pointer(PointerBuilder(/*id=*/0, ToolType::STYLUS))
1240                      .build()});
1241     mFakeEventHub->enqueueEvent(ARBITRARY_TIME, ARBITRARY_TIME, SECOND_DEVICE_ID, 0, 0, 0);
1242     mReader->loopOnce();
1243     ASSERT_EQ(FIRST_DEVICE_ID, mReader->getLastUsedInputDeviceId());
1244     secondMapper.setProcessResult({MotionArgsBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
1245                                            .deviceId(SECOND_DEVICE_ID)
1246                                            .pointer(PointerBuilder(/*id=*/0, ToolType::STYLUS))
1247                                            .build()});
1248     mFakeEventHub->enqueueEvent(ARBITRARY_TIME, ARBITRARY_TIME, SECOND_DEVICE_ID, 0, 0, 0);
1249     mReader->loopOnce();
1250     ASSERT_EQ(FIRST_DEVICE_ID, mReader->getLastUsedInputDeviceId());
1251 
1252     // Starting a new hover gesture updates the last used device
1253     secondMapper.setProcessResult(
1254             {MotionArgsBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER, AINPUT_SOURCE_STYLUS)
1255                      .deviceId(SECOND_DEVICE_ID)
1256                      .pointer(PointerBuilder(/*id=*/0, ToolType::STYLUS))
1257                      .build()});
1258     mFakeEventHub->enqueueEvent(ARBITRARY_TIME, ARBITRARY_TIME, SECOND_DEVICE_ID, 0, 0, 0);
1259     mReader->loopOnce();
1260     ASSERT_EQ(SECOND_DEVICE_ID, mReader->getLastUsedInputDeviceId());
1261 }
1262 
1263 class FakeVibratorInputMapper : public FakeInputMapper {
1264 public:
FakeVibratorInputMapper(InputDeviceContext & deviceContext,const InputReaderConfiguration & readerConfig,uint32_t sources)1265     FakeVibratorInputMapper(InputDeviceContext& deviceContext,
1266                             const InputReaderConfiguration& readerConfig, uint32_t sources)
1267           : FakeInputMapper(deviceContext, readerConfig, sources) {}
1268 
getVibratorIds()1269     std::vector<int32_t> getVibratorIds() override { return getDeviceContext().getVibratorIds(); }
1270 };
1271 
TEST_F(InputReaderTest,VibratorGetVibratorIds)1272 TEST_F(InputReaderTest, VibratorGetVibratorIds) {
1273     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1274     ftl::Flags<InputDeviceClass> deviceClass =
1275             InputDeviceClass::KEYBOARD | InputDeviceClass::VIBRATOR;
1276     constexpr int32_t eventHubId = 1;
1277     const char* DEVICE_LOCATION = "BLUETOOTH";
1278     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
1279     FakeVibratorInputMapper& mapper =
1280             device->addMapper<FakeVibratorInputMapper>(eventHubId,
1281                                                        mFakePolicy->getReaderConfiguration(),
1282                                                        AINPUT_SOURCE_KEYBOARD);
1283     mReader->pushNextDevice(device);
1284 
1285     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1286     ASSERT_NO_FATAL_FAILURE(mapper.assertConfigureWasCalled());
1287 
1288     ASSERT_EQ(mapper.getVibratorIds().size(), 2U);
1289     ASSERT_EQ(mReader->getVibratorIds(deviceId).size(), 2U);
1290 }
1291 
1292 // --- FakePeripheralController ---
1293 
1294 class FakePeripheralController : public PeripheralControllerInterface {
1295 public:
FakePeripheralController(InputDeviceContext & deviceContext)1296     FakePeripheralController(InputDeviceContext& deviceContext) : mDeviceContext(deviceContext) {}
1297 
~FakePeripheralController()1298     ~FakePeripheralController() override {}
1299 
getEventHubId() const1300     int32_t getEventHubId() const { return getDeviceContext().getEventHubId(); }
1301 
populateDeviceInfo(InputDeviceInfo * deviceInfo)1302     void populateDeviceInfo(InputDeviceInfo* deviceInfo) override {}
1303 
dump(std::string & dump)1304     void dump(std::string& dump) override {}
1305 
getBatteryCapacity(int32_t batteryId)1306     std::optional<int32_t> getBatteryCapacity(int32_t batteryId) override {
1307         return getDeviceContext().getBatteryCapacity(batteryId);
1308     }
1309 
getBatteryStatus(int32_t batteryId)1310     std::optional<int32_t> getBatteryStatus(int32_t batteryId) override {
1311         return getDeviceContext().getBatteryStatus(batteryId);
1312     }
1313 
setLightColor(int32_t lightId,int32_t color)1314     bool setLightColor(int32_t lightId, int32_t color) override {
1315         getDeviceContext().setLightBrightness(lightId, color >> 24);
1316         return true;
1317     }
1318 
getLightColor(int32_t lightId)1319     std::optional<int32_t> getLightColor(int32_t lightId) override {
1320         std::optional<int32_t> result = getDeviceContext().getLightBrightness(lightId);
1321         if (!result.has_value()) {
1322             return std::nullopt;
1323         }
1324         return result.value() << 24;
1325     }
1326 
setLightPlayerId(int32_t lightId,int32_t playerId)1327     bool setLightPlayerId(int32_t lightId, int32_t playerId) override { return true; }
1328 
getLightPlayerId(int32_t lightId)1329     std::optional<int32_t> getLightPlayerId(int32_t lightId) override { return std::nullopt; }
1330 
1331 private:
1332     InputDeviceContext& mDeviceContext;
getDeviceId()1333     inline int32_t getDeviceId() { return mDeviceContext.getId(); }
getDeviceContext()1334     inline InputDeviceContext& getDeviceContext() { return mDeviceContext; }
getDeviceContext() const1335     inline InputDeviceContext& getDeviceContext() const { return mDeviceContext; }
1336 };
1337 
TEST_F(InputReaderTest,BatteryGetCapacity)1338 TEST_F(InputReaderTest, BatteryGetCapacity) {
1339     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1340     ftl::Flags<InputDeviceClass> deviceClass =
1341             InputDeviceClass::KEYBOARD | InputDeviceClass::BATTERY;
1342     constexpr int32_t eventHubId = 1;
1343     const char* DEVICE_LOCATION = "BLUETOOTH";
1344     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
1345     FakePeripheralController& controller =
1346             device->addController<FakePeripheralController>(eventHubId);
1347     mReader->pushNextDevice(device);
1348 
1349     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1350 
1351     ASSERT_EQ(controller.getBatteryCapacity(FakeEventHub::DEFAULT_BATTERY),
1352               FakeEventHub::BATTERY_CAPACITY);
1353     ASSERT_EQ(mReader->getBatteryCapacity(deviceId), FakeEventHub::BATTERY_CAPACITY);
1354 }
1355 
TEST_F(InputReaderTest,BatteryGetStatus)1356 TEST_F(InputReaderTest, BatteryGetStatus) {
1357     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1358     ftl::Flags<InputDeviceClass> deviceClass =
1359             InputDeviceClass::KEYBOARD | InputDeviceClass::BATTERY;
1360     constexpr int32_t eventHubId = 1;
1361     const char* DEVICE_LOCATION = "BLUETOOTH";
1362     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
1363     FakePeripheralController& controller =
1364             device->addController<FakePeripheralController>(eventHubId);
1365     mReader->pushNextDevice(device);
1366 
1367     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1368 
1369     ASSERT_EQ(controller.getBatteryStatus(FakeEventHub::DEFAULT_BATTERY),
1370               FakeEventHub::BATTERY_STATUS);
1371     ASSERT_EQ(mReader->getBatteryStatus(deviceId), FakeEventHub::BATTERY_STATUS);
1372 }
1373 
TEST_F(InputReaderTest,BatteryGetDevicePath)1374 TEST_F(InputReaderTest, BatteryGetDevicePath) {
1375     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1376     ftl::Flags<InputDeviceClass> deviceClass =
1377             InputDeviceClass::KEYBOARD | InputDeviceClass::BATTERY;
1378     constexpr int32_t eventHubId = 1;
1379     const char* DEVICE_LOCATION = "BLUETOOTH";
1380     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
1381     device->addController<FakePeripheralController>(eventHubId);
1382     mReader->pushNextDevice(device);
1383 
1384     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1385 
1386     ASSERT_EQ(mReader->getBatteryDevicePath(deviceId), FakeEventHub::BATTERY_DEVPATH);
1387 }
1388 
TEST_F(InputReaderTest,LightGetColor)1389 TEST_F(InputReaderTest, LightGetColor) {
1390     constexpr int32_t deviceId = END_RESERVED_ID + 1000;
1391     ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD | InputDeviceClass::LIGHT;
1392     constexpr int32_t eventHubId = 1;
1393     const char* DEVICE_LOCATION = "BLUETOOTH";
1394     std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
1395     FakePeripheralController& controller =
1396             device->addController<FakePeripheralController>(eventHubId);
1397     mReader->pushNextDevice(device);
1398     RawLightInfo info = {.id = 1,
1399                          .name = "Mono",
1400                          .maxBrightness = 255,
1401                          .flags = InputLightClass::BRIGHTNESS,
1402                          .path = ""};
1403     mFakeEventHub->addRawLightInfo(/*rawId=*/1, std::move(info));
1404     mFakeEventHub->fakeLightBrightness(/*rawId=*/1, 0x55);
1405 
1406     ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
1407 
1408     ASSERT_TRUE(controller.setLightColor(/*lightId=*/1, LIGHT_BRIGHTNESS));
1409     ASSERT_EQ(controller.getLightColor(/*lightId=*/1), LIGHT_BRIGHTNESS);
1410     ASSERT_TRUE(mReader->setLightColor(deviceId, /*lightId=*/1, LIGHT_BRIGHTNESS));
1411     ASSERT_EQ(mReader->getLightColor(deviceId, /*lightId=*/1), LIGHT_BRIGHTNESS);
1412 }
1413 
1414 // --- InputReaderIntegrationTest ---
1415 
1416 // These tests create and interact with the InputReader only through its interface.
1417 // The InputReader is started during SetUp(), which starts its processing in its own
1418 // thread. The tests use linux uinput to emulate input devices.
1419 // NOTE: Interacting with the physical device while these tests are running may cause
1420 // the tests to fail.
1421 class InputReaderIntegrationTest : public testing::Test {
1422 protected:
1423     std::unique_ptr<TestInputListener> mTestListener;
1424     sp<FakeInputReaderPolicy> mFakePolicy;
1425     std::unique_ptr<InputReaderInterface> mReader;
1426 
1427     constexpr static auto EVENT_HAPPENED_TIMEOUT = 2000ms;
1428     constexpr static auto EVENT_DID_NOT_HAPPEN_TIMEOUT = 30ms;
1429 
SetUp()1430     void SetUp() override {
1431 #if !defined(__ANDROID__)
1432         GTEST_SKIP();
1433 #endif
1434         mFakePolicy = sp<FakeInputReaderPolicy>::make();
1435 
1436         setupInputReader();
1437     }
1438 
TearDown()1439     void TearDown() override {
1440 #if !defined(__ANDROID__)
1441         return;
1442 #endif
1443         ASSERT_EQ(mReader->stop(), OK);
1444         mReader.reset();
1445         mTestListener.reset();
1446         mFakePolicy.clear();
1447     }
1448 
waitForDevice(const std::string & deviceName)1449     std::optional<InputDeviceInfo> waitForDevice(const std::string& deviceName) {
1450         std::chrono::time_point start = std::chrono::steady_clock::now();
1451         while (true) {
1452             const std::vector<InputDeviceInfo> inputDevices = mFakePolicy->getInputDevices();
1453             const auto& it = std::find_if(inputDevices.begin(), inputDevices.end(),
1454                                           [&deviceName](const InputDeviceInfo& info) {
1455                                               return info.getIdentifier().name == deviceName;
1456                                           });
1457             if (it != inputDevices.end()) {
1458                 return std::make_optional(*it);
1459             }
1460             std::this_thread::sleep_for(1ms);
1461             std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
1462             if (elapsed > 5s) {
1463                 return {};
1464             }
1465         }
1466     }
1467 
setupInputReader()1468     void setupInputReader() {
1469         mTestListener = std::make_unique<TestInputListener>(EVENT_HAPPENED_TIMEOUT,
1470                                                             EVENT_DID_NOT_HAPPEN_TIMEOUT);
1471 
1472         mReader = std::make_unique<InputReader>(std::make_shared<EventHub>(), mFakePolicy,
1473                                                 *mTestListener);
1474         ASSERT_EQ(mReader->start(), OK);
1475 
1476         // Since this test is run on a real device, all the input devices connected
1477         // to the test device will show up in mReader. We wait for those input devices to
1478         // show up before beginning the tests.
1479         ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1480         ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyInputDevicesChangedWasCalled());
1481         ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
1482     }
1483 };
1484 
TEST_F(InputReaderIntegrationTest,TestInvalidDevice)1485 TEST_F(InputReaderIntegrationTest, TestInvalidDevice) {
1486     // An invalid input device that is only used for this test.
1487     class InvalidUinputDevice : public UinputDevice {
1488     public:
1489         InvalidUinputDevice() : UinputDevice("Invalid Device", /*productId=*/99) {}
1490 
1491     private:
1492         void configureDevice(int fd, uinput_user_dev* device) override {}
1493     };
1494 
1495     const size_t numDevices = mFakePolicy->getInputDevices().size();
1496 
1497     // UinputDevice does not set any event or key bits, so InputReader should not
1498     // consider it as a valid device.
1499     std::unique_ptr<UinputDevice> invalidDevice = createUinputDevice<InvalidUinputDevice>();
1500     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesNotChanged());
1501     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasNotCalled());
1502     ASSERT_EQ(numDevices, mFakePolicy->getInputDevices().size());
1503 
1504     invalidDevice.reset();
1505     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesNotChanged());
1506     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasNotCalled());
1507     ASSERT_EQ(numDevices, mFakePolicy->getInputDevices().size());
1508 }
1509 
TEST_F(InputReaderIntegrationTest,AddNewDevice)1510 TEST_F(InputReaderIntegrationTest, AddNewDevice) {
1511     const size_t initialNumDevices = mFakePolicy->getInputDevices().size();
1512 
1513     std::unique_ptr<UinputHomeKey> keyboard = createUinputDevice<UinputHomeKey>();
1514     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1515     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
1516     ASSERT_EQ(initialNumDevices + 1, mFakePolicy->getInputDevices().size());
1517 
1518     const auto device = waitForDevice(keyboard->getName());
1519     ASSERT_TRUE(device.has_value());
1520     ASSERT_EQ(AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC, device->getKeyboardType());
1521     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, device->getSources());
1522     ASSERT_EQ(0U, device->getMotionRanges().size());
1523 
1524     keyboard.reset();
1525     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1526     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
1527     ASSERT_EQ(initialNumDevices, mFakePolicy->getInputDevices().size());
1528 }
1529 
TEST_F(InputReaderIntegrationTest,SendsEventsToInputListener)1530 TEST_F(InputReaderIntegrationTest, SendsEventsToInputListener) {
1531     std::unique_ptr<UinputHomeKey> keyboard = createUinputDevice<UinputHomeKey>();
1532     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1533 
1534     NotifyConfigurationChangedArgs configChangedArgs;
1535     ASSERT_NO_FATAL_FAILURE(
1536             mTestListener->assertNotifyConfigurationChangedWasCalled(&configChangedArgs));
1537     int32_t prevId = configChangedArgs.id;
1538     nsecs_t prevTimestamp = configChangedArgs.eventTime;
1539 
1540     NotifyKeyArgs keyArgs;
1541     keyboard->pressAndReleaseHomeKey();
1542     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(&keyArgs));
1543     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
1544     ASSERT_NE(prevId, keyArgs.id);
1545     prevId = keyArgs.id;
1546     ASSERT_LE(prevTimestamp, keyArgs.eventTime);
1547     ASSERT_LE(keyArgs.eventTime, keyArgs.readTime);
1548     prevTimestamp = keyArgs.eventTime;
1549 
1550     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(&keyArgs));
1551     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
1552     ASSERT_NE(prevId, keyArgs.id);
1553     ASSERT_LE(prevTimestamp, keyArgs.eventTime);
1554     ASSERT_LE(keyArgs.eventTime, keyArgs.readTime);
1555 }
1556 
TEST_F(InputReaderIntegrationTest,ExternalStylusesButtons)1557 TEST_F(InputReaderIntegrationTest, ExternalStylusesButtons) {
1558     std::unique_ptr<UinputExternalStylus> stylus = createUinputDevice<UinputExternalStylus>();
1559     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1560 
1561     const auto device = waitForDevice(stylus->getName());
1562     ASSERT_TRUE(device.has_value());
1563 
1564     // An external stylus with buttons should also be recognized as a keyboard.
1565     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_STYLUS, device->getSources())
1566             << "Unexpected source " << inputEventSourceToString(device->getSources()).c_str();
1567     ASSERT_EQ(AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC, device->getKeyboardType());
1568 
1569     const auto DOWN =
1570             AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN), WithSource(AINPUT_SOURCE_KEYBOARD));
1571     const auto UP = AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP), WithSource(AINPUT_SOURCE_KEYBOARD));
1572 
1573     stylus->pressAndReleaseKey(BTN_STYLUS);
1574     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(
1575             AllOf(DOWN, WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY))));
1576     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(
1577             AllOf(UP, WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY))));
1578 
1579     stylus->pressAndReleaseKey(BTN_STYLUS2);
1580     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(
1581             AllOf(DOWN, WithKeyCode(AKEYCODE_STYLUS_BUTTON_SECONDARY))));
1582     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(
1583             AllOf(UP, WithKeyCode(AKEYCODE_STYLUS_BUTTON_SECONDARY))));
1584 
1585     stylus->pressAndReleaseKey(BTN_STYLUS3);
1586     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(
1587             AllOf(DOWN, WithKeyCode(AKEYCODE_STYLUS_BUTTON_TERTIARY))));
1588     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(
1589             AllOf(UP, WithKeyCode(AKEYCODE_STYLUS_BUTTON_TERTIARY))));
1590 }
1591 
TEST_F(InputReaderIntegrationTest,KeyboardWithStylusButtons)1592 TEST_F(InputReaderIntegrationTest, KeyboardWithStylusButtons) {
1593     std::unique_ptr<UinputKeyboard> keyboard =
1594             createUinputDevice<UinputKeyboard>("KeyboardWithStylusButtons", /*productId=*/99,
1595                                                std::initializer_list<int>{KEY_Q, KEY_W, KEY_E,
1596                                                                           KEY_R, KEY_T, KEY_Y,
1597                                                                           BTN_STYLUS, BTN_STYLUS2,
1598                                                                           BTN_STYLUS3});
1599     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1600 
1601     const auto device = waitForDevice(keyboard->getName());
1602     ASSERT_TRUE(device.has_value());
1603 
1604     // An alphabetical keyboard that reports stylus buttons should not be recognized as a stylus.
1605     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, device->getSources())
1606             << "Unexpected source " << inputEventSourceToString(device->getSources()).c_str();
1607     ASSERT_EQ(AINPUT_KEYBOARD_TYPE_ALPHABETIC, device->getKeyboardType());
1608 }
1609 
TEST_F(InputReaderIntegrationTest,HidUsageKeyboardIsNotAStylus)1610 TEST_F(InputReaderIntegrationTest, HidUsageKeyboardIsNotAStylus) {
1611     // Create a Uinput keyboard that simulates a keyboard that can report HID usage codes. The
1612     // hid-input driver reports HID usage codes using the value for EV_MSC MSC_SCAN event.
1613     std::unique_ptr<UinputKeyboardWithHidUsage> keyboard =
1614             createUinputDevice<UinputKeyboardWithHidUsage>(
1615                     std::initializer_list<int>{KEY_VOLUMEUP, KEY_VOLUMEDOWN});
1616     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1617 
1618     const auto device = waitForDevice(keyboard->getName());
1619     ASSERT_TRUE(device.has_value());
1620 
1621     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, device->getSources())
1622             << "Unexpected source " << inputEventSourceToString(device->getSources()).c_str();
1623 
1624     // If a device supports reporting HID usage codes, it shouldn't automatically support
1625     // stylus keys.
1626     const std::vector<int> keycodes{AKEYCODE_STYLUS_BUTTON_PRIMARY};
1627     uint8_t outFlags[] = {0};
1628     ASSERT_TRUE(mReader->hasKeys(device->getId(), AINPUT_SOURCE_KEYBOARD, keycodes, outFlags));
1629     ASSERT_EQ(0, outFlags[0]) << "Keyboard should not have stylus button";
1630 }
1631 
1632 /**
1633  * The Steam controller sends BTN_GEAR_DOWN and BTN_GEAR_UP for the two "paddle" buttons
1634  * on the back. In this test, we make sure that BTN_GEAR_DOWN / BTN_WHEEL and BTN_GEAR_UP
1635  * are passed to the listener.
1636  */
1637 static_assert(BTN_GEAR_DOWN == BTN_WHEEL);
TEST_F(InputReaderIntegrationTest,SendsGearDownAndUpToInputListener)1638 TEST_F(InputReaderIntegrationTest, SendsGearDownAndUpToInputListener) {
1639     std::unique_ptr<UinputSteamController> controller = createUinputDevice<UinputSteamController>();
1640     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1641     NotifyKeyArgs keyArgs;
1642 
1643     controller->pressAndReleaseKey(BTN_GEAR_DOWN);
1644     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(&keyArgs)); // ACTION_DOWN
1645     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(&keyArgs)); // ACTION_UP
1646     ASSERT_EQ(BTN_GEAR_DOWN, keyArgs.scanCode);
1647 
1648     controller->pressAndReleaseKey(BTN_GEAR_UP);
1649     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(&keyArgs)); // ACTION_DOWN
1650     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasCalled(&keyArgs)); // ACTION_UP
1651     ASSERT_EQ(BTN_GEAR_UP, keyArgs.scanCode);
1652 }
1653 
1654 // --- TouchIntegrationTest ---
1655 
1656 class BaseTouchIntegrationTest : public InputReaderIntegrationTest {
1657 protected:
1658     const std::string UNIQUE_ID = "local:0";
1659 
SetUp()1660     void SetUp() override {
1661 #if !defined(__ANDROID__)
1662         GTEST_SKIP();
1663 #endif
1664         InputReaderIntegrationTest::SetUp();
1665         // At least add an internal display.
1666         setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
1667                                      UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
1668 
1669         mDevice = createUinputDevice<UinputTouchScreen>(Rect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT));
1670         ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1671         ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
1672         const auto info = waitForDevice(mDevice->getName());
1673         ASSERT_TRUE(info);
1674         mDeviceInfo = *info;
1675     }
1676 
setDisplayInfoAndReconfigure(ui::LogicalDisplayId displayId,int32_t width,int32_t height,ui::Rotation orientation,const std::string & uniqueId,std::optional<uint8_t> physicalPort,ViewportType viewportType)1677     void setDisplayInfoAndReconfigure(ui::LogicalDisplayId displayId, int32_t width, int32_t height,
1678                                       ui::Rotation orientation, const std::string& uniqueId,
1679                                       std::optional<uint8_t> physicalPort,
1680                                       ViewportType viewportType) {
1681         mFakePolicy->addDisplayViewport(displayId, width, height, orientation, /*isActive=*/true,
1682                                         uniqueId, physicalPort, viewportType);
1683         mReader->requestRefreshConfiguration(InputReaderConfiguration::Change::DISPLAY_INFO);
1684     }
1685 
assertReceivedMotion(int32_t action,const std::vector<Point> & points)1686     void assertReceivedMotion(int32_t action, const std::vector<Point>& points) {
1687         NotifyMotionArgs args;
1688         ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1689         EXPECT_EQ(action, args.action);
1690         ASSERT_EQ(points.size(), args.getPointerCount());
1691         for (size_t i = 0; i < args.getPointerCount(); i++) {
1692             EXPECT_EQ(points[i].x, args.pointerCoords[i].getX());
1693             EXPECT_EQ(points[i].y, args.pointerCoords[i].getY());
1694         }
1695     }
1696 
1697     std::unique_ptr<UinputTouchScreen> mDevice;
1698     InputDeviceInfo mDeviceInfo;
1699 };
1700 
1701 enum class TouchIntegrationTestDisplays { DISPLAY_INTERNAL, DISPLAY_INPUT_PORT, DISPLAY_UNIQUE_ID };
1702 
1703 class TouchIntegrationTest : public BaseTouchIntegrationTest,
1704                              public testing::WithParamInterface<TouchIntegrationTestDisplays> {
1705 protected:
1706     static constexpr std::optional<uint8_t> DISPLAY_PORT = 0;
1707     const std::string INPUT_PORT = "uinput_touch/input0";
1708 
SetUp()1709     void SetUp() override {
1710 #if !defined(__ANDROID__)
1711         GTEST_SKIP();
1712 #endif
1713         if (GetParam() == TouchIntegrationTestDisplays::DISPLAY_INTERNAL) {
1714             BaseTouchIntegrationTest::SetUp();
1715             return;
1716         }
1717 
1718         // setup policy with a input-port or UniqueId association to the display
1719         bool isInputPortAssociation =
1720                 GetParam() == TouchIntegrationTestDisplays::DISPLAY_INPUT_PORT;
1721 
1722         mFakePolicy = sp<FakeInputReaderPolicy>::make();
1723         if (isInputPortAssociation) {
1724             mFakePolicy->addInputPortAssociation(INPUT_PORT, DISPLAY_PORT.value());
1725         } else {
1726             mFakePolicy->addInputUniqueIdAssociation(INPUT_PORT, UNIQUE_ID);
1727         }
1728 
1729         InputReaderIntegrationTest::setupInputReader();
1730 
1731         mDevice = createUinputDevice<UinputTouchScreen>(Rect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT),
1732                                                         INPUT_PORT);
1733         ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1734 
1735         // Add a display linked to a physical port or UniqueId.
1736         setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
1737                                      UNIQUE_ID, isInputPortAssociation ? DISPLAY_PORT : NO_PORT,
1738                                      ViewportType::INTERNAL);
1739         ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
1740         ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
1741         const auto info = waitForDevice(mDevice->getName());
1742         ASSERT_TRUE(info);
1743         mDeviceInfo = *info;
1744     }
1745 };
1746 
TEST_P(TouchIntegrationTest,MultiTouchDeviceSource)1747 TEST_P(TouchIntegrationTest, MultiTouchDeviceSource) {
1748     // The UinputTouchScreen is an MT device that supports MT_TOOL_TYPE and also supports stylus
1749     // buttons. It should show up as a touchscreen, stylus, and keyboard (for reporting button
1750     // presses).
1751     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS | AINPUT_SOURCE_KEYBOARD,
1752               mDeviceInfo.getSources());
1753 }
1754 
TEST_P(TouchIntegrationTest,InputEvent_ProcessSingleTouch)1755 TEST_P(TouchIntegrationTest, InputEvent_ProcessSingleTouch) {
1756     NotifyMotionArgs args;
1757     const Point centerPoint = mDevice->getCenterPoint();
1758 
1759     // ACTION_DOWN
1760     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1761     mDevice->sendDown(centerPoint);
1762     mDevice->sendSync();
1763     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1764     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
1765 
1766     // ACTION_MOVE
1767     mDevice->sendMove(centerPoint + Point(1, 1));
1768     mDevice->sendSync();
1769     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1770     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
1771 
1772     // ACTION_UP
1773     mDevice->sendUp();
1774     mDevice->sendSync();
1775     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1776     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
1777 }
1778 
TEST_P(TouchIntegrationTest,InputEvent_ProcessMultiTouch)1779 TEST_P(TouchIntegrationTest, InputEvent_ProcessMultiTouch) {
1780     NotifyMotionArgs args;
1781     const Point centerPoint = mDevice->getCenterPoint();
1782 
1783     // ACTION_DOWN
1784     mDevice->sendSlot(FIRST_SLOT);
1785     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1786     mDevice->sendDown(centerPoint);
1787     mDevice->sendSync();
1788     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1789     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
1790 
1791     // ACTION_POINTER_DOWN (Second slot)
1792     const Point secondPoint = centerPoint + Point(100, 100);
1793     mDevice->sendSlot(SECOND_SLOT);
1794     mDevice->sendTrackingId(SECOND_TRACKING_ID);
1795     mDevice->sendDown(secondPoint);
1796     mDevice->sendSync();
1797     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1798     ASSERT_EQ(ACTION_POINTER_1_DOWN, args.action);
1799 
1800     // ACTION_MOVE (Second slot)
1801     mDevice->sendMove(secondPoint + Point(1, 1));
1802     mDevice->sendSync();
1803     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1804     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
1805 
1806     // ACTION_POINTER_UP (Second slot)
1807     mDevice->sendPointerUp();
1808     mDevice->sendSync();
1809     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1810     ASSERT_EQ(ACTION_POINTER_1_UP, args.action);
1811 
1812     // ACTION_UP
1813     mDevice->sendSlot(FIRST_SLOT);
1814     mDevice->sendUp();
1815     mDevice->sendSync();
1816     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1817     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
1818 }
1819 
1820 /**
1821  * What happens when a pointer goes up while another pointer moves in the same frame? Are POINTER_UP
1822  * events guaranteed to contain the same data as a preceding MOVE, or can they contain different
1823  * data?
1824  * In this test, we try to send a change in coordinates in Pointer 0 in the same frame as the
1825  * liftoff of Pointer 1. We check that POINTER_UP event is generated first, and the MOVE event
1826  * for Pointer 0 only is generated after.
1827  * Suppose we are only interested in learning the movement of Pointer 0. If we only observe MOVE
1828  * events, we will not miss any information.
1829  * Even though the Pointer 1 up event contains updated Pointer 0 coordinates, there is another MOVE
1830  * event generated afterwards that contains the newest movement of pointer 0.
1831  * This is important for palm rejection. If there is a subsequent InputListener stage that detects
1832  * palms, and wants to cancel Pointer 1, then it is safe to simply drop POINTER_1_UP event without
1833  * losing information about non-palm pointers.
1834  */
TEST_P(TouchIntegrationTest,MultiTouch_PointerMoveAndSecondPointerUp)1835 TEST_P(TouchIntegrationTest, MultiTouch_PointerMoveAndSecondPointerUp) {
1836     NotifyMotionArgs args;
1837     const Point centerPoint = mDevice->getCenterPoint();
1838 
1839     // ACTION_DOWN
1840     mDevice->sendSlot(FIRST_SLOT);
1841     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1842     mDevice->sendDown(centerPoint);
1843     mDevice->sendSync();
1844     assertReceivedMotion(AMOTION_EVENT_ACTION_DOWN, {centerPoint});
1845 
1846     // ACTION_POINTER_DOWN (Second slot)
1847     const Point secondPoint = centerPoint + Point(100, 100);
1848     mDevice->sendSlot(SECOND_SLOT);
1849     mDevice->sendTrackingId(SECOND_TRACKING_ID);
1850     mDevice->sendDown(secondPoint);
1851     mDevice->sendSync();
1852     assertReceivedMotion(ACTION_POINTER_1_DOWN, {centerPoint, secondPoint});
1853 
1854     // ACTION_MOVE (First slot)
1855     mDevice->sendSlot(FIRST_SLOT);
1856     mDevice->sendMove(centerPoint + Point(5, 5));
1857     // ACTION_POINTER_UP (Second slot)
1858     mDevice->sendSlot(SECOND_SLOT);
1859     mDevice->sendPointerUp();
1860     // Send a single sync for the above 2 pointer updates
1861     mDevice->sendSync();
1862 
1863     // First, we should get POINTER_UP for the second pointer
1864     assertReceivedMotion(ACTION_POINTER_1_UP,
1865                          {/*first pointer */ centerPoint + Point(5, 5),
1866                           /*second pointer*/ secondPoint});
1867 
1868     // Next, the MOVE event for the first pointer
1869     assertReceivedMotion(AMOTION_EVENT_ACTION_MOVE, {centerPoint + Point(5, 5)});
1870 }
1871 
1872 /**
1873  * Similar scenario as above. The difference is that when the second pointer goes up, it will first
1874  * move, and then it will go up, all in the same frame.
1875  * In this scenario, the movement of the second pointer just prior to liftoff is ignored, and never
1876  * gets sent to the listener.
1877  */
TEST_P(TouchIntegrationTest,MultiTouch_PointerMoveAndSecondPointerMoveAndUp)1878 TEST_P(TouchIntegrationTest, MultiTouch_PointerMoveAndSecondPointerMoveAndUp) {
1879     NotifyMotionArgs args;
1880     const Point centerPoint = mDevice->getCenterPoint();
1881 
1882     // ACTION_DOWN
1883     mDevice->sendSlot(FIRST_SLOT);
1884     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1885     mDevice->sendDown(centerPoint);
1886     mDevice->sendSync();
1887     assertReceivedMotion(AMOTION_EVENT_ACTION_DOWN, {centerPoint});
1888 
1889     // ACTION_POINTER_DOWN (Second slot)
1890     const Point secondPoint = centerPoint + Point(100, 100);
1891     mDevice->sendSlot(SECOND_SLOT);
1892     mDevice->sendTrackingId(SECOND_TRACKING_ID);
1893     mDevice->sendDown(secondPoint);
1894     mDevice->sendSync();
1895     assertReceivedMotion(ACTION_POINTER_1_DOWN, {centerPoint, secondPoint});
1896 
1897     // ACTION_MOVE (First slot)
1898     mDevice->sendSlot(FIRST_SLOT);
1899     mDevice->sendMove(centerPoint + Point(5, 5));
1900     // ACTION_POINTER_UP (Second slot)
1901     mDevice->sendSlot(SECOND_SLOT);
1902     mDevice->sendMove(secondPoint + Point(6, 6));
1903     mDevice->sendPointerUp();
1904     // Send a single sync for the above 2 pointer updates
1905     mDevice->sendSync();
1906 
1907     // First, we should get POINTER_UP for the second pointer
1908     // The movement of the second pointer during the liftoff frame is ignored.
1909     // The coordinates 'secondPoint + Point(6, 6)' are never sent to the listener.
1910     assertReceivedMotion(ACTION_POINTER_1_UP,
1911                          {/*first pointer */ centerPoint + Point(5, 5),
1912                           /*second pointer*/ secondPoint});
1913 
1914     // Next, the MOVE event for the first pointer
1915     assertReceivedMotion(AMOTION_EVENT_ACTION_MOVE, {centerPoint + Point(5, 5)});
1916 }
1917 
TEST_P(TouchIntegrationTest,InputEvent_ProcessPalm)1918 TEST_P(TouchIntegrationTest, InputEvent_ProcessPalm) {
1919     NotifyMotionArgs args;
1920     const Point centerPoint = mDevice->getCenterPoint();
1921 
1922     // ACTION_DOWN
1923     mDevice->sendSlot(FIRST_SLOT);
1924     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1925     mDevice->sendDown(centerPoint);
1926     mDevice->sendSync();
1927     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1928     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
1929 
1930     // ACTION_POINTER_DOWN (second slot)
1931     const Point secondPoint = centerPoint + Point(100, 100);
1932     mDevice->sendSlot(SECOND_SLOT);
1933     mDevice->sendTrackingId(SECOND_TRACKING_ID);
1934     mDevice->sendDown(secondPoint);
1935     mDevice->sendSync();
1936     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1937     ASSERT_EQ(ACTION_POINTER_1_DOWN, args.action);
1938 
1939     // ACTION_MOVE (second slot)
1940     mDevice->sendMove(secondPoint + Point(1, 1));
1941     mDevice->sendSync();
1942     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1943     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
1944 
1945     // Send MT_TOOL_PALM (second slot), which indicates that the touch IC has determined this to be
1946     // a palm event.
1947     // Expect to receive the ACTION_POINTER_UP with cancel flag.
1948     mDevice->sendToolType(MT_TOOL_PALM);
1949     mDevice->sendSync();
1950     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1951     ASSERT_EQ(ACTION_POINTER_1_UP, args.action);
1952     ASSERT_EQ(AMOTION_EVENT_FLAG_CANCELED, args.flags);
1953 
1954     // Send up to second slot, expect first slot send moving.
1955     mDevice->sendPointerUp();
1956     mDevice->sendSync();
1957     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1958     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
1959 
1960     // Send ACTION_UP (first slot)
1961     mDevice->sendSlot(FIRST_SLOT);
1962     mDevice->sendUp();
1963     mDevice->sendSync();
1964 
1965     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(&args));
1966     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
1967 }
1968 
1969 /**
1970  * Some drivers historically have reported axis values outside of the range specified in the
1971  * evdev axis info. Ensure we don't crash when this happens. For example, a driver may report a
1972  * pressure value greater than the reported maximum, since it unclear what specific meaning the
1973  * maximum value for pressure has (beyond the maximum value that can be produced by a sensor),
1974  * and no units for pressure (resolution) is specified by the evdev documentation.
1975  */
TEST_P(TouchIntegrationTest,AcceptsAxisValuesOutsideReportedRange)1976 TEST_P(TouchIntegrationTest, AcceptsAxisValuesOutsideReportedRange) {
1977     const Point centerPoint = mDevice->getCenterPoint();
1978 
1979     // Down with pressure outside the reported range
1980     mDevice->sendSlot(FIRST_SLOT);
1981     mDevice->sendTrackingId(FIRST_TRACKING_ID);
1982     mDevice->sendDown(centerPoint);
1983     mDevice->sendPressure(UinputTouchScreen::RAW_PRESSURE_MAX + 2);
1984     mDevice->sendSync();
1985     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
1986             WithMotionAction(AMOTION_EVENT_ACTION_DOWN)));
1987 
1988     // Move to a point outside the reported range
1989     mDevice->sendMove(Point(DISPLAY_WIDTH, DISPLAY_HEIGHT) + Point(1, 1));
1990     mDevice->sendSync();
1991     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
1992             WithMotionAction(AMOTION_EVENT_ACTION_MOVE)));
1993 
1994     // Up
1995     mDevice->sendUp();
1996     mDevice->sendSync();
1997     ASSERT_NO_FATAL_FAILURE(
1998             mTestListener->assertNotifyMotionWasCalled(WithMotionAction(AMOTION_EVENT_ACTION_UP)));
1999 }
2000 
TEST_P(TouchIntegrationTest,NotifiesPolicyWhenStylusGestureStarted)2001 TEST_P(TouchIntegrationTest, NotifiesPolicyWhenStylusGestureStarted) {
2002     const Point centerPoint = mDevice->getCenterPoint();
2003 
2004     // Send down with the pen tool selected. The policy should be notified of the stylus presence.
2005     mDevice->sendSlot(FIRST_SLOT);
2006     mDevice->sendTrackingId(FIRST_TRACKING_ID);
2007     mDevice->sendToolType(MT_TOOL_PEN);
2008     mDevice->sendDown(centerPoint);
2009     mDevice->sendSync();
2010     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2011             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2012                   WithToolType(ToolType::STYLUS))));
2013 
2014     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertStylusGestureNotified(mDeviceInfo.getId()));
2015 
2016     // Release the stylus touch.
2017     mDevice->sendUp();
2018     mDevice->sendSync();
2019     ASSERT_NO_FATAL_FAILURE(
2020             mTestListener->assertNotifyMotionWasCalled(WithMotionAction(AMOTION_EVENT_ACTION_UP)));
2021 
2022     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertStylusGestureNotNotified());
2023 
2024     // Touch down with the finger, without the pen tool selected. The policy is not notified.
2025     mDevice->sendTrackingId(FIRST_TRACKING_ID);
2026     mDevice->sendToolType(MT_TOOL_FINGER);
2027     mDevice->sendDown(centerPoint);
2028     mDevice->sendSync();
2029     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2030             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2031                   WithToolType(ToolType::FINGER))));
2032 
2033     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertStylusGestureNotNotified());
2034 
2035     mDevice->sendUp();
2036     mDevice->sendSync();
2037     ASSERT_NO_FATAL_FAILURE(
2038             mTestListener->assertNotifyMotionWasCalled(WithMotionAction(AMOTION_EVENT_ACTION_UP)));
2039 
2040     // Send a move event with the stylus tool without BTN_TOUCH to generate a hover enter.
2041     // The policy should be notified of the stylus presence.
2042     mDevice->sendTrackingId(FIRST_TRACKING_ID);
2043     mDevice->sendToolType(MT_TOOL_PEN);
2044     mDevice->sendMove(centerPoint);
2045     mDevice->sendSync();
2046     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2047             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2048                   WithToolType(ToolType::STYLUS))));
2049 
2050     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertStylusGestureNotified(mDeviceInfo.getId()));
2051 }
2052 
TEST_P(TouchIntegrationTest,ExternalStylusConnectedDuringTouchGesture)2053 TEST_P(TouchIntegrationTest, ExternalStylusConnectedDuringTouchGesture) {
2054     const Point centerPoint = mDevice->getCenterPoint();
2055 
2056     // Down
2057     mDevice->sendSlot(FIRST_SLOT);
2058     mDevice->sendTrackingId(FIRST_TRACKING_ID);
2059     mDevice->sendDown(centerPoint);
2060     mDevice->sendSync();
2061     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2062             WithMotionAction(AMOTION_EVENT_ACTION_DOWN)));
2063 
2064     // Move
2065     mDevice->sendMove(centerPoint + Point(1, 1));
2066     mDevice->sendSync();
2067     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2068             WithMotionAction(AMOTION_EVENT_ACTION_MOVE)));
2069 
2070     // Connecting an external stylus mid-gesture should not interrupt the ongoing gesture stream.
2071     auto externalStylus = createUinputDevice<UinputExternalStylus>();
2072     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
2073     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
2074     const auto stylusInfo = waitForDevice(externalStylus->getName());
2075     ASSERT_TRUE(stylusInfo);
2076 
2077     // Move
2078     mDevice->sendMove(centerPoint + Point(2, 2));
2079     mDevice->sendSync();
2080     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2081             WithMotionAction(AMOTION_EVENT_ACTION_MOVE)));
2082 
2083     // Disconnecting an external stylus mid-gesture should not interrupt the ongoing gesture stream.
2084     externalStylus.reset();
2085     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
2086     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
2087     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2088 
2089     // Up
2090     mDevice->sendUp();
2091     mDevice->sendSync();
2092     ASSERT_NO_FATAL_FAILURE(
2093             mTestListener->assertNotifyMotionWasCalled(WithMotionAction(AMOTION_EVENT_ACTION_UP)));
2094 
2095     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2096 }
2097 
2098 INSTANTIATE_TEST_SUITE_P(TouchIntegrationTestDisplayVariants, TouchIntegrationTest,
2099                          testing::Values(TouchIntegrationTestDisplays::DISPLAY_INTERNAL,
2100                                          TouchIntegrationTestDisplays::DISPLAY_INPUT_PORT,
2101                                          TouchIntegrationTestDisplays::DISPLAY_UNIQUE_ID));
2102 
2103 // --- StylusButtonIntegrationTest ---
2104 
2105 // Verify the behavior of button presses reported by various kinds of styluses, including buttons
2106 // reported by the touchscreen's device, by a fused external stylus, and by an un-fused external
2107 // stylus.
2108 template <typename UinputStylusDevice>
2109 class StylusButtonIntegrationTest : public BaseTouchIntegrationTest {
2110 protected:
SetUp()2111     void SetUp() override {
2112 #if !defined(__ANDROID__)
2113         GTEST_SKIP();
2114 #endif
2115         BaseTouchIntegrationTest::SetUp();
2116         mTouchscreen = mDevice.get();
2117         mTouchscreenInfo = mDeviceInfo;
2118 
2119         setUpStylusDevice();
2120     }
2121 
2122     UinputStylusDevice* mStylus{nullptr};
2123     InputDeviceInfo mStylusInfo{};
2124 
2125     UinputTouchScreen* mTouchscreen{nullptr};
2126     InputDeviceInfo mTouchscreenInfo{};
2127 
2128 private:
2129     // When we are attempting to test stylus button events that are sent from the touchscreen,
2130     // use the same Uinput device for the touchscreen and the stylus.
2131     template <typename T = UinputStylusDevice>
setUpStylusDevice()2132     std::enable_if_t<std::is_same_v<UinputTouchScreen, T>, void> setUpStylusDevice() {
2133         mStylus = mDevice.get();
2134         mStylusInfo = mDeviceInfo;
2135     }
2136 
2137     // When we are attempting to stylus buttons from an external stylus being merged with touches
2138     // from a touchscreen, create a new Uinput device through which stylus buttons can be injected.
2139     template <typename T = UinputStylusDevice>
setUpStylusDevice()2140     std::enable_if_t<!std::is_same_v<UinputTouchScreen, T>, void> setUpStylusDevice() {
2141         mStylusDeviceLifecycleTracker = createUinputDevice<T>();
2142         mStylus = mStylusDeviceLifecycleTracker.get();
2143         ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
2144         ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
2145         const auto info = waitForDevice(mStylus->getName());
2146         ASSERT_TRUE(info);
2147         mStylusInfo = *info;
2148     }
2149 
2150     std::unique_ptr<UinputStylusDevice> mStylusDeviceLifecycleTracker{};
2151 
2152     // Hide the base class's device to expose it with a different name for readability.
2153     using BaseTouchIntegrationTest::mDevice;
2154     using BaseTouchIntegrationTest::mDeviceInfo;
2155 };
2156 
2157 using StylusButtonIntegrationTestTypes =
2158         ::testing::Types<UinputTouchScreen, UinputExternalStylus, UinputExternalStylusWithPressure>;
2159 TYPED_TEST_SUITE(StylusButtonIntegrationTest, StylusButtonIntegrationTestTypes);
2160 
TYPED_TEST(StylusButtonIntegrationTest,StylusButtonsGenerateKeyEvents)2161 TYPED_TEST(StylusButtonIntegrationTest, StylusButtonsGenerateKeyEvents) {
2162     const auto stylusId = TestFixture::mStylusInfo.getId();
2163 
2164     TestFixture::mStylus->pressKey(BTN_STYLUS);
2165     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2166             AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN), WithSource(AINPUT_SOURCE_KEYBOARD),
2167                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2168 
2169     TestFixture::mStylus->releaseKey(BTN_STYLUS);
2170     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2171             AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP), WithSource(AINPUT_SOURCE_KEYBOARD),
2172                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2173 }
2174 
TYPED_TEST(StylusButtonIntegrationTest,StylusButtonsSurroundingTouchGesture)2175 TYPED_TEST(StylusButtonIntegrationTest, StylusButtonsSurroundingTouchGesture) {
2176     const Point centerPoint = TestFixture::mTouchscreen->getCenterPoint();
2177     const auto touchscreenId = TestFixture::mTouchscreenInfo.getId();
2178     const auto stylusId = TestFixture::mStylusInfo.getId();
2179 
2180     // Press the stylus button.
2181     TestFixture::mStylus->pressKey(BTN_STYLUS);
2182     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2183             AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN), WithSource(AINPUT_SOURCE_KEYBOARD),
2184                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2185 
2186     // Start and finish a stylus gesture.
2187     TestFixture::mTouchscreen->sendSlot(FIRST_SLOT);
2188     TestFixture::mTouchscreen->sendTrackingId(FIRST_TRACKING_ID);
2189     TestFixture::mTouchscreen->sendToolType(MT_TOOL_PEN);
2190     TestFixture::mTouchscreen->sendDown(centerPoint);
2191     TestFixture::mTouchscreen->sendSync();
2192     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2193             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2194                   WithToolType(ToolType::STYLUS),
2195                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY),
2196                   WithDeviceId(touchscreenId))));
2197     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2198             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
2199                   WithToolType(ToolType::STYLUS),
2200                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY),
2201                   WithDeviceId(touchscreenId))));
2202 
2203     TestFixture::mTouchscreen->sendTrackingId(INVALID_TRACKING_ID);
2204     TestFixture::mTouchscreen->sendSync();
2205     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2206             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
2207                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2208                   WithDeviceId(touchscreenId))));
2209     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2210             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2211                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2212                   WithDeviceId(touchscreenId))));
2213 
2214     // Release the stylus button.
2215     TestFixture::mStylus->releaseKey(BTN_STYLUS);
2216     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2217             AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP), WithSource(AINPUT_SOURCE_KEYBOARD),
2218                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2219 }
2220 
TYPED_TEST(StylusButtonIntegrationTest,StylusButtonsSurroundingHoveringTouchGesture)2221 TYPED_TEST(StylusButtonIntegrationTest, StylusButtonsSurroundingHoveringTouchGesture) {
2222     const Point centerPoint = TestFixture::mTouchscreen->getCenterPoint();
2223     const auto touchscreenId = TestFixture::mTouchscreenInfo.getId();
2224     const auto stylusId = TestFixture::mStylusInfo.getId();
2225     auto toolTypeDevice =
2226             AllOf(WithToolType(ToolType::STYLUS), WithDeviceId(touchscreenId));
2227 
2228     // Press the stylus button.
2229     TestFixture::mStylus->pressKey(BTN_STYLUS);
2230     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2231             AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN), WithSource(AINPUT_SOURCE_KEYBOARD),
2232                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2233 
2234     // Start hovering with the stylus.
2235     TestFixture::mTouchscreen->sendSlot(FIRST_SLOT);
2236     TestFixture::mTouchscreen->sendTrackingId(FIRST_TRACKING_ID);
2237     TestFixture::mTouchscreen->sendToolType(MT_TOOL_PEN);
2238     TestFixture::mTouchscreen->sendMove(centerPoint);
2239     TestFixture::mTouchscreen->sendSync();
2240     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2241             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2242                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2243     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2244             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2245                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2246     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2247             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
2248                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2249 
2250     // Touch down with the stylus.
2251     TestFixture::mTouchscreen->sendTrackingId(FIRST_TRACKING_ID);
2252     TestFixture::mTouchscreen->sendToolType(MT_TOOL_PEN);
2253     TestFixture::mTouchscreen->sendDown(centerPoint);
2254     TestFixture::mTouchscreen->sendSync();
2255     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2256             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
2257                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2258 
2259     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2260             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2261                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2262 
2263     // Stop touching with the stylus, and start hovering.
2264     TestFixture::mTouchscreen->sendUp();
2265     TestFixture::mTouchscreen->sendTrackingId(FIRST_TRACKING_ID);
2266     TestFixture::mTouchscreen->sendToolType(MT_TOOL_PEN);
2267     TestFixture::mTouchscreen->sendMove(centerPoint);
2268     TestFixture::mTouchscreen->sendSync();
2269     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2270             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_UP),
2271                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2272     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2273             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER),
2274                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2275     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2276             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
2277                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2278 
2279     // Stop hovering.
2280     TestFixture::mTouchscreen->sendTrackingId(INVALID_TRACKING_ID);
2281     TestFixture::mTouchscreen->sendSync();
2282     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2283             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
2284                   WithButtonState(0))));
2285     // TODO(b/257971675): Fix inconsistent button state when exiting hover.
2286     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2287             AllOf(toolTypeDevice, WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT),
2288                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
2289 
2290     // Release the stylus button.
2291     TestFixture::mStylus->releaseKey(BTN_STYLUS);
2292     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2293             AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP), WithSource(AINPUT_SOURCE_KEYBOARD),
2294                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2295 }
2296 
TYPED_TEST(StylusButtonIntegrationTest,StylusButtonsWithinTouchGesture)2297 TYPED_TEST(StylusButtonIntegrationTest, StylusButtonsWithinTouchGesture) {
2298     const Point centerPoint = TestFixture::mTouchscreen->getCenterPoint();
2299     const auto touchscreenId = TestFixture::mTouchscreenInfo.getId();
2300     const auto stylusId = TestFixture::mStylusInfo.getId();
2301 
2302     // Start a stylus gesture.
2303     TestFixture::mTouchscreen->sendSlot(FIRST_SLOT);
2304     TestFixture::mTouchscreen->sendTrackingId(FIRST_TRACKING_ID);
2305     TestFixture::mTouchscreen->sendToolType(MT_TOOL_PEN);
2306     TestFixture::mTouchscreen->sendDown(centerPoint);
2307     TestFixture::mTouchscreen->sendSync();
2308     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2309             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2310                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2311                   WithDeviceId(touchscreenId))));
2312 
2313     // Press and release a stylus button. Each change in button state also generates a MOVE event.
2314     TestFixture::mStylus->pressKey(BTN_STYLUS);
2315     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2316             AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN), WithSource(AINPUT_SOURCE_KEYBOARD),
2317                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2318     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2319             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
2320                   WithToolType(ToolType::STYLUS),
2321                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY),
2322                   WithDeviceId(touchscreenId))));
2323     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2324             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
2325                   WithToolType(ToolType::STYLUS),
2326                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY),
2327                   WithDeviceId(touchscreenId))));
2328 
2329     TestFixture::mStylus->releaseKey(BTN_STYLUS);
2330     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2331             AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP), WithSource(AINPUT_SOURCE_KEYBOARD),
2332                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2333     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2334             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
2335                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2336                   WithDeviceId(touchscreenId))));
2337     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2338             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
2339                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2340                   WithDeviceId(touchscreenId))));
2341 
2342     // Finish the stylus gesture.
2343     TestFixture::mTouchscreen->sendTrackingId(INVALID_TRACKING_ID);
2344     TestFixture::mTouchscreen->sendSync();
2345     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2346             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2347                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2348                   WithDeviceId(touchscreenId))));
2349 }
2350 
TYPED_TEST(StylusButtonIntegrationTest,StylusButtonMotionEventsDisabled)2351 TYPED_TEST(StylusButtonIntegrationTest, StylusButtonMotionEventsDisabled) {
2352     TestFixture::mFakePolicy->setStylusButtonMotionEventsEnabled(false);
2353     TestFixture::mReader->requestRefreshConfiguration(
2354             InputReaderConfiguration::Change::STYLUS_BUTTON_REPORTING);
2355 
2356     const Point centerPoint = TestFixture::mTouchscreen->getCenterPoint();
2357     const auto touchscreenId = TestFixture::mTouchscreenInfo.getId();
2358     const auto stylusId = TestFixture::mStylusInfo.getId();
2359 
2360     // Start a stylus gesture. By the time this event is processed, the configuration change that
2361     // was requested is guaranteed to be completed.
2362     TestFixture::mTouchscreen->sendSlot(FIRST_SLOT);
2363     TestFixture::mTouchscreen->sendTrackingId(FIRST_TRACKING_ID);
2364     TestFixture::mTouchscreen->sendToolType(MT_TOOL_PEN);
2365     TestFixture::mTouchscreen->sendDown(centerPoint);
2366     TestFixture::mTouchscreen->sendSync();
2367     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2368             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
2369                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2370                   WithDeviceId(touchscreenId))));
2371 
2372     // Press and release a stylus button. Each change only generates a MOVE motion event.
2373     // Key events are unaffected.
2374     TestFixture::mStylus->pressKey(BTN_STYLUS);
2375     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2376             AllOf(WithKeyAction(AKEY_EVENT_ACTION_DOWN), WithSource(AINPUT_SOURCE_KEYBOARD),
2377                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2378     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2379             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
2380                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2381                   WithDeviceId(touchscreenId))));
2382 
2383     TestFixture::mStylus->releaseKey(BTN_STYLUS);
2384     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyKeyWasCalled(
2385             AllOf(WithKeyAction(AKEY_EVENT_ACTION_UP), WithSource(AINPUT_SOURCE_KEYBOARD),
2386                   WithKeyCode(AKEYCODE_STYLUS_BUTTON_PRIMARY), WithDeviceId(stylusId))));
2387     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2388             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
2389                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2390                   WithDeviceId(touchscreenId))));
2391 
2392     // Finish the stylus gesture.
2393     TestFixture::mTouchscreen->sendTrackingId(INVALID_TRACKING_ID);
2394     TestFixture::mTouchscreen->sendSync();
2395     ASSERT_NO_FATAL_FAILURE(TestFixture::mTestListener->assertNotifyMotionWasCalled(
2396             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2397                   WithToolType(ToolType::STYLUS), WithButtonState(0),
2398                   WithDeviceId(touchscreenId))));
2399 }
2400 
2401 // --- ExternalStylusIntegrationTest ---
2402 
2403 // Verify the behavior of an external stylus. An external stylus can report pressure or button
2404 // data independently of the touchscreen, which is then sent as a MotionEvent as part of an
2405 // ongoing stylus gesture that is being emitted by the touchscreen.
2406 using ExternalStylusIntegrationTest = BaseTouchIntegrationTest;
2407 
TEST_F(ExternalStylusIntegrationTest,ExternalStylusConnectionChangesTouchscreenSource)2408 TEST_F(ExternalStylusIntegrationTest, ExternalStylusConnectionChangesTouchscreenSource) {
2409     // Create an external stylus capable of reporting pressure data that
2410     // should be fused with a touch pointer.
2411     std::unique_ptr<UinputExternalStylusWithPressure> stylus =
2412             createUinputDevice<UinputExternalStylusWithPressure>();
2413     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
2414     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
2415     const auto stylusInfo = waitForDevice(stylus->getName());
2416     ASSERT_TRUE(stylusInfo);
2417 
2418     // Connecting an external stylus changes the source of the touchscreen.
2419     const auto deviceInfo = waitForDevice(mDevice->getName());
2420     ASSERT_TRUE(deviceInfo);
2421     ASSERT_TRUE(isFromSource(deviceInfo->getSources(), STYLUS_FUSION_SOURCE));
2422 }
2423 
TEST_F(ExternalStylusIntegrationTest,FusedExternalStylusPressureReported)2424 TEST_F(ExternalStylusIntegrationTest, FusedExternalStylusPressureReported) {
2425     const Point centerPoint = mDevice->getCenterPoint();
2426 
2427     // Create an external stylus capable of reporting pressure data that
2428     // should be fused with a touch pointer.
2429     std::unique_ptr<UinputExternalStylusWithPressure> stylus =
2430             createUinputDevice<UinputExternalStylusWithPressure>();
2431     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
2432     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
2433     const auto stylusInfo = waitForDevice(stylus->getName());
2434     ASSERT_TRUE(stylusInfo);
2435 
2436     ASSERT_EQ(AINPUT_SOURCE_STYLUS | AINPUT_SOURCE_KEYBOARD, stylusInfo->getSources());
2437 
2438     const auto touchscreenId = mDeviceInfo.getId();
2439 
2440     // Set a pressure value on the stylus. It doesn't generate any events.
2441     const auto& RAW_PRESSURE_MAX = UinputExternalStylusWithPressure::RAW_PRESSURE_MAX;
2442     stylus->setPressure(100);
2443     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2444 
2445     // Start a finger gesture, and ensure it shows up as stylus gesture
2446     // with the pressure set by the external stylus.
2447     mDevice->sendSlot(FIRST_SLOT);
2448     mDevice->sendTrackingId(FIRST_TRACKING_ID);
2449     mDevice->sendToolType(MT_TOOL_FINGER);
2450     mDevice->sendDown(centerPoint);
2451     mDevice->sendSync();
2452     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2453             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithToolType(ToolType::STYLUS),
2454                   WithButtonState(0), WithSource(STYLUS_FUSION_SOURCE), WithDeviceId(touchscreenId),
2455                   WithPressure(100.f / RAW_PRESSURE_MAX))));
2456 
2457     // Change the pressure on the external stylus, and ensure the touchscreen generates a MOVE
2458     // event with the updated pressure.
2459     stylus->setPressure(200);
2460     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2461             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE), WithToolType(ToolType::STYLUS),
2462                   WithButtonState(0), WithSource(STYLUS_FUSION_SOURCE), WithDeviceId(touchscreenId),
2463                   WithPressure(200.f / RAW_PRESSURE_MAX))));
2464 
2465     // The external stylus did not generate any events.
2466     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2467     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasNotCalled());
2468 }
2469 
TEST_F(ExternalStylusIntegrationTest,FusedExternalStylusPressureNotReported)2470 TEST_F(ExternalStylusIntegrationTest, FusedExternalStylusPressureNotReported) {
2471     const Point centerPoint = mDevice->getCenterPoint();
2472 
2473     // Create an external stylus capable of reporting pressure data that
2474     // should be fused with a touch pointer.
2475     std::unique_ptr<UinputExternalStylusWithPressure> stylus =
2476             createUinputDevice<UinputExternalStylusWithPressure>();
2477     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
2478     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
2479     const auto stylusInfo = waitForDevice(stylus->getName());
2480     ASSERT_TRUE(stylusInfo);
2481 
2482     ASSERT_EQ(AINPUT_SOURCE_STYLUS | AINPUT_SOURCE_KEYBOARD, stylusInfo->getSources());
2483 
2484     const auto touchscreenId = mDeviceInfo.getId();
2485 
2486     // Set a pressure value of 0 on the stylus. It doesn't generate any events.
2487     const auto& RAW_PRESSURE_MAX = UinputExternalStylusWithPressure::RAW_PRESSURE_MAX;
2488     // Send a non-zero value first to prevent the kernel from consuming the zero event.
2489     stylus->setPressure(100);
2490     stylus->setPressure(0);
2491     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2492 
2493     // Start a finger gesture. The touch device will withhold generating any touches for
2494     // up to 72 milliseconds while waiting for pressure data from the external stylus.
2495     mDevice->sendSlot(FIRST_SLOT);
2496     mDevice->sendTrackingId(FIRST_TRACKING_ID);
2497     mDevice->sendToolType(MT_TOOL_FINGER);
2498     mDevice->sendDown(centerPoint);
2499     const auto syncTime = std::chrono::system_clock::now();
2500     // After 72 ms, the event *will* be generated. If we wait the full 72 ms to check that NO event
2501     // is generated in that period, there will be a race condition between the event being generated
2502     // and the test's wait timeout expiring. Thus, we wait for a shorter duration in the test, which
2503     // will reduce the liklihood of the race condition occurring.
2504     const auto waitUntilTimeForNoEvent =
2505             syncTime + std::chrono::milliseconds(ns2ms(EXTERNAL_STYLUS_DATA_TIMEOUT / 2));
2506     mDevice->sendSync();
2507     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled(waitUntilTimeForNoEvent));
2508 
2509     // Since the external stylus did not report a pressure value within the timeout,
2510     // it shows up as a finger pointer.
2511     const auto waitUntilTimeForEvent = syncTime +
2512             std::chrono::milliseconds(ns2ms(EXTERNAL_STYLUS_DATA_TIMEOUT)) + EVENT_HAPPENED_TIMEOUT;
2513     ASSERT_NO_FATAL_FAILURE(
2514             mTestListener->assertNotifyMotionWasCalled(AllOf(WithMotionAction(
2515                                                                      AMOTION_EVENT_ACTION_DOWN),
2516                                                              WithSource(AINPUT_SOURCE_TOUCHSCREEN |
2517                                                                         AINPUT_SOURCE_STYLUS),
2518                                                              WithToolType(ToolType::FINGER),
2519                                                              WithDeviceId(touchscreenId),
2520                                                              WithPressure(1.f)),
2521                                                        waitUntilTimeForEvent));
2522 
2523     // Change the pressure on the external stylus. Since the pressure was not present at the start
2524     // of the gesture, it is ignored for now.
2525     stylus->setPressure(200);
2526     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2527 
2528     // Finish the finger gesture.
2529     mDevice->sendTrackingId(INVALID_TRACKING_ID);
2530     mDevice->sendSync();
2531     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2532             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
2533                   WithSource(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS),
2534                   WithToolType(ToolType::FINGER))));
2535 
2536     // Start a new gesture. Since we have a valid pressure value, it shows up as a stylus.
2537     mDevice->sendTrackingId(FIRST_TRACKING_ID);
2538     mDevice->sendToolType(MT_TOOL_FINGER);
2539     mDevice->sendDown(centerPoint);
2540     mDevice->sendSync();
2541     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasCalled(
2542             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithSource(STYLUS_FUSION_SOURCE),
2543                   WithToolType(ToolType::STYLUS), WithButtonState(0), WithDeviceId(touchscreenId),
2544                   WithPressure(200.f / RAW_PRESSURE_MAX))));
2545 
2546     // The external stylus did not generate any events.
2547     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2548     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasNotCalled());
2549 }
2550 
TEST_F(ExternalStylusIntegrationTest,UnfusedExternalStylus)2551 TEST_F(ExternalStylusIntegrationTest, UnfusedExternalStylus) {
2552     const Point centerPoint = mDevice->getCenterPoint();
2553 
2554     // Create an external stylus device that does not support pressure. It should not affect any
2555     // touch pointers.
2556     std::unique_ptr<UinputExternalStylus> stylus = createUinputDevice<UinputExternalStylus>();
2557     ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertInputDevicesChanged());
2558     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyConfigurationChangedWasCalled());
2559     const auto stylusInfo = waitForDevice(stylus->getName());
2560     ASSERT_TRUE(stylusInfo);
2561 
2562     ASSERT_EQ(AINPUT_SOURCE_STYLUS | AINPUT_SOURCE_KEYBOARD, stylusInfo->getSources());
2563 
2564     const auto touchscreenId = mDeviceInfo.getId();
2565 
2566     // Start a finger gesture and ensure a finger pointer is generated for it, without waiting for
2567     // pressure data from the external stylus.
2568     mDevice->sendSlot(FIRST_SLOT);
2569     mDevice->sendTrackingId(FIRST_TRACKING_ID);
2570     mDevice->sendToolType(MT_TOOL_FINGER);
2571     mDevice->sendDown(centerPoint);
2572     auto waitUntil = std::chrono::system_clock::now() +
2573             std::chrono::milliseconds(ns2ms(EXTERNAL_STYLUS_DATA_TIMEOUT));
2574     mDevice->sendSync();
2575     ASSERT_NO_FATAL_FAILURE(
2576             mTestListener->assertNotifyMotionWasCalled(AllOf(WithMotionAction(
2577                                                                      AMOTION_EVENT_ACTION_DOWN),
2578                                                              WithToolType(ToolType::FINGER),
2579                                                              WithSource(AINPUT_SOURCE_TOUCHSCREEN |
2580                                                                         AINPUT_SOURCE_STYLUS),
2581                                                              WithButtonState(0),
2582                                                              WithDeviceId(touchscreenId),
2583                                                              WithPressure(1.f)),
2584                                                        waitUntil));
2585 
2586     // The external stylus did not generate any events.
2587     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyMotionWasNotCalled());
2588     ASSERT_NO_FATAL_FAILURE(mTestListener->assertNotifyKeyWasNotCalled());
2589 }
2590 
2591 // --- InputDeviceTest ---
2592 class InputDeviceTest : public testing::Test {
2593 protected:
2594     static const char* DEVICE_NAME;
2595     static const char* DEVICE_LOCATION;
2596     static const int32_t DEVICE_ID;
2597     static const int32_t DEVICE_GENERATION;
2598     static const int32_t DEVICE_CONTROLLER_NUMBER;
2599     static const ftl::Flags<InputDeviceClass> DEVICE_CLASSES;
2600     static const int32_t EVENTHUB_ID;
2601     static const std::string DEVICE_BLUETOOTH_ADDRESS;
2602 
2603     std::shared_ptr<FakeEventHub> mFakeEventHub;
2604     sp<FakeInputReaderPolicy> mFakePolicy;
2605     std::unique_ptr<TestInputListener> mFakeListener;
2606     std::unique_ptr<InstrumentedInputReader> mReader;
2607     std::shared_ptr<InputDevice> mDevice;
2608 
SetUp()2609     void SetUp() override {
2610         mFakeEventHub = std::make_unique<FakeEventHub>();
2611         mFakePolicy = sp<FakeInputReaderPolicy>::make();
2612         mFakeListener = std::make_unique<TestInputListener>();
2613         mReader = std::make_unique<InstrumentedInputReader>(mFakeEventHub, mFakePolicy,
2614                                                             *mFakeListener);
2615         InputDeviceIdentifier identifier;
2616         identifier.name = DEVICE_NAME;
2617         identifier.location = DEVICE_LOCATION;
2618         identifier.bluetoothAddress = DEVICE_BLUETOOTH_ADDRESS;
2619         mDevice = std::make_shared<InputDevice>(mReader->getContext(), DEVICE_ID, DEVICE_GENERATION,
2620                                                 identifier);
2621         mReader->pushNextDevice(mDevice);
2622         mFakeEventHub->addDevice(EVENTHUB_ID, DEVICE_NAME, ftl::Flags<InputDeviceClass>(0));
2623         mReader->loopOnce();
2624     }
2625 
TearDown()2626     void TearDown() override {
2627         mFakeListener.reset();
2628         mFakePolicy.clear();
2629     }
2630 };
2631 
2632 const char* InputDeviceTest::DEVICE_NAME = "device";
2633 const char* InputDeviceTest::DEVICE_LOCATION = "USB1";
2634 const int32_t InputDeviceTest::DEVICE_ID = END_RESERVED_ID + 1000;
2635 const int32_t InputDeviceTest::DEVICE_GENERATION = 2;
2636 const int32_t InputDeviceTest::DEVICE_CONTROLLER_NUMBER = 0;
2637 const ftl::Flags<InputDeviceClass> InputDeviceTest::DEVICE_CLASSES =
2638         InputDeviceClass::KEYBOARD | InputDeviceClass::TOUCH | InputDeviceClass::JOYSTICK;
2639 const int32_t InputDeviceTest::EVENTHUB_ID = 1;
2640 const std::string InputDeviceTest::DEVICE_BLUETOOTH_ADDRESS = "11:AA:22:BB:33:CC";
2641 
TEST_F(InputDeviceTest,ImmutableProperties)2642 TEST_F(InputDeviceTest, ImmutableProperties) {
2643     ASSERT_EQ(DEVICE_ID, mDevice->getId());
2644     ASSERT_STREQ(DEVICE_NAME, mDevice->getName().c_str());
2645     ASSERT_EQ(ftl::Flags<InputDeviceClass>(0), mDevice->getClasses());
2646 }
2647 
TEST_F(InputDeviceTest,WhenDeviceCreated_EnabledIsFalse)2648 TEST_F(InputDeviceTest, WhenDeviceCreated_EnabledIsFalse) {
2649     ASSERT_EQ(mDevice->isEnabled(), false);
2650 }
2651 
TEST_F(InputDeviceTest,WhenNoMappersAreRegistered_DeviceIsIgnored)2652 TEST_F(InputDeviceTest, WhenNoMappersAreRegistered_DeviceIsIgnored) {
2653     // Configuration.
2654     InputReaderConfiguration config;
2655     std::list<NotifyArgs> unused = mDevice->configure(ARBITRARY_TIME, config, /*changes=*/{});
2656 
2657     // Reset.
2658     unused += mDevice->reset(ARBITRARY_TIME);
2659 
2660     NotifyDeviceResetArgs resetArgs;
2661     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
2662     ASSERT_EQ(ARBITRARY_TIME, resetArgs.eventTime);
2663     ASSERT_EQ(DEVICE_ID, resetArgs.deviceId);
2664 
2665     // Metadata.
2666     ASSERT_TRUE(mDevice->isIgnored());
2667     ASSERT_EQ(AINPUT_SOURCE_UNKNOWN, mDevice->getSources());
2668 
2669     InputDeviceInfo info = mDevice->getDeviceInfo();
2670     ASSERT_EQ(DEVICE_ID, info.getId());
2671     ASSERT_STREQ(DEVICE_NAME, info.getIdentifier().name.c_str());
2672     ASSERT_EQ(AINPUT_KEYBOARD_TYPE_NONE, info.getKeyboardType());
2673     ASSERT_EQ(AINPUT_SOURCE_UNKNOWN, info.getSources());
2674 
2675     // State queries.
2676     ASSERT_EQ(0, mDevice->getMetaState());
2677 
2678     ASSERT_EQ(AKEY_STATE_UNKNOWN, mDevice->getKeyCodeState(AINPUT_SOURCE_KEYBOARD, 0))
2679             << "Ignored device should return unknown key code state.";
2680     ASSERT_EQ(AKEY_STATE_UNKNOWN, mDevice->getScanCodeState(AINPUT_SOURCE_KEYBOARD, 0))
2681             << "Ignored device should return unknown scan code state.";
2682     ASSERT_EQ(AKEY_STATE_UNKNOWN, mDevice->getSwitchState(AINPUT_SOURCE_KEYBOARD, 0))
2683             << "Ignored device should return unknown switch state.";
2684 
2685     const std::vector<int32_t> keyCodes{AKEYCODE_A, AKEYCODE_B};
2686     uint8_t flags[2] = { 0, 1 };
2687     ASSERT_FALSE(mDevice->markSupportedKeyCodes(AINPUT_SOURCE_KEYBOARD, keyCodes, flags))
2688             << "Ignored device should never mark any key codes.";
2689     ASSERT_EQ(0, flags[0]) << "Flag for unsupported key should be unchanged.";
2690     ASSERT_EQ(1, flags[1]) << "Flag for unsupported key should be unchanged.";
2691 }
2692 
TEST_F(InputDeviceTest,WhenMappersAreRegistered_DeviceIsNotIgnoredAndForwardsRequestsToMappers)2693 TEST_F(InputDeviceTest, WhenMappersAreRegistered_DeviceIsNotIgnoredAndForwardsRequestsToMappers) {
2694     // Configuration.
2695     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "key", "value");
2696 
2697     FakeInputMapper& mapper1 =
2698             mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2699                                                 AINPUT_SOURCE_KEYBOARD);
2700     mapper1.setKeyboardType(AINPUT_KEYBOARD_TYPE_ALPHABETIC);
2701     mapper1.setMetaState(AMETA_ALT_ON);
2702     mapper1.addSupportedKeyCode(AKEYCODE_A);
2703     mapper1.addSupportedKeyCode(AKEYCODE_B);
2704     mapper1.setKeyCodeState(AKEYCODE_A, AKEY_STATE_DOWN);
2705     mapper1.setKeyCodeState(AKEYCODE_B, AKEY_STATE_UP);
2706     mapper1.setScanCodeState(2, AKEY_STATE_DOWN);
2707     mapper1.setScanCodeState(3, AKEY_STATE_UP);
2708     mapper1.setSwitchState(4, AKEY_STATE_DOWN);
2709 
2710     FakeInputMapper& mapper2 =
2711             mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2712                                                 AINPUT_SOURCE_TOUCHSCREEN);
2713     mapper2.setMetaState(AMETA_SHIFT_ON);
2714 
2715     InputReaderConfiguration config;
2716     std::list<NotifyArgs> unused = mDevice->configure(ARBITRARY_TIME, config, /*changes=*/{});
2717 
2718     std::optional<std::string> propertyValue = mDevice->getConfiguration().getString("key");
2719     ASSERT_TRUE(propertyValue.has_value())
2720             << "Device should have read configuration during configuration phase.";
2721     ASSERT_EQ("value", *propertyValue);
2722 
2723     ASSERT_NO_FATAL_FAILURE(mapper1.assertConfigureWasCalled());
2724     ASSERT_NO_FATAL_FAILURE(mapper2.assertConfigureWasCalled());
2725 
2726     // Reset
2727     unused += mDevice->reset(ARBITRARY_TIME);
2728     ASSERT_NO_FATAL_FAILURE(mapper1.assertResetWasCalled());
2729     ASSERT_NO_FATAL_FAILURE(mapper2.assertResetWasCalled());
2730 
2731     NotifyDeviceResetArgs resetArgs;
2732     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
2733     ASSERT_EQ(ARBITRARY_TIME, resetArgs.eventTime);
2734     ASSERT_EQ(DEVICE_ID, resetArgs.deviceId);
2735 
2736     // Metadata.
2737     ASSERT_FALSE(mDevice->isIgnored());
2738     ASSERT_EQ(uint32_t(AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TOUCHSCREEN), mDevice->getSources());
2739 
2740     InputDeviceInfo info = mDevice->getDeviceInfo();
2741     ASSERT_EQ(DEVICE_ID, info.getId());
2742     ASSERT_STREQ(DEVICE_NAME, info.getIdentifier().name.c_str());
2743     ASSERT_EQ(AINPUT_KEYBOARD_TYPE_ALPHABETIC, info.getKeyboardType());
2744     ASSERT_EQ(uint32_t(AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TOUCHSCREEN), info.getSources());
2745 
2746     // State queries.
2747     ASSERT_EQ(AMETA_ALT_ON | AMETA_SHIFT_ON, mDevice->getMetaState())
2748             << "Should query mappers and combine meta states.";
2749 
2750     ASSERT_EQ(AKEY_STATE_UNKNOWN, mDevice->getKeyCodeState(AINPUT_SOURCE_TRACKBALL, AKEYCODE_A))
2751             << "Should return unknown key code state when source not supported.";
2752     ASSERT_EQ(AKEY_STATE_UNKNOWN, mDevice->getScanCodeState(AINPUT_SOURCE_TRACKBALL, AKEYCODE_A))
2753             << "Should return unknown scan code state when source not supported.";
2754     ASSERT_EQ(AKEY_STATE_UNKNOWN, mDevice->getSwitchState(AINPUT_SOURCE_TRACKBALL, AKEYCODE_A))
2755             << "Should return unknown switch state when source not supported.";
2756 
2757     ASSERT_EQ(AKEY_STATE_DOWN, mDevice->getKeyCodeState(AINPUT_SOURCE_KEYBOARD, AKEYCODE_A))
2758             << "Should query mapper when source is supported.";
2759     ASSERT_EQ(AKEY_STATE_UP, mDevice->getScanCodeState(AINPUT_SOURCE_KEYBOARD, 3))
2760             << "Should query mapper when source is supported.";
2761     ASSERT_EQ(AKEY_STATE_DOWN, mDevice->getSwitchState(AINPUT_SOURCE_KEYBOARD, 4))
2762             << "Should query mapper when source is supported.";
2763 
2764     const std::vector<int32_t> keyCodes{AKEYCODE_A, AKEYCODE_B, AKEYCODE_1, AKEYCODE_2};
2765     uint8_t flags[4] = { 0, 0, 0, 1 };
2766     ASSERT_FALSE(mDevice->markSupportedKeyCodes(AINPUT_SOURCE_TRACKBALL, keyCodes, flags))
2767             << "Should do nothing when source is unsupported.";
2768     ASSERT_EQ(0, flags[0]) << "Flag should be unchanged when source is unsupported.";
2769     ASSERT_EQ(0, flags[1]) << "Flag should be unchanged when source is unsupported.";
2770     ASSERT_EQ(0, flags[2]) << "Flag should be unchanged when source is unsupported.";
2771     ASSERT_EQ(1, flags[3]) << "Flag should be unchanged when source is unsupported.";
2772 
2773     ASSERT_TRUE(mDevice->markSupportedKeyCodes(AINPUT_SOURCE_KEYBOARD, keyCodes, flags))
2774             << "Should query mapper when source is supported.";
2775     ASSERT_EQ(1, flags[0]) << "Flag for supported key should be set.";
2776     ASSERT_EQ(1, flags[1]) << "Flag for supported key should be set.";
2777     ASSERT_EQ(0, flags[2]) << "Flag for unsupported key should be unchanged.";
2778     ASSERT_EQ(1, flags[3]) << "Flag for unsupported key should be unchanged.";
2779 
2780     // Event handling.
2781     RawEvent event;
2782     event.deviceId = EVENTHUB_ID;
2783     unused += mDevice->process(&event, 1);
2784 
2785     ASSERT_NO_FATAL_FAILURE(mapper1.assertProcessWasCalled());
2786     ASSERT_NO_FATAL_FAILURE(mapper2.assertProcessWasCalled());
2787 }
2788 
TEST_F(InputDeviceTest,Configure_SmoothScrollViewBehaviorNotSet)2789 TEST_F(InputDeviceTest, Configure_SmoothScrollViewBehaviorNotSet) {
2790     // Set some behavior to force the configuration to be update.
2791     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "device.wake", "1");
2792     mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2793                                         AINPUT_SOURCE_KEYBOARD);
2794 
2795     std::list<NotifyArgs> unused =
2796             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2797                                /*changes=*/{});
2798 
2799     ASSERT_FALSE(mDevice->getDeviceInfo().getViewBehavior().shouldSmoothScroll.has_value());
2800 }
2801 
TEST_F(InputDeviceTest,Configure_SmoothScrollViewBehaviorEnabled)2802 TEST_F(InputDeviceTest, Configure_SmoothScrollViewBehaviorEnabled) {
2803     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "device.viewBehavior_smoothScroll", "1");
2804     mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2805                                         AINPUT_SOURCE_KEYBOARD);
2806 
2807     std::list<NotifyArgs> unused =
2808             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2809                                /*changes=*/{});
2810 
2811     ASSERT_TRUE(mDevice->getDeviceInfo().getViewBehavior().shouldSmoothScroll.value_or(false));
2812 }
2813 
TEST_F(InputDeviceTest,WakeDevice_AddsWakeFlagToProcessNotifyArgs)2814 TEST_F(InputDeviceTest, WakeDevice_AddsWakeFlagToProcessNotifyArgs) {
2815     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "device.wake", "1");
2816     FakeInputMapper& mapper =
2817             mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2818                                                 AINPUT_SOURCE_KEYBOARD);
2819     NotifyMotionArgs args1;
2820     NotifySwitchArgs args2;
2821     NotifyKeyArgs args3;
2822     mapper.setProcessResult({args1, args2, args3});
2823 
2824     InputReaderConfiguration config;
2825     std::list<NotifyArgs> unused = mDevice->configure(ARBITRARY_TIME, config, /*changes=*/{});
2826 
2827     RawEvent event;
2828     event.deviceId = EVENTHUB_ID;
2829     std::list<NotifyArgs> notifyArgs = mDevice->process(&event, 1);
2830 
2831     for (auto& arg : notifyArgs) {
2832         if (const auto notifyMotionArgs = std::get_if<NotifyMotionArgs>(&arg)) {
2833             ASSERT_EQ(POLICY_FLAG_WAKE, notifyMotionArgs->policyFlags);
2834         } else if (const auto notifySwitchArgs = std::get_if<NotifySwitchArgs>(&arg)) {
2835             ASSERT_EQ(POLICY_FLAG_WAKE, notifySwitchArgs->policyFlags);
2836         } else if (const auto notifyKeyArgs = std::get_if<NotifyKeyArgs>(&arg)) {
2837             ASSERT_EQ(POLICY_FLAG_WAKE, notifyKeyArgs->policyFlags);
2838         }
2839     }
2840 }
2841 
TEST_F(InputDeviceTest,NotWakeDevice_DoesNotAddWakeFlagToProcessNotifyArgs)2842 TEST_F(InputDeviceTest, NotWakeDevice_DoesNotAddWakeFlagToProcessNotifyArgs) {
2843     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "device.wake", "0");
2844     FakeInputMapper& mapper =
2845             mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2846                                                 AINPUT_SOURCE_KEYBOARD);
2847     NotifyMotionArgs args;
2848     mapper.setProcessResult({args});
2849 
2850     InputReaderConfiguration config;
2851     std::list<NotifyArgs> unused = mDevice->configure(ARBITRARY_TIME, config, /*changes=*/{});
2852 
2853     RawEvent event;
2854     event.deviceId = EVENTHUB_ID;
2855     std::list<NotifyArgs> notifyArgs = mDevice->process(&event, 1);
2856 
2857     // POLICY_FLAG_WAKE is not added to the NotifyArgs.
2858     ASSERT_EQ(0u, std::get<NotifyMotionArgs>(notifyArgs.front()).policyFlags);
2859 }
2860 
TEST_F(InputDeviceTest,NotWakeDevice_DoesNotRemoveExistingWakeFlagFromProcessNotifyArgs)2861 TEST_F(InputDeviceTest, NotWakeDevice_DoesNotRemoveExistingWakeFlagFromProcessNotifyArgs) {
2862     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "device.wake", "0");
2863     FakeInputMapper& mapper =
2864             mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2865                                                 AINPUT_SOURCE_KEYBOARD);
2866     NotifyMotionArgs args;
2867     args.policyFlags = POLICY_FLAG_WAKE;
2868     mapper.setProcessResult({args});
2869 
2870     InputReaderConfiguration config;
2871     std::list<NotifyArgs> unused = mDevice->configure(ARBITRARY_TIME, config, /*changes=*/{});
2872 
2873     RawEvent event;
2874     event.deviceId = EVENTHUB_ID;
2875     std::list<NotifyArgs> notifyArgs = mDevice->process(&event, 1);
2876 
2877     // The POLICY_FLAG_WAKE is preserved, despite the device being a non-wake device.
2878     ASSERT_EQ(POLICY_FLAG_WAKE, std::get<NotifyMotionArgs>(notifyArgs.front()).policyFlags);
2879 }
2880 
2881 // A single input device is associated with a specific display. Check that:
2882 // 1. Device is disabled if the viewport corresponding to the associated display is not found
2883 // 2. Device is disabled when configure API is called
TEST_F(InputDeviceTest,Configure_AssignsDisplayPort)2884 TEST_F(InputDeviceTest, Configure_AssignsDisplayPort) {
2885     mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2886                                         AINPUT_SOURCE_TOUCHSCREEN);
2887 
2888     // First Configuration.
2889     std::list<NotifyArgs> unused =
2890             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2891                                /*changes=*/{});
2892 
2893     // Device should be enabled by default.
2894     ASSERT_TRUE(mDevice->isEnabled());
2895 
2896     // Prepare associated info.
2897     constexpr uint8_t hdmi = 1;
2898     const std::string UNIQUE_ID = "local:1";
2899 
2900     mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi);
2901     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2902                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2903     // Device should be disabled because it is associated with a specific display via
2904     // input port <-> display port association, but the corresponding display is not found
2905     ASSERT_FALSE(mDevice->isEnabled());
2906 
2907     // Prepare displays.
2908     mFakePolicy->addDisplayViewport(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
2909                                     ui::ROTATION_0, /*isActive=*/true, UNIQUE_ID, hdmi,
2910                                     ViewportType::INTERNAL);
2911     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2912                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2913     ASSERT_TRUE(mDevice->isEnabled());
2914 
2915     // Device should be disabled after set disable.
2916     mFakePolicy->addDisabledDevice(mDevice->getId());
2917     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2918                                  InputReaderConfiguration::Change::ENABLED_STATE);
2919     ASSERT_FALSE(mDevice->isEnabled());
2920 
2921     // Device should still be disabled even found the associated display.
2922     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2923                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2924     ASSERT_FALSE(mDevice->isEnabled());
2925 }
2926 
TEST_F(InputDeviceTest,Configure_AssignsDisplayUniqueId)2927 TEST_F(InputDeviceTest, Configure_AssignsDisplayUniqueId) {
2928     // Device should be enabled by default.
2929     mFakePolicy->clearViewports();
2930     mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2931                                         AINPUT_SOURCE_KEYBOARD);
2932     std::list<NotifyArgs> unused =
2933             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2934                                /*changes=*/{});
2935     ASSERT_TRUE(mDevice->isEnabled());
2936 
2937     // Device should be disabled because it is associated with a specific display, but the
2938     // corresponding display is not found.
2939     mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, DISPLAY_UNIQUE_ID);
2940     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2941                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2942     ASSERT_FALSE(mDevice->isEnabled());
2943 
2944     // Device should be enabled when a display is found.
2945     mFakePolicy->addDisplayViewport(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
2946                                     ui::ROTATION_0, /* isActive= */ true, DISPLAY_UNIQUE_ID,
2947                                     NO_PORT, ViewportType::INTERNAL);
2948     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2949                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2950     ASSERT_TRUE(mDevice->isEnabled());
2951 
2952     // Device should be disabled after set disable.
2953     mFakePolicy->addDisabledDevice(mDevice->getId());
2954     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2955                                  InputReaderConfiguration::Change::ENABLED_STATE);
2956     ASSERT_FALSE(mDevice->isEnabled());
2957 
2958     // Device should still be disabled even found the associated display.
2959     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2960                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2961     ASSERT_FALSE(mDevice->isEnabled());
2962 }
2963 
TEST_F(InputDeviceTest,Configure_UniqueId_CorrectlyMatches)2964 TEST_F(InputDeviceTest, Configure_UniqueId_CorrectlyMatches) {
2965     mFakePolicy->clearViewports();
2966     mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
2967                                         AINPUT_SOURCE_KEYBOARD);
2968     std::list<NotifyArgs> unused =
2969             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2970                                /*changes=*/{});
2971 
2972     mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, DISPLAY_UNIQUE_ID);
2973     mFakePolicy->addDisplayViewport(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
2974                                     ui::ROTATION_0, /* isActive= */ true, DISPLAY_UNIQUE_ID,
2975                                     NO_PORT, ViewportType::INTERNAL);
2976     const auto initialGeneration = mDevice->getGeneration();
2977     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
2978                                  InputReaderConfiguration::Change::DISPLAY_INFO);
2979     ASSERT_EQ(DISPLAY_UNIQUE_ID, mDevice->getAssociatedDisplayUniqueIdByPort());
2980     ASSERT_GT(mDevice->getGeneration(), initialGeneration);
2981     ASSERT_EQ(mDevice->getDeviceInfo().getAssociatedDisplayId(), SECONDARY_DISPLAY_ID);
2982 }
2983 
2984 /**
2985  * This test reproduces a crash caused by a dangling reference that remains after device is added
2986  * and removed. The reference is accessed in InputDevice::dump(..);
2987  */
TEST_F(InputDeviceTest,DumpDoesNotCrash)2988 TEST_F(InputDeviceTest, DumpDoesNotCrash) {
2989     constexpr int32_t TEST_EVENTHUB_ID = 10;
2990     mFakeEventHub->addDevice(TEST_EVENTHUB_ID, "Test EventHub device", InputDeviceClass::BATTERY);
2991 
2992     InputDevice device(mReader->getContext(), /*id=*/1, /*generation=*/2, /*identifier=*/{});
2993     auto _ = device.addEventHubDevice(ARBITRARY_TIME, TEST_EVENTHUB_ID,
2994                                       mFakePolicy->getReaderConfiguration());
2995     device.removeEventHubDevice(TEST_EVENTHUB_ID);
2996     std::string dumpStr, eventHubDevStr;
2997     device.dump(dumpStr, eventHubDevStr);
2998 }
2999 
TEST_F(InputDeviceTest,GetBluetoothAddress)3000 TEST_F(InputDeviceTest, GetBluetoothAddress) {
3001     const auto& address = mReader->getBluetoothAddress(DEVICE_ID);
3002     ASSERT_TRUE(address);
3003     ASSERT_EQ(DEVICE_BLUETOOTH_ADDRESS, *address);
3004 }
3005 
TEST_F(InputDeviceTest,KernelBufferOverflowResetsMappers)3006 TEST_F(InputDeviceTest, KernelBufferOverflowResetsMappers) {
3007     mFakePolicy->clearViewports();
3008     FakeInputMapper& mapper =
3009             mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, mFakePolicy->getReaderConfiguration(),
3010                                                 AINPUT_SOURCE_KEYBOARD);
3011     std::list<NotifyArgs> unused =
3012             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3013                                /*changes=*/{});
3014 
3015     mapper.assertConfigureWasCalled();
3016     mapper.assertResetWasNotCalled();
3017 
3018     RawEvent event{.when = ARBITRARY_TIME,
3019                    .readTime = ARBITRARY_TIME,
3020                    .deviceId = EVENTHUB_ID,
3021                    .type = EV_SYN,
3022                    .code = SYN_REPORT,
3023                    .value = 0};
3024 
3025     // Events are processed normally.
3026     unused = mDevice->process(&event, /*count=*/1);
3027     mapper.assertProcessWasCalled();
3028 
3029     // Simulate a kernel buffer overflow, which generates a SYN_DROPPED event.
3030     event.type = EV_SYN;
3031     event.code = SYN_DROPPED;
3032     event.value = 0;
3033     unused = mDevice->process(&event, /*count=*/1);
3034     mapper.assertProcessWasNotCalled();
3035 
3036     // All events until the next SYN_REPORT should be dropped.
3037     event.type = EV_KEY;
3038     event.code = KEY_A;
3039     event.value = 1;
3040     unused = mDevice->process(&event, /*count=*/1);
3041     mapper.assertProcessWasNotCalled();
3042 
3043     // We get the SYN_REPORT event now, which is not forwarded to mappers.
3044     // This should reset the mapper.
3045     event.type = EV_SYN;
3046     event.code = SYN_REPORT;
3047     event.value = 0;
3048     unused = mDevice->process(&event, /*count=*/1);
3049     mapper.assertProcessWasNotCalled();
3050     mapper.assertResetWasCalled();
3051 
3052     // The mapper receives events normally now.
3053     event.type = EV_KEY;
3054     event.code = KEY_B;
3055     event.value = 1;
3056     unused = mDevice->process(&event, /*count=*/1);
3057     mapper.assertProcessWasCalled();
3058 }
3059 
3060 // --- SwitchInputMapperTest ---
3061 
3062 class SwitchInputMapperTest : public InputMapperTest {
3063 protected:
3064 };
3065 
TEST_F(SwitchInputMapperTest,GetSources)3066 TEST_F(SwitchInputMapperTest, GetSources) {
3067     SwitchInputMapper& mapper = constructAndAddMapper<SwitchInputMapper>();
3068 
3069     ASSERT_EQ(uint32_t(AINPUT_SOURCE_SWITCH), mapper.getSources());
3070 }
3071 
TEST_F(SwitchInputMapperTest,GetSwitchState)3072 TEST_F(SwitchInputMapperTest, GetSwitchState) {
3073     SwitchInputMapper& mapper = constructAndAddMapper<SwitchInputMapper>();
3074 
3075     mFakeEventHub->setSwitchState(EVENTHUB_ID, SW_LID, 1);
3076     ASSERT_EQ(1, mapper.getSwitchState(AINPUT_SOURCE_ANY, SW_LID));
3077 
3078     mFakeEventHub->setSwitchState(EVENTHUB_ID, SW_LID, 0);
3079     ASSERT_EQ(0, mapper.getSwitchState(AINPUT_SOURCE_ANY, SW_LID));
3080 }
3081 
TEST_F(SwitchInputMapperTest,Process)3082 TEST_F(SwitchInputMapperTest, Process) {
3083     SwitchInputMapper& mapper = constructAndAddMapper<SwitchInputMapper>();
3084     std::list<NotifyArgs> out;
3085     out = process(mapper, ARBITRARY_TIME, READ_TIME, EV_SW, SW_LID, 1);
3086     ASSERT_TRUE(out.empty());
3087     out = process(mapper, ARBITRARY_TIME, READ_TIME, EV_SW, SW_JACK_PHYSICAL_INSERT, 1);
3088     ASSERT_TRUE(out.empty());
3089     out = process(mapper, ARBITRARY_TIME, READ_TIME, EV_SW, SW_HEADPHONE_INSERT, 0);
3090     ASSERT_TRUE(out.empty());
3091     out = process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
3092 
3093     ASSERT_EQ(1u, out.size());
3094     const NotifySwitchArgs& args = std::get<NotifySwitchArgs>(*out.begin());
3095     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
3096     ASSERT_EQ((1U << SW_LID) | (1U << SW_JACK_PHYSICAL_INSERT), args.switchValues);
3097     ASSERT_EQ((1U << SW_LID) | (1U << SW_JACK_PHYSICAL_INSERT) | (1 << SW_HEADPHONE_INSERT),
3098             args.switchMask);
3099     ASSERT_EQ(uint32_t(0), args.policyFlags);
3100 }
3101 
3102 // --- VibratorInputMapperTest ---
3103 class VibratorInputMapperTest : public InputMapperTest {
3104 protected:
SetUp()3105     void SetUp() override { InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::VIBRATOR); }
3106 };
3107 
TEST_F(VibratorInputMapperTest,GetSources)3108 TEST_F(VibratorInputMapperTest, GetSources) {
3109     VibratorInputMapper& mapper = constructAndAddMapper<VibratorInputMapper>();
3110 
3111     ASSERT_EQ(AINPUT_SOURCE_UNKNOWN, mapper.getSources());
3112 }
3113 
TEST_F(VibratorInputMapperTest,GetVibratorIds)3114 TEST_F(VibratorInputMapperTest, GetVibratorIds) {
3115     VibratorInputMapper& mapper = constructAndAddMapper<VibratorInputMapper>();
3116 
3117     ASSERT_EQ(mapper.getVibratorIds().size(), 2U);
3118 }
3119 
TEST_F(VibratorInputMapperTest,Vibrate)3120 TEST_F(VibratorInputMapperTest, Vibrate) {
3121     constexpr uint8_t DEFAULT_AMPLITUDE = 192;
3122     constexpr int32_t VIBRATION_TOKEN = 100;
3123     VibratorInputMapper& mapper = constructAndAddMapper<VibratorInputMapper>();
3124 
3125     VibrationElement pattern(2);
3126     VibrationSequence sequence(2);
3127     pattern.duration = std::chrono::milliseconds(200);
3128     pattern.channels = {{/*vibratorId=*/0, DEFAULT_AMPLITUDE / 2},
3129                         {/*vibratorId=*/1, DEFAULT_AMPLITUDE}};
3130     sequence.addElement(pattern);
3131     pattern.duration = std::chrono::milliseconds(500);
3132     pattern.channels = {{/*vibratorId=*/0, DEFAULT_AMPLITUDE / 4},
3133                         {/*vibratorId=*/1, DEFAULT_AMPLITUDE}};
3134     sequence.addElement(pattern);
3135 
3136     std::vector<int64_t> timings = {0, 1};
3137     std::vector<uint8_t> amplitudes = {DEFAULT_AMPLITUDE, DEFAULT_AMPLITUDE / 2};
3138 
3139     ASSERT_FALSE(mapper.isVibrating());
3140     // Start vibrating
3141     std::list<NotifyArgs> out = mapper.vibrate(sequence, /*repeat=*/-1, VIBRATION_TOKEN);
3142     ASSERT_TRUE(mapper.isVibrating());
3143     // Verify vibrator state listener was notified.
3144     mReader->loopOnce();
3145     ASSERT_EQ(1u, out.size());
3146     const NotifyVibratorStateArgs& vibrateArgs = std::get<NotifyVibratorStateArgs>(*out.begin());
3147     ASSERT_EQ(DEVICE_ID, vibrateArgs.deviceId);
3148     ASSERT_TRUE(vibrateArgs.isOn);
3149     // Stop vibrating
3150     out = mapper.cancelVibrate(VIBRATION_TOKEN);
3151     ASSERT_FALSE(mapper.isVibrating());
3152     // Verify vibrator state listener was notified.
3153     mReader->loopOnce();
3154     ASSERT_EQ(1u, out.size());
3155     const NotifyVibratorStateArgs& cancelArgs = std::get<NotifyVibratorStateArgs>(*out.begin());
3156     ASSERT_EQ(DEVICE_ID, cancelArgs.deviceId);
3157     ASSERT_FALSE(cancelArgs.isOn);
3158 }
3159 
3160 // --- SensorInputMapperTest ---
3161 
3162 class SensorInputMapperTest : public InputMapperTest {
3163 protected:
3164     static const int32_t ACCEL_RAW_MIN;
3165     static const int32_t ACCEL_RAW_MAX;
3166     static const int32_t ACCEL_RAW_FUZZ;
3167     static const int32_t ACCEL_RAW_FLAT;
3168     static const int32_t ACCEL_RAW_RESOLUTION;
3169 
3170     static const int32_t GYRO_RAW_MIN;
3171     static const int32_t GYRO_RAW_MAX;
3172     static const int32_t GYRO_RAW_FUZZ;
3173     static const int32_t GYRO_RAW_FLAT;
3174     static const int32_t GYRO_RAW_RESOLUTION;
3175 
3176     static const float GRAVITY_MS2_UNIT;
3177     static const float DEGREE_RADIAN_UNIT;
3178 
3179     void prepareAccelAxes();
3180     void prepareGyroAxes();
3181     void setAccelProperties();
3182     void setGyroProperties();
SetUp()3183     void SetUp() override { InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::SENSOR); }
3184 };
3185 
3186 const int32_t SensorInputMapperTest::ACCEL_RAW_MIN = -32768;
3187 const int32_t SensorInputMapperTest::ACCEL_RAW_MAX = 32768;
3188 const int32_t SensorInputMapperTest::ACCEL_RAW_FUZZ = 16;
3189 const int32_t SensorInputMapperTest::ACCEL_RAW_FLAT = 0;
3190 const int32_t SensorInputMapperTest::ACCEL_RAW_RESOLUTION = 8192;
3191 
3192 const int32_t SensorInputMapperTest::GYRO_RAW_MIN = -2097152;
3193 const int32_t SensorInputMapperTest::GYRO_RAW_MAX = 2097152;
3194 const int32_t SensorInputMapperTest::GYRO_RAW_FUZZ = 16;
3195 const int32_t SensorInputMapperTest::GYRO_RAW_FLAT = 0;
3196 const int32_t SensorInputMapperTest::GYRO_RAW_RESOLUTION = 1024;
3197 
3198 const float SensorInputMapperTest::GRAVITY_MS2_UNIT = 9.80665f;
3199 const float SensorInputMapperTest::DEGREE_RADIAN_UNIT = 0.0174533f;
3200 
prepareAccelAxes()3201 void SensorInputMapperTest::prepareAccelAxes() {
3202     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_X, ACCEL_RAW_MIN, ACCEL_RAW_MAX, ACCEL_RAW_FUZZ,
3203                                    ACCEL_RAW_FLAT, ACCEL_RAW_RESOLUTION);
3204     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_Y, ACCEL_RAW_MIN, ACCEL_RAW_MAX, ACCEL_RAW_FUZZ,
3205                                    ACCEL_RAW_FLAT, ACCEL_RAW_RESOLUTION);
3206     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_Z, ACCEL_RAW_MIN, ACCEL_RAW_MAX, ACCEL_RAW_FUZZ,
3207                                    ACCEL_RAW_FLAT, ACCEL_RAW_RESOLUTION);
3208 }
3209 
prepareGyroAxes()3210 void SensorInputMapperTest::prepareGyroAxes() {
3211     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_RX, GYRO_RAW_MIN, GYRO_RAW_MAX, GYRO_RAW_FUZZ,
3212                                    GYRO_RAW_FLAT, GYRO_RAW_RESOLUTION);
3213     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_RY, GYRO_RAW_MIN, GYRO_RAW_MAX, GYRO_RAW_FUZZ,
3214                                    GYRO_RAW_FLAT, GYRO_RAW_RESOLUTION);
3215     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_RZ, GYRO_RAW_MIN, GYRO_RAW_MAX, GYRO_RAW_FUZZ,
3216                                    GYRO_RAW_FLAT, GYRO_RAW_RESOLUTION);
3217 }
3218 
setAccelProperties()3219 void SensorInputMapperTest::setAccelProperties() {
3220     mFakeEventHub->addSensorAxis(EVENTHUB_ID, /* absCode */ 0, InputDeviceSensorType::ACCELEROMETER,
3221                                  /* sensorDataIndex */ 0);
3222     mFakeEventHub->addSensorAxis(EVENTHUB_ID, /* absCode */ 1, InputDeviceSensorType::ACCELEROMETER,
3223                                  /* sensorDataIndex */ 1);
3224     mFakeEventHub->addSensorAxis(EVENTHUB_ID, /* absCode */ 2, InputDeviceSensorType::ACCELEROMETER,
3225                                  /* sensorDataIndex */ 2);
3226     mFakeEventHub->setMscEvent(EVENTHUB_ID, MSC_TIMESTAMP);
3227     addConfigurationProperty("sensor.accelerometer.reportingMode", "0");
3228     addConfigurationProperty("sensor.accelerometer.maxDelay", "100000");
3229     addConfigurationProperty("sensor.accelerometer.minDelay", "5000");
3230     addConfigurationProperty("sensor.accelerometer.power", "1.5");
3231 }
3232 
setGyroProperties()3233 void SensorInputMapperTest::setGyroProperties() {
3234     mFakeEventHub->addSensorAxis(EVENTHUB_ID, /* absCode */ 3, InputDeviceSensorType::GYROSCOPE,
3235                                  /* sensorDataIndex */ 0);
3236     mFakeEventHub->addSensorAxis(EVENTHUB_ID, /* absCode */ 4, InputDeviceSensorType::GYROSCOPE,
3237                                  /* sensorDataIndex */ 1);
3238     mFakeEventHub->addSensorAxis(EVENTHUB_ID, /* absCode */ 5, InputDeviceSensorType::GYROSCOPE,
3239                                  /* sensorDataIndex */ 2);
3240     mFakeEventHub->setMscEvent(EVENTHUB_ID, MSC_TIMESTAMP);
3241     addConfigurationProperty("sensor.gyroscope.reportingMode", "0");
3242     addConfigurationProperty("sensor.gyroscope.maxDelay", "100000");
3243     addConfigurationProperty("sensor.gyroscope.minDelay", "5000");
3244     addConfigurationProperty("sensor.gyroscope.power", "0.8");
3245 }
3246 
TEST_F(SensorInputMapperTest,GetSources)3247 TEST_F(SensorInputMapperTest, GetSources) {
3248     SensorInputMapper& mapper = constructAndAddMapper<SensorInputMapper>();
3249 
3250     ASSERT_EQ(static_cast<uint32_t>(AINPUT_SOURCE_SENSOR), mapper.getSources());
3251 }
3252 
TEST_F(SensorInputMapperTest,ProcessAccelerometerSensor)3253 TEST_F(SensorInputMapperTest, ProcessAccelerometerSensor) {
3254     setAccelProperties();
3255     prepareAccelAxes();
3256     SensorInputMapper& mapper = constructAndAddMapper<SensorInputMapper>();
3257 
3258     ASSERT_TRUE(mapper.enableSensor(InputDeviceSensorType::ACCELEROMETER,
3259                                     std::chrono::microseconds(10000),
3260                                     std::chrono::microseconds(0)));
3261     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(EVENTHUB_ID));
3262     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_X, 20000);
3263     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_Y, -20000);
3264     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_Z, 40000);
3265     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_TIMESTAMP, 1000);
3266     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
3267 
3268     NotifySensorArgs args;
3269     std::vector<float> values = {20000.0f / ACCEL_RAW_RESOLUTION * GRAVITY_MS2_UNIT,
3270                                  -20000.0f / ACCEL_RAW_RESOLUTION * GRAVITY_MS2_UNIT,
3271                                  40000.0f / ACCEL_RAW_RESOLUTION * GRAVITY_MS2_UNIT};
3272 
3273     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifySensorWasCalled(&args));
3274     ASSERT_EQ(args.source, AINPUT_SOURCE_SENSOR);
3275     ASSERT_EQ(args.deviceId, DEVICE_ID);
3276     ASSERT_EQ(args.sensorType, InputDeviceSensorType::ACCELEROMETER);
3277     ASSERT_EQ(args.accuracy, InputDeviceSensorAccuracy::ACCURACY_HIGH);
3278     ASSERT_EQ(args.hwTimestamp, ARBITRARY_TIME);
3279     ASSERT_EQ(args.values, values);
3280     mapper.flushSensor(InputDeviceSensorType::ACCELEROMETER);
3281 }
3282 
TEST_F(SensorInputMapperTest,ProcessGyroscopeSensor)3283 TEST_F(SensorInputMapperTest, ProcessGyroscopeSensor) {
3284     setGyroProperties();
3285     prepareGyroAxes();
3286     SensorInputMapper& mapper = constructAndAddMapper<SensorInputMapper>();
3287 
3288     ASSERT_TRUE(mapper.enableSensor(InputDeviceSensorType::GYROSCOPE,
3289                                     std::chrono::microseconds(10000),
3290                                     std::chrono::microseconds(0)));
3291     ASSERT_TRUE(mFakeEventHub->isDeviceEnabled(EVENTHUB_ID));
3292     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_RX, 20000);
3293     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_RY, -20000);
3294     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_RZ, 40000);
3295     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_TIMESTAMP, 1000);
3296     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
3297 
3298     NotifySensorArgs args;
3299     std::vector<float> values = {20000.0f / GYRO_RAW_RESOLUTION * DEGREE_RADIAN_UNIT,
3300                                  -20000.0f / GYRO_RAW_RESOLUTION * DEGREE_RADIAN_UNIT,
3301                                  40000.0f / GYRO_RAW_RESOLUTION * DEGREE_RADIAN_UNIT};
3302 
3303     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifySensorWasCalled(&args));
3304     ASSERT_EQ(args.source, AINPUT_SOURCE_SENSOR);
3305     ASSERT_EQ(args.deviceId, DEVICE_ID);
3306     ASSERT_EQ(args.sensorType, InputDeviceSensorType::GYROSCOPE);
3307     ASSERT_EQ(args.accuracy, InputDeviceSensorAccuracy::ACCURACY_HIGH);
3308     ASSERT_EQ(args.hwTimestamp, ARBITRARY_TIME);
3309     ASSERT_EQ(args.values, values);
3310     mapper.flushSensor(InputDeviceSensorType::GYROSCOPE);
3311 }
3312 
3313 // --- KeyboardInputMapperTest ---
3314 
3315 class KeyboardInputMapperTest : public InputMapperTest {
3316 protected:
SetUp()3317     void SetUp() override {
3318         InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::KEYBOARD |
3319                                InputDeviceClass::ALPHAKEY);
3320     }
3321     const std::string UNIQUE_ID = "local:0";
3322     const KeyboardLayoutInfo DEVICE_KEYBOARD_LAYOUT_INFO = KeyboardLayoutInfo("en-US", "qwerty");
3323     void prepareDisplay(ui::Rotation orientation);
3324 
3325     void testDPadKeyRotation(KeyboardInputMapper& mapper, int32_t originalScanCode,
3326                              int32_t originalKeyCode, int32_t rotatedKeyCode,
3327                              ui::LogicalDisplayId displayId = ui::LogicalDisplayId::INVALID);
3328 };
3329 
3330 /* Similar to setDisplayInfoAndReconfigure, but pre-populates all parameters except for the
3331  * orientation.
3332  */
prepareDisplay(ui::Rotation orientation)3333 void KeyboardInputMapperTest::prepareDisplay(ui::Rotation orientation) {
3334     setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, orientation, UNIQUE_ID,
3335                                  NO_PORT, ViewportType::INTERNAL);
3336 }
3337 
testDPadKeyRotation(KeyboardInputMapper & mapper,int32_t originalScanCode,int32_t originalKeyCode,int32_t rotatedKeyCode,ui::LogicalDisplayId displayId)3338 void KeyboardInputMapperTest::testDPadKeyRotation(KeyboardInputMapper& mapper,
3339                                                   int32_t originalScanCode, int32_t originalKeyCode,
3340                                                   int32_t rotatedKeyCode,
3341                                                   ui::LogicalDisplayId displayId) {
3342     NotifyKeyArgs args;
3343 
3344     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, originalScanCode, 1);
3345     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3346     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3347     ASSERT_EQ(originalScanCode, args.scanCode);
3348     ASSERT_EQ(rotatedKeyCode, args.keyCode);
3349     ASSERT_EQ(displayId, args.displayId);
3350 
3351     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, originalScanCode, 0);
3352     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3353     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3354     ASSERT_EQ(originalScanCode, args.scanCode);
3355     ASSERT_EQ(rotatedKeyCode, args.keyCode);
3356     ASSERT_EQ(displayId, args.displayId);
3357 }
3358 
TEST_F(KeyboardInputMapperTest,GetSources)3359 TEST_F(KeyboardInputMapperTest, GetSources) {
3360     KeyboardInputMapper& mapper =
3361             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3362 
3363     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, mapper.getSources());
3364 }
3365 
TEST_F(KeyboardInputMapperTest,Process_SimpleKeyPress)3366 TEST_F(KeyboardInputMapperTest, Process_SimpleKeyPress) {
3367     const int32_t USAGE_A = 0x070004;
3368     const int32_t USAGE_UNKNOWN = 0x07ffff;
3369     mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, POLICY_FLAG_WAKE);
3370     mFakeEventHub->addKey(EVENTHUB_ID, 0, USAGE_A, AKEYCODE_A, POLICY_FLAG_WAKE);
3371     mFakeEventHub->addKey(EVENTHUB_ID, 0, KEY_NUMLOCK, AKEYCODE_NUM_LOCK, POLICY_FLAG_WAKE);
3372     mFakeEventHub->addKey(EVENTHUB_ID, 0, KEY_CAPSLOCK, AKEYCODE_CAPS_LOCK, POLICY_FLAG_WAKE);
3373     mFakeEventHub->addKey(EVENTHUB_ID, 0, KEY_SCROLLLOCK, AKEYCODE_SCROLL_LOCK, POLICY_FLAG_WAKE);
3374 
3375     KeyboardInputMapper& mapper =
3376             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3377     // Initial metastate is AMETA_NONE.
3378     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3379 
3380     // Key down by scan code.
3381     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_HOME, 1);
3382     NotifyKeyArgs args;
3383     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3384     ASSERT_EQ(DEVICE_ID, args.deviceId);
3385     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3386     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
3387     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3388     ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
3389     ASSERT_EQ(KEY_HOME, args.scanCode);
3390     ASSERT_EQ(AMETA_NONE, args.metaState);
3391     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3392     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3393     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
3394 
3395     // Key up by scan code.
3396     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_HOME, 0);
3397     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3398     ASSERT_EQ(DEVICE_ID, args.deviceId);
3399     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3400     ASSERT_EQ(ARBITRARY_TIME + 1, args.eventTime);
3401     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3402     ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
3403     ASSERT_EQ(KEY_HOME, args.scanCode);
3404     ASSERT_EQ(AMETA_NONE, args.metaState);
3405     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3406     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3407     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
3408 
3409     // Key down by usage code.
3410     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_SCAN, USAGE_A);
3411     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, 0, 1);
3412     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3413     ASSERT_EQ(DEVICE_ID, args.deviceId);
3414     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3415     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
3416     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3417     ASSERT_EQ(AKEYCODE_A, args.keyCode);
3418     ASSERT_EQ(0, args.scanCode);
3419     ASSERT_EQ(AMETA_NONE, args.metaState);
3420     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3421     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3422     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
3423 
3424     // Key up by usage code.
3425     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_SCAN, USAGE_A);
3426     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, 0, 0);
3427     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3428     ASSERT_EQ(DEVICE_ID, args.deviceId);
3429     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3430     ASSERT_EQ(ARBITRARY_TIME + 1, args.eventTime);
3431     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3432     ASSERT_EQ(AKEYCODE_A, args.keyCode);
3433     ASSERT_EQ(0, args.scanCode);
3434     ASSERT_EQ(AMETA_NONE, args.metaState);
3435     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3436     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
3437     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
3438 
3439     // Key down with unknown scan code or usage code.
3440     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_SCAN, USAGE_UNKNOWN);
3441     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UNKNOWN, 1);
3442     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3443     ASSERT_EQ(DEVICE_ID, args.deviceId);
3444     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3445     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
3446     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3447     ASSERT_EQ(0, args.keyCode);
3448     ASSERT_EQ(KEY_UNKNOWN, args.scanCode);
3449     ASSERT_EQ(AMETA_NONE, args.metaState);
3450     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3451     ASSERT_EQ(0U, args.policyFlags);
3452     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
3453 
3454     // Key up with unknown scan code or usage code.
3455     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_SCAN, USAGE_UNKNOWN);
3456     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_UNKNOWN, 0);
3457     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3458     ASSERT_EQ(DEVICE_ID, args.deviceId);
3459     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
3460     ASSERT_EQ(ARBITRARY_TIME + 1, args.eventTime);
3461     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3462     ASSERT_EQ(0, args.keyCode);
3463     ASSERT_EQ(KEY_UNKNOWN, args.scanCode);
3464     ASSERT_EQ(AMETA_NONE, args.metaState);
3465     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
3466     ASSERT_EQ(0U, args.policyFlags);
3467     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
3468 }
3469 
TEST_F(KeyboardInputMapperTest,Process_KeyRemapping)3470 TEST_F(KeyboardInputMapperTest, Process_KeyRemapping) {
3471     mFakeEventHub->addKey(EVENTHUB_ID, KEY_A, 0, AKEYCODE_A, 0);
3472     mFakeEventHub->addKey(EVENTHUB_ID, KEY_B, 0, AKEYCODE_B, 0);
3473     mFakeEventHub->addKeyRemapping(EVENTHUB_ID, AKEYCODE_A, AKEYCODE_B);
3474 
3475     KeyboardInputMapper& mapper =
3476             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3477 
3478     // Key down by scan code.
3479     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_A, 1);
3480     NotifyKeyArgs args;
3481     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3482     ASSERT_EQ(AKEYCODE_B, args.keyCode);
3483 
3484     // Key up by scan code.
3485     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_A, 0);
3486     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3487     ASSERT_EQ(AKEYCODE_B, args.keyCode);
3488 }
3489 
3490 /**
3491  * Ensure that the readTime is set to the time when the EV_KEY is received.
3492  */
TEST_F(KeyboardInputMapperTest,Process_SendsReadTime)3493 TEST_F(KeyboardInputMapperTest, Process_SendsReadTime) {
3494     mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, POLICY_FLAG_WAKE);
3495 
3496     KeyboardInputMapper& mapper =
3497             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3498     NotifyKeyArgs args;
3499 
3500     // Key down
3501     process(mapper, ARBITRARY_TIME, /*readTime=*/12, EV_KEY, KEY_HOME, 1);
3502     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3503     ASSERT_EQ(12, args.readTime);
3504 
3505     // Key up
3506     process(mapper, ARBITRARY_TIME, /*readTime=*/15, EV_KEY, KEY_HOME, 1);
3507     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3508     ASSERT_EQ(15, args.readTime);
3509 }
3510 
TEST_F(KeyboardInputMapperTest,Process_ShouldUpdateMetaState)3511 TEST_F(KeyboardInputMapperTest, Process_ShouldUpdateMetaState) {
3512     mFakeEventHub->addKey(EVENTHUB_ID, KEY_LEFTSHIFT, 0, AKEYCODE_SHIFT_LEFT, 0);
3513     mFakeEventHub->addKey(EVENTHUB_ID, KEY_A, 0, AKEYCODE_A, 0);
3514     mFakeEventHub->addKey(EVENTHUB_ID, 0, KEY_NUMLOCK, AKEYCODE_NUM_LOCK, 0);
3515     mFakeEventHub->addKey(EVENTHUB_ID, 0, KEY_CAPSLOCK, AKEYCODE_CAPS_LOCK, 0);
3516     mFakeEventHub->addKey(EVENTHUB_ID, 0, KEY_SCROLLLOCK, AKEYCODE_SCROLL_LOCK, 0);
3517 
3518     KeyboardInputMapper& mapper =
3519             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3520 
3521     // Initial metastate is AMETA_NONE.
3522     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3523 
3524     // Metakey down.
3525     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_LEFTSHIFT, 1);
3526     NotifyKeyArgs args;
3527     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3528     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
3529     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, mapper.getMetaState());
3530     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertUpdateGlobalMetaStateWasCalled());
3531 
3532     // Key down.
3533     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_A, 1);
3534     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3535     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
3536     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, mapper.getMetaState());
3537 
3538     // Key up.
3539     process(mapper, ARBITRARY_TIME + 2, READ_TIME, EV_KEY, KEY_A, 0);
3540     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3541     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
3542     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, mapper.getMetaState());
3543 
3544     // Metakey up.
3545     process(mapper, ARBITRARY_TIME + 3, READ_TIME, EV_KEY, KEY_LEFTSHIFT, 0);
3546     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3547     ASSERT_EQ(AMETA_NONE, args.metaState);
3548     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3549     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertUpdateGlobalMetaStateWasCalled());
3550 }
3551 
TEST_F(KeyboardInputMapperTest,Process_WhenNotOrientationAware_ShouldNotRotateDPad)3552 TEST_F(KeyboardInputMapperTest, Process_WhenNotOrientationAware_ShouldNotRotateDPad) {
3553     mFakeEventHub->addKey(EVENTHUB_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0);
3554     mFakeEventHub->addKey(EVENTHUB_ID, KEY_RIGHT, 0, AKEYCODE_DPAD_RIGHT, 0);
3555     mFakeEventHub->addKey(EVENTHUB_ID, KEY_DOWN, 0, AKEYCODE_DPAD_DOWN, 0);
3556     mFakeEventHub->addKey(EVENTHUB_ID, KEY_LEFT, 0, AKEYCODE_DPAD_LEFT, 0);
3557 
3558     KeyboardInputMapper& mapper =
3559             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3560 
3561     prepareDisplay(ui::ROTATION_90);
3562     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper,
3563             KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_UP));
3564     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper,
3565             KEY_RIGHT, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_RIGHT));
3566     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper,
3567             KEY_DOWN, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_DOWN));
3568     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper,
3569             KEY_LEFT, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_LEFT));
3570 }
3571 
TEST_F(KeyboardInputMapperTest,Process_WhenOrientationAware_ShouldRotateDPad)3572 TEST_F(KeyboardInputMapperTest, Process_WhenOrientationAware_ShouldRotateDPad) {
3573     mFakeEventHub->addKey(EVENTHUB_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0);
3574     mFakeEventHub->addKey(EVENTHUB_ID, KEY_RIGHT, 0, AKEYCODE_DPAD_RIGHT, 0);
3575     mFakeEventHub->addKey(EVENTHUB_ID, KEY_DOWN, 0, AKEYCODE_DPAD_DOWN, 0);
3576     mFakeEventHub->addKey(EVENTHUB_ID, KEY_LEFT, 0, AKEYCODE_DPAD_LEFT, 0);
3577 
3578     addConfigurationProperty("keyboard.orientationAware", "1");
3579     KeyboardInputMapper& mapper =
3580             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3581 
3582     prepareDisplay(ui::ROTATION_0);
3583     ASSERT_NO_FATAL_FAILURE(
3584             testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_UP, DISPLAY_ID));
3585     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_RIGHT, AKEYCODE_DPAD_RIGHT,
3586                                                 AKEYCODE_DPAD_RIGHT, DISPLAY_ID));
3587     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_DOWN, AKEYCODE_DPAD_DOWN,
3588                                                 AKEYCODE_DPAD_DOWN, DISPLAY_ID));
3589     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT,
3590                                                 AKEYCODE_DPAD_LEFT, DISPLAY_ID));
3591 
3592     clearViewports();
3593     prepareDisplay(ui::ROTATION_90);
3594     ASSERT_NO_FATAL_FAILURE(
3595             testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, DISPLAY_ID));
3596     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_RIGHT, AKEYCODE_DPAD_RIGHT,
3597                                                 AKEYCODE_DPAD_UP, DISPLAY_ID));
3598     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_DOWN, AKEYCODE_DPAD_DOWN,
3599                                                 AKEYCODE_DPAD_RIGHT, DISPLAY_ID));
3600     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT,
3601                                                 AKEYCODE_DPAD_DOWN, DISPLAY_ID));
3602 
3603     clearViewports();
3604     prepareDisplay(ui::ROTATION_180);
3605     ASSERT_NO_FATAL_FAILURE(
3606             testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_DOWN, DISPLAY_ID));
3607     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_RIGHT, AKEYCODE_DPAD_RIGHT,
3608                                                 AKEYCODE_DPAD_LEFT, DISPLAY_ID));
3609     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_DOWN, AKEYCODE_DPAD_DOWN,
3610                                                 AKEYCODE_DPAD_UP, DISPLAY_ID));
3611     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT,
3612                                                 AKEYCODE_DPAD_RIGHT, DISPLAY_ID));
3613 
3614     clearViewports();
3615     prepareDisplay(ui::ROTATION_270);
3616     ASSERT_NO_FATAL_FAILURE(
3617             testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_RIGHT, DISPLAY_ID));
3618     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_RIGHT, AKEYCODE_DPAD_RIGHT,
3619                                                 AKEYCODE_DPAD_DOWN, DISPLAY_ID));
3620     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_DOWN, AKEYCODE_DPAD_DOWN,
3621                                                 AKEYCODE_DPAD_LEFT, DISPLAY_ID));
3622     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT,
3623                                                 AKEYCODE_DPAD_UP, DISPLAY_ID));
3624 
3625     // Special case: if orientation changes while key is down, we still emit the same keycode
3626     // in the key up as we did in the key down.
3627     NotifyKeyArgs args;
3628     clearViewports();
3629     prepareDisplay(ui::ROTATION_270);
3630     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 1);
3631     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3632     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3633     ASSERT_EQ(KEY_UP, args.scanCode);
3634     ASSERT_EQ(AKEYCODE_DPAD_RIGHT, args.keyCode);
3635 
3636     clearViewports();
3637     prepareDisplay(ui::ROTATION_180);
3638     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 0);
3639     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3640     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3641     ASSERT_EQ(KEY_UP, args.scanCode);
3642     ASSERT_EQ(AKEYCODE_DPAD_RIGHT, args.keyCode);
3643 }
3644 
TEST_F(KeyboardInputMapperTest,DisplayIdConfigurationChange_NotOrientationAware)3645 TEST_F(KeyboardInputMapperTest, DisplayIdConfigurationChange_NotOrientationAware) {
3646     // If the keyboard is not orientation aware,
3647     // key events should not be associated with a specific display id
3648     mFakeEventHub->addKey(EVENTHUB_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0);
3649 
3650     KeyboardInputMapper& mapper =
3651             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3652     NotifyKeyArgs args;
3653 
3654     // Display id should be LogicalDisplayId::INVALID without any display configuration.
3655     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 1);
3656     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3657     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 0);
3658     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3659     ASSERT_EQ(ui::LogicalDisplayId::INVALID, args.displayId);
3660 
3661     prepareDisplay(ui::ROTATION_0);
3662     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 1);
3663     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3664     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 0);
3665     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3666     ASSERT_EQ(ui::LogicalDisplayId::INVALID, args.displayId);
3667 }
3668 
TEST_F(KeyboardInputMapperTest,DisplayIdConfigurationChange_OrientationAware)3669 TEST_F(KeyboardInputMapperTest, DisplayIdConfigurationChange_OrientationAware) {
3670     // If the keyboard is orientation aware,
3671     // key events should be associated with the internal viewport
3672     mFakeEventHub->addKey(EVENTHUB_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0);
3673 
3674     addConfigurationProperty("keyboard.orientationAware", "1");
3675     KeyboardInputMapper& mapper =
3676             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3677     NotifyKeyArgs args;
3678 
3679     // Display id should be LogicalDisplayId::INVALID without any display configuration.
3680     // ^--- already checked by the previous test
3681 
3682     setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
3683                                  UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
3684     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 1);
3685     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3686     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 0);
3687     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3688     ASSERT_EQ(DISPLAY_ID, args.displayId);
3689 
3690     constexpr ui::LogicalDisplayId newDisplayId = ui::LogicalDisplayId{2};
3691     clearViewports();
3692     setDisplayInfoAndReconfigure(newDisplayId, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
3693                                  UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
3694     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 1);
3695     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3696     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UP, 0);
3697     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3698     ASSERT_EQ(newDisplayId, args.displayId);
3699 }
3700 
TEST_F(KeyboardInputMapperTest,GetKeyCodeState)3701 TEST_F(KeyboardInputMapperTest, GetKeyCodeState) {
3702     KeyboardInputMapper& mapper =
3703             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3704 
3705     mFakeEventHub->setKeyCodeState(EVENTHUB_ID, AKEYCODE_A, 1);
3706     ASSERT_EQ(1, mapper.getKeyCodeState(AINPUT_SOURCE_ANY, AKEYCODE_A));
3707 
3708     mFakeEventHub->setKeyCodeState(EVENTHUB_ID, AKEYCODE_A, 0);
3709     ASSERT_EQ(0, mapper.getKeyCodeState(AINPUT_SOURCE_ANY, AKEYCODE_A));
3710 }
3711 
TEST_F(KeyboardInputMapperTest,GetKeyCodeForKeyLocation)3712 TEST_F(KeyboardInputMapperTest, GetKeyCodeForKeyLocation) {
3713     KeyboardInputMapper& mapper =
3714             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3715 
3716     mFakeEventHub->addKeyCodeMapping(EVENTHUB_ID, AKEYCODE_Y, AKEYCODE_Z);
3717     ASSERT_EQ(AKEYCODE_Z, mapper.getKeyCodeForKeyLocation(AKEYCODE_Y))
3718             << "If a mapping is available, the result is equal to the mapping";
3719 
3720     ASSERT_EQ(AKEYCODE_A, mapper.getKeyCodeForKeyLocation(AKEYCODE_A))
3721             << "If no mapping is available, the result is the key location";
3722 }
3723 
TEST_F(KeyboardInputMapperTest,GetScanCodeState)3724 TEST_F(KeyboardInputMapperTest, GetScanCodeState) {
3725     KeyboardInputMapper& mapper =
3726             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3727 
3728     mFakeEventHub->setScanCodeState(EVENTHUB_ID, KEY_A, 1);
3729     ASSERT_EQ(1, mapper.getScanCodeState(AINPUT_SOURCE_ANY, KEY_A));
3730 
3731     mFakeEventHub->setScanCodeState(EVENTHUB_ID, KEY_A, 0);
3732     ASSERT_EQ(0, mapper.getScanCodeState(AINPUT_SOURCE_ANY, KEY_A));
3733 }
3734 
TEST_F(KeyboardInputMapperTest,MarkSupportedKeyCodes)3735 TEST_F(KeyboardInputMapperTest, MarkSupportedKeyCodes) {
3736     KeyboardInputMapper& mapper =
3737             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3738 
3739     mFakeEventHub->addKey(EVENTHUB_ID, KEY_A, 0, AKEYCODE_A, 0);
3740 
3741     uint8_t flags[2] = { 0, 0 };
3742     ASSERT_TRUE(mapper.markSupportedKeyCodes(AINPUT_SOURCE_ANY, {AKEYCODE_A, AKEYCODE_B}, flags));
3743     ASSERT_TRUE(flags[0]);
3744     ASSERT_FALSE(flags[1]);
3745 }
3746 
TEST_F(KeyboardInputMapperTest,Process_LockedKeysShouldToggleMetaStateAndLeds)3747 TEST_F(KeyboardInputMapperTest, Process_LockedKeysShouldToggleMetaStateAndLeds) {
3748     mFakeEventHub->addLed(EVENTHUB_ID, LED_CAPSL, true /*initially on*/);
3749     mFakeEventHub->addLed(EVENTHUB_ID, LED_NUML, false /*initially off*/);
3750     mFakeEventHub->addLed(EVENTHUB_ID, LED_SCROLLL, false /*initially off*/);
3751     mFakeEventHub->addKey(EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
3752     mFakeEventHub->addKey(EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
3753     mFakeEventHub->addKey(EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
3754 
3755     KeyboardInputMapper& mapper =
3756             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3757     // Initial metastate is AMETA_NONE.
3758     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3759 
3760     // Initialization should have turned all of the lights off.
3761     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3762     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3763     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3764 
3765     // Toggle caps lock on.
3766     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 1);
3767     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 0);
3768     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3769     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3770     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3771     ASSERT_EQ(AMETA_CAPS_LOCK_ON, mapper.getMetaState());
3772 
3773     // Toggle num lock on.
3774     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 1);
3775     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 0);
3776     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3777     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3778     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3779     ASSERT_EQ(AMETA_CAPS_LOCK_ON | AMETA_NUM_LOCK_ON, mapper.getMetaState());
3780 
3781     // Toggle caps lock off.
3782     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 1);
3783     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 0);
3784     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3785     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3786     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3787     ASSERT_EQ(AMETA_NUM_LOCK_ON, mapper.getMetaState());
3788 
3789     // Toggle scroll lock on.
3790     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 1);
3791     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 0);
3792     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3793     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3794     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3795     ASSERT_EQ(AMETA_NUM_LOCK_ON | AMETA_SCROLL_LOCK_ON, mapper.getMetaState());
3796 
3797     // Toggle num lock off.
3798     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 1);
3799     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 0);
3800     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3801     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3802     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3803     ASSERT_EQ(AMETA_SCROLL_LOCK_ON, mapper.getMetaState());
3804 
3805     // Toggle scroll lock off.
3806     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 1);
3807     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 0);
3808     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3809     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3810     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3811     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3812 }
3813 
TEST_F(KeyboardInputMapperTest,NoMetaStateWhenMetaKeysNotPresent)3814 TEST_F(KeyboardInputMapperTest, NoMetaStateWhenMetaKeysNotPresent) {
3815     mFakeEventHub->addKey(EVENTHUB_ID, BTN_A, 0, AKEYCODE_BUTTON_A, 0);
3816     mFakeEventHub->addKey(EVENTHUB_ID, BTN_B, 0, AKEYCODE_BUTTON_B, 0);
3817     mFakeEventHub->addKey(EVENTHUB_ID, BTN_X, 0, AKEYCODE_BUTTON_X, 0);
3818     mFakeEventHub->addKey(EVENTHUB_ID, BTN_Y, 0, AKEYCODE_BUTTON_Y, 0);
3819 
3820     KeyboardInputMapper& mapper =
3821             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3822 
3823     // Meta state should be AMETA_NONE after reset
3824     std::list<NotifyArgs> unused = mapper.reset(ARBITRARY_TIME);
3825     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3826     // Meta state should be AMETA_NONE with update, as device doesn't have the keys.
3827     mapper.updateMetaState(AKEYCODE_NUM_LOCK);
3828     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3829 
3830     NotifyKeyArgs args;
3831     // Press button "A"
3832     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_A, 1);
3833     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3834     ASSERT_EQ(AMETA_NONE, args.metaState);
3835     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3836     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
3837     ASSERT_EQ(AKEYCODE_BUTTON_A, args.keyCode);
3838 
3839     // Button up.
3840     process(mapper, ARBITRARY_TIME + 2, READ_TIME, EV_KEY, BTN_A, 0);
3841     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
3842     ASSERT_EQ(AMETA_NONE, args.metaState);
3843     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3844     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
3845     ASSERT_EQ(AKEYCODE_BUTTON_A, args.keyCode);
3846 }
3847 
TEST_F(KeyboardInputMapperTest,Configure_AssignsDisplayPort)3848 TEST_F(KeyboardInputMapperTest, Configure_AssignsDisplayPort) {
3849     // keyboard 1.
3850     mFakeEventHub->addKey(EVENTHUB_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0);
3851     mFakeEventHub->addKey(EVENTHUB_ID, KEY_RIGHT, 0, AKEYCODE_DPAD_RIGHT, 0);
3852     mFakeEventHub->addKey(EVENTHUB_ID, KEY_DOWN, 0, AKEYCODE_DPAD_DOWN, 0);
3853     mFakeEventHub->addKey(EVENTHUB_ID, KEY_LEFT, 0, AKEYCODE_DPAD_LEFT, 0);
3854 
3855     // keyboard 2.
3856     const std::string USB2 = "USB2";
3857     const std::string DEVICE_NAME2 = "KEYBOARD2";
3858     constexpr int32_t SECOND_DEVICE_ID = DEVICE_ID + 1;
3859     constexpr int32_t SECOND_EVENTHUB_ID = EVENTHUB_ID + 1;
3860     std::shared_ptr<InputDevice> device2 =
3861             newDevice(SECOND_DEVICE_ID, DEVICE_NAME2, USB2, SECOND_EVENTHUB_ID,
3862                       ftl::Flags<InputDeviceClass>(0));
3863 
3864     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0);
3865     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_RIGHT, 0, AKEYCODE_DPAD_RIGHT, 0);
3866     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_DOWN, 0, AKEYCODE_DPAD_DOWN, 0);
3867     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_LEFT, 0, AKEYCODE_DPAD_LEFT, 0);
3868 
3869     KeyboardInputMapper& mapper =
3870             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3871 
3872     device2->addEmptyEventHubDevice(SECOND_EVENTHUB_ID);
3873     KeyboardInputMapper& mapper2 =
3874             device2->constructAndAddMapper<KeyboardInputMapper>(SECOND_EVENTHUB_ID,
3875                                                                 mFakePolicy
3876                                                                         ->getReaderConfiguration(),
3877                                                                 AINPUT_SOURCE_KEYBOARD);
3878     std::list<NotifyArgs> unused =
3879             device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3880                                /*changes=*/{});
3881     unused += device2->reset(ARBITRARY_TIME);
3882 
3883     // Prepared displays and associated info.
3884     constexpr uint8_t hdmi1 = 0;
3885     constexpr uint8_t hdmi2 = 1;
3886     const std::string SECONDARY_UNIQUE_ID = "local:1";
3887 
3888     mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi1);
3889     mFakePolicy->addInputPortAssociation(USB2, hdmi2);
3890 
3891     // No associated display viewport found, should disable the device.
3892     unused += device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3893                                  InputReaderConfiguration::Change::DISPLAY_INFO);
3894     ASSERT_FALSE(device2->isEnabled());
3895 
3896     // Prepare second display.
3897     constexpr ui::LogicalDisplayId newDisplayId = ui::LogicalDisplayId{2};
3898     setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
3899                                  UNIQUE_ID, hdmi1, ViewportType::INTERNAL);
3900     setDisplayInfoAndReconfigure(newDisplayId, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
3901                                  SECONDARY_UNIQUE_ID, hdmi2, ViewportType::EXTERNAL);
3902     // Default device will reconfigure above, need additional reconfiguration for another device.
3903     unused += device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3904                                  InputReaderConfiguration::Change::DISPLAY_INFO);
3905 
3906     // Device should be enabled after the associated display is found.
3907     ASSERT_TRUE(mDevice->isEnabled());
3908     ASSERT_TRUE(device2->isEnabled());
3909 
3910     // Test pad key events
3911     ASSERT_NO_FATAL_FAILURE(
3912             testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_UP, DISPLAY_ID));
3913     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_RIGHT, AKEYCODE_DPAD_RIGHT,
3914                                                 AKEYCODE_DPAD_RIGHT, DISPLAY_ID));
3915     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_DOWN, AKEYCODE_DPAD_DOWN,
3916                                                 AKEYCODE_DPAD_DOWN, DISPLAY_ID));
3917     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT,
3918                                                 AKEYCODE_DPAD_LEFT, DISPLAY_ID));
3919 
3920     ASSERT_NO_FATAL_FAILURE(
3921             testDPadKeyRotation(mapper2, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_UP, newDisplayId));
3922     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper2, KEY_RIGHT, AKEYCODE_DPAD_RIGHT,
3923                                                 AKEYCODE_DPAD_RIGHT, newDisplayId));
3924     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper2, KEY_DOWN, AKEYCODE_DPAD_DOWN,
3925                                                 AKEYCODE_DPAD_DOWN, newDisplayId));
3926     ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper2, KEY_LEFT, AKEYCODE_DPAD_LEFT,
3927                                                 AKEYCODE_DPAD_LEFT, newDisplayId));
3928 }
3929 
TEST_F(KeyboardInputMapperTest,Process_LockedKeysShouldToggleAfterReattach)3930 TEST_F(KeyboardInputMapperTest, Process_LockedKeysShouldToggleAfterReattach) {
3931     mFakeEventHub->addLed(EVENTHUB_ID, LED_CAPSL, true /*initially on*/);
3932     mFakeEventHub->addLed(EVENTHUB_ID, LED_NUML, false /*initially off*/);
3933     mFakeEventHub->addLed(EVENTHUB_ID, LED_SCROLLL, false /*initially off*/);
3934     mFakeEventHub->addKey(EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
3935     mFakeEventHub->addKey(EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
3936     mFakeEventHub->addKey(EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
3937 
3938     KeyboardInputMapper& mapper =
3939             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
3940     // Initial metastate is AMETA_NONE.
3941     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
3942 
3943     // Initialization should have turned all of the lights off.
3944     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3945     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3946     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3947 
3948     // Toggle caps lock on.
3949     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 1);
3950     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 0);
3951     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
3952     ASSERT_EQ(AMETA_CAPS_LOCK_ON, mapper.getMetaState());
3953 
3954     // Toggle num lock on.
3955     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 1);
3956     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 0);
3957     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
3958     ASSERT_EQ(AMETA_CAPS_LOCK_ON | AMETA_NUM_LOCK_ON, mapper.getMetaState());
3959 
3960     // Toggle scroll lock on.
3961     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 1);
3962     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 0);
3963     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
3964     ASSERT_EQ(AMETA_CAPS_LOCK_ON | AMETA_NUM_LOCK_ON | AMETA_SCROLL_LOCK_ON, mapper.getMetaState());
3965 
3966     mFakeEventHub->removeDevice(EVENTHUB_ID);
3967     mReader->loopOnce();
3968 
3969     // keyboard 2 should default toggle keys.
3970     const std::string USB2 = "USB2";
3971     const std::string DEVICE_NAME2 = "KEYBOARD2";
3972     constexpr int32_t SECOND_DEVICE_ID = DEVICE_ID + 1;
3973     constexpr int32_t SECOND_EVENTHUB_ID = EVENTHUB_ID + 1;
3974     std::shared_ptr<InputDevice> device2 =
3975             newDevice(SECOND_DEVICE_ID, DEVICE_NAME2, USB2, SECOND_EVENTHUB_ID,
3976                       ftl::Flags<InputDeviceClass>(0));
3977     mFakeEventHub->addLed(SECOND_EVENTHUB_ID, LED_CAPSL, true /*initially on*/);
3978     mFakeEventHub->addLed(SECOND_EVENTHUB_ID, LED_NUML, false /*initially off*/);
3979     mFakeEventHub->addLed(SECOND_EVENTHUB_ID, LED_SCROLLL, false /*initially off*/);
3980     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
3981     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
3982     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
3983 
3984     device2->addEmptyEventHubDevice(SECOND_EVENTHUB_ID);
3985     KeyboardInputMapper& mapper2 =
3986             device2->constructAndAddMapper<KeyboardInputMapper>(SECOND_EVENTHUB_ID,
3987                                                                 mFakePolicy
3988                                                                         ->getReaderConfiguration(),
3989                                                                 AINPUT_SOURCE_KEYBOARD);
3990     std::list<NotifyArgs> unused =
3991             device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
3992                                /*changes=*/{});
3993     unused += device2->reset(ARBITRARY_TIME);
3994 
3995     ASSERT_TRUE(mFakeEventHub->getLedState(SECOND_EVENTHUB_ID, LED_CAPSL));
3996     ASSERT_TRUE(mFakeEventHub->getLedState(SECOND_EVENTHUB_ID, LED_NUML));
3997     ASSERT_TRUE(mFakeEventHub->getLedState(SECOND_EVENTHUB_ID, LED_SCROLLL));
3998     ASSERT_EQ(AMETA_CAPS_LOCK_ON | AMETA_NUM_LOCK_ON | AMETA_SCROLL_LOCK_ON,
3999               mapper2.getMetaState());
4000 }
4001 
TEST_F(KeyboardInputMapperTest,Process_toggleCapsLockState)4002 TEST_F(KeyboardInputMapperTest, Process_toggleCapsLockState) {
4003     mFakeEventHub->addKey(EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
4004     mFakeEventHub->addKey(EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
4005     mFakeEventHub->addKey(EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
4006 
4007     // Suppose we have two mappers. (DPAD + KEYBOARD)
4008     constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_DPAD);
4009     KeyboardInputMapper& mapper =
4010             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
4011     // Initial metastate is AMETA_NONE.
4012     ASSERT_EQ(AMETA_NONE, mapper.getMetaState());
4013 
4014     mReader->toggleCapsLockState(DEVICE_ID);
4015     ASSERT_EQ(AMETA_CAPS_LOCK_ON, mapper.getMetaState());
4016 }
4017 
TEST_F(KeyboardInputMapperTest,Process_LockedKeysShouldToggleInMultiDevices)4018 TEST_F(KeyboardInputMapperTest, Process_LockedKeysShouldToggleInMultiDevices) {
4019     // keyboard 1.
4020     mFakeEventHub->addLed(EVENTHUB_ID, LED_CAPSL, true /*initially on*/);
4021     mFakeEventHub->addLed(EVENTHUB_ID, LED_NUML, false /*initially off*/);
4022     mFakeEventHub->addLed(EVENTHUB_ID, LED_SCROLLL, false /*initially off*/);
4023     mFakeEventHub->addKey(EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
4024     mFakeEventHub->addKey(EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
4025     mFakeEventHub->addKey(EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
4026 
4027     KeyboardInputMapper& mapper1 =
4028             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
4029 
4030     // keyboard 2.
4031     const std::string USB2 = "USB2";
4032     const std::string DEVICE_NAME2 = "KEYBOARD2";
4033     constexpr int32_t SECOND_DEVICE_ID = DEVICE_ID + 1;
4034     constexpr int32_t SECOND_EVENTHUB_ID = EVENTHUB_ID + 1;
4035     std::shared_ptr<InputDevice> device2 =
4036             newDevice(SECOND_DEVICE_ID, DEVICE_NAME2, USB2, SECOND_EVENTHUB_ID,
4037                       ftl::Flags<InputDeviceClass>(0));
4038     mFakeEventHub->addLed(SECOND_EVENTHUB_ID, LED_CAPSL, true /*initially on*/);
4039     mFakeEventHub->addLed(SECOND_EVENTHUB_ID, LED_NUML, false /*initially off*/);
4040     mFakeEventHub->addLed(SECOND_EVENTHUB_ID, LED_SCROLLL, false /*initially off*/);
4041     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_CAPSLOCK, 0, AKEYCODE_CAPS_LOCK, 0);
4042     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_NUMLOCK, 0, AKEYCODE_NUM_LOCK, 0);
4043     mFakeEventHub->addKey(SECOND_EVENTHUB_ID, KEY_SCROLLLOCK, 0, AKEYCODE_SCROLL_LOCK, 0);
4044 
4045     device2->addEmptyEventHubDevice(SECOND_EVENTHUB_ID);
4046     KeyboardInputMapper& mapper2 =
4047             device2->constructAndAddMapper<KeyboardInputMapper>(SECOND_EVENTHUB_ID,
4048                                                                 mFakePolicy
4049                                                                         ->getReaderConfiguration(),
4050                                                                 AINPUT_SOURCE_KEYBOARD);
4051     std::list<NotifyArgs> unused =
4052             device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
4053                                /*changes=*/{});
4054     unused += device2->reset(ARBITRARY_TIME);
4055 
4056     // Initial metastate is AMETA_NONE.
4057     ASSERT_EQ(AMETA_NONE, mapper1.getMetaState());
4058     ASSERT_EQ(AMETA_NONE, mapper2.getMetaState());
4059 
4060     // Toggle num lock on and off.
4061     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 1);
4062     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 0);
4063     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
4064     ASSERT_EQ(AMETA_NUM_LOCK_ON, mapper1.getMetaState());
4065     ASSERT_EQ(AMETA_NUM_LOCK_ON, mapper2.getMetaState());
4066 
4067     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 1);
4068     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_NUMLOCK, 0);
4069     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_NUML));
4070     ASSERT_EQ(AMETA_NONE, mapper1.getMetaState());
4071     ASSERT_EQ(AMETA_NONE, mapper2.getMetaState());
4072 
4073     // Toggle caps lock on and off.
4074     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 1);
4075     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 0);
4076     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
4077     ASSERT_EQ(AMETA_CAPS_LOCK_ON, mapper1.getMetaState());
4078     ASSERT_EQ(AMETA_CAPS_LOCK_ON, mapper2.getMetaState());
4079 
4080     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 1);
4081     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_CAPSLOCK, 0);
4082     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_CAPSL));
4083     ASSERT_EQ(AMETA_NONE, mapper1.getMetaState());
4084     ASSERT_EQ(AMETA_NONE, mapper2.getMetaState());
4085 
4086     // Toggle scroll lock on and off.
4087     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 1);
4088     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 0);
4089     ASSERT_TRUE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
4090     ASSERT_EQ(AMETA_SCROLL_LOCK_ON, mapper1.getMetaState());
4091     ASSERT_EQ(AMETA_SCROLL_LOCK_ON, mapper2.getMetaState());
4092 
4093     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 1);
4094     process(mapper1, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_SCROLLLOCK, 0);
4095     ASSERT_FALSE(mFakeEventHub->getLedState(EVENTHUB_ID, LED_SCROLLL));
4096     ASSERT_EQ(AMETA_NONE, mapper1.getMetaState());
4097     ASSERT_EQ(AMETA_NONE, mapper2.getMetaState());
4098 }
4099 
TEST_F(KeyboardInputMapperTest,Process_DisabledDevice)4100 TEST_F(KeyboardInputMapperTest, Process_DisabledDevice) {
4101     const int32_t USAGE_A = 0x070004;
4102     mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, POLICY_FLAG_WAKE);
4103     mFakeEventHub->addKey(EVENTHUB_ID, 0, USAGE_A, AKEYCODE_A, POLICY_FLAG_WAKE);
4104 
4105     KeyboardInputMapper& mapper =
4106             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
4107     // Key down by scan code.
4108     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_HOME, 1);
4109     NotifyKeyArgs args;
4110     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4111     ASSERT_EQ(DEVICE_ID, args.deviceId);
4112     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
4113     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
4114     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
4115     ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
4116     ASSERT_EQ(KEY_HOME, args.scanCode);
4117     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
4118 
4119     // Disable device, it should synthesize cancellation events for down events.
4120     mFakePolicy->addDisabledDevice(DEVICE_ID);
4121     configureDevice(InputReaderConfiguration::Change::ENABLED_STATE);
4122 
4123     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4124     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
4125     ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
4126     ASSERT_EQ(KEY_HOME, args.scanCode);
4127     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_CANCELED, args.flags);
4128 }
4129 
TEST_F(KeyboardInputMapperTest,Configure_AssignKeyboardLayoutInfo)4130 TEST_F(KeyboardInputMapperTest, Configure_AssignKeyboardLayoutInfo) {
4131     constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
4132     std::list<NotifyArgs> unused =
4133             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
4134                                /*changes=*/{});
4135 
4136     uint32_t generation = mReader->getContext()->getGeneration();
4137     mFakePolicy->addKeyboardLayoutAssociation(DEVICE_LOCATION, DEVICE_KEYBOARD_LAYOUT_INFO);
4138 
4139     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
4140                                  InputReaderConfiguration::Change::KEYBOARD_LAYOUT_ASSOCIATION);
4141 
4142     InputDeviceInfo deviceInfo = mDevice->getDeviceInfo();
4143     ASSERT_EQ(DEVICE_KEYBOARD_LAYOUT_INFO.languageTag,
4144               deviceInfo.getKeyboardLayoutInfo()->languageTag);
4145     ASSERT_EQ(DEVICE_KEYBOARD_LAYOUT_INFO.layoutType,
4146               deviceInfo.getKeyboardLayoutInfo()->layoutType);
4147     ASSERT_TRUE(mReader->getContext()->getGeneration() != generation);
4148 
4149     // Call change layout association with the same values: Generation shouldn't change
4150     generation = mReader->getContext()->getGeneration();
4151     mFakePolicy->addKeyboardLayoutAssociation(DEVICE_LOCATION, DEVICE_KEYBOARD_LAYOUT_INFO);
4152     unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
4153                                  InputReaderConfiguration::Change::KEYBOARD_LAYOUT_ASSOCIATION);
4154     ASSERT_TRUE(mReader->getContext()->getGeneration() == generation);
4155 }
4156 
TEST_F(KeyboardInputMapperTest,LayoutInfoCorrectlyMapped)4157 TEST_F(KeyboardInputMapperTest, LayoutInfoCorrectlyMapped) {
4158     mFakeEventHub->setRawLayoutInfo(EVENTHUB_ID,
4159                                     RawLayoutInfo{.languageTag = "en", .layoutType = "extended"});
4160 
4161     // Configuration
4162     constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
4163     InputReaderConfiguration config;
4164     std::list<NotifyArgs> unused = mDevice->configure(ARBITRARY_TIME, config, /*changes=*/{});
4165 
4166     ASSERT_EQ("en", mDevice->getDeviceInfo().getKeyboardLayoutInfo()->languageTag);
4167     ASSERT_EQ("extended", mDevice->getDeviceInfo().getKeyboardLayoutInfo()->layoutType);
4168 }
4169 
TEST_F(KeyboardInputMapperTest,Process_GesureEventToSetFlagKeepTouchMode)4170 TEST_F(KeyboardInputMapperTest, Process_GesureEventToSetFlagKeepTouchMode) {
4171     mFakeEventHub->addKey(EVENTHUB_ID, KEY_LEFT, 0, AKEYCODE_DPAD_LEFT, POLICY_FLAG_GESTURE);
4172     KeyboardInputMapper& mapper =
4173             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
4174     NotifyKeyArgs args;
4175 
4176     // Key down
4177     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_LEFT, 1);
4178     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4179     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_KEEP_TOUCH_MODE, args.flags);
4180 }
4181 
4182 // --- KeyboardInputMapperTest_ExternalAlphabeticDevice ---
4183 
4184 class KeyboardInputMapperTest_ExternalAlphabeticDevice : public InputMapperTest {
4185 protected:
SetUp()4186     void SetUp() override {
4187         InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::KEYBOARD |
4188                                InputDeviceClass::ALPHAKEY | InputDeviceClass::EXTERNAL);
4189     }
4190 };
4191 
4192 // --- KeyboardInputMapperTest_ExternalNonAlphabeticDevice ---
4193 
4194 class KeyboardInputMapperTest_ExternalNonAlphabeticDevice : public InputMapperTest {
4195 protected:
SetUp()4196     void SetUp() override {
4197         InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::KEYBOARD |
4198                                InputDeviceClass::EXTERNAL);
4199     }
4200 };
4201 
TEST_F(KeyboardInputMapperTest_ExternalAlphabeticDevice,WakeBehavior_AlphabeticKeyboard)4202 TEST_F(KeyboardInputMapperTest_ExternalAlphabeticDevice, WakeBehavior_AlphabeticKeyboard) {
4203     // For external devices, keys will trigger wake on key down. Media keys should also trigger
4204     // wake if triggered from external devices.
4205 
4206     mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, 0);
4207     mFakeEventHub->addKey(EVENTHUB_ID, KEY_PLAY, 0, AKEYCODE_MEDIA_PLAY, 0);
4208     mFakeEventHub->addKey(EVENTHUB_ID, KEY_PLAYPAUSE, 0, AKEYCODE_MEDIA_PLAY_PAUSE,
4209                           POLICY_FLAG_WAKE);
4210 
4211     KeyboardInputMapper& mapper =
4212             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
4213 
4214     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_HOME, 1);
4215     NotifyKeyArgs args;
4216     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4217     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
4218 
4219     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_HOME, 0);
4220     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4221     ASSERT_EQ(uint32_t(0), args.policyFlags);
4222 
4223     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_PLAY, 1);
4224     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4225     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
4226 
4227     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_PLAY, 0);
4228     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4229     ASSERT_EQ(uint32_t(0), args.policyFlags);
4230 
4231     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_PLAYPAUSE, 1);
4232     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4233     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
4234 
4235     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_PLAYPAUSE, 0);
4236     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4237     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
4238 }
4239 
TEST_F(KeyboardInputMapperTest_ExternalNonAlphabeticDevice,WakeBehavior_NonAlphabeticKeyboard)4240 TEST_F(KeyboardInputMapperTest_ExternalNonAlphabeticDevice, WakeBehavior_NonAlphabeticKeyboard) {
4241     // For external devices, keys will trigger wake on key down. Media keys should not trigger
4242     // wake if triggered from external non-alphaebtic keyboard (e.g. headsets).
4243 
4244     mFakeEventHub->addKey(EVENTHUB_ID, KEY_PLAY, 0, AKEYCODE_MEDIA_PLAY, 0);
4245     mFakeEventHub->addKey(EVENTHUB_ID, KEY_PLAYPAUSE, 0, AKEYCODE_MEDIA_PLAY_PAUSE,
4246                           POLICY_FLAG_WAKE);
4247 
4248     KeyboardInputMapper& mapper =
4249             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
4250 
4251     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_PLAY, 1);
4252     NotifyKeyArgs args;
4253     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4254     ASSERT_EQ(uint32_t(0), args.policyFlags);
4255 
4256     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_PLAY, 0);
4257     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4258     ASSERT_EQ(uint32_t(0), args.policyFlags);
4259 
4260     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_PLAYPAUSE, 1);
4261     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4262     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
4263 
4264     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_PLAYPAUSE, 0);
4265     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4266     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
4267 }
4268 
TEST_F(KeyboardInputMapperTest_ExternalAlphabeticDevice,DoNotWakeByDefaultBehavior)4269 TEST_F(KeyboardInputMapperTest_ExternalAlphabeticDevice, DoNotWakeByDefaultBehavior) {
4270     // Tv Remote key's wake behavior is prescribed by the keylayout file.
4271 
4272     mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, POLICY_FLAG_WAKE);
4273     mFakeEventHub->addKey(EVENTHUB_ID, KEY_DOWN, 0, AKEYCODE_DPAD_DOWN, 0);
4274     mFakeEventHub->addKey(EVENTHUB_ID, KEY_PLAY, 0, AKEYCODE_MEDIA_PLAY, POLICY_FLAG_WAKE);
4275 
4276     addConfigurationProperty("keyboard.doNotWakeByDefault", "1");
4277     KeyboardInputMapper& mapper =
4278             constructAndAddMapper<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD);
4279 
4280     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_HOME, 1);
4281     NotifyKeyArgs args;
4282     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4283     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
4284 
4285     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_HOME, 0);
4286     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4287     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
4288 
4289     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_DOWN, 1);
4290     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4291     ASSERT_EQ(uint32_t(0), args.policyFlags);
4292 
4293     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_DOWN, 0);
4294     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4295     ASSERT_EQ(uint32_t(0), args.policyFlags);
4296 
4297     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_PLAY, 1);
4298     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4299     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
4300 
4301     process(mapper, ARBITRARY_TIME + 1, READ_TIME, EV_KEY, KEY_PLAY, 0);
4302     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4303     ASSERT_EQ(POLICY_FLAG_WAKE, args.policyFlags);
4304 }
4305 
4306 // --- TouchInputMapperTest ---
4307 
4308 class TouchInputMapperTest : public InputMapperTest {
4309 protected:
4310     static const int32_t RAW_X_MIN;
4311     static const int32_t RAW_X_MAX;
4312     static const int32_t RAW_Y_MIN;
4313     static const int32_t RAW_Y_MAX;
4314     static const int32_t RAW_TOUCH_MIN;
4315     static const int32_t RAW_TOUCH_MAX;
4316     static const int32_t RAW_TOOL_MIN;
4317     static const int32_t RAW_TOOL_MAX;
4318     static const int32_t RAW_PRESSURE_MIN;
4319     static const int32_t RAW_PRESSURE_MAX;
4320     static const int32_t RAW_ORIENTATION_MIN;
4321     static const int32_t RAW_ORIENTATION_MAX;
4322     static const int32_t RAW_DISTANCE_MIN;
4323     static const int32_t RAW_DISTANCE_MAX;
4324     static const int32_t RAW_TILT_MIN;
4325     static const int32_t RAW_TILT_MAX;
4326     static const int32_t RAW_ID_MIN;
4327     static const int32_t RAW_ID_MAX;
4328     static const int32_t RAW_SLOT_MIN;
4329     static const int32_t RAW_SLOT_MAX;
4330     static const float X_PRECISION;
4331     static const float Y_PRECISION;
4332     static const float X_PRECISION_VIRTUAL;
4333     static const float Y_PRECISION_VIRTUAL;
4334 
4335     static const float GEOMETRIC_SCALE;
4336     static const TouchAffineTransformation AFFINE_TRANSFORM;
4337 
4338     static const VirtualKeyDefinition VIRTUAL_KEYS[2];
4339 
4340     const std::string UNIQUE_ID = "local:0";
4341     const std::string SECONDARY_UNIQUE_ID = "local:1";
4342 
4343     enum Axes {
4344         POSITION = 1 << 0,
4345         TOUCH = 1 << 1,
4346         TOOL = 1 << 2,
4347         PRESSURE = 1 << 3,
4348         ORIENTATION = 1 << 4,
4349         MINOR = 1 << 5,
4350         ID = 1 << 6,
4351         DISTANCE = 1 << 7,
4352         TILT = 1 << 8,
4353         SLOT = 1 << 9,
4354         TOOL_TYPE = 1 << 10,
4355     };
4356 
4357     void prepareDisplay(ui::Rotation orientation, std::optional<uint8_t> port = NO_PORT);
4358     void prepareSecondaryDisplay(ViewportType type, std::optional<uint8_t> port = NO_PORT);
4359     void prepareVirtualDisplay(ui::Rotation orientation);
4360     void prepareVirtualKeys();
4361     void prepareLocationCalibration();
4362     int32_t toRawX(float displayX);
4363     int32_t toRawY(float displayY);
4364     int32_t toRotatedRawX(float displayX);
4365     int32_t toRotatedRawY(float displayY);
4366     float toCookedX(float rawX, float rawY);
4367     float toCookedY(float rawX, float rawY);
4368     float toDisplayX(int32_t rawX);
4369     float toDisplayX(int32_t rawX, int32_t displayWidth);
4370     float toDisplayY(int32_t rawY);
4371     float toDisplayY(int32_t rawY, int32_t displayHeight);
4372 
4373 };
4374 
4375 const int32_t TouchInputMapperTest::RAW_X_MIN = 25;
4376 const int32_t TouchInputMapperTest::RAW_X_MAX = 1019;
4377 const int32_t TouchInputMapperTest::RAW_Y_MIN = 30;
4378 const int32_t TouchInputMapperTest::RAW_Y_MAX = 1009;
4379 const int32_t TouchInputMapperTest::RAW_TOUCH_MIN = 0;
4380 const int32_t TouchInputMapperTest::RAW_TOUCH_MAX = 31;
4381 const int32_t TouchInputMapperTest::RAW_TOOL_MIN = 0;
4382 const int32_t TouchInputMapperTest::RAW_TOOL_MAX = 15;
4383 const int32_t TouchInputMapperTest::RAW_PRESSURE_MIN = 0;
4384 const int32_t TouchInputMapperTest::RAW_PRESSURE_MAX = 255;
4385 const int32_t TouchInputMapperTest::RAW_ORIENTATION_MIN = -7;
4386 const int32_t TouchInputMapperTest::RAW_ORIENTATION_MAX = 7;
4387 const int32_t TouchInputMapperTest::RAW_DISTANCE_MIN = 0;
4388 const int32_t TouchInputMapperTest::RAW_DISTANCE_MAX = 7;
4389 const int32_t TouchInputMapperTest::RAW_TILT_MIN = 0;
4390 const int32_t TouchInputMapperTest::RAW_TILT_MAX = 150;
4391 const int32_t TouchInputMapperTest::RAW_ID_MIN = 0;
4392 const int32_t TouchInputMapperTest::RAW_ID_MAX = 9;
4393 const int32_t TouchInputMapperTest::RAW_SLOT_MIN = 0;
4394 const int32_t TouchInputMapperTest::RAW_SLOT_MAX = 9;
4395 const float TouchInputMapperTest::X_PRECISION = float(RAW_X_MAX - RAW_X_MIN + 1) / DISPLAY_WIDTH;
4396 const float TouchInputMapperTest::Y_PRECISION = float(RAW_Y_MAX - RAW_Y_MIN + 1) / DISPLAY_HEIGHT;
4397 const float TouchInputMapperTest::X_PRECISION_VIRTUAL =
4398         float(RAW_X_MAX - RAW_X_MIN + 1) / VIRTUAL_DISPLAY_WIDTH;
4399 const float TouchInputMapperTest::Y_PRECISION_VIRTUAL =
4400         float(RAW_Y_MAX - RAW_Y_MIN + 1) / VIRTUAL_DISPLAY_HEIGHT;
4401 const TouchAffineTransformation TouchInputMapperTest::AFFINE_TRANSFORM =
4402         TouchAffineTransformation(1, -2, 3, -4, 5, -6);
4403 
4404 const float TouchInputMapperTest::GEOMETRIC_SCALE =
4405         avg(float(DISPLAY_WIDTH) / (RAW_X_MAX - RAW_X_MIN + 1),
4406                 float(DISPLAY_HEIGHT) / (RAW_Y_MAX - RAW_Y_MIN + 1));
4407 
4408 const VirtualKeyDefinition TouchInputMapperTest::VIRTUAL_KEYS[2] = {
4409         { KEY_HOME, 60, DISPLAY_HEIGHT + 15, 20, 20 },
4410         { KEY_MENU, DISPLAY_HEIGHT - 60, DISPLAY_WIDTH + 15, 20, 20 },
4411 };
4412 
prepareDisplay(ui::Rotation orientation,std::optional<uint8_t> port)4413 void TouchInputMapperTest::prepareDisplay(ui::Rotation orientation, std::optional<uint8_t> port) {
4414     setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, orientation, UNIQUE_ID,
4415                                  port, ViewportType::INTERNAL);
4416 }
4417 
prepareSecondaryDisplay(ViewportType type,std::optional<uint8_t> port)4418 void TouchInputMapperTest::prepareSecondaryDisplay(ViewportType type, std::optional<uint8_t> port) {
4419     setDisplayInfoAndReconfigure(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
4420                                  ui::ROTATION_0, SECONDARY_UNIQUE_ID, port, type);
4421 }
4422 
prepareVirtualDisplay(ui::Rotation orientation)4423 void TouchInputMapperTest::prepareVirtualDisplay(ui::Rotation orientation) {
4424     setDisplayInfoAndReconfigure(VIRTUAL_DISPLAY_ID, VIRTUAL_DISPLAY_WIDTH, VIRTUAL_DISPLAY_HEIGHT,
4425                                  orientation, VIRTUAL_DISPLAY_UNIQUE_ID, NO_PORT,
4426                                  ViewportType::VIRTUAL);
4427 }
4428 
prepareVirtualKeys()4429 void TouchInputMapperTest::prepareVirtualKeys() {
4430     mFakeEventHub->addVirtualKeyDefinition(EVENTHUB_ID, VIRTUAL_KEYS[0]);
4431     mFakeEventHub->addVirtualKeyDefinition(EVENTHUB_ID, VIRTUAL_KEYS[1]);
4432     mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, POLICY_FLAG_WAKE);
4433     mFakeEventHub->addKey(EVENTHUB_ID, KEY_MENU, 0, AKEYCODE_MENU, POLICY_FLAG_WAKE);
4434 }
4435 
prepareLocationCalibration()4436 void TouchInputMapperTest::prepareLocationCalibration() {
4437     mFakePolicy->setTouchAffineTransformation(AFFINE_TRANSFORM);
4438 }
4439 
toRawX(float displayX)4440 int32_t TouchInputMapperTest::toRawX(float displayX) {
4441     return int32_t(displayX * (RAW_X_MAX - RAW_X_MIN + 1) / DISPLAY_WIDTH + RAW_X_MIN);
4442 }
4443 
toRawY(float displayY)4444 int32_t TouchInputMapperTest::toRawY(float displayY) {
4445     return int32_t(displayY * (RAW_Y_MAX - RAW_Y_MIN + 1) / DISPLAY_HEIGHT + RAW_Y_MIN);
4446 }
4447 
toRotatedRawX(float displayX)4448 int32_t TouchInputMapperTest::toRotatedRawX(float displayX) {
4449     return int32_t(displayX * (RAW_X_MAX - RAW_X_MIN + 1) / DISPLAY_HEIGHT + RAW_X_MIN);
4450 }
4451 
toRotatedRawY(float displayY)4452 int32_t TouchInputMapperTest::toRotatedRawY(float displayY) {
4453     return int32_t(displayY * (RAW_Y_MAX - RAW_Y_MIN + 1) / DISPLAY_WIDTH + RAW_Y_MIN);
4454 }
4455 
toCookedX(float rawX,float rawY)4456 float TouchInputMapperTest::toCookedX(float rawX, float rawY) {
4457     AFFINE_TRANSFORM.applyTo(rawX, rawY);
4458     return rawX;
4459 }
4460 
toCookedY(float rawX,float rawY)4461 float TouchInputMapperTest::toCookedY(float rawX, float rawY) {
4462     AFFINE_TRANSFORM.applyTo(rawX, rawY);
4463     return rawY;
4464 }
4465 
toDisplayX(int32_t rawX)4466 float TouchInputMapperTest::toDisplayX(int32_t rawX) {
4467     return toDisplayX(rawX, DISPLAY_WIDTH);
4468 }
4469 
toDisplayX(int32_t rawX,int32_t displayWidth)4470 float TouchInputMapperTest::toDisplayX(int32_t rawX, int32_t displayWidth) {
4471     return float(rawX - RAW_X_MIN) * displayWidth / (RAW_X_MAX - RAW_X_MIN + 1);
4472 }
4473 
toDisplayY(int32_t rawY)4474 float TouchInputMapperTest::toDisplayY(int32_t rawY) {
4475     return toDisplayY(rawY, DISPLAY_HEIGHT);
4476 }
4477 
toDisplayY(int32_t rawY,int32_t displayHeight)4478 float TouchInputMapperTest::toDisplayY(int32_t rawY, int32_t displayHeight) {
4479     return float(rawY - RAW_Y_MIN) * displayHeight / (RAW_Y_MAX - RAW_Y_MIN + 1);
4480 }
4481 
4482 
4483 // --- SingleTouchInputMapperTest ---
4484 
4485 class SingleTouchInputMapperTest : public TouchInputMapperTest {
4486 protected:
4487     void prepareButtons();
4488     void prepareAxes(int axes);
4489 
4490     void processDown(SingleTouchInputMapper& mapper, int32_t x, int32_t y);
4491     void processMove(SingleTouchInputMapper& mapper, int32_t x, int32_t y);
4492     void processUp(SingleTouchInputMapper& mappery);
4493     void processPressure(SingleTouchInputMapper& mapper, int32_t pressure);
4494     void processToolMajor(SingleTouchInputMapper& mapper, int32_t toolMajor);
4495     void processDistance(SingleTouchInputMapper& mapper, int32_t distance);
4496     void processTilt(SingleTouchInputMapper& mapper, int32_t tiltX, int32_t tiltY);
4497     void processKey(SingleTouchInputMapper& mapper, int32_t code, int32_t value);
4498     void processSync(SingleTouchInputMapper& mapper);
4499 };
4500 
prepareButtons()4501 void SingleTouchInputMapperTest::prepareButtons() {
4502     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOUCH, 0, AKEYCODE_UNKNOWN, 0);
4503 }
4504 
prepareAxes(int axes)4505 void SingleTouchInputMapperTest::prepareAxes(int axes) {
4506     if (axes & POSITION) {
4507         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_X, RAW_X_MIN, RAW_X_MAX, 0, 0);
4508         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_Y, RAW_Y_MIN, RAW_Y_MAX, 0, 0);
4509     }
4510     if (axes & PRESSURE) {
4511         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_PRESSURE, RAW_PRESSURE_MIN,
4512                                        RAW_PRESSURE_MAX, 0, 0);
4513     }
4514     if (axes & TOOL) {
4515         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_TOOL_WIDTH, RAW_TOOL_MIN, RAW_TOOL_MAX, 0,
4516                                        0);
4517     }
4518     if (axes & DISTANCE) {
4519         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_DISTANCE, RAW_DISTANCE_MIN,
4520                                        RAW_DISTANCE_MAX, 0, 0);
4521     }
4522     if (axes & TILT) {
4523         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_TILT_X, RAW_TILT_MIN, RAW_TILT_MAX, 0, 0);
4524         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_TILT_Y, RAW_TILT_MIN, RAW_TILT_MAX, 0, 0);
4525     }
4526 }
4527 
processDown(SingleTouchInputMapper & mapper,int32_t x,int32_t y)4528 void SingleTouchInputMapperTest::processDown(SingleTouchInputMapper& mapper, int32_t x, int32_t y) {
4529     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_TOUCH, 1);
4530     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_X, x);
4531     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_Y, y);
4532 }
4533 
processMove(SingleTouchInputMapper & mapper,int32_t x,int32_t y)4534 void SingleTouchInputMapperTest::processMove(SingleTouchInputMapper& mapper, int32_t x, int32_t y) {
4535     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_X, x);
4536     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_Y, y);
4537 }
4538 
processUp(SingleTouchInputMapper & mapper)4539 void SingleTouchInputMapperTest::processUp(SingleTouchInputMapper& mapper) {
4540     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_TOUCH, 0);
4541 }
4542 
processPressure(SingleTouchInputMapper & mapper,int32_t pressure)4543 void SingleTouchInputMapperTest::processPressure(SingleTouchInputMapper& mapper, int32_t pressure) {
4544     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_PRESSURE, pressure);
4545 }
4546 
processToolMajor(SingleTouchInputMapper & mapper,int32_t toolMajor)4547 void SingleTouchInputMapperTest::processToolMajor(SingleTouchInputMapper& mapper,
4548                                                   int32_t toolMajor) {
4549     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_TOOL_WIDTH, toolMajor);
4550 }
4551 
processDistance(SingleTouchInputMapper & mapper,int32_t distance)4552 void SingleTouchInputMapperTest::processDistance(SingleTouchInputMapper& mapper, int32_t distance) {
4553     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_DISTANCE, distance);
4554 }
4555 
processTilt(SingleTouchInputMapper & mapper,int32_t tiltX,int32_t tiltY)4556 void SingleTouchInputMapperTest::processTilt(SingleTouchInputMapper& mapper, int32_t tiltX,
4557                                              int32_t tiltY) {
4558     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_TILT_X, tiltX);
4559     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_TILT_Y, tiltY);
4560 }
4561 
processKey(SingleTouchInputMapper & mapper,int32_t code,int32_t value)4562 void SingleTouchInputMapperTest::processKey(SingleTouchInputMapper& mapper, int32_t code,
4563                                             int32_t value) {
4564     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, code, value);
4565 }
4566 
processSync(SingleTouchInputMapper & mapper)4567 void SingleTouchInputMapperTest::processSync(SingleTouchInputMapper& mapper) {
4568     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
4569 }
4570 
TEST_F(SingleTouchInputMapperTest,GetSources_WhenDeviceTypeIsNotSpecifiedAndNotACursor_ReturnsPointer)4571 TEST_F(SingleTouchInputMapperTest, GetSources_WhenDeviceTypeIsNotSpecifiedAndNotACursor_ReturnsPointer) {
4572     prepareButtons();
4573     prepareAxes(POSITION);
4574     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
4575 
4576     ASSERT_EQ(AINPUT_SOURCE_MOUSE, mapper.getSources());
4577 }
4578 
TEST_F(SingleTouchInputMapperTest,GetSources_WhenDeviceTypeIsTouchScreen_ReturnsTouchScreen)4579 TEST_F(SingleTouchInputMapperTest, GetSources_WhenDeviceTypeIsTouchScreen_ReturnsTouchScreen) {
4580     prepareButtons();
4581     prepareAxes(POSITION);
4582     addConfigurationProperty("touch.deviceType", "touchScreen");
4583     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
4584 
4585     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, mapper.getSources());
4586 }
4587 
TEST_F(SingleTouchInputMapperTest,GetKeyCodeState)4588 TEST_F(SingleTouchInputMapperTest, GetKeyCodeState) {
4589     addConfigurationProperty("touch.deviceType", "touchScreen");
4590     prepareDisplay(ui::ROTATION_0);
4591     prepareButtons();
4592     prepareAxes(POSITION);
4593     prepareVirtualKeys();
4594     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
4595 
4596     // Unknown key.
4597     ASSERT_EQ(AKEY_STATE_UNKNOWN, mapper.getKeyCodeState(AINPUT_SOURCE_ANY, AKEYCODE_A));
4598 
4599     // Virtual key is down.
4600     int32_t x = toRawX(VIRTUAL_KEYS[0].centerX);
4601     int32_t y = toRawY(VIRTUAL_KEYS[0].centerY);
4602     processDown(mapper, x, y);
4603     processSync(mapper);
4604     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled());
4605 
4606     ASSERT_EQ(AKEY_STATE_VIRTUAL, mapper.getKeyCodeState(AINPUT_SOURCE_ANY, AKEYCODE_HOME));
4607 
4608     // Virtual key is up.
4609     processUp(mapper);
4610     processSync(mapper);
4611     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled());
4612 
4613     ASSERT_EQ(AKEY_STATE_UP, mapper.getKeyCodeState(AINPUT_SOURCE_ANY, AKEYCODE_HOME));
4614 }
4615 
TEST_F(SingleTouchInputMapperTest,GetScanCodeState)4616 TEST_F(SingleTouchInputMapperTest, GetScanCodeState) {
4617     addConfigurationProperty("touch.deviceType", "touchScreen");
4618     prepareDisplay(ui::ROTATION_0);
4619     prepareButtons();
4620     prepareAxes(POSITION);
4621     prepareVirtualKeys();
4622     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
4623 
4624     // Unknown key.
4625     ASSERT_EQ(AKEY_STATE_UNKNOWN, mapper.getScanCodeState(AINPUT_SOURCE_ANY, KEY_A));
4626 
4627     // Virtual key is down.
4628     int32_t x = toRawX(VIRTUAL_KEYS[0].centerX);
4629     int32_t y = toRawY(VIRTUAL_KEYS[0].centerY);
4630     processDown(mapper, x, y);
4631     processSync(mapper);
4632     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled());
4633 
4634     ASSERT_EQ(AKEY_STATE_VIRTUAL, mapper.getScanCodeState(AINPUT_SOURCE_ANY, KEY_HOME));
4635 
4636     // Virtual key is up.
4637     processUp(mapper);
4638     processSync(mapper);
4639     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled());
4640 
4641     ASSERT_EQ(AKEY_STATE_UP, mapper.getScanCodeState(AINPUT_SOURCE_ANY, KEY_HOME));
4642 }
4643 
TEST_F(SingleTouchInputMapperTest,MarkSupportedKeyCodes)4644 TEST_F(SingleTouchInputMapperTest, MarkSupportedKeyCodes) {
4645     addConfigurationProperty("touch.deviceType", "touchScreen");
4646     prepareDisplay(ui::ROTATION_0);
4647     prepareButtons();
4648     prepareAxes(POSITION);
4649     prepareVirtualKeys();
4650     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
4651 
4652     uint8_t flags[2] = { 0, 0 };
4653     ASSERT_TRUE(
4654             mapper.markSupportedKeyCodes(AINPUT_SOURCE_ANY, {AKEYCODE_HOME, AKEYCODE_A}, flags));
4655     ASSERT_TRUE(flags[0]);
4656     ASSERT_FALSE(flags[1]);
4657 }
4658 
TEST_F(SingleTouchInputMapperTest,Process_WhenVirtualKeyIsPressedAndReleasedNormally_SendsKeyDownAndKeyUp)4659 TEST_F(SingleTouchInputMapperTest, Process_WhenVirtualKeyIsPressedAndReleasedNormally_SendsKeyDownAndKeyUp) {
4660     addConfigurationProperty("touch.deviceType", "touchScreen");
4661     prepareDisplay(ui::ROTATION_0);
4662     prepareButtons();
4663     prepareAxes(POSITION);
4664     prepareVirtualKeys();
4665     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
4666 
4667     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
4668 
4669     NotifyKeyArgs args;
4670 
4671     // Press virtual key.
4672     int32_t x = toRawX(VIRTUAL_KEYS[0].centerX);
4673     int32_t y = toRawY(VIRTUAL_KEYS[0].centerY);
4674     processDown(mapper, x, y);
4675     processSync(mapper);
4676 
4677     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4678     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
4679     ASSERT_EQ(DEVICE_ID, args.deviceId);
4680     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
4681     ASSERT_EQ(POLICY_FLAG_VIRTUAL, args.policyFlags);
4682     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
4683     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY, args.flags);
4684     ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
4685     ASSERT_EQ(KEY_HOME, args.scanCode);
4686     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
4687     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
4688 
4689     // Release virtual key.
4690     processUp(mapper);
4691     processSync(mapper);
4692 
4693     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
4694     ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
4695     ASSERT_EQ(DEVICE_ID, args.deviceId);
4696     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
4697     ASSERT_EQ(POLICY_FLAG_VIRTUAL, args.policyFlags);
4698     ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
4699     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY, args.flags);
4700     ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
4701     ASSERT_EQ(KEY_HOME, args.scanCode);
4702     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, args.metaState);
4703     ASSERT_EQ(ARBITRARY_TIME, args.downTime);
4704 
4705     // Should not have sent any motions.
4706     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
4707 }
4708 
TEST_F(SingleTouchInputMapperTest,Process_WhenVirtualKeyIsPressedAndMovedOutOfBounds_SendsKeyDownAndKeyCancel)4709 TEST_F(SingleTouchInputMapperTest, Process_WhenVirtualKeyIsPressedAndMovedOutOfBounds_SendsKeyDownAndKeyCancel) {
4710     addConfigurationProperty("touch.deviceType", "touchScreen");
4711     prepareDisplay(ui::ROTATION_0);
4712     prepareButtons();
4713     prepareAxes(POSITION);
4714     prepareVirtualKeys();
4715     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
4716 
4717     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
4718 
4719     NotifyKeyArgs keyArgs;
4720 
4721     // Press virtual key.
4722     int32_t x = toRawX(VIRTUAL_KEYS[0].centerX);
4723     int32_t y = toRawY(VIRTUAL_KEYS[0].centerY);
4724     processDown(mapper, x, y);
4725     processSync(mapper);
4726 
4727     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
4728     ASSERT_EQ(ARBITRARY_TIME, keyArgs.eventTime);
4729     ASSERT_EQ(DEVICE_ID, keyArgs.deviceId);
4730     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, keyArgs.source);
4731     ASSERT_EQ(POLICY_FLAG_VIRTUAL, keyArgs.policyFlags);
4732     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
4733     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY, keyArgs.flags);
4734     ASSERT_EQ(AKEYCODE_HOME, keyArgs.keyCode);
4735     ASSERT_EQ(KEY_HOME, keyArgs.scanCode);
4736     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, keyArgs.metaState);
4737     ASSERT_EQ(ARBITRARY_TIME, keyArgs.downTime);
4738 
4739     // Move out of bounds.  This should generate a cancel and a pointer down since we moved
4740     // into the display area.
4741     y -= 100;
4742     processMove(mapper, x, y);
4743     processSync(mapper);
4744 
4745     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
4746     ASSERT_EQ(ARBITRARY_TIME, keyArgs.eventTime);
4747     ASSERT_EQ(DEVICE_ID, keyArgs.deviceId);
4748     ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, keyArgs.source);
4749     ASSERT_EQ(POLICY_FLAG_VIRTUAL, keyArgs.policyFlags);
4750     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
4751     ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4752             | AKEY_EVENT_FLAG_CANCELED, keyArgs.flags);
4753     ASSERT_EQ(AKEYCODE_HOME, keyArgs.keyCode);
4754     ASSERT_EQ(KEY_HOME, keyArgs.scanCode);
4755     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, keyArgs.metaState);
4756     ASSERT_EQ(ARBITRARY_TIME, keyArgs.downTime);
4757 
4758     NotifyMotionArgs motionArgs;
4759     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4760     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
4761     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
4762     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
4763     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
4764     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
4765     ASSERT_EQ(0, motionArgs.flags);
4766     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
4767     ASSERT_EQ(0, motionArgs.buttonState);
4768     ASSERT_EQ(0, motionArgs.edgeFlags);
4769     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
4770     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
4771     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
4772     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
4773             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
4774     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
4775     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
4776     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
4777 
4778     // Keep moving out of bounds.  Should generate a pointer move.
4779     y -= 50;
4780     processMove(mapper, x, y);
4781     processSync(mapper);
4782 
4783     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4784     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
4785     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
4786     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
4787     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
4788     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
4789     ASSERT_EQ(0, motionArgs.flags);
4790     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
4791     ASSERT_EQ(0, motionArgs.buttonState);
4792     ASSERT_EQ(0, motionArgs.edgeFlags);
4793     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
4794     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
4795     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
4796     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
4797             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
4798     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
4799     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
4800     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
4801 
4802     // Release out of bounds.  Should generate a pointer up.
4803     processUp(mapper);
4804     processSync(mapper);
4805 
4806     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4807     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
4808     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
4809     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
4810     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
4811     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
4812     ASSERT_EQ(0, motionArgs.flags);
4813     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
4814     ASSERT_EQ(0, motionArgs.buttonState);
4815     ASSERT_EQ(0, motionArgs.edgeFlags);
4816     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
4817     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
4818     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
4819     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
4820             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
4821     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
4822     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
4823     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
4824 
4825     // Should not have sent any more keys or motions.
4826     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
4827     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
4828 }
4829 
TEST_F(SingleTouchInputMapperTest,Process_WhenTouchStartsOutsideDisplayAndMovesIn_SendsDownAsTouchEntersDisplay)4830 TEST_F(SingleTouchInputMapperTest, Process_WhenTouchStartsOutsideDisplayAndMovesIn_SendsDownAsTouchEntersDisplay) {
4831     addConfigurationProperty("touch.deviceType", "touchScreen");
4832     prepareDisplay(ui::ROTATION_0);
4833     prepareButtons();
4834     prepareAxes(POSITION);
4835     prepareVirtualKeys();
4836     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
4837 
4838     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
4839 
4840     NotifyMotionArgs motionArgs;
4841 
4842     // Initially go down out of bounds.
4843     int32_t x = -10;
4844     int32_t y = -10;
4845     processDown(mapper, x, y);
4846     processSync(mapper);
4847 
4848     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
4849 
4850     // Move into the display area.  Should generate a pointer down.
4851     x = 50;
4852     y = 75;
4853     processMove(mapper, x, y);
4854     processSync(mapper);
4855 
4856     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4857     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
4858     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
4859     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
4860     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
4861     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
4862     ASSERT_EQ(0, motionArgs.flags);
4863     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
4864     ASSERT_EQ(0, motionArgs.buttonState);
4865     ASSERT_EQ(0, motionArgs.edgeFlags);
4866     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
4867     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
4868     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
4869     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
4870             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
4871     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
4872     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
4873     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
4874 
4875     // Release.  Should generate a pointer up.
4876     processUp(mapper);
4877     processSync(mapper);
4878 
4879     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4880     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
4881     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
4882     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
4883     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
4884     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
4885     ASSERT_EQ(0, motionArgs.flags);
4886     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
4887     ASSERT_EQ(0, motionArgs.buttonState);
4888     ASSERT_EQ(0, motionArgs.edgeFlags);
4889     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
4890     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
4891     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
4892     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
4893             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
4894     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
4895     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
4896     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
4897 
4898     // Should not have sent any more keys or motions.
4899     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
4900     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
4901 }
4902 
TEST_F(SingleTouchInputMapperTest,Process_NormalSingleTouchGesture_VirtualDisplay)4903 TEST_F(SingleTouchInputMapperTest, Process_NormalSingleTouchGesture_VirtualDisplay) {
4904     addConfigurationProperty("touch.deviceType", "touchScreen");
4905     addConfigurationProperty("touch.displayId", VIRTUAL_DISPLAY_UNIQUE_ID);
4906 
4907     prepareVirtualDisplay(ui::ROTATION_0);
4908     prepareButtons();
4909     prepareAxes(POSITION);
4910     prepareVirtualKeys();
4911     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
4912 
4913     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
4914 
4915     NotifyMotionArgs motionArgs;
4916 
4917     // Down.
4918     int32_t x = 100;
4919     int32_t y = 125;
4920     processDown(mapper, x, y);
4921     processSync(mapper);
4922 
4923     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4924     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
4925     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
4926     ASSERT_EQ(VIRTUAL_DISPLAY_ID, motionArgs.displayId);
4927     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
4928     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
4929     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
4930     ASSERT_EQ(0, motionArgs.flags);
4931     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
4932     ASSERT_EQ(0, motionArgs.buttonState);
4933     ASSERT_EQ(0, motionArgs.edgeFlags);
4934     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
4935     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
4936     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
4937     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
4938             toDisplayX(x, VIRTUAL_DISPLAY_WIDTH), toDisplayY(y, VIRTUAL_DISPLAY_HEIGHT),
4939             1, 0, 0, 0, 0, 0, 0, 0));
4940     ASSERT_NEAR(X_PRECISION_VIRTUAL, motionArgs.xPrecision, EPSILON);
4941     ASSERT_NEAR(Y_PRECISION_VIRTUAL, motionArgs.yPrecision, EPSILON);
4942     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
4943 
4944     // Move.
4945     x += 50;
4946     y += 75;
4947     processMove(mapper, x, y);
4948     processSync(mapper);
4949 
4950     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4951     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
4952     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
4953     ASSERT_EQ(VIRTUAL_DISPLAY_ID, motionArgs.displayId);
4954     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
4955     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
4956     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
4957     ASSERT_EQ(0, motionArgs.flags);
4958     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
4959     ASSERT_EQ(0, motionArgs.buttonState);
4960     ASSERT_EQ(0, motionArgs.edgeFlags);
4961     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
4962     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
4963     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
4964     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
4965             toDisplayX(x, VIRTUAL_DISPLAY_WIDTH), toDisplayY(y, VIRTUAL_DISPLAY_HEIGHT),
4966             1, 0, 0, 0, 0, 0, 0, 0));
4967     ASSERT_NEAR(X_PRECISION_VIRTUAL, motionArgs.xPrecision, EPSILON);
4968     ASSERT_NEAR(Y_PRECISION_VIRTUAL, motionArgs.yPrecision, EPSILON);
4969     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
4970 
4971     // Up.
4972     processUp(mapper);
4973     processSync(mapper);
4974 
4975     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
4976     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
4977     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
4978     ASSERT_EQ(VIRTUAL_DISPLAY_ID, motionArgs.displayId);
4979     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
4980     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
4981     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
4982     ASSERT_EQ(0, motionArgs.flags);
4983     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
4984     ASSERT_EQ(0, motionArgs.buttonState);
4985     ASSERT_EQ(0, motionArgs.edgeFlags);
4986     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
4987     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
4988     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
4989     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
4990             toDisplayX(x, VIRTUAL_DISPLAY_WIDTH), toDisplayY(y, VIRTUAL_DISPLAY_HEIGHT),
4991             1, 0, 0, 0, 0, 0, 0, 0));
4992     ASSERT_NEAR(X_PRECISION_VIRTUAL, motionArgs.xPrecision, EPSILON);
4993     ASSERT_NEAR(Y_PRECISION_VIRTUAL, motionArgs.yPrecision, EPSILON);
4994     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
4995 
4996     // Should not have sent any more keys or motions.
4997     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
4998     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
4999 }
5000 
TEST_F(SingleTouchInputMapperTest,Process_NormalSingleTouchGesture)5001 TEST_F(SingleTouchInputMapperTest, Process_NormalSingleTouchGesture) {
5002     addConfigurationProperty("touch.deviceType", "touchScreen");
5003     prepareDisplay(ui::ROTATION_0);
5004     prepareButtons();
5005     prepareAxes(POSITION);
5006     prepareVirtualKeys();
5007     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5008 
5009     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
5010 
5011     NotifyMotionArgs motionArgs;
5012 
5013     // Down.
5014     int32_t x = 100;
5015     int32_t y = 125;
5016     processDown(mapper, x, y);
5017     processSync(mapper);
5018 
5019     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5020     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5021     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5022     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5023     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5024     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
5025     ASSERT_EQ(0, motionArgs.flags);
5026     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5027     ASSERT_EQ(0, motionArgs.buttonState);
5028     ASSERT_EQ(0, motionArgs.edgeFlags);
5029     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5030     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5031     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5032     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5033             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
5034     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
5035     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
5036     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5037 
5038     // Move.
5039     x += 50;
5040     y += 75;
5041     processMove(mapper, x, y);
5042     processSync(mapper);
5043 
5044     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5045     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5046     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5047     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5048     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5049     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5050     ASSERT_EQ(0, motionArgs.flags);
5051     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5052     ASSERT_EQ(0, motionArgs.buttonState);
5053     ASSERT_EQ(0, motionArgs.edgeFlags);
5054     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5055     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5056     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5057     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5058             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
5059     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
5060     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
5061     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5062 
5063     // Up.
5064     processUp(mapper);
5065     processSync(mapper);
5066 
5067     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5068     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
5069     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
5070     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
5071     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
5072     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
5073     ASSERT_EQ(0, motionArgs.flags);
5074     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
5075     ASSERT_EQ(0, motionArgs.buttonState);
5076     ASSERT_EQ(0, motionArgs.edgeFlags);
5077     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
5078     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
5079     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5080     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5081             toDisplayX(x), toDisplayY(y), 1, 0, 0, 0, 0, 0, 0, 0));
5082     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
5083     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
5084     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
5085 
5086     // Should not have sent any more keys or motions.
5087     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
5088     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
5089 }
5090 
TEST_F(SingleTouchInputMapperTest,Process_WhenOrientationAware_DoesNotRotateMotions)5091 TEST_F(SingleTouchInputMapperTest, Process_WhenOrientationAware_DoesNotRotateMotions) {
5092     addConfigurationProperty("touch.deviceType", "touchScreen");
5093     prepareButtons();
5094     prepareAxes(POSITION);
5095     // InputReader works in the un-rotated coordinate space, so orientation-aware devices do not
5096     // need to be rotated. Touchscreens are orientation-aware by default.
5097     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5098 
5099     NotifyMotionArgs args;
5100 
5101     // Rotation 90.
5102     prepareDisplay(ui::ROTATION_90);
5103     processDown(mapper, toRawX(50), toRawY(75));
5104     processSync(mapper);
5105 
5106     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5107     ASSERT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5108     ASSERT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5109 
5110     processUp(mapper);
5111     processSync(mapper);
5112     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5113 }
5114 
TEST_F(SingleTouchInputMapperTest,Process_WhenNotOrientationAware_RotatesMotions)5115 TEST_F(SingleTouchInputMapperTest, Process_WhenNotOrientationAware_RotatesMotions) {
5116     addConfigurationProperty("touch.deviceType", "touchScreen");
5117     prepareButtons();
5118     prepareAxes(POSITION);
5119     // Since InputReader works in the un-rotated coordinate space, only devices that are not
5120     // orientation-aware are affected by display rotation.
5121     addConfigurationProperty("touch.orientationAware", "0");
5122     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5123 
5124     NotifyMotionArgs args;
5125 
5126     // Rotation 0.
5127     clearViewports();
5128     prepareDisplay(ui::ROTATION_0);
5129     processDown(mapper, toRawX(50), toRawY(75));
5130     processSync(mapper);
5131 
5132     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5133     ASSERT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5134     ASSERT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5135 
5136     processUp(mapper);
5137     processSync(mapper);
5138     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5139 
5140     // Rotation 90.
5141     clearViewports();
5142     prepareDisplay(ui::ROTATION_90);
5143     processDown(mapper, toRotatedRawX(75), RAW_Y_MAX - toRotatedRawY(50) + RAW_Y_MIN);
5144     processSync(mapper);
5145 
5146     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5147     ASSERT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5148     ASSERT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5149 
5150     processUp(mapper);
5151     processSync(mapper);
5152     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5153 
5154     // Rotation 180.
5155     clearViewports();
5156     prepareDisplay(ui::ROTATION_180);
5157     processDown(mapper, RAW_X_MAX - toRawX(50) + RAW_X_MIN, RAW_Y_MAX - toRawY(75) + RAW_Y_MIN);
5158     processSync(mapper);
5159 
5160     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5161     ASSERT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5162     ASSERT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5163 
5164     processUp(mapper);
5165     processSync(mapper);
5166     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5167 
5168     // Rotation 270.
5169     clearViewports();
5170     prepareDisplay(ui::ROTATION_270);
5171     processDown(mapper, RAW_X_MAX - toRotatedRawX(75) + RAW_X_MIN, toRotatedRawY(50));
5172     processSync(mapper);
5173 
5174     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5175     ASSERT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5176     ASSERT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5177 
5178     processUp(mapper);
5179     processSync(mapper);
5180     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5181 }
5182 
TEST_F(SingleTouchInputMapperTest,Process_WhenOrientation0_RotatesMotions)5183 TEST_F(SingleTouchInputMapperTest, Process_WhenOrientation0_RotatesMotions) {
5184     addConfigurationProperty("touch.deviceType", "touchScreen");
5185     prepareButtons();
5186     prepareAxes(POSITION);
5187     addConfigurationProperty("touch.orientationAware", "1");
5188     addConfigurationProperty("touch.orientation", "ORIENTATION_0");
5189     clearViewports();
5190     prepareDisplay(ui::ROTATION_0);
5191     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5192     NotifyMotionArgs args;
5193 
5194     // Orientation 0.
5195     processDown(mapper, toRawX(50), toRawY(75));
5196     processSync(mapper);
5197 
5198     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5199     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5200     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5201 
5202     processUp(mapper);
5203     processSync(mapper);
5204     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5205 }
5206 
TEST_F(SingleTouchInputMapperTest,Process_WhenOrientation90_RotatesMotions)5207 TEST_F(SingleTouchInputMapperTest, Process_WhenOrientation90_RotatesMotions) {
5208     addConfigurationProperty("touch.deviceType", "touchScreen");
5209     prepareButtons();
5210     prepareAxes(POSITION);
5211     addConfigurationProperty("touch.orientationAware", "1");
5212     addConfigurationProperty("touch.orientation", "ORIENTATION_90");
5213     clearViewports();
5214     prepareDisplay(ui::ROTATION_0);
5215     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5216     NotifyMotionArgs args;
5217 
5218     // Orientation 90.
5219     processDown(mapper, RAW_X_MAX - toRotatedRawX(75) + RAW_X_MIN, toRotatedRawY(50));
5220     processSync(mapper);
5221 
5222     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5223     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5224     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5225 
5226     processUp(mapper);
5227     processSync(mapper);
5228     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5229 }
5230 
TEST_F(SingleTouchInputMapperTest,Process_WhenOrientation180_RotatesMotions)5231 TEST_F(SingleTouchInputMapperTest, Process_WhenOrientation180_RotatesMotions) {
5232     addConfigurationProperty("touch.deviceType", "touchScreen");
5233     prepareButtons();
5234     prepareAxes(POSITION);
5235     addConfigurationProperty("touch.orientationAware", "1");
5236     addConfigurationProperty("touch.orientation", "ORIENTATION_180");
5237     clearViewports();
5238     prepareDisplay(ui::ROTATION_0);
5239     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5240     NotifyMotionArgs args;
5241 
5242     // Orientation 180.
5243     processDown(mapper, RAW_X_MAX - toRawX(50) + RAW_X_MIN, RAW_Y_MAX - toRawY(75) + RAW_Y_MIN);
5244     processSync(mapper);
5245 
5246     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5247     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5248     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5249 
5250     processUp(mapper);
5251     processSync(mapper);
5252     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5253 }
5254 
TEST_F(SingleTouchInputMapperTest,Process_WhenOrientation270_RotatesMotions)5255 TEST_F(SingleTouchInputMapperTest, Process_WhenOrientation270_RotatesMotions) {
5256     addConfigurationProperty("touch.deviceType", "touchScreen");
5257     prepareButtons();
5258     prepareAxes(POSITION);
5259     addConfigurationProperty("touch.orientationAware", "1");
5260     addConfigurationProperty("touch.orientation", "ORIENTATION_270");
5261     clearViewports();
5262     prepareDisplay(ui::ROTATION_0);
5263     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5264     NotifyMotionArgs args;
5265 
5266     // Orientation 270.
5267     processDown(mapper, toRotatedRawX(75), RAW_Y_MAX - toRotatedRawY(50) + RAW_Y_MIN);
5268     processSync(mapper);
5269 
5270     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5271     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5272     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5273 
5274     processUp(mapper);
5275     processSync(mapper);
5276     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5277 }
5278 
TEST_F(SingleTouchInputMapperTest,Process_WhenOrientationSpecified_RotatesMotionWithDisplay)5279 TEST_F(SingleTouchInputMapperTest, Process_WhenOrientationSpecified_RotatesMotionWithDisplay) {
5280     addConfigurationProperty("touch.deviceType", "touchScreen");
5281     prepareButtons();
5282     prepareAxes(POSITION);
5283     // Since InputReader works in the un-rotated coordinate space, only devices that are not
5284     // orientation-aware are affected by display rotation.
5285     addConfigurationProperty("touch.orientationAware", "0");
5286     addConfigurationProperty("touch.orientation", "ORIENTATION_90");
5287     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5288 
5289     NotifyMotionArgs args;
5290 
5291     // Orientation 90, Rotation 0.
5292     clearViewports();
5293     prepareDisplay(ui::ROTATION_0);
5294     processDown(mapper, RAW_X_MAX - toRotatedRawX(75) + RAW_X_MIN, toRotatedRawY(50));
5295     processSync(mapper);
5296 
5297     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5298     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5299     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5300 
5301     processUp(mapper);
5302     processSync(mapper);
5303     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5304 
5305     // Orientation 90, Rotation 90.
5306     clearViewports();
5307     prepareDisplay(ui::ROTATION_90);
5308     processDown(mapper, toRawX(50), toRawY(75));
5309     processSync(mapper);
5310 
5311     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5312     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5313     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5314 
5315     processUp(mapper);
5316     processSync(mapper);
5317     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5318 
5319     // Orientation 90, Rotation 180.
5320     clearViewports();
5321     prepareDisplay(ui::ROTATION_180);
5322     processDown(mapper, toRotatedRawX(75), RAW_Y_MAX - toRotatedRawY(50) + RAW_Y_MIN);
5323     processSync(mapper);
5324 
5325     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5326     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5327     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5328 
5329     processUp(mapper);
5330     processSync(mapper);
5331     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5332 
5333     // Orientation 90, Rotation 270.
5334     clearViewports();
5335     prepareDisplay(ui::ROTATION_270);
5336     processDown(mapper, RAW_X_MAX - toRawX(50) + RAW_X_MIN, RAW_Y_MAX - toRawY(75) + RAW_Y_MIN);
5337     processSync(mapper);
5338 
5339     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5340     EXPECT_NEAR(50, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5341     EXPECT_NEAR(75, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5342 
5343     processUp(mapper);
5344     processSync(mapper);
5345     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5346 }
5347 
TEST_F(SingleTouchInputMapperTest,Process_IgnoresTouchesOutsidePhysicalFrame)5348 TEST_F(SingleTouchInputMapperTest, Process_IgnoresTouchesOutsidePhysicalFrame) {
5349     addConfigurationProperty("touch.deviceType", "touchScreen");
5350     prepareButtons();
5351     prepareAxes(POSITION);
5352     addConfigurationProperty("touch.orientationAware", "1");
5353     prepareDisplay(ui::ROTATION_0);
5354     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5355 
5356     // Set a physical frame in the display viewport.
5357     auto viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
5358     viewport->physicalLeft = 20;
5359     viewport->physicalTop = 600;
5360     viewport->physicalRight = 30;
5361     viewport->physicalBottom = 610;
5362     mFakePolicy->updateViewport(*viewport);
5363     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
5364 
5365     // Start the touch.
5366     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_TOUCH, 1);
5367     processSync(mapper);
5368 
5369     // Expect all input starting outside the physical frame to be ignored.
5370     const std::array<Point, 6> outsidePoints = {
5371             {{0, 0}, {19, 605}, {31, 605}, {25, 599}, {25, 611}, {DISPLAY_WIDTH, DISPLAY_HEIGHT}}};
5372     for (const auto& p : outsidePoints) {
5373         processMove(mapper, toRawX(p.x), toRawY(p.y));
5374         processSync(mapper);
5375         EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
5376     }
5377 
5378     // Move the touch into the physical frame.
5379     processMove(mapper, toRawX(25), toRawY(605));
5380     processSync(mapper);
5381     NotifyMotionArgs args;
5382     EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5383     EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
5384     EXPECT_NEAR(25, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5385     EXPECT_NEAR(605, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5386 
5387     // Once the touch down is reported, continue reporting input, even if it is outside the frame.
5388     for (const auto& p : outsidePoints) {
5389         processMove(mapper, toRawX(p.x), toRawY(p.y));
5390         processSync(mapper);
5391         EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5392         EXPECT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
5393         EXPECT_NEAR(p.x, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
5394         EXPECT_NEAR(p.y, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
5395     }
5396 
5397     processUp(mapper);
5398     processSync(mapper);
5399     EXPECT_NO_FATAL_FAILURE(
5400             mFakeListener->assertNotifyMotionWasCalled(WithMotionAction(AMOTION_EVENT_ACTION_UP)));
5401 }
5402 
TEST_F(SingleTouchInputMapperTest,Process_DoesntCheckPhysicalFrameForTouchpads)5403 TEST_F(SingleTouchInputMapperTest, Process_DoesntCheckPhysicalFrameForTouchpads) {
5404     addConfigurationProperty("touch.deviceType", "pointer");
5405     prepareAxes(POSITION);
5406     prepareDisplay(ui::ROTATION_0);
5407     auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5408 
5409     // Set a physical frame in the display viewport.
5410     auto viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
5411     viewport->physicalLeft = 20;
5412     viewport->physicalTop = 600;
5413     viewport->physicalRight = 30;
5414     viewport->physicalBottom = 610;
5415     mFakePolicy->updateViewport(*viewport);
5416     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
5417 
5418     // Start the touch.
5419     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_TOUCH, 1);
5420     processSync(mapper);
5421 
5422     // Expect all input starting outside the physical frame to result in NotifyMotionArgs being
5423     // produced.
5424     const std::array<Point, 6> outsidePoints = {
5425             {{0, 0}, {19, 605}, {31, 605}, {25, 599}, {25, 611}, {DISPLAY_WIDTH, DISPLAY_HEIGHT}}};
5426     for (const auto& p : outsidePoints) {
5427         processMove(mapper, toRawX(p.x), toRawY(p.y));
5428         processSync(mapper);
5429         EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
5430     }
5431 }
5432 
TEST_F(SingleTouchInputMapperTest,Process_AllAxes_DefaultCalibration)5433 TEST_F(SingleTouchInputMapperTest, Process_AllAxes_DefaultCalibration) {
5434     addConfigurationProperty("touch.deviceType", "touchScreen");
5435     prepareDisplay(ui::ROTATION_0);
5436     prepareButtons();
5437     prepareAxes(POSITION | PRESSURE | TOOL | DISTANCE | TILT);
5438     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5439 
5440     // These calculations are based on the input device calibration documentation.
5441     int32_t rawX = 100;
5442     int32_t rawY = 200;
5443     int32_t rawPressure = 10;
5444     int32_t rawToolMajor = 12;
5445     int32_t rawDistance = 2;
5446     int32_t rawTiltX = 30;
5447     int32_t rawTiltY = 110;
5448 
5449     float x = toDisplayX(rawX);
5450     float y = toDisplayY(rawY);
5451     float pressure = float(rawPressure) / RAW_PRESSURE_MAX;
5452     float size = float(rawToolMajor) / RAW_TOOL_MAX;
5453     float tool = float(rawToolMajor) * GEOMETRIC_SCALE;
5454     float distance = float(rawDistance);
5455 
5456     float tiltCenter = (RAW_TILT_MAX + RAW_TILT_MIN) * 0.5f;
5457     float tiltScale = M_PI / 180;
5458     float tiltXAngle = (rawTiltX - tiltCenter) * tiltScale;
5459     float tiltYAngle = (rawTiltY - tiltCenter) * tiltScale;
5460     float orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5461     float tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5462 
5463     processDown(mapper, rawX, rawY);
5464     processPressure(mapper, rawPressure);
5465     processToolMajor(mapper, rawToolMajor);
5466     processDistance(mapper, rawDistance);
5467     processTilt(mapper, rawTiltX, rawTiltY);
5468     processSync(mapper);
5469 
5470     NotifyMotionArgs args;
5471     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5472     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
5473             x, y, pressure, size, tool, tool, tool, tool, orientation, distance));
5474     ASSERT_EQ(tilt, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_TILT));
5475     ASSERT_EQ(args.flags,
5476               AMOTION_EVENT_PRIVATE_FLAG_SUPPORTS_ORIENTATION |
5477                       AMOTION_EVENT_PRIVATE_FLAG_SUPPORTS_DIRECTIONAL_ORIENTATION);
5478 }
5479 
TEST_F(SingleTouchInputMapperTest,Process_XYAxes_AffineCalibration)5480 TEST_F(SingleTouchInputMapperTest, Process_XYAxes_AffineCalibration) {
5481     addConfigurationProperty("touch.deviceType", "touchScreen");
5482     prepareDisplay(ui::ROTATION_0);
5483     prepareLocationCalibration();
5484     prepareButtons();
5485     prepareAxes(POSITION);
5486     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5487 
5488     int32_t rawX = 100;
5489     int32_t rawY = 200;
5490 
5491     float x = toDisplayX(toCookedX(rawX, rawY));
5492     float y = toDisplayY(toCookedY(rawX, rawY));
5493 
5494     processDown(mapper, rawX, rawY);
5495     processSync(mapper);
5496 
5497     NotifyMotionArgs args;
5498     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
5499     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
5500             x, y, 1, 0, 0, 0, 0, 0, 0, 0));
5501 }
5502 
TEST_F(SingleTouchInputMapperTest,Process_ShouldHandleAllButtons)5503 TEST_F(SingleTouchInputMapperTest, Process_ShouldHandleAllButtons) {
5504     addConfigurationProperty("touch.deviceType", "touchScreen");
5505     prepareDisplay(ui::ROTATION_0);
5506     prepareButtons();
5507     prepareAxes(POSITION);
5508     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5509 
5510     NotifyMotionArgs motionArgs;
5511     NotifyKeyArgs keyArgs;
5512 
5513     processDown(mapper, 100, 200);
5514     processSync(mapper);
5515     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5516     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
5517     ASSERT_EQ(0, motionArgs.buttonState);
5518 
5519     // press BTN_LEFT, release BTN_LEFT
5520     processKey(mapper, BTN_LEFT, 1);
5521     processSync(mapper);
5522     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5523     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5524     ASSERT_EQ(AMOTION_EVENT_BUTTON_PRIMARY, motionArgs.buttonState);
5525 
5526     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5527     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
5528     ASSERT_EQ(AMOTION_EVENT_BUTTON_PRIMARY, motionArgs.buttonState);
5529 
5530     processKey(mapper, BTN_LEFT, 0);
5531     processSync(mapper);
5532     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5533     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
5534     ASSERT_EQ(0, motionArgs.buttonState);
5535 
5536     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5537     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5538     ASSERT_EQ(0, motionArgs.buttonState);
5539 
5540     // press BTN_RIGHT + BTN_MIDDLE, release BTN_RIGHT, release BTN_MIDDLE
5541     processKey(mapper, BTN_RIGHT, 1);
5542     processKey(mapper, BTN_MIDDLE, 1);
5543     processSync(mapper);
5544     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5545     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5546     ASSERT_EQ(AMOTION_EVENT_BUTTON_SECONDARY | AMOTION_EVENT_BUTTON_TERTIARY,
5547             motionArgs.buttonState);
5548 
5549     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5550     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
5551     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
5552 
5553     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5554     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
5555     ASSERT_EQ(AMOTION_EVENT_BUTTON_SECONDARY | AMOTION_EVENT_BUTTON_TERTIARY,
5556             motionArgs.buttonState);
5557 
5558     processKey(mapper, BTN_RIGHT, 0);
5559     processSync(mapper);
5560     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5561     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
5562     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
5563 
5564     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5565     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5566     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
5567 
5568     processKey(mapper, BTN_MIDDLE, 0);
5569     processSync(mapper);
5570     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5571     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
5572     ASSERT_EQ(0, motionArgs.buttonState);
5573 
5574     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5575     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5576     ASSERT_EQ(0, motionArgs.buttonState);
5577 
5578     // press BTN_BACK, release BTN_BACK
5579     processKey(mapper, BTN_BACK, 1);
5580     processSync(mapper);
5581     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
5582     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
5583     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
5584 
5585     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5586     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5587     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
5588 
5589     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5590     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
5591     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
5592 
5593     processKey(mapper, BTN_BACK, 0);
5594     processSync(mapper);
5595     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5596     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
5597     ASSERT_EQ(0, motionArgs.buttonState);
5598 
5599     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5600     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5601     ASSERT_EQ(0, motionArgs.buttonState);
5602 
5603     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
5604     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
5605     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
5606 
5607     // press BTN_SIDE, release BTN_SIDE
5608     processKey(mapper, BTN_SIDE, 1);
5609     processSync(mapper);
5610     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
5611     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
5612     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
5613 
5614     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5615     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5616     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
5617 
5618     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5619     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
5620     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
5621 
5622     processKey(mapper, BTN_SIDE, 0);
5623     processSync(mapper);
5624     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5625     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
5626     ASSERT_EQ(0, motionArgs.buttonState);
5627 
5628     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5629     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5630     ASSERT_EQ(0, motionArgs.buttonState);
5631 
5632     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
5633     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
5634     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
5635 
5636     // press BTN_FORWARD, release BTN_FORWARD
5637     processKey(mapper, BTN_FORWARD, 1);
5638     processSync(mapper);
5639     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
5640     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
5641     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
5642 
5643     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5644     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5645     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
5646 
5647     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5648     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
5649     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
5650 
5651     processKey(mapper, BTN_FORWARD, 0);
5652     processSync(mapper);
5653     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5654     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
5655     ASSERT_EQ(0, motionArgs.buttonState);
5656 
5657     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5658     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5659     ASSERT_EQ(0, motionArgs.buttonState);
5660 
5661     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
5662     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
5663     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
5664 
5665     // press BTN_EXTRA, release BTN_EXTRA
5666     processKey(mapper, BTN_EXTRA, 1);
5667     processSync(mapper);
5668     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
5669     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
5670     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
5671 
5672     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5673     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5674     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
5675 
5676     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5677     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
5678     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
5679 
5680     processKey(mapper, BTN_EXTRA, 0);
5681     processSync(mapper);
5682     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5683     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
5684     ASSERT_EQ(0, motionArgs.buttonState);
5685 
5686     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5687     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5688     ASSERT_EQ(0, motionArgs.buttonState);
5689 
5690     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
5691     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
5692     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
5693 
5694     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
5695 
5696     // press BTN_STYLUS, release BTN_STYLUS
5697     processKey(mapper, BTN_STYLUS, 1);
5698     processSync(mapper);
5699     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5700     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5701     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY, motionArgs.buttonState);
5702 
5703     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5704     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
5705     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY, motionArgs.buttonState);
5706 
5707     processKey(mapper, BTN_STYLUS, 0);
5708     processSync(mapper);
5709     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5710     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
5711     ASSERT_EQ(0, motionArgs.buttonState);
5712 
5713     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5714     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5715     ASSERT_EQ(0, motionArgs.buttonState);
5716 
5717     // press BTN_STYLUS2, release BTN_STYLUS2
5718     processKey(mapper, BTN_STYLUS2, 1);
5719     processSync(mapper);
5720     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5721     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5722     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_SECONDARY, motionArgs.buttonState);
5723 
5724     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5725     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
5726     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_SECONDARY, motionArgs.buttonState);
5727 
5728     processKey(mapper, BTN_STYLUS2, 0);
5729     processSync(mapper);
5730     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5731     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
5732     ASSERT_EQ(0, motionArgs.buttonState);
5733 
5734     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5735     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5736     ASSERT_EQ(0, motionArgs.buttonState);
5737 
5738     // release touch
5739     processUp(mapper);
5740     processSync(mapper);
5741     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5742     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
5743     ASSERT_EQ(0, motionArgs.buttonState);
5744 }
5745 
TEST_F(SingleTouchInputMapperTest,Process_ShouldHandleAllToolTypes)5746 TEST_F(SingleTouchInputMapperTest, Process_ShouldHandleAllToolTypes) {
5747     addConfigurationProperty("touch.deviceType", "touchScreen");
5748     prepareDisplay(ui::ROTATION_0);
5749     prepareButtons();
5750     prepareAxes(POSITION);
5751     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5752 
5753     NotifyMotionArgs motionArgs;
5754 
5755     // default tool type is finger
5756     processDown(mapper, 100, 200);
5757     processSync(mapper);
5758     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5759     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
5760     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5761 
5762     // eraser
5763     processKey(mapper, BTN_TOOL_RUBBER, 1);
5764     processSync(mapper);
5765     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5766     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5767     ASSERT_EQ(ToolType::ERASER, motionArgs.pointerProperties[0].toolType);
5768 
5769     // stylus
5770     processKey(mapper, BTN_TOOL_RUBBER, 0);
5771     processKey(mapper, BTN_TOOL_PEN, 1);
5772     processSync(mapper);
5773     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5774     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5775     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
5776 
5777     // brush
5778     processKey(mapper, BTN_TOOL_PEN, 0);
5779     processKey(mapper, BTN_TOOL_BRUSH, 1);
5780     processSync(mapper);
5781     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5782     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5783     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
5784 
5785     // pencil
5786     processKey(mapper, BTN_TOOL_BRUSH, 0);
5787     processKey(mapper, BTN_TOOL_PENCIL, 1);
5788     processSync(mapper);
5789     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5790     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5791     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
5792 
5793     // air-brush
5794     processKey(mapper, BTN_TOOL_PENCIL, 0);
5795     processKey(mapper, BTN_TOOL_AIRBRUSH, 1);
5796     processSync(mapper);
5797     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5798     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5799     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
5800 
5801     // mouse
5802     processKey(mapper, BTN_TOOL_AIRBRUSH, 0);
5803     processKey(mapper, BTN_TOOL_MOUSE, 1);
5804     processSync(mapper);
5805     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5806     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5807     ASSERT_EQ(ToolType::MOUSE, motionArgs.pointerProperties[0].toolType);
5808 
5809     // lens
5810     processKey(mapper, BTN_TOOL_MOUSE, 0);
5811     processKey(mapper, BTN_TOOL_LENS, 1);
5812     processSync(mapper);
5813     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5814     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5815     ASSERT_EQ(ToolType::MOUSE, motionArgs.pointerProperties[0].toolType);
5816 
5817     // double-tap
5818     processKey(mapper, BTN_TOOL_LENS, 0);
5819     processKey(mapper, BTN_TOOL_DOUBLETAP, 1);
5820     processSync(mapper);
5821     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5822     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5823     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5824 
5825     // triple-tap
5826     processKey(mapper, BTN_TOOL_DOUBLETAP, 0);
5827     processKey(mapper, BTN_TOOL_TRIPLETAP, 1);
5828     processSync(mapper);
5829     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5830     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5831     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5832 
5833     // quad-tap
5834     processKey(mapper, BTN_TOOL_TRIPLETAP, 0);
5835     processKey(mapper, BTN_TOOL_QUADTAP, 1);
5836     processSync(mapper);
5837     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5838     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5839     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5840 
5841     // finger
5842     processKey(mapper, BTN_TOOL_QUADTAP, 0);
5843     processKey(mapper, BTN_TOOL_FINGER, 1);
5844     processSync(mapper);
5845     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5846     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5847     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5848 
5849     // stylus trumps finger
5850     processKey(mapper, BTN_TOOL_PEN, 1);
5851     processSync(mapper);
5852     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5853     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5854     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
5855 
5856     // eraser trumps stylus
5857     processKey(mapper, BTN_TOOL_RUBBER, 1);
5858     processSync(mapper);
5859     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5860     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5861     ASSERT_EQ(ToolType::ERASER, motionArgs.pointerProperties[0].toolType);
5862 
5863     // mouse trumps eraser
5864     processKey(mapper, BTN_TOOL_MOUSE, 1);
5865     processSync(mapper);
5866     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5867     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5868     ASSERT_EQ(ToolType::MOUSE, motionArgs.pointerProperties[0].toolType);
5869 
5870     // back to default tool type
5871     processKey(mapper, BTN_TOOL_MOUSE, 0);
5872     processKey(mapper, BTN_TOOL_RUBBER, 0);
5873     processKey(mapper, BTN_TOOL_PEN, 0);
5874     processKey(mapper, BTN_TOOL_FINGER, 0);
5875     processSync(mapper);
5876     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5877     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
5878     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
5879 }
5880 
TEST_F(SingleTouchInputMapperTest,Process_WhenBtnTouchPresent_HoversIfItsValueIsZero)5881 TEST_F(SingleTouchInputMapperTest, Process_WhenBtnTouchPresent_HoversIfItsValueIsZero) {
5882     addConfigurationProperty("touch.deviceType", "touchScreen");
5883     prepareDisplay(ui::ROTATION_0);
5884     prepareButtons();
5885     prepareAxes(POSITION);
5886     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOOL_FINGER, 0, AKEYCODE_UNKNOWN, 0);
5887     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5888 
5889     NotifyMotionArgs motionArgs;
5890 
5891     // initially hovering because BTN_TOUCH not sent yet, pressure defaults to 0
5892     processKey(mapper, BTN_TOOL_FINGER, 1);
5893     processMove(mapper, 100, 200);
5894     processSync(mapper);
5895     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5896     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
5897     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5898             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
5899 
5900     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5901     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
5902     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5903             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
5904 
5905     // move a little
5906     processMove(mapper, 150, 250);
5907     processSync(mapper);
5908     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5909     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
5910     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5911             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
5912 
5913     // down when BTN_TOUCH is pressed, pressure defaults to 1
5914     processKey(mapper, BTN_TOUCH, 1);
5915     processSync(mapper);
5916     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5917     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
5918     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5919             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
5920 
5921     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5922     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
5923     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5924             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
5925 
5926     // up when BTN_TOUCH is released, hover restored
5927     processKey(mapper, BTN_TOUCH, 0);
5928     processSync(mapper);
5929     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5930     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
5931     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5932             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
5933 
5934     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5935     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
5936     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5937             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
5938 
5939     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5940     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
5941     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5942             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
5943 
5944     // exit hover when pointer goes away
5945     processKey(mapper, BTN_TOOL_FINGER, 0);
5946     processSync(mapper);
5947     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5948     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
5949     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5950             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
5951 }
5952 
TEST_F(SingleTouchInputMapperTest,Process_WhenAbsPressureIsPresent_HoversIfItsValueIsZero)5953 TEST_F(SingleTouchInputMapperTest, Process_WhenAbsPressureIsPresent_HoversIfItsValueIsZero) {
5954     addConfigurationProperty("touch.deviceType", "touchScreen");
5955     prepareDisplay(ui::ROTATION_0);
5956     prepareButtons();
5957     prepareAxes(POSITION | PRESSURE);
5958     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
5959 
5960     NotifyMotionArgs motionArgs;
5961 
5962     // initially hovering because pressure is 0
5963     processDown(mapper, 100, 200);
5964     processPressure(mapper, 0);
5965     processSync(mapper);
5966     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5967     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
5968     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5969             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
5970 
5971     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5972     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
5973     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5974             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
5975 
5976     // move a little
5977     processMove(mapper, 150, 250);
5978     processSync(mapper);
5979     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5980     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
5981     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5982             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
5983 
5984     // down when pressure is non-zero
5985     processPressure(mapper, RAW_PRESSURE_MAX);
5986     processSync(mapper);
5987     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5988     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
5989     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5990             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
5991 
5992     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
5993     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
5994     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
5995             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
5996 
5997     // up when pressure becomes 0, hover restored
5998     processPressure(mapper, 0);
5999     processSync(mapper);
6000     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6001     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
6002     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6003             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
6004 
6005     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6006     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
6007     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6008             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6009 
6010     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6011     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
6012     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6013             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6014 
6015     // exit hover when pointer goes away
6016     processUp(mapper);
6017     processSync(mapper);
6018     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6019     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
6020     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
6021             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
6022 }
6023 
TEST_F(SingleTouchInputMapperTest,Reset_CancelsOngoingGesture)6024 TEST_F(SingleTouchInputMapperTest, Reset_CancelsOngoingGesture) {
6025     addConfigurationProperty("touch.deviceType", "touchScreen");
6026     prepareDisplay(ui::ROTATION_0);
6027     prepareButtons();
6028     prepareAxes(POSITION | PRESSURE);
6029     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6030 
6031     // Touch down.
6032     processDown(mapper, 100, 200);
6033     processPressure(mapper, 1);
6034     processSync(mapper);
6035     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6036             WithMotionAction(AMOTION_EVENT_ACTION_DOWN)));
6037 
6038     // Reset the mapper. This should cancel the ongoing gesture.
6039     resetMapper(mapper, ARBITRARY_TIME);
6040     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6041             WithMotionAction(AMOTION_EVENT_ACTION_CANCEL)));
6042 
6043     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6044 }
6045 
TEST_F(SingleTouchInputMapperTest,Reset_RecreatesTouchState)6046 TEST_F(SingleTouchInputMapperTest, Reset_RecreatesTouchState) {
6047     addConfigurationProperty("touch.deviceType", "touchScreen");
6048     prepareDisplay(ui::ROTATION_0);
6049     prepareButtons();
6050     prepareAxes(POSITION | PRESSURE);
6051     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6052 
6053     // Set the initial state for the touch pointer.
6054     mFakeEventHub->setAbsoluteAxisValue(EVENTHUB_ID, ABS_X, 100);
6055     mFakeEventHub->setAbsoluteAxisValue(EVENTHUB_ID, ABS_Y, 200);
6056     mFakeEventHub->setAbsoluteAxisValue(EVENTHUB_ID, ABS_PRESSURE, RAW_PRESSURE_MAX);
6057     mFakeEventHub->setScanCodeState(EVENTHUB_ID, BTN_TOUCH, 1);
6058 
6059     // Reset the mapper. When the mapper is reset, we expect it to attempt to recreate the touch
6060     // state by reading the current axis values. Since there was no ongoing gesture, calling reset
6061     // does not generate any events.
6062     resetMapper(mapper, ARBITRARY_TIME);
6063 
6064     // Send a sync to simulate an empty touch frame where nothing changes. The mapper should use
6065     // the recreated touch state to generate a down event.
6066     processSync(mapper);
6067     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6068             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithPressure(1.f))));
6069 
6070     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6071 }
6072 
TEST_F(SingleTouchInputMapperTest,Process_WhenViewportDisplayIdChanged_TouchIsCanceledAndDeviceIsReset)6073 TEST_F(SingleTouchInputMapperTest,
6074        Process_WhenViewportDisplayIdChanged_TouchIsCanceledAndDeviceIsReset) {
6075     addConfigurationProperty("touch.deviceType", "touchScreen");
6076     prepareDisplay(ui::ROTATION_0);
6077     prepareButtons();
6078     prepareAxes(POSITION);
6079     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6080     NotifyMotionArgs motionArgs;
6081 
6082     // Down.
6083     processDown(mapper, 100, 200);
6084     processSync(mapper);
6085 
6086     // We should receive a down event
6087     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6088     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
6089 
6090     // Change display id
6091     clearViewports();
6092     prepareSecondaryDisplay(ViewportType::INTERNAL);
6093 
6094     // We should receive a cancel event
6095     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6096     ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionArgs.action);
6097     // Then receive reset called
6098     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6099 }
6100 
TEST_F(SingleTouchInputMapperTest,Process_WhenViewportActiveStatusChanged_TouchIsCanceledAndDeviceIsReset)6101 TEST_F(SingleTouchInputMapperTest,
6102        Process_WhenViewportActiveStatusChanged_TouchIsCanceledAndDeviceIsReset) {
6103     addConfigurationProperty("touch.deviceType", "touchScreen");
6104     prepareDisplay(ui::ROTATION_0);
6105     prepareButtons();
6106     prepareAxes(POSITION);
6107     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6108     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6109     NotifyMotionArgs motionArgs;
6110 
6111     // Start a new gesture.
6112     processDown(mapper, 100, 200);
6113     processSync(mapper);
6114     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6115     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
6116 
6117     // Make the viewport inactive. This will put the device in disabled mode.
6118     auto viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
6119     viewport->isActive = false;
6120     mFakePolicy->updateViewport(*viewport);
6121     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
6122 
6123     // We should receive a cancel event for the ongoing gesture.
6124     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6125     ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionArgs.action);
6126     // Then we should be notified that the device was reset.
6127     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6128 
6129     // No events are generated while the viewport is inactive.
6130     processMove(mapper, 101, 201);
6131     processSync(mapper);
6132     processUp(mapper);
6133     processSync(mapper);
6134     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6135 
6136     // Start a new gesture while the viewport is still inactive.
6137     processDown(mapper, 300, 400);
6138     mFakeEventHub->setAbsoluteAxisValue(EVENTHUB_ID, ABS_X, 300);
6139     mFakeEventHub->setAbsoluteAxisValue(EVENTHUB_ID, ABS_Y, 400);
6140     mFakeEventHub->setScanCodeState(EVENTHUB_ID, BTN_TOUCH, 1);
6141     processSync(mapper);
6142 
6143     // Make the viewport active again. The device should resume processing events.
6144     viewport->isActive = true;
6145     mFakePolicy->updateViewport(*viewport);
6146     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
6147 
6148     // The device is reset because it changes back to direct mode, without generating any events.
6149     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6150     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6151 
6152     // In the next sync, the touch state that was recreated when the device was reset is reported.
6153     processSync(mapper);
6154     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6155             WithMotionAction(AMOTION_EVENT_ACTION_DOWN)));
6156 
6157     // No more events.
6158     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6159     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasNotCalled());
6160 }
6161 
TEST_F(SingleTouchInputMapperTest,ButtonIsReleasedOnTouchUp)6162 TEST_F(SingleTouchInputMapperTest, ButtonIsReleasedOnTouchUp) {
6163     addConfigurationProperty("touch.deviceType", "touchScreen");
6164     prepareDisplay(ui::ROTATION_0);
6165     prepareButtons();
6166     prepareAxes(POSITION);
6167     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6168     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6169 
6170     // Press a stylus button.
6171     processKey(mapper, BTN_STYLUS, 1);
6172     processSync(mapper);
6173 
6174     // Start a touch gesture and ensure the BUTTON_PRESS event is generated.
6175     processDown(mapper, 100, 200);
6176     processSync(mapper);
6177     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6178             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
6179                   WithCoords(toDisplayX(100), toDisplayY(200)),
6180                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
6181     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6182             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
6183                   WithCoords(toDisplayX(100), toDisplayY(200)),
6184                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
6185 
6186     // Release the touch gesture. Ensure that the BUTTON_RELEASE event is generated even though
6187     // the button has not actually been released, since there will be no pointers through which the
6188     // button state can be reported. The event is generated at the location of the pointer before
6189     // it went up.
6190     processUp(mapper);
6191     processSync(mapper);
6192     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6193             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
6194                   WithCoords(toDisplayX(100), toDisplayY(200)), WithButtonState(0))));
6195     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6196             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
6197                   WithCoords(toDisplayX(100), toDisplayY(200)), WithButtonState(0))));
6198 }
6199 
TEST_F(SingleTouchInputMapperTest,StylusButtonMotionEventsDisabled)6200 TEST_F(SingleTouchInputMapperTest, StylusButtonMotionEventsDisabled) {
6201     addConfigurationProperty("touch.deviceType", "touchScreen");
6202     prepareDisplay(ui::ROTATION_0);
6203     prepareButtons();
6204     prepareAxes(POSITION);
6205 
6206     mFakePolicy->setStylusButtonMotionEventsEnabled(false);
6207 
6208     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6209     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6210 
6211     // Press a stylus button.
6212     processKey(mapper, BTN_STYLUS, 1);
6213     processSync(mapper);
6214 
6215     // Start a touch gesture and ensure that the stylus button is not reported.
6216     processDown(mapper, 100, 200);
6217     processSync(mapper);
6218     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6219             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithButtonState(0))));
6220 
6221     // Release and press the stylus button again.
6222     processKey(mapper, BTN_STYLUS, 0);
6223     processSync(mapper);
6224     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6225             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE), WithButtonState(0))));
6226     processKey(mapper, BTN_STYLUS, 1);
6227     processSync(mapper);
6228     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6229             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE), WithButtonState(0))));
6230 
6231     // Release the touch gesture.
6232     processUp(mapper);
6233     processSync(mapper);
6234     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6235             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP), WithButtonState(0))));
6236 
6237     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6238 }
6239 
TEST_F(SingleTouchInputMapperTest,WhenDeviceTypeIsSetToTouchNavigation_setsCorrectType)6240 TEST_F(SingleTouchInputMapperTest, WhenDeviceTypeIsSetToTouchNavigation_setsCorrectType) {
6241     mFakePolicy->addDeviceTypeAssociation(DEVICE_LOCATION, "touchNavigation");
6242     prepareDisplay(ui::ROTATION_0);
6243     prepareButtons();
6244     prepareAxes(POSITION);
6245     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6246     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
6247 
6248     ASSERT_EQ(AINPUT_SOURCE_TOUCH_NAVIGATION, mapper.getSources());
6249 }
6250 
TEST_F(SingleTouchInputMapperTest,WhenDeviceTypeIsChangedToTouchNavigation_updatesDeviceType)6251 TEST_F(SingleTouchInputMapperTest, WhenDeviceTypeIsChangedToTouchNavigation_updatesDeviceType) {
6252     // Initialize the device without setting device source to touch navigation.
6253     addConfigurationProperty("touch.deviceType", "touchScreen");
6254     prepareDisplay(ui::ROTATION_0);
6255     prepareButtons();
6256     prepareAxes(POSITION);
6257     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6258 
6259     // Ensure that the device is created as a touchscreen, not touch navigation.
6260     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, mapper.getSources());
6261 
6262     // Add device type association after the device was created.
6263     mFakePolicy->addDeviceTypeAssociation(DEVICE_LOCATION, "touchNavigation");
6264 
6265     // Send update to the mapper.
6266     std::list<NotifyArgs> unused2 =
6267             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
6268                                InputReaderConfiguration::Change::DEVICE_TYPE /*changes*/);
6269 
6270     // Check whether device type update was successful.
6271     ASSERT_EQ(AINPUT_SOURCE_TOUCH_NAVIGATION, mDevice->getSources());
6272 }
6273 
TEST_F(SingleTouchInputMapperTest,HoverEventsOutsidePhysicalFrameAreIgnored)6274 TEST_F(SingleTouchInputMapperTest, HoverEventsOutsidePhysicalFrameAreIgnored) {
6275     // Initialize the device without setting device source to touch navigation.
6276     addConfigurationProperty("touch.deviceType", "touchScreen");
6277     prepareDisplay(ui::ROTATION_0);
6278     prepareButtons();
6279     prepareAxes(POSITION);
6280     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOOL_PEN, 0, AKEYCODE_UNKNOWN, 0);
6281 
6282     // Set a physical frame in the display viewport.
6283     auto viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
6284     viewport->physicalLeft = 0;
6285     viewport->physicalTop = 0;
6286     viewport->physicalRight = DISPLAY_WIDTH / 2;
6287     viewport->physicalBottom = DISPLAY_HEIGHT / 2;
6288     mFakePolicy->updateViewport(*viewport);
6289     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
6290 
6291     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6292 
6293     // Hovering inside the physical frame produces events.
6294     processKey(mapper, BTN_TOOL_PEN, 1);
6295     processMove(mapper, RAW_X_MIN + 1, RAW_Y_MIN + 1);
6296     processSync(mapper);
6297     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6298             WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER)));
6299     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6300             WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE)));
6301 
6302     // Leaving the physical frame ends the hovering gesture.
6303     processMove(mapper, RAW_X_MAX - 1, RAW_Y_MAX - 1);
6304     processSync(mapper);
6305     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6306             WithMotionAction(AMOTION_EVENT_ACTION_HOVER_EXIT)));
6307 
6308     // Moving outside the physical frame does not produce events.
6309     processMove(mapper, RAW_X_MAX - 2, RAW_Y_MAX - 2);
6310     processSync(mapper);
6311     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6312 
6313     // Re-entering the physical frame produces events.
6314     processMove(mapper, RAW_X_MIN, RAW_Y_MIN);
6315     processSync(mapper);
6316     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6317             WithMotionAction(AMOTION_EVENT_ACTION_HOVER_ENTER)));
6318     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6319             WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE)));
6320 }
6321 
6322 // --- TouchDisplayProjectionTest ---
6323 
6324 class TouchDisplayProjectionTest : public SingleTouchInputMapperTest {
6325 public:
6326     // The values inside DisplayViewport are expected to be pre-rotated. This updates the current
6327     // DisplayViewport to pre-rotate the values. The viewport's physical display will be set to the
6328     // 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)6329     void configurePhysicalDisplay(ui::Rotation orientation, Rect naturalPhysicalDisplay,
6330                                   int32_t naturalDisplayWidth = DISPLAY_WIDTH,
6331                                   int32_t naturalDisplayHeight = DISPLAY_HEIGHT) {
6332         uint32_t inverseRotationFlags;
6333         auto rotatedWidth = naturalDisplayWidth;
6334         auto rotatedHeight = naturalDisplayHeight;
6335         switch (orientation) {
6336             case ui::ROTATION_90:
6337                 inverseRotationFlags = ui::Transform::ROT_270;
6338                 std::swap(rotatedWidth, rotatedHeight);
6339                 break;
6340             case ui::ROTATION_180:
6341                 inverseRotationFlags = ui::Transform::ROT_180;
6342                 break;
6343             case ui::ROTATION_270:
6344                 inverseRotationFlags = ui::Transform::ROT_90;
6345                 std::swap(rotatedWidth, rotatedHeight);
6346                 break;
6347             case ui::ROTATION_0:
6348                 inverseRotationFlags = ui::Transform::ROT_0;
6349                 break;
6350         }
6351 
6352         const ui::Transform rotation(inverseRotationFlags, rotatedWidth, rotatedHeight);
6353         const Rect rotatedPhysicalDisplay = rotation.transform(naturalPhysicalDisplay);
6354 
6355         std::optional<DisplayViewport> internalViewport =
6356                 *mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
6357         DisplayViewport& v = *internalViewport;
6358         v.displayId = DISPLAY_ID;
6359         v.orientation = orientation;
6360 
6361         v.logicalLeft = 0;
6362         v.logicalTop = 0;
6363         v.logicalRight = 100;
6364         v.logicalBottom = 100;
6365 
6366         v.physicalLeft = rotatedPhysicalDisplay.left;
6367         v.physicalTop = rotatedPhysicalDisplay.top;
6368         v.physicalRight = rotatedPhysicalDisplay.right;
6369         v.physicalBottom = rotatedPhysicalDisplay.bottom;
6370 
6371         v.deviceWidth = rotatedWidth;
6372         v.deviceHeight = rotatedHeight;
6373 
6374         v.isActive = true;
6375         v.uniqueId = UNIQUE_ID;
6376         v.type = ViewportType::INTERNAL;
6377         mFakePolicy->updateViewport(v);
6378         configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
6379     }
6380 
assertReceivedMove(const Point & point)6381     void assertReceivedMove(const Point& point) {
6382         NotifyMotionArgs motionArgs;
6383         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6384         ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
6385         ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
6386         ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0], point.x, point.y,
6387                                                     1, 0, 0, 0, 0, 0, 0, 0));
6388     }
6389 };
6390 
TEST_F(TouchDisplayProjectionTest,IgnoresTouchesOutsidePhysicalDisplay)6391 TEST_F(TouchDisplayProjectionTest, IgnoresTouchesOutsidePhysicalDisplay) {
6392     addConfigurationProperty("touch.deviceType", "touchScreen");
6393     prepareDisplay(ui::ROTATION_0);
6394 
6395     prepareButtons();
6396     prepareAxes(POSITION);
6397     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6398 
6399     NotifyMotionArgs motionArgs;
6400 
6401     // Configure the DisplayViewport such that the logical display maps to a subsection of
6402     // the display panel called the physical display. Here, the physical display is bounded by the
6403     // points (10, 20) and (70, 160) inside the display space, which is of the size 400 x 800.
6404     static const Rect kPhysicalDisplay{10, 20, 70, 160};
6405     static const std::array<Point, 6> kPointsOutsidePhysicalDisplay{
6406             {{-10, -10}, {0, 0}, {5, 100}, {50, 15}, {75, 100}, {50, 165}}};
6407 
6408     for (auto orientation : {ui::ROTATION_0, ui::ROTATION_90, ui::ROTATION_180, ui::ROTATION_270}) {
6409         configurePhysicalDisplay(orientation, kPhysicalDisplay);
6410 
6411         // Touches outside the physical display should be ignored, and should not generate any
6412         // events. Ensure touches at the following points that lie outside of the physical display
6413         // area do not generate any events.
6414         for (const auto& point : kPointsOutsidePhysicalDisplay) {
6415             processDown(mapper, toRawX(point.x), toRawY(point.y));
6416             processSync(mapper);
6417             processUp(mapper);
6418             processSync(mapper);
6419             ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled())
6420                     << "Unexpected event generated for touch outside physical display at point: "
6421                     << point.x << ", " << point.y;
6422         }
6423     }
6424 }
6425 
TEST_F(TouchDisplayProjectionTest,EmitsTouchDownAfterEnteringPhysicalDisplay)6426 TEST_F(TouchDisplayProjectionTest, EmitsTouchDownAfterEnteringPhysicalDisplay) {
6427     addConfigurationProperty("touch.deviceType", "touchScreen");
6428     prepareDisplay(ui::ROTATION_0);
6429 
6430     prepareButtons();
6431     prepareAxes(POSITION);
6432     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6433 
6434     NotifyMotionArgs motionArgs;
6435 
6436     // Configure the DisplayViewport such that the logical display maps to a subsection of
6437     // the display panel called the physical display. Here, the physical display is bounded by the
6438     // points (10, 20) and (70, 160) inside the display space, which is of the size 400 x 800.
6439     static const Rect kPhysicalDisplay{10, 20, 70, 160};
6440 
6441     for (auto orientation : {ui::ROTATION_0, ui::ROTATION_90, ui::ROTATION_180, ui::ROTATION_270}) {
6442         configurePhysicalDisplay(orientation, kPhysicalDisplay);
6443 
6444         // Touches that start outside the physical display should be ignored until it enters the
6445         // physical display bounds, at which point it should generate a down event. Start a touch at
6446         // the point (5, 100), which is outside the physical display bounds.
6447         static const Point kOutsidePoint{5, 100};
6448         processDown(mapper, toRawX(kOutsidePoint.x), toRawY(kOutsidePoint.y));
6449         processSync(mapper);
6450         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6451 
6452         // Move the touch into the physical display area. This should generate a pointer down.
6453         processMove(mapper, toRawX(11), toRawY(21));
6454         processSync(mapper);
6455         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6456         ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
6457         ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
6458         ASSERT_NO_FATAL_FAILURE(
6459                 assertPointerCoords(motionArgs.pointerCoords[0], 11, 21, 1, 0, 0, 0, 0, 0, 0, 0));
6460 
6461         // Move the touch inside the physical display area. This should generate a pointer move.
6462         processMove(mapper, toRawX(69), toRawY(159));
6463         processSync(mapper);
6464         assertReceivedMove({69, 159});
6465 
6466         // Move outside the physical display area. Since the pointer is already down, this should
6467         // now continue generating events.
6468         processMove(mapper, toRawX(kOutsidePoint.x), toRawY(kOutsidePoint.y));
6469         processSync(mapper);
6470         assertReceivedMove(kOutsidePoint);
6471 
6472         // Release. This should generate a pointer up.
6473         processUp(mapper);
6474         processSync(mapper);
6475         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
6476         ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
6477         ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0], kOutsidePoint.x,
6478                                                     kOutsidePoint.y, 1, 0, 0, 0, 0, 0, 0, 0));
6479 
6480         // Ensure no more events were generated.
6481         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
6482         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6483     }
6484 }
6485 
6486 // --- TouchscreenPrecisionTests ---
6487 
6488 // This test suite is used to ensure that touchscreen devices are scaled and configured correctly
6489 // in various orientations and with different display rotations. We configure the touchscreen to
6490 // have a higher resolution than that of the display by an integer scale factor in each axis so that
6491 // we can enforce that coordinates match precisely as expected.
6492 class TouchscreenPrecisionTestsFixture : public TouchDisplayProjectionTest,
6493                                          public ::testing::WithParamInterface<ui::Rotation> {
6494 public:
SetUp()6495     void SetUp() override {
6496         SingleTouchInputMapperTest::SetUp();
6497 
6498         // Prepare the raw axes to have twice the resolution of the display in the X axis and
6499         // four times the resolution of the display in the Y axis.
6500         prepareButtons();
6501         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_X, PRECISION_RAW_X_MIN, PRECISION_RAW_X_MAX,
6502                                        PRECISION_RAW_X_FLAT, PRECISION_RAW_X_FUZZ,
6503                                        PRECISION_RAW_X_RES);
6504         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_Y, PRECISION_RAW_Y_MIN, PRECISION_RAW_Y_MAX,
6505                                        PRECISION_RAW_Y_FLAT, PRECISION_RAW_Y_FUZZ,
6506                                        PRECISION_RAW_Y_RES);
6507     }
6508 
6509     static const int32_t PRECISION_RAW_X_MIN = TouchInputMapperTest::RAW_X_MIN;
6510     static const int32_t PRECISION_RAW_X_MAX = PRECISION_RAW_X_MIN + DISPLAY_WIDTH * 2 - 1;
6511     static const int32_t PRECISION_RAW_Y_MIN = TouchInputMapperTest::RAW_Y_MIN;
6512     static const int32_t PRECISION_RAW_Y_MAX = PRECISION_RAW_Y_MIN + DISPLAY_HEIGHT * 4 - 1;
6513 
6514     static const int32_t PRECISION_RAW_X_RES = 50;  // units per millimeter
6515     static const int32_t PRECISION_RAW_Y_RES = 100; // units per millimeter
6516 
6517     static const int32_t PRECISION_RAW_X_FLAT = 16;
6518     static const int32_t PRECISION_RAW_Y_FLAT = 32;
6519 
6520     static const int32_t PRECISION_RAW_X_FUZZ = 4;
6521     static const int32_t PRECISION_RAW_Y_FUZZ = 8;
6522 
6523     static const std::array<Point, 4> kRawCorners;
6524 };
6525 
6526 const std::array<Point, 4> TouchscreenPrecisionTestsFixture::kRawCorners = {{
6527         {PRECISION_RAW_X_MIN, PRECISION_RAW_Y_MIN}, // left-top
6528         {PRECISION_RAW_X_MAX, PRECISION_RAW_Y_MIN}, // right-top
6529         {PRECISION_RAW_X_MAX, PRECISION_RAW_Y_MAX}, // right-bottom
6530         {PRECISION_RAW_X_MIN, PRECISION_RAW_Y_MAX}, // left-bottom
6531 }};
6532 
6533 // Tests for how the touchscreen is oriented relative to the natural orientation of the display.
6534 // For example, if a touchscreen is configured with an orientation of 90 degrees, it is a portrait
6535 // touchscreen panel that is used on a device whose natural display orientation is in landscape.
TEST_P(TouchscreenPrecisionTestsFixture,OrientationPrecision)6536 TEST_P(TouchscreenPrecisionTestsFixture, OrientationPrecision) {
6537     enum class Orientation {
6538         ORIENTATION_0 = ui::toRotationInt(ui::ROTATION_0),
6539         ORIENTATION_90 = ui::toRotationInt(ui::ROTATION_90),
6540         ORIENTATION_180 = ui::toRotationInt(ui::ROTATION_180),
6541         ORIENTATION_270 = ui::toRotationInt(ui::ROTATION_270),
6542         ftl_last = ORIENTATION_270,
6543     };
6544     using Orientation::ORIENTATION_0, Orientation::ORIENTATION_90, Orientation::ORIENTATION_180,
6545             Orientation::ORIENTATION_270;
6546     static const std::map<Orientation, std::array<vec2, 4> /*mappedCorners*/> kMappedCorners = {
6547             {ORIENTATION_0, {{{0, 0}, {479.5, 0}, {479.5, 799.75}, {0, 799.75}}}},
6548             {ORIENTATION_90, {{{0, 479.5}, {0, 0}, {799.75, 0}, {799.75, 479.5}}}},
6549             {ORIENTATION_180, {{{479.5, 799.75}, {0, 799.75}, {0, 0}, {479.5, 0}}}},
6550             {ORIENTATION_270, {{{799.75, 0}, {799.75, 479.5}, {0, 479.5}, {0, 0}}}},
6551     };
6552 
6553     const auto touchscreenOrientation = static_cast<Orientation>(ui::toRotationInt(GetParam()));
6554 
6555     // Configure the touchscreen as being installed in the one of the four different orientations
6556     // relative to the display.
6557     addConfigurationProperty("touch.deviceType", "touchScreen");
6558     addConfigurationProperty("touch.orientation", ftl::enum_string(touchscreenOrientation).c_str());
6559     prepareDisplay(ui::ROTATION_0);
6560 
6561     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6562 
6563     // If the touchscreen is installed in a rotated orientation relative to the display (i.e. in
6564     // orientations of either 90 or 270) this means the display's natural resolution will be
6565     // flipped.
6566     const bool displayRotated =
6567             touchscreenOrientation == ORIENTATION_90 || touchscreenOrientation == ORIENTATION_270;
6568     const int32_t width = displayRotated ? DISPLAY_HEIGHT : DISPLAY_WIDTH;
6569     const int32_t height = displayRotated ? DISPLAY_WIDTH : DISPLAY_HEIGHT;
6570     const Rect physicalFrame{0, 0, width, height};
6571     configurePhysicalDisplay(ui::ROTATION_0, physicalFrame, width, height);
6572 
6573     const auto& expectedPoints = kMappedCorners.at(touchscreenOrientation);
6574     const float expectedPrecisionX = displayRotated ? 4 : 2;
6575     const float expectedPrecisionY = displayRotated ? 2 : 4;
6576 
6577     // Test all four corners.
6578     for (int i = 0; i < 4; i++) {
6579         const auto& raw = kRawCorners[i];
6580         processDown(mapper, raw.x, raw.y);
6581         processSync(mapper);
6582         const auto& expected = expectedPoints[i];
6583         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6584                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
6585                       WithCoords(expected.x, expected.y),
6586                       WithPrecision(expectedPrecisionX, expectedPrecisionY))))
6587                 << "Failed to process raw point (" << raw.x << ", " << raw.y << ") "
6588                 << "with touchscreen orientation "
6589                 << ftl::enum_string(touchscreenOrientation).c_str() << ", expected point ("
6590                 << expected.x << ", " << expected.y << ").";
6591         processUp(mapper);
6592         processSync(mapper);
6593         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6594                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
6595                       WithCoords(expected.x, expected.y))));
6596     }
6597 }
6598 
TEST_P(TouchscreenPrecisionTestsFixture,RotationPrecisionWhenOrientationAware)6599 TEST_P(TouchscreenPrecisionTestsFixture, RotationPrecisionWhenOrientationAware) {
6600     static const std::map<ui::Rotation /*rotation*/, std::array<vec2, 4> /*mappedCorners*/>
6601             kMappedCorners = {
6602                     {ui::ROTATION_0, {{{0, 0}, {479.5, 0}, {479.5, 799.75}, {0, 799.75}}}},
6603                     {ui::ROTATION_90, {{{0.5, 0}, {480, 0}, {480, 799.75}, {0.5, 799.75}}}},
6604                     {ui::ROTATION_180, {{{0.5, 0.25}, {480, 0.25}, {480, 800}, {0.5, 800}}}},
6605                     {ui::ROTATION_270, {{{0, 0.25}, {479.5, 0.25}, {479.5, 800}, {0, 800}}}},
6606             };
6607 
6608     const ui::Rotation displayRotation = GetParam();
6609 
6610     addConfigurationProperty("touch.deviceType", "touchScreen");
6611     prepareDisplay(displayRotation);
6612 
6613     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6614 
6615     const auto& expectedPoints = kMappedCorners.at(displayRotation);
6616 
6617     // Test all four corners.
6618     for (int i = 0; i < 4; i++) {
6619         const auto& expected = expectedPoints[i];
6620         const auto& raw = kRawCorners[i];
6621         processDown(mapper, raw.x, raw.y);
6622         processSync(mapper);
6623         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6624                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
6625                       WithCoords(expected.x, expected.y), WithPrecision(2, 4))))
6626                 << "Failed to process raw point (" << raw.x << ", " << raw.y << ") "
6627                 << "with display rotation " << ui::toCString(displayRotation)
6628                 << ", expected point (" << expected.x << ", " << expected.y << ").";
6629         processUp(mapper);
6630         processSync(mapper);
6631         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6632                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
6633                       WithCoords(expected.x, expected.y))));
6634     }
6635 }
6636 
TEST_P(TouchscreenPrecisionTestsFixture,RotationPrecisionOrientationAwareInOri270)6637 TEST_P(TouchscreenPrecisionTestsFixture, RotationPrecisionOrientationAwareInOri270) {
6638     static const std::map<ui::Rotation /*orientation*/, std::array<vec2, 4> /*mappedCorners*/>
6639             kMappedCorners = {
6640                     {ui::ROTATION_0, {{{799.75, 0}, {799.75, 479.5}, {0, 479.5}, {0, 0}}}},
6641                     {ui::ROTATION_90, {{{800, 0}, {800, 479.5}, {0.25, 479.5}, {0.25, 0}}}},
6642                     {ui::ROTATION_180, {{{800, 0.5}, {800, 480}, {0.25, 480}, {0.25, 0.5}}}},
6643                     {ui::ROTATION_270, {{{799.75, 0.5}, {799.75, 480}, {0, 480}, {0, 0.5}}}},
6644             };
6645 
6646     const ui::Rotation displayRotation = GetParam();
6647 
6648     addConfigurationProperty("touch.deviceType", "touchScreen");
6649     addConfigurationProperty("touch.orientation", "ORIENTATION_270");
6650 
6651     SingleTouchInputMapper& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6652 
6653     // Ori 270, so width and height swapped
6654     const Rect physicalFrame{0, 0, DISPLAY_HEIGHT, DISPLAY_WIDTH};
6655     prepareDisplay(displayRotation);
6656     configurePhysicalDisplay(displayRotation, physicalFrame, DISPLAY_HEIGHT, DISPLAY_WIDTH);
6657 
6658     const auto& expectedPoints = kMappedCorners.at(displayRotation);
6659 
6660     // Test all four corners.
6661     for (int i = 0; i < 4; i++) {
6662         const auto& expected = expectedPoints[i];
6663         const auto& raw = kRawCorners[i];
6664         processDown(mapper, raw.x, raw.y);
6665         processSync(mapper);
6666         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6667                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
6668                       WithCoords(expected.x, expected.y), WithPrecision(4, 2))))
6669                 << "Failed to process raw point (" << raw.x << ", " << raw.y << ") "
6670                 << "with display rotation " << ui::toCString(displayRotation)
6671                 << ", expected point (" << expected.x << ", " << expected.y << ").";
6672         processUp(mapper);
6673         processSync(mapper);
6674         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6675                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
6676                       WithCoords(expected.x, expected.y))));
6677     }
6678 }
6679 
TEST_P(TouchscreenPrecisionTestsFixture,MotionRangesAreOrientedInRotatedDisplay)6680 TEST_P(TouchscreenPrecisionTestsFixture, MotionRangesAreOrientedInRotatedDisplay) {
6681     const ui::Rotation displayRotation = GetParam();
6682 
6683     addConfigurationProperty("touch.deviceType", "touchScreen");
6684     prepareDisplay(displayRotation);
6685 
6686     __attribute__((unused)) SingleTouchInputMapper& mapper =
6687             constructAndAddMapper<SingleTouchInputMapper>();
6688 
6689     const InputDeviceInfo deviceInfo = mDevice->getDeviceInfo();
6690     // MotionRanges use display pixels as their units
6691     const auto* xRange = deviceInfo.getMotionRange(AMOTION_EVENT_AXIS_X, AINPUT_SOURCE_TOUCHSCREEN);
6692     const auto* yRange = deviceInfo.getMotionRange(AMOTION_EVENT_AXIS_Y, AINPUT_SOURCE_TOUCHSCREEN);
6693 
6694     // The MotionRanges should be oriented in the rotated display's coordinate space
6695     const bool displayRotated =
6696             displayRotation == ui::ROTATION_90 || displayRotation == ui::ROTATION_270;
6697 
6698     constexpr float MAX_X = 479.5;
6699     constexpr float MAX_Y = 799.75;
6700     EXPECT_EQ(xRange->min, 0.f);
6701     EXPECT_EQ(yRange->min, 0.f);
6702     EXPECT_EQ(xRange->max, displayRotated ? MAX_Y : MAX_X);
6703     EXPECT_EQ(yRange->max, displayRotated ? MAX_X : MAX_Y);
6704 
6705     EXPECT_EQ(xRange->flat, 8.f);
6706     EXPECT_EQ(yRange->flat, 8.f);
6707 
6708     EXPECT_EQ(xRange->fuzz, 2.f);
6709     EXPECT_EQ(yRange->fuzz, 2.f);
6710 
6711     EXPECT_EQ(xRange->resolution, 25.f); // pixels per millimeter
6712     EXPECT_EQ(yRange->resolution, 25.f); // pixels per millimeter
6713 }
6714 
6715 // Run the precision tests for all rotations.
6716 INSTANTIATE_TEST_SUITE_P(TouchscreenPrecisionTests, TouchscreenPrecisionTestsFixture,
6717                          ::testing::Values(ui::ROTATION_0, ui::ROTATION_90, ui::ROTATION_180,
6718                                            ui::ROTATION_270),
__anonf6e3cc130202(const testing::TestParamInfo<ui::Rotation>& testParamInfo) 6719                          [](const testing::TestParamInfo<ui::Rotation>& testParamInfo) {
6720                              return ftl::enum_string(testParamInfo.param);
6721                          });
6722 
6723 // --- ExternalStylusFusionTest ---
6724 
6725 class ExternalStylusFusionTest : public SingleTouchInputMapperTest {
6726 public:
initializeInputMapperWithExternalStylus()6727     SingleTouchInputMapper& initializeInputMapperWithExternalStylus() {
6728         addConfigurationProperty("touch.deviceType", "touchScreen");
6729         prepareDisplay(ui::ROTATION_0);
6730         prepareButtons();
6731         prepareAxes(POSITION);
6732         auto& mapper = constructAndAddMapper<SingleTouchInputMapper>();
6733 
6734         mStylusState.when = ARBITRARY_TIME;
6735         mStylusState.pressure = 0.f;
6736         mStylusState.toolType = ToolType::STYLUS;
6737         mReader->getContext()->setExternalStylusDevices({mExternalStylusDeviceInfo});
6738         configureDevice(InputReaderConfiguration::Change::EXTERNAL_STYLUS_PRESENCE);
6739         processExternalStylusState(mapper);
6740         return mapper;
6741     }
6742 
processExternalStylusState(InputMapper & mapper)6743     std::list<NotifyArgs> processExternalStylusState(InputMapper& mapper) {
6744         std::list<NotifyArgs> generatedArgs = mapper.updateExternalStylusState(mStylusState);
6745         for (const NotifyArgs& args : generatedArgs) {
6746             mFakeListener->notify(args);
6747         }
6748         // Loop the reader to flush the input listener queue.
6749         mReader->loopOnce();
6750         return generatedArgs;
6751     }
6752 
6753 protected:
6754     StylusState mStylusState{};
6755 
testStartFusedStylusGesture(SingleTouchInputMapper & mapper)6756     void testStartFusedStylusGesture(SingleTouchInputMapper& mapper) {
6757         auto toolTypeSource =
6758                 AllOf(WithSource(STYLUS_FUSION_SOURCE), WithToolType(ToolType::STYLUS));
6759 
6760         // The first pointer is withheld.
6761         processDown(mapper, 100, 200);
6762         processSync(mapper);
6763         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6764         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasRequested(
6765                 ARBITRARY_TIME + EXTERNAL_STYLUS_DATA_TIMEOUT));
6766 
6767         // The external stylus reports pressure. The withheld finger pointer is released as a
6768         // stylus.
6769         mStylusState.pressure = 1.f;
6770         processExternalStylusState(mapper);
6771         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6772                 AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_DOWN))));
6773         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
6774 
6775         // Subsequent pointer events are not withheld.
6776         processMove(mapper, 101, 201);
6777         processSync(mapper);
6778         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6779                 AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE))));
6780 
6781         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
6782         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6783     }
6784 
testSuccessfulFusionGesture(SingleTouchInputMapper & mapper)6785     void testSuccessfulFusionGesture(SingleTouchInputMapper& mapper) {
6786         ASSERT_NO_FATAL_FAILURE(testStartFusedStylusGesture(mapper));
6787 
6788         // Releasing the touch pointer ends the gesture.
6789         processUp(mapper);
6790         processSync(mapper);
6791         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6792                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP), WithSource(STYLUS_FUSION_SOURCE),
6793                       WithToolType(ToolType::STYLUS))));
6794 
6795         mStylusState.pressure = 0.f;
6796         processExternalStylusState(mapper);
6797         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
6798         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6799     }
6800 
testUnsuccessfulFusionGesture(SingleTouchInputMapper & mapper)6801     void testUnsuccessfulFusionGesture(SingleTouchInputMapper& mapper) {
6802         // When stylus fusion is not successful, events should be reported with the original source.
6803         // In this case, it is from a touchscreen.
6804         auto toolTypeSource =
6805                 AllOf(WithSource(AINPUT_SOURCE_TOUCHSCREEN), WithToolType(ToolType::FINGER));
6806 
6807         // The first pointer is withheld when an external stylus is connected,
6808         // and a timeout is requested.
6809         processDown(mapper, 100, 200);
6810         processSync(mapper);
6811         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6812         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasRequested(
6813                 ARBITRARY_TIME + EXTERNAL_STYLUS_DATA_TIMEOUT));
6814 
6815         // If the timeout expires early, it is requested again.
6816         handleTimeout(mapper, ARBITRARY_TIME + 1);
6817         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasRequested(
6818                 ARBITRARY_TIME + EXTERNAL_STYLUS_DATA_TIMEOUT));
6819 
6820         // When the timeout expires, the withheld touch is released as a finger pointer.
6821         handleTimeout(mapper, ARBITRARY_TIME + EXTERNAL_STYLUS_DATA_TIMEOUT);
6822         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6823                 AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_DOWN))));
6824 
6825         // Subsequent pointer events are not withheld.
6826         processMove(mapper, 101, 201);
6827         processSync(mapper);
6828         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6829                 AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE))));
6830         processUp(mapper);
6831         processSync(mapper);
6832         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6833                 AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_UP))));
6834 
6835         ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
6836         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6837     }
6838 
6839 private:
6840     InputDeviceInfo mExternalStylusDeviceInfo{};
6841 };
6842 
TEST_F(ExternalStylusFusionTest,UsesBluetoothStylusSource)6843 TEST_F(ExternalStylusFusionTest, UsesBluetoothStylusSource) {
6844     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
6845     ASSERT_EQ(STYLUS_FUSION_SOURCE, mapper.getSources());
6846 }
6847 
TEST_F(ExternalStylusFusionTest,UnsuccessfulFusion)6848 TEST_F(ExternalStylusFusionTest, UnsuccessfulFusion) {
6849     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
6850     ASSERT_NO_FATAL_FAILURE(testUnsuccessfulFusionGesture(mapper));
6851 }
6852 
TEST_F(ExternalStylusFusionTest,SuccessfulFusion_TouchFirst)6853 TEST_F(ExternalStylusFusionTest, SuccessfulFusion_TouchFirst) {
6854     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
6855     ASSERT_NO_FATAL_FAILURE(testSuccessfulFusionGesture(mapper));
6856 }
6857 
6858 // Test a successful stylus fusion gesture where the pressure is reported by the external
6859 // before the touch is reported by the touchscreen.
TEST_F(ExternalStylusFusionTest,SuccessfulFusion_PressureFirst)6860 TEST_F(ExternalStylusFusionTest, SuccessfulFusion_PressureFirst) {
6861     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
6862     auto toolTypeSource = AllOf(WithSource(STYLUS_FUSION_SOURCE), WithToolType(ToolType::STYLUS));
6863 
6864     // The external stylus reports pressure first. It is ignored for now.
6865     mStylusState.pressure = 1.f;
6866     processExternalStylusState(mapper);
6867     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6868     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
6869 
6870     // When the touch goes down afterwards, it is reported as a stylus pointer.
6871     processDown(mapper, 100, 200);
6872     processSync(mapper);
6873     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6874             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_DOWN))));
6875     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
6876 
6877     processMove(mapper, 101, 201);
6878     processSync(mapper);
6879     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6880             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE))));
6881     processUp(mapper);
6882     processSync(mapper);
6883     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6884             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_UP))));
6885 
6886     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
6887     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6888 }
6889 
TEST_F(ExternalStylusFusionTest,FusionIsRepeatedForEachNewGesture)6890 TEST_F(ExternalStylusFusionTest, FusionIsRepeatedForEachNewGesture) {
6891     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
6892 
6893     ASSERT_NO_FATAL_FAILURE(testSuccessfulFusionGesture(mapper));
6894     ASSERT_NO_FATAL_FAILURE(testUnsuccessfulFusionGesture(mapper));
6895 
6896     ASSERT_NO_FATAL_FAILURE(testSuccessfulFusionGesture(mapper));
6897     ASSERT_NO_FATAL_FAILURE(testSuccessfulFusionGesture(mapper));
6898     ASSERT_NO_FATAL_FAILURE(testUnsuccessfulFusionGesture(mapper));
6899     ASSERT_NO_FATAL_FAILURE(testUnsuccessfulFusionGesture(mapper));
6900 }
6901 
TEST_F(ExternalStylusFusionTest,FusedPointerReportsPressureChanges)6902 TEST_F(ExternalStylusFusionTest, FusedPointerReportsPressureChanges) {
6903     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
6904     auto toolTypeSource = AllOf(WithSource(STYLUS_FUSION_SOURCE), WithToolType(ToolType::STYLUS));
6905 
6906     mStylusState.pressure = 0.8f;
6907     processExternalStylusState(mapper);
6908     processDown(mapper, 100, 200);
6909     processSync(mapper);
6910     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6911             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
6912                   WithPressure(0.8f))));
6913     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
6914 
6915     // The external stylus reports a pressure change. We wait for some time for a touch event.
6916     mStylusState.pressure = 0.6f;
6917     processExternalStylusState(mapper);
6918     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6919     ASSERT_NO_FATAL_FAILURE(
6920             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
6921 
6922     // If a touch is reported within the timeout, it reports the updated pressure.
6923     processMove(mapper, 101, 201);
6924     processSync(mapper);
6925     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6926             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
6927                   WithPressure(0.6f))));
6928     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
6929 
6930     // There is another pressure change.
6931     mStylusState.pressure = 0.5f;
6932     processExternalStylusState(mapper);
6933     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6934     ASSERT_NO_FATAL_FAILURE(
6935             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
6936 
6937     // If a touch is not reported within the timeout, a move event is generated to report
6938     // the new pressure.
6939     handleTimeout(mapper, ARBITRARY_TIME + TOUCH_DATA_TIMEOUT);
6940     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6941             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
6942                   WithPressure(0.5f))));
6943 
6944     // If a zero pressure is reported before the touch goes up, the previous pressure value is
6945     // repeated indefinitely.
6946     mStylusState.pressure = 0.0f;
6947     processExternalStylusState(mapper);
6948     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6949     ASSERT_NO_FATAL_FAILURE(
6950             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
6951     processMove(mapper, 102, 202);
6952     processSync(mapper);
6953     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6954             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
6955                   WithPressure(0.5f))));
6956     processMove(mapper, 103, 203);
6957     processSync(mapper);
6958     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6959             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
6960                   WithPressure(0.5f))));
6961 
6962     processUp(mapper);
6963     processSync(mapper);
6964     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6965             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP), WithSource(STYLUS_FUSION_SOURCE),
6966                   WithToolType(ToolType::STYLUS))));
6967 
6968     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
6969     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6970 }
6971 
TEST_F(ExternalStylusFusionTest,FusedPointerReportsToolTypeChanges)6972 TEST_F(ExternalStylusFusionTest, FusedPointerReportsToolTypeChanges) {
6973     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
6974     auto source = WithSource(STYLUS_FUSION_SOURCE);
6975 
6976     mStylusState.pressure = 1.f;
6977     mStylusState.toolType = ToolType::ERASER;
6978     processExternalStylusState(mapper);
6979     processDown(mapper, 100, 200);
6980     processSync(mapper);
6981     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6982             AllOf(source, WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
6983                   WithToolType(ToolType::ERASER))));
6984     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
6985 
6986     // The external stylus reports a tool change. We wait for some time for a touch event.
6987     mStylusState.toolType = ToolType::STYLUS;
6988     processExternalStylusState(mapper);
6989     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
6990     ASSERT_NO_FATAL_FAILURE(
6991             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
6992 
6993     // If a touch is reported within the timeout, it reports the updated pressure.
6994     processMove(mapper, 101, 201);
6995     processSync(mapper);
6996     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
6997             AllOf(source, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
6998                   WithToolType(ToolType::STYLUS))));
6999     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7000 
7001     // There is another tool type change.
7002     mStylusState.toolType = ToolType::FINGER;
7003     processExternalStylusState(mapper);
7004     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7005     ASSERT_NO_FATAL_FAILURE(
7006             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
7007 
7008     // If a touch is not reported within the timeout, a move event is generated to report
7009     // the new tool type.
7010     handleTimeout(mapper, ARBITRARY_TIME + TOUCH_DATA_TIMEOUT);
7011     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7012             AllOf(source, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
7013                   WithToolType(ToolType::FINGER))));
7014 
7015     processUp(mapper);
7016     processSync(mapper);
7017     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7018             AllOf(source, WithMotionAction(AMOTION_EVENT_ACTION_UP),
7019                   WithToolType(ToolType::FINGER))));
7020 
7021     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7022     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7023 }
7024 
TEST_F(ExternalStylusFusionTest,FusedPointerReportsButtons)7025 TEST_F(ExternalStylusFusionTest, FusedPointerReportsButtons) {
7026     SingleTouchInputMapper& mapper = initializeInputMapperWithExternalStylus();
7027     auto toolTypeSource = AllOf(WithSource(STYLUS_FUSION_SOURCE), WithToolType(ToolType::STYLUS));
7028 
7029     ASSERT_NO_FATAL_FAILURE(testStartFusedStylusGesture(mapper));
7030 
7031     // The external stylus reports a button change. We wait for some time for a touch event.
7032     mStylusState.buttons = AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
7033     processExternalStylusState(mapper);
7034     ASSERT_NO_FATAL_FAILURE(
7035             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
7036 
7037     // If a touch is reported within the timeout, it reports the updated button state.
7038     processMove(mapper, 101, 201);
7039     processSync(mapper);
7040     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7041             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
7042                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
7043     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7044             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
7045                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
7046     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7047 
7048     // The button is now released.
7049     mStylusState.buttons = 0;
7050     processExternalStylusState(mapper);
7051     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7052     ASSERT_NO_FATAL_FAILURE(
7053             mReader->getContext()->assertTimeoutWasRequested(ARBITRARY_TIME + TOUCH_DATA_TIMEOUT));
7054 
7055     // If a touch is not reported within the timeout, a move event is generated to report
7056     // the new button state.
7057     handleTimeout(mapper, ARBITRARY_TIME + TOUCH_DATA_TIMEOUT);
7058     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7059             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
7060                   WithButtonState(0))));
7061     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7062             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
7063                   WithButtonState(0))));
7064 
7065     processUp(mapper);
7066     processSync(mapper);
7067     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
7068             AllOf(toolTypeSource, WithMotionAction(AMOTION_EVENT_ACTION_UP), WithButtonState(0))));
7069 
7070     ASSERT_NO_FATAL_FAILURE(mReader->getContext()->assertTimeoutWasNotRequested());
7071     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7072 }
7073 
7074 // --- MultiTouchInputMapperTest ---
7075 
7076 class MultiTouchInputMapperTest : public TouchInputMapperTest {
7077 protected:
7078     void prepareAxes(int axes);
7079 
7080     void processPosition(MultiTouchInputMapper& mapper, int32_t x, int32_t y);
7081     void processTouchMajor(MultiTouchInputMapper& mapper, int32_t touchMajor);
7082     void processTouchMinor(MultiTouchInputMapper& mapper, int32_t touchMinor);
7083     void processToolMajor(MultiTouchInputMapper& mapper, int32_t toolMajor);
7084     void processToolMinor(MultiTouchInputMapper& mapper, int32_t toolMinor);
7085     void processOrientation(MultiTouchInputMapper& mapper, int32_t orientation);
7086     void processPressure(MultiTouchInputMapper& mapper, int32_t pressure);
7087     void processDistance(MultiTouchInputMapper& mapper, int32_t distance);
7088     void processId(MultiTouchInputMapper& mapper, int32_t id);
7089     void processSlot(MultiTouchInputMapper& mapper, int32_t slot);
7090     void processToolType(MultiTouchInputMapper& mapper, int32_t toolType);
7091     void processKey(MultiTouchInputMapper& mapper, int32_t code, int32_t value);
7092     void processHidUsage(MultiTouchInputMapper& mapper, int32_t usageCode, int32_t value);
7093     void processMTSync(MultiTouchInputMapper& mapper);
7094     void processSync(MultiTouchInputMapper& mapper, nsecs_t eventTime = ARBITRARY_TIME,
7095                      nsecs_t readTime = READ_TIME);
7096 };
7097 
prepareAxes(int axes)7098 void MultiTouchInputMapperTest::prepareAxes(int axes) {
7099     if (axes & POSITION) {
7100         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_X, RAW_X_MIN, RAW_X_MAX, 0, 0);
7101         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_Y, RAW_Y_MIN, RAW_Y_MAX, 0, 0);
7102     }
7103     if (axes & TOUCH) {
7104         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_TOUCH_MAJOR, RAW_TOUCH_MIN,
7105                                        RAW_TOUCH_MAX, 0, 0);
7106         if (axes & MINOR) {
7107             mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_TOUCH_MINOR, RAW_TOUCH_MIN,
7108                                            RAW_TOUCH_MAX, 0, 0);
7109         }
7110     }
7111     if (axes & TOOL) {
7112         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_WIDTH_MAJOR, RAW_TOOL_MIN, RAW_TOOL_MAX,
7113                                        0, 0);
7114         if (axes & MINOR) {
7115             mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_WIDTH_MINOR, RAW_TOOL_MIN,
7116                                            RAW_TOOL_MAX, 0, 0);
7117         }
7118     }
7119     if (axes & ORIENTATION) {
7120         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_ORIENTATION, RAW_ORIENTATION_MIN,
7121                                        RAW_ORIENTATION_MAX, 0, 0);
7122     }
7123     if (axes & PRESSURE) {
7124         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_PRESSURE, RAW_PRESSURE_MIN,
7125                                        RAW_PRESSURE_MAX, 0, 0);
7126     }
7127     if (axes & DISTANCE) {
7128         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_DISTANCE, RAW_DISTANCE_MIN,
7129                                        RAW_DISTANCE_MAX, 0, 0);
7130     }
7131     if (axes & ID) {
7132         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_TRACKING_ID, RAW_ID_MIN, RAW_ID_MAX, 0,
7133                                        0);
7134     }
7135     if (axes & SLOT) {
7136         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_SLOT, RAW_SLOT_MIN, RAW_SLOT_MAX, 0, 0);
7137         mFakeEventHub->setAbsoluteAxisValue(EVENTHUB_ID, ABS_MT_SLOT, 0);
7138     }
7139     if (axes & TOOL_TYPE) {
7140         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_TOOL_TYPE, 0, MT_TOOL_MAX, 0, 0);
7141     }
7142 }
7143 
processPosition(MultiTouchInputMapper & mapper,int32_t x,int32_t y)7144 void MultiTouchInputMapperTest::processPosition(MultiTouchInputMapper& mapper, int32_t x,
7145                                                 int32_t y) {
7146     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_POSITION_X, x);
7147     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_POSITION_Y, y);
7148 }
7149 
processTouchMajor(MultiTouchInputMapper & mapper,int32_t touchMajor)7150 void MultiTouchInputMapperTest::processTouchMajor(MultiTouchInputMapper& mapper,
7151                                                   int32_t touchMajor) {
7152     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_TOUCH_MAJOR, touchMajor);
7153 }
7154 
processTouchMinor(MultiTouchInputMapper & mapper,int32_t touchMinor)7155 void MultiTouchInputMapperTest::processTouchMinor(MultiTouchInputMapper& mapper,
7156                                                   int32_t touchMinor) {
7157     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_TOUCH_MINOR, touchMinor);
7158 }
7159 
processToolMajor(MultiTouchInputMapper & mapper,int32_t toolMajor)7160 void MultiTouchInputMapperTest::processToolMajor(MultiTouchInputMapper& mapper, int32_t toolMajor) {
7161     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_WIDTH_MAJOR, toolMajor);
7162 }
7163 
processToolMinor(MultiTouchInputMapper & mapper,int32_t toolMinor)7164 void MultiTouchInputMapperTest::processToolMinor(MultiTouchInputMapper& mapper, int32_t toolMinor) {
7165     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_WIDTH_MINOR, toolMinor);
7166 }
7167 
processOrientation(MultiTouchInputMapper & mapper,int32_t orientation)7168 void MultiTouchInputMapperTest::processOrientation(MultiTouchInputMapper& mapper,
7169                                                    int32_t orientation) {
7170     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_ORIENTATION, orientation);
7171 }
7172 
processPressure(MultiTouchInputMapper & mapper,int32_t pressure)7173 void MultiTouchInputMapperTest::processPressure(MultiTouchInputMapper& mapper, int32_t pressure) {
7174     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_PRESSURE, pressure);
7175 }
7176 
processDistance(MultiTouchInputMapper & mapper,int32_t distance)7177 void MultiTouchInputMapperTest::processDistance(MultiTouchInputMapper& mapper, int32_t distance) {
7178     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_DISTANCE, distance);
7179 }
7180 
processId(MultiTouchInputMapper & mapper,int32_t id)7181 void MultiTouchInputMapperTest::processId(MultiTouchInputMapper& mapper, int32_t id) {
7182     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_TRACKING_ID, id);
7183 }
7184 
processSlot(MultiTouchInputMapper & mapper,int32_t slot)7185 void MultiTouchInputMapperTest::processSlot(MultiTouchInputMapper& mapper, int32_t slot) {
7186     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_SLOT, slot);
7187 }
7188 
processToolType(MultiTouchInputMapper & mapper,int32_t toolType)7189 void MultiTouchInputMapperTest::processToolType(MultiTouchInputMapper& mapper, int32_t toolType) {
7190     process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, ABS_MT_TOOL_TYPE, toolType);
7191 }
7192 
processKey(MultiTouchInputMapper & mapper,int32_t code,int32_t value)7193 void MultiTouchInputMapperTest::processKey(MultiTouchInputMapper& mapper, int32_t code,
7194                                            int32_t value) {
7195     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, code, value);
7196 }
7197 
processHidUsage(MultiTouchInputMapper & mapper,int32_t usageCode,int32_t value)7198 void MultiTouchInputMapperTest::processHidUsage(MultiTouchInputMapper& mapper, int32_t usageCode,
7199                                                 int32_t value) {
7200     process(mapper, ARBITRARY_TIME, READ_TIME, EV_MSC, MSC_SCAN, usageCode);
7201     process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_UNKNOWN, value);
7202 }
7203 
processMTSync(MultiTouchInputMapper & mapper)7204 void MultiTouchInputMapperTest::processMTSync(MultiTouchInputMapper& mapper) {
7205     process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_MT_REPORT, 0);
7206 }
7207 
processSync(MultiTouchInputMapper & mapper,nsecs_t eventTime,nsecs_t readTime)7208 void MultiTouchInputMapperTest::processSync(MultiTouchInputMapper& mapper, nsecs_t eventTime,
7209                                             nsecs_t readTime) {
7210     process(mapper, eventTime, readTime, EV_SYN, SYN_REPORT, 0);
7211 }
7212 
TEST_F(MultiTouchInputMapperTest,Process_NormalMultiTouchGesture_WithoutTrackingIds)7213 TEST_F(MultiTouchInputMapperTest, Process_NormalMultiTouchGesture_WithoutTrackingIds) {
7214     addConfigurationProperty("touch.deviceType", "touchScreen");
7215     prepareDisplay(ui::ROTATION_0);
7216     prepareAxes(POSITION);
7217     prepareVirtualKeys();
7218     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
7219 
7220     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
7221 
7222     NotifyMotionArgs motionArgs;
7223 
7224     // Two fingers down at once.
7225     int32_t x1 = 100, y1 = 125, x2 = 300, y2 = 500;
7226     processPosition(mapper, x1, y1);
7227     processMTSync(mapper);
7228     processPosition(mapper, x2, y2);
7229     processMTSync(mapper);
7230     processSync(mapper);
7231 
7232     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7233     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7234     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7235     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7236     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7237     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
7238     ASSERT_EQ(0, motionArgs.flags);
7239     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7240     ASSERT_EQ(0, motionArgs.buttonState);
7241     ASSERT_EQ(0, motionArgs.edgeFlags);
7242     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7243     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7244     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7245     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7246             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7247     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7248     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7249     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7250 
7251     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7252     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7253     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7254     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7255     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7256     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
7257     ASSERT_EQ(0, motionArgs.flags);
7258     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7259     ASSERT_EQ(0, motionArgs.buttonState);
7260     ASSERT_EQ(0, motionArgs.edgeFlags);
7261     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7262     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7263     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7264     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7265     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7266     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7267             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7268     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7269             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7270     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7271     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7272     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7273 
7274     // Move.
7275     x1 += 10; y1 += 15; x2 += 5; y2 -= 10;
7276     processPosition(mapper, x1, y1);
7277     processMTSync(mapper);
7278     processPosition(mapper, x2, y2);
7279     processMTSync(mapper);
7280     processSync(mapper);
7281 
7282     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7283     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7284     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7285     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7286     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7287     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7288     ASSERT_EQ(0, motionArgs.flags);
7289     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7290     ASSERT_EQ(0, motionArgs.buttonState);
7291     ASSERT_EQ(0, motionArgs.edgeFlags);
7292     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7293     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7294     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7295     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7296     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7297     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7298             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7299     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7300             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7301     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7302     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7303     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7304 
7305     // First finger up.
7306     x2 += 15; y2 -= 20;
7307     processPosition(mapper, x2, y2);
7308     processMTSync(mapper);
7309     processSync(mapper);
7310 
7311     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7312     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7313     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7314     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7315     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7316     ASSERT_EQ(ACTION_POINTER_0_UP, motionArgs.action);
7317     ASSERT_EQ(0, motionArgs.flags);
7318     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7319     ASSERT_EQ(0, motionArgs.buttonState);
7320     ASSERT_EQ(0, motionArgs.edgeFlags);
7321     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7322     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7323     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7324     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7325     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7326     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7327             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7328     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7329             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7330     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7331     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7332     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7333 
7334     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7335     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7336     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7337     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7338     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7339     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7340     ASSERT_EQ(0, motionArgs.flags);
7341     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7342     ASSERT_EQ(0, motionArgs.buttonState);
7343     ASSERT_EQ(0, motionArgs.edgeFlags);
7344     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7345     ASSERT_EQ(1, motionArgs.pointerProperties[0].id);
7346     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7347     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7348             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7349     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7350     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7351     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7352 
7353     // Move.
7354     x2 += 20; y2 -= 25;
7355     processPosition(mapper, x2, y2);
7356     processMTSync(mapper);
7357     processSync(mapper);
7358 
7359     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7360     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7361     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7362     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7363     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7364     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7365     ASSERT_EQ(0, motionArgs.flags);
7366     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7367     ASSERT_EQ(0, motionArgs.buttonState);
7368     ASSERT_EQ(0, motionArgs.edgeFlags);
7369     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7370     ASSERT_EQ(1, motionArgs.pointerProperties[0].id);
7371     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7372     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7373             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7374     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7375     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7376     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7377 
7378     // New finger down.
7379     int32_t x3 = 700, y3 = 300;
7380     processPosition(mapper, x2, y2);
7381     processMTSync(mapper);
7382     processPosition(mapper, x3, y3);
7383     processMTSync(mapper);
7384     processSync(mapper);
7385 
7386     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7387     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7388     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7389     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7390     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7391     ASSERT_EQ(ACTION_POINTER_0_DOWN, motionArgs.action);
7392     ASSERT_EQ(0, motionArgs.flags);
7393     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7394     ASSERT_EQ(0, motionArgs.buttonState);
7395     ASSERT_EQ(0, motionArgs.edgeFlags);
7396     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7397     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7398     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7399     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7400     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7401     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7402             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
7403     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7404             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7405     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7406     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7407     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7408 
7409     // Second finger up.
7410     x3 += 30; y3 -= 20;
7411     processPosition(mapper, x3, y3);
7412     processMTSync(mapper);
7413     processSync(mapper);
7414 
7415     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7416     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7417     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7418     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7419     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7420     ASSERT_EQ(ACTION_POINTER_1_UP, motionArgs.action);
7421     ASSERT_EQ(0, motionArgs.flags);
7422     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7423     ASSERT_EQ(0, motionArgs.buttonState);
7424     ASSERT_EQ(0, motionArgs.edgeFlags);
7425     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7426     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7427     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7428     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7429     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7430     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7431             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
7432     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7433             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7434     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7435     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7436     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7437 
7438     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7439     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7440     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7441     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7442     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7443     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7444     ASSERT_EQ(0, motionArgs.flags);
7445     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7446     ASSERT_EQ(0, motionArgs.buttonState);
7447     ASSERT_EQ(0, motionArgs.edgeFlags);
7448     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7449     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7450     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7451     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7452             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
7453     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7454     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7455     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7456 
7457     // Last finger up.
7458     processMTSync(mapper);
7459     processSync(mapper);
7460 
7461     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7462     ASSERT_EQ(ARBITRARY_TIME, motionArgs.eventTime);
7463     ASSERT_EQ(DEVICE_ID, motionArgs.deviceId);
7464     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, motionArgs.source);
7465     ASSERT_EQ(uint32_t(0), motionArgs.policyFlags);
7466     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
7467     ASSERT_EQ(0, motionArgs.flags);
7468     ASSERT_EQ(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON, motionArgs.metaState);
7469     ASSERT_EQ(0, motionArgs.buttonState);
7470     ASSERT_EQ(0, motionArgs.edgeFlags);
7471     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7472     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7473     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7474     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7475             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
7476     ASSERT_NEAR(X_PRECISION, motionArgs.xPrecision, EPSILON);
7477     ASSERT_NEAR(Y_PRECISION, motionArgs.yPrecision, EPSILON);
7478     ASSERT_EQ(ARBITRARY_TIME, motionArgs.downTime);
7479 
7480     // Should not have sent any more keys or motions.
7481     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
7482     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7483 }
7484 
TEST_F(MultiTouchInputMapperTest,AxisResolution_IsPopulated)7485 TEST_F(MultiTouchInputMapperTest, AxisResolution_IsPopulated) {
7486     addConfigurationProperty("touch.deviceType", "touchScreen");
7487     prepareDisplay(ui::ROTATION_0);
7488 
7489     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_X, RAW_X_MIN, RAW_X_MAX, /*flat*/ 0,
7490                                    /*fuzz*/ 0, /*resolution*/ 10);
7491     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_Y, RAW_Y_MIN, RAW_Y_MAX, /*flat*/ 0,
7492                                    /*fuzz*/ 0, /*resolution*/ 11);
7493     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_TOUCH_MAJOR, RAW_TOUCH_MIN, RAW_TOUCH_MAX,
7494                                    /*flat*/ 0, /*fuzz*/ 0, /*resolution*/ 12);
7495     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_TOUCH_MINOR, RAW_TOUCH_MIN, RAW_TOUCH_MAX,
7496                                    /*flat*/ 0, /*fuzz*/ 0, /*resolution*/ 13);
7497     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_WIDTH_MAJOR, RAW_TOOL_MIN, RAW_TOOL_MAX,
7498                                    /*flat*/ 0, /*flat*/ 0, /*resolution*/ 14);
7499     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_WIDTH_MINOR, RAW_TOOL_MIN, RAW_TOOL_MAX,
7500                                    /*flat*/ 0, /*flat*/ 0, /*resolution*/ 15);
7501 
7502     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
7503 
7504     // X and Y axes
7505     assertAxisResolution(mapper, AMOTION_EVENT_AXIS_X, 10 / X_PRECISION);
7506     assertAxisResolution(mapper, AMOTION_EVENT_AXIS_Y, 11 / Y_PRECISION);
7507     // Touch major and minor
7508     assertAxisResolution(mapper, AMOTION_EVENT_AXIS_TOUCH_MAJOR, 12 * GEOMETRIC_SCALE);
7509     assertAxisResolution(mapper, AMOTION_EVENT_AXIS_TOUCH_MINOR, 13 * GEOMETRIC_SCALE);
7510     // Tool major and minor
7511     assertAxisResolution(mapper, AMOTION_EVENT_AXIS_TOOL_MAJOR, 14 * GEOMETRIC_SCALE);
7512     assertAxisResolution(mapper, AMOTION_EVENT_AXIS_TOOL_MINOR, 15 * GEOMETRIC_SCALE);
7513 }
7514 
TEST_F(MultiTouchInputMapperTest,TouchMajorAndMinorAxes_DoNotAppearIfNotSupported)7515 TEST_F(MultiTouchInputMapperTest, TouchMajorAndMinorAxes_DoNotAppearIfNotSupported) {
7516     addConfigurationProperty("touch.deviceType", "touchScreen");
7517     prepareDisplay(ui::ROTATION_0);
7518 
7519     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_X, RAW_X_MIN, RAW_X_MAX, /*flat*/ 0,
7520                                    /*fuzz*/ 0, /*resolution*/ 10);
7521     mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_Y, RAW_Y_MIN, RAW_Y_MAX, /*flat*/ 0,
7522                                    /*fuzz*/ 0, /*resolution*/ 11);
7523 
7524     // We do not add ABS_MT_TOUCH_MAJOR / MINOR or ABS_MT_WIDTH_MAJOR / MINOR axes
7525 
7526     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
7527 
7528     // Touch major and minor
7529     assertAxisNotPresent(mapper, AMOTION_EVENT_AXIS_TOUCH_MAJOR);
7530     assertAxisNotPresent(mapper, AMOTION_EVENT_AXIS_TOUCH_MINOR);
7531     // Tool major and minor
7532     assertAxisNotPresent(mapper, AMOTION_EVENT_AXIS_TOOL_MAJOR);
7533     assertAxisNotPresent(mapper, AMOTION_EVENT_AXIS_TOOL_MINOR);
7534 }
7535 
TEST_F(MultiTouchInputMapperTest,Process_NormalMultiTouchGesture_WithTrackingIds)7536 TEST_F(MultiTouchInputMapperTest, Process_NormalMultiTouchGesture_WithTrackingIds) {
7537     addConfigurationProperty("touch.deviceType", "touchScreen");
7538     prepareDisplay(ui::ROTATION_0);
7539     prepareAxes(POSITION | ID);
7540     prepareVirtualKeys();
7541     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
7542 
7543     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
7544 
7545     NotifyMotionArgs motionArgs;
7546 
7547     // Two fingers down at once.
7548     int32_t x1 = 100, y1 = 125, x2 = 300, y2 = 500;
7549     processPosition(mapper, x1, y1);
7550     processId(mapper, 1);
7551     processMTSync(mapper);
7552     processPosition(mapper, x2, y2);
7553     processId(mapper, 2);
7554     processMTSync(mapper);
7555     processSync(mapper);
7556 
7557     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7558     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
7559     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7560     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7561     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7562     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7563             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7564 
7565     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7566     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
7567     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7568     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7569     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7570     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7571     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7572     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7573             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7574     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7575             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7576 
7577     // Move.
7578     x1 += 10; y1 += 15; x2 += 5; y2 -= 10;
7579     processPosition(mapper, x1, y1);
7580     processId(mapper, 1);
7581     processMTSync(mapper);
7582     processPosition(mapper, x2, y2);
7583     processId(mapper, 2);
7584     processMTSync(mapper);
7585     processSync(mapper);
7586 
7587     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7588     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7589     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7590     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7591     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7592     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7593     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7594     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7595             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7596     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7597             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7598 
7599     // First finger up.
7600     x2 += 15; y2 -= 20;
7601     processPosition(mapper, x2, y2);
7602     processId(mapper, 2);
7603     processMTSync(mapper);
7604     processSync(mapper);
7605 
7606     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7607     ASSERT_EQ(ACTION_POINTER_0_UP, motionArgs.action);
7608     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7609     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7610     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7611     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7612     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7613     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7614             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7615     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7616             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7617 
7618     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7619     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7620     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7621     ASSERT_EQ(1, motionArgs.pointerProperties[0].id);
7622     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7623     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7624             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7625 
7626     // Move.
7627     x2 += 20; y2 -= 25;
7628     processPosition(mapper, x2, y2);
7629     processId(mapper, 2);
7630     processMTSync(mapper);
7631     processSync(mapper);
7632 
7633     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7634     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7635     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7636     ASSERT_EQ(1, motionArgs.pointerProperties[0].id);
7637     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7638     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7639             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7640 
7641     // New finger down.
7642     int32_t x3 = 700, y3 = 300;
7643     processPosition(mapper, x2, y2);
7644     processId(mapper, 2);
7645     processMTSync(mapper);
7646     processPosition(mapper, x3, y3);
7647     processId(mapper, 3);
7648     processMTSync(mapper);
7649     processSync(mapper);
7650 
7651     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7652     ASSERT_EQ(ACTION_POINTER_0_DOWN, motionArgs.action);
7653     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7654     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7655     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7656     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7657     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7658     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7659             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
7660     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7661             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7662 
7663     // Second finger up.
7664     x3 += 30; y3 -= 20;
7665     processPosition(mapper, x3, y3);
7666     processId(mapper, 3);
7667     processMTSync(mapper);
7668     processSync(mapper);
7669 
7670     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7671     ASSERT_EQ(ACTION_POINTER_1_UP, motionArgs.action);
7672     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7673     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7674     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7675     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7676     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7677     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7678             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
7679     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7680             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7681 
7682     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7683     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7684     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7685     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7686     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7687     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7688             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
7689 
7690     // Last finger up.
7691     processMTSync(mapper);
7692     processSync(mapper);
7693 
7694     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7695     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
7696     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7697     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7698     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7699     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7700             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
7701 
7702     // Should not have sent any more keys or motions.
7703     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
7704     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7705 }
7706 
TEST_F(MultiTouchInputMapperTest,Process_NormalMultiTouchGesture_WithSlots)7707 TEST_F(MultiTouchInputMapperTest, Process_NormalMultiTouchGesture_WithSlots) {
7708     addConfigurationProperty("touch.deviceType", "touchScreen");
7709     prepareDisplay(ui::ROTATION_0);
7710     prepareAxes(POSITION | ID | SLOT);
7711     prepareVirtualKeys();
7712     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
7713 
7714     mReader->getContext()->setGlobalMetaState(AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_ON);
7715 
7716     NotifyMotionArgs motionArgs;
7717 
7718     // Two fingers down at once.
7719     int32_t x1 = 100, y1 = 125, x2 = 300, y2 = 500;
7720     processPosition(mapper, x1, y1);
7721     processId(mapper, 1);
7722     processSlot(mapper, 1);
7723     processPosition(mapper, x2, y2);
7724     processId(mapper, 2);
7725     processSync(mapper);
7726 
7727     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7728     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
7729     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7730     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7731     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7732     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7733             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7734 
7735     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7736     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
7737     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7738     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7739     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7740     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7741     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7742     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7743             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7744     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7745             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7746 
7747     // Move.
7748     x1 += 10; y1 += 15; x2 += 5; y2 -= 10;
7749     processSlot(mapper, 0);
7750     processPosition(mapper, x1, y1);
7751     processSlot(mapper, 1);
7752     processPosition(mapper, x2, y2);
7753     processSync(mapper);
7754 
7755     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7756     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7757     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7758     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7759     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7760     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7761     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7762     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7763             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7764     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7765             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7766 
7767     // First finger up.
7768     x2 += 15; y2 -= 20;
7769     processSlot(mapper, 0);
7770     processId(mapper, -1);
7771     processSlot(mapper, 1);
7772     processPosition(mapper, x2, y2);
7773     processSync(mapper);
7774 
7775     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7776     ASSERT_EQ(ACTION_POINTER_0_UP, motionArgs.action);
7777     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7778     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7779     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7780     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7781     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7782     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7783             toDisplayX(x1), toDisplayY(y1), 1, 0, 0, 0, 0, 0, 0, 0));
7784     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7785             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7786 
7787     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7788     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7789     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7790     ASSERT_EQ(1, motionArgs.pointerProperties[0].id);
7791     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7792     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7793             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7794 
7795     // Move.
7796     x2 += 20; y2 -= 25;
7797     processPosition(mapper, x2, y2);
7798     processSync(mapper);
7799 
7800     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7801     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7802     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7803     ASSERT_EQ(1, motionArgs.pointerProperties[0].id);
7804     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7805     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7806             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7807 
7808     // New finger down.
7809     int32_t x3 = 700, y3 = 300;
7810     processPosition(mapper, x2, y2);
7811     processSlot(mapper, 0);
7812     processId(mapper, 3);
7813     processPosition(mapper, x3, y3);
7814     processSync(mapper);
7815 
7816     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7817     ASSERT_EQ(ACTION_POINTER_0_DOWN, motionArgs.action);
7818     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7819     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7820     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7821     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7822     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7823     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7824             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
7825     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7826             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7827 
7828     // Second finger up.
7829     x3 += 30; y3 -= 20;
7830     processSlot(mapper, 1);
7831     processId(mapper, -1);
7832     processSlot(mapper, 0);
7833     processPosition(mapper, x3, y3);
7834     processSync(mapper);
7835 
7836     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7837     ASSERT_EQ(ACTION_POINTER_1_UP, motionArgs.action);
7838     ASSERT_EQ(size_t(2), motionArgs.getPointerCount());
7839     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7840     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7841     ASSERT_EQ(1, motionArgs.pointerProperties[1].id);
7842     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
7843     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7844             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
7845     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1],
7846             toDisplayX(x2), toDisplayY(y2), 1, 0, 0, 0, 0, 0, 0, 0));
7847 
7848     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7849     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
7850     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7851     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7852     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7853     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7854             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
7855 
7856     // Last finger up.
7857     processId(mapper, -1);
7858     processSync(mapper);
7859 
7860     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
7861     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
7862     ASSERT_EQ(size_t(1), motionArgs.getPointerCount());
7863     ASSERT_EQ(0, motionArgs.pointerProperties[0].id);
7864     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
7865     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
7866             toDisplayX(x3), toDisplayY(y3), 1, 0, 0, 0, 0, 0, 0, 0));
7867 
7868     // Should not have sent any more keys or motions.
7869     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
7870     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
7871 }
7872 
TEST_F(MultiTouchInputMapperTest,Process_AllAxes_WithDefaultCalibration)7873 TEST_F(MultiTouchInputMapperTest, Process_AllAxes_WithDefaultCalibration) {
7874     addConfigurationProperty("touch.deviceType", "touchScreen");
7875     prepareDisplay(ui::ROTATION_0);
7876     prepareAxes(POSITION | TOUCH | TOOL | PRESSURE | ORIENTATION | ID | MINOR | DISTANCE);
7877     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
7878 
7879     // These calculations are based on the input device calibration documentation.
7880     int32_t rawX = 100;
7881     int32_t rawY = 200;
7882     int32_t rawTouchMajor = 7;
7883     int32_t rawTouchMinor = 6;
7884     int32_t rawToolMajor = 9;
7885     int32_t rawToolMinor = 8;
7886     int32_t rawPressure = 11;
7887     int32_t rawDistance = 0;
7888     int32_t rawOrientation = 3;
7889     int32_t id = 5;
7890 
7891     float x = toDisplayX(rawX);
7892     float y = toDisplayY(rawY);
7893     float pressure = float(rawPressure) / RAW_PRESSURE_MAX;
7894     float size = avg(rawTouchMajor, rawTouchMinor) / RAW_TOUCH_MAX;
7895     float toolMajor = float(rawToolMajor) * GEOMETRIC_SCALE;
7896     float toolMinor = float(rawToolMinor) * GEOMETRIC_SCALE;
7897     float touchMajor = float(rawTouchMajor) * GEOMETRIC_SCALE;
7898     float touchMinor = float(rawTouchMinor) * GEOMETRIC_SCALE;
7899     float orientation = float(rawOrientation) / RAW_ORIENTATION_MAX * M_PI_2;
7900     float distance = float(rawDistance);
7901 
7902     processPosition(mapper, rawX, rawY);
7903     processTouchMajor(mapper, rawTouchMajor);
7904     processTouchMinor(mapper, rawTouchMinor);
7905     processToolMajor(mapper, rawToolMajor);
7906     processToolMinor(mapper, rawToolMinor);
7907     processPressure(mapper, rawPressure);
7908     processOrientation(mapper, rawOrientation);
7909     processDistance(mapper, rawDistance);
7910     processId(mapper, id);
7911     processMTSync(mapper);
7912     processSync(mapper);
7913 
7914     NotifyMotionArgs args;
7915     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
7916     ASSERT_EQ(0, args.pointerProperties[0].id);
7917     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
7918             x, y, pressure, size, touchMajor, touchMinor, toolMajor, toolMinor,
7919             orientation, distance));
7920     ASSERT_EQ(args.flags, AMOTION_EVENT_PRIVATE_FLAG_SUPPORTS_ORIENTATION);
7921 }
7922 
TEST_F(MultiTouchInputMapperTest,Process_TouchAndToolAxes_GeometricCalibration)7923 TEST_F(MultiTouchInputMapperTest, Process_TouchAndToolAxes_GeometricCalibration) {
7924     addConfigurationProperty("touch.deviceType", "touchScreen");
7925     prepareDisplay(ui::ROTATION_0);
7926     prepareAxes(POSITION | TOUCH | TOOL | MINOR);
7927     addConfigurationProperty("touch.size.calibration", "geometric");
7928     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
7929 
7930     // These calculations are based on the input device calibration documentation.
7931     int32_t rawX = 100;
7932     int32_t rawY = 200;
7933     int32_t rawTouchMajor = 140;
7934     int32_t rawTouchMinor = 120;
7935     int32_t rawToolMajor = 180;
7936     int32_t rawToolMinor = 160;
7937 
7938     float x = toDisplayX(rawX);
7939     float y = toDisplayY(rawY);
7940     float size = avg(rawTouchMajor, rawTouchMinor) / RAW_TOUCH_MAX;
7941     float toolMajor = float(rawToolMajor) * GEOMETRIC_SCALE;
7942     float toolMinor = float(rawToolMinor) * GEOMETRIC_SCALE;
7943     float touchMajor = float(rawTouchMajor) * GEOMETRIC_SCALE;
7944     float touchMinor = float(rawTouchMinor) * GEOMETRIC_SCALE;
7945 
7946     processPosition(mapper, rawX, rawY);
7947     processTouchMajor(mapper, rawTouchMajor);
7948     processTouchMinor(mapper, rawTouchMinor);
7949     processToolMajor(mapper, rawToolMajor);
7950     processToolMinor(mapper, rawToolMinor);
7951     processMTSync(mapper);
7952     processSync(mapper);
7953 
7954     NotifyMotionArgs args;
7955     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
7956     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
7957             x, y, 1.0f, size, touchMajor, touchMinor, toolMajor, toolMinor, 0, 0));
7958 }
7959 
TEST_F(MultiTouchInputMapperTest,Process_TouchAndToolAxes_SummedLinearCalibration)7960 TEST_F(MultiTouchInputMapperTest, Process_TouchAndToolAxes_SummedLinearCalibration) {
7961     addConfigurationProperty("touch.deviceType", "touchScreen");
7962     prepareDisplay(ui::ROTATION_0);
7963     prepareAxes(POSITION | TOUCH | TOOL);
7964     addConfigurationProperty("touch.size.calibration", "diameter");
7965     addConfigurationProperty("touch.size.scale", "10");
7966     addConfigurationProperty("touch.size.bias", "160");
7967     addConfigurationProperty("touch.size.isSummed", "1");
7968     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
7969 
7970     // These calculations are based on the input device calibration documentation.
7971     // Note: We only provide a single common touch/tool value because the device is assumed
7972     //       not to emit separate values for each pointer (isSummed = 1).
7973     int32_t rawX = 100;
7974     int32_t rawY = 200;
7975     int32_t rawX2 = 150;
7976     int32_t rawY2 = 250;
7977     int32_t rawTouchMajor = 5;
7978     int32_t rawToolMajor = 8;
7979 
7980     float x = toDisplayX(rawX);
7981     float y = toDisplayY(rawY);
7982     float x2 = toDisplayX(rawX2);
7983     float y2 = toDisplayY(rawY2);
7984     float size = float(rawTouchMajor) / 2 / RAW_TOUCH_MAX;
7985     float touch = float(rawTouchMajor) / 2 * 10.0f + 160.0f;
7986     float tool = float(rawToolMajor) / 2 * 10.0f + 160.0f;
7987 
7988     processPosition(mapper, rawX, rawY);
7989     processTouchMajor(mapper, rawTouchMajor);
7990     processToolMajor(mapper, rawToolMajor);
7991     processMTSync(mapper);
7992     processPosition(mapper, rawX2, rawY2);
7993     processTouchMajor(mapper, rawTouchMajor);
7994     processToolMajor(mapper, rawToolMajor);
7995     processMTSync(mapper);
7996     processSync(mapper);
7997 
7998     NotifyMotionArgs args;
7999     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8000     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
8001 
8002     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8003     ASSERT_EQ(ACTION_POINTER_1_DOWN, args.action);
8004     ASSERT_EQ(size_t(2), args.getPointerCount());
8005     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
8006             x, y, 1.0f, size, touch, touch, tool, tool, 0, 0));
8007     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[1],
8008             x2, y2, 1.0f, size, touch, touch, tool, tool, 0, 0));
8009 }
8010 
TEST_F(MultiTouchInputMapperTest,Process_TouchAndToolAxes_AreaCalibration)8011 TEST_F(MultiTouchInputMapperTest, Process_TouchAndToolAxes_AreaCalibration) {
8012     addConfigurationProperty("touch.deviceType", "touchScreen");
8013     prepareDisplay(ui::ROTATION_0);
8014     prepareAxes(POSITION | TOUCH | TOOL);
8015     addConfigurationProperty("touch.size.calibration", "area");
8016     addConfigurationProperty("touch.size.scale", "43");
8017     addConfigurationProperty("touch.size.bias", "3");
8018     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8019 
8020     // These calculations are based on the input device calibration documentation.
8021     int32_t rawX = 100;
8022     int32_t rawY = 200;
8023     int32_t rawTouchMajor = 5;
8024     int32_t rawToolMajor = 8;
8025 
8026     float x = toDisplayX(rawX);
8027     float y = toDisplayY(rawY);
8028     float size = float(rawTouchMajor) / RAW_TOUCH_MAX;
8029     float touch = sqrtf(rawTouchMajor) * 43.0f + 3.0f;
8030     float tool = sqrtf(rawToolMajor) * 43.0f + 3.0f;
8031 
8032     processPosition(mapper, rawX, rawY);
8033     processTouchMajor(mapper, rawTouchMajor);
8034     processToolMajor(mapper, rawToolMajor);
8035     processMTSync(mapper);
8036     processSync(mapper);
8037 
8038     NotifyMotionArgs args;
8039     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8040     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
8041             x, y, 1.0f, size, touch, touch, tool, tool, 0, 0));
8042 }
8043 
TEST_F(MultiTouchInputMapperTest,Process_PressureAxis_AmplitudeCalibration)8044 TEST_F(MultiTouchInputMapperTest, Process_PressureAxis_AmplitudeCalibration) {
8045     addConfigurationProperty("touch.deviceType", "touchScreen");
8046     prepareDisplay(ui::ROTATION_0);
8047     prepareAxes(POSITION | PRESSURE);
8048     addConfigurationProperty("touch.pressure.calibration", "amplitude");
8049     addConfigurationProperty("touch.pressure.scale", "0.01");
8050     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8051 
8052     InputDeviceInfo info;
8053     mapper.populateDeviceInfo(info);
8054     ASSERT_NO_FATAL_FAILURE(assertMotionRange(info,
8055             AINPUT_MOTION_RANGE_PRESSURE, AINPUT_SOURCE_TOUCHSCREEN,
8056             0.0f, RAW_PRESSURE_MAX * 0.01, 0.0f, 0.0f));
8057 
8058     // These calculations are based on the input device calibration documentation.
8059     int32_t rawX = 100;
8060     int32_t rawY = 200;
8061     int32_t rawPressure = 60;
8062 
8063     float x = toDisplayX(rawX);
8064     float y = toDisplayY(rawY);
8065     float pressure = float(rawPressure) * 0.01f;
8066 
8067     processPosition(mapper, rawX, rawY);
8068     processPressure(mapper, rawPressure);
8069     processMTSync(mapper);
8070     processSync(mapper);
8071 
8072     NotifyMotionArgs args;
8073     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8074     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
8075             x, y, pressure, 0, 0, 0, 0, 0, 0, 0));
8076 }
8077 
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandleAllButtons)8078 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandleAllButtons) {
8079     addConfigurationProperty("touch.deviceType", "touchScreen");
8080     prepareDisplay(ui::ROTATION_0);
8081     prepareAxes(POSITION | ID | SLOT);
8082     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8083 
8084     NotifyMotionArgs motionArgs;
8085     NotifyKeyArgs keyArgs;
8086 
8087     processId(mapper, 1);
8088     processPosition(mapper, 100, 200);
8089     processSync(mapper);
8090     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8091     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
8092     ASSERT_EQ(0, motionArgs.buttonState);
8093 
8094     // press BTN_LEFT, release BTN_LEFT
8095     processKey(mapper, BTN_LEFT, 1);
8096     processSync(mapper);
8097     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8098     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8099     ASSERT_EQ(AMOTION_EVENT_BUTTON_PRIMARY, motionArgs.buttonState);
8100 
8101     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8102     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8103     ASSERT_EQ(AMOTION_EVENT_BUTTON_PRIMARY, motionArgs.buttonState);
8104 
8105     processKey(mapper, BTN_LEFT, 0);
8106     processSync(mapper);
8107     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8108     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8109     ASSERT_EQ(0, motionArgs.buttonState);
8110 
8111     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8112     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8113     ASSERT_EQ(0, motionArgs.buttonState);
8114 
8115     // press BTN_RIGHT + BTN_MIDDLE, release BTN_RIGHT, release BTN_MIDDLE
8116     processKey(mapper, BTN_RIGHT, 1);
8117     processKey(mapper, BTN_MIDDLE, 1);
8118     processSync(mapper);
8119     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8120     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8121     ASSERT_EQ(AMOTION_EVENT_BUTTON_SECONDARY | AMOTION_EVENT_BUTTON_TERTIARY,
8122             motionArgs.buttonState);
8123 
8124     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8125     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8126     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
8127 
8128     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8129     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8130     ASSERT_EQ(AMOTION_EVENT_BUTTON_SECONDARY | AMOTION_EVENT_BUTTON_TERTIARY,
8131             motionArgs.buttonState);
8132 
8133     processKey(mapper, BTN_RIGHT, 0);
8134     processSync(mapper);
8135     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8136     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8137     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
8138 
8139     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8140     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8141     ASSERT_EQ(AMOTION_EVENT_BUTTON_TERTIARY, motionArgs.buttonState);
8142 
8143     processKey(mapper, BTN_MIDDLE, 0);
8144     processSync(mapper);
8145     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8146     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8147     ASSERT_EQ(0, motionArgs.buttonState);
8148 
8149     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8150     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8151     ASSERT_EQ(0, motionArgs.buttonState);
8152 
8153     // press BTN_BACK, release BTN_BACK
8154     processKey(mapper, BTN_BACK, 1);
8155     processSync(mapper);
8156     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8157     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
8158     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
8159 
8160     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8161     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8162     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
8163 
8164     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8165     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8166     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
8167 
8168     processKey(mapper, BTN_BACK, 0);
8169     processSync(mapper);
8170     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8171     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8172     ASSERT_EQ(0, motionArgs.buttonState);
8173 
8174     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8175     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8176     ASSERT_EQ(0, motionArgs.buttonState);
8177 
8178     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8179     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
8180     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
8181 
8182     // press BTN_SIDE, release BTN_SIDE
8183     processKey(mapper, BTN_SIDE, 1);
8184     processSync(mapper);
8185     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8186     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
8187     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
8188 
8189     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8190     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8191     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
8192 
8193     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8194     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8195     ASSERT_EQ(AMOTION_EVENT_BUTTON_BACK, motionArgs.buttonState);
8196 
8197     processKey(mapper, BTN_SIDE, 0);
8198     processSync(mapper);
8199     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8200     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8201     ASSERT_EQ(0, motionArgs.buttonState);
8202 
8203     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8204     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8205     ASSERT_EQ(0, motionArgs.buttonState);
8206 
8207     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8208     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
8209     ASSERT_EQ(AKEYCODE_BACK, keyArgs.keyCode);
8210 
8211     // press BTN_FORWARD, release BTN_FORWARD
8212     processKey(mapper, BTN_FORWARD, 1);
8213     processSync(mapper);
8214     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8215     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
8216     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
8217 
8218     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8219     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8220     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
8221 
8222     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8223     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8224     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
8225 
8226     processKey(mapper, BTN_FORWARD, 0);
8227     processSync(mapper);
8228     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8229     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8230     ASSERT_EQ(0, motionArgs.buttonState);
8231 
8232     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8233     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8234     ASSERT_EQ(0, motionArgs.buttonState);
8235 
8236     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8237     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
8238     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
8239 
8240     // press BTN_EXTRA, release BTN_EXTRA
8241     processKey(mapper, BTN_EXTRA, 1);
8242     processSync(mapper);
8243     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8244     ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, keyArgs.action);
8245     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
8246 
8247     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8248     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8249     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
8250 
8251     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8252     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8253     ASSERT_EQ(AMOTION_EVENT_BUTTON_FORWARD, motionArgs.buttonState);
8254 
8255     processKey(mapper, BTN_EXTRA, 0);
8256     processSync(mapper);
8257     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8258     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8259     ASSERT_EQ(0, motionArgs.buttonState);
8260 
8261     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8262     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8263     ASSERT_EQ(0, motionArgs.buttonState);
8264 
8265     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&keyArgs));
8266     ASSERT_EQ(AKEY_EVENT_ACTION_UP, keyArgs.action);
8267     ASSERT_EQ(AKEYCODE_FORWARD, keyArgs.keyCode);
8268 
8269     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasNotCalled());
8270 
8271     // press BTN_STYLUS, release BTN_STYLUS
8272     processKey(mapper, BTN_STYLUS, 1);
8273     processSync(mapper);
8274     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8275     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8276     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY, motionArgs.buttonState);
8277 
8278     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8279     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8280     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY, motionArgs.buttonState);
8281 
8282     processKey(mapper, BTN_STYLUS, 0);
8283     processSync(mapper);
8284     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8285     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8286     ASSERT_EQ(0, motionArgs.buttonState);
8287 
8288     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8289     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8290     ASSERT_EQ(0, motionArgs.buttonState);
8291 
8292     // press BTN_STYLUS2, release BTN_STYLUS2
8293     processKey(mapper, BTN_STYLUS2, 1);
8294     processSync(mapper);
8295     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8296     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8297     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_SECONDARY, motionArgs.buttonState);
8298 
8299     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8300     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, motionArgs.action);
8301     ASSERT_EQ(AMOTION_EVENT_BUTTON_STYLUS_SECONDARY, motionArgs.buttonState);
8302 
8303     processKey(mapper, BTN_STYLUS2, 0);
8304     processSync(mapper);
8305     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8306     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, motionArgs.action);
8307     ASSERT_EQ(0, motionArgs.buttonState);
8308 
8309     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8310     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8311     ASSERT_EQ(0, motionArgs.buttonState);
8312 
8313     // release touch
8314     processId(mapper, -1);
8315     processSync(mapper);
8316     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8317     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
8318     ASSERT_EQ(0, motionArgs.buttonState);
8319 }
8320 
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandleMappedStylusButtons)8321 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandleMappedStylusButtons) {
8322     addConfigurationProperty("touch.deviceType", "touchScreen");
8323     prepareDisplay(ui::ROTATION_0);
8324     prepareAxes(POSITION | ID | SLOT);
8325     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8326 
8327     mFakeEventHub->addKey(EVENTHUB_ID, BTN_A, 0, AKEYCODE_STYLUS_BUTTON_PRIMARY, 0);
8328     mFakeEventHub->addKey(EVENTHUB_ID, 0, 0xabcd, AKEYCODE_STYLUS_BUTTON_SECONDARY, 0);
8329 
8330     // Touch down.
8331     processId(mapper, 1);
8332     processPosition(mapper, 100, 200);
8333     processSync(mapper);
8334     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8335             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithButtonState(0))));
8336 
8337     // Press and release button mapped to the primary stylus button.
8338     processKey(mapper, BTN_A, 1);
8339     processSync(mapper);
8340     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8341             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
8342                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
8343     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8344             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
8345                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY))));
8346 
8347     processKey(mapper, BTN_A, 0);
8348     processSync(mapper);
8349     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8350             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE), WithButtonState(0))));
8351     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8352             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE), WithButtonState(0))));
8353 
8354     // Press and release the HID usage mapped to the secondary stylus button.
8355     processHidUsage(mapper, 0xabcd, 1);
8356     processSync(mapper);
8357     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8358             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
8359                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_SECONDARY))));
8360     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8361             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
8362                   WithButtonState(AMOTION_EVENT_BUTTON_STYLUS_SECONDARY))));
8363 
8364     processHidUsage(mapper, 0xabcd, 0);
8365     processSync(mapper);
8366     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8367             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE), WithButtonState(0))));
8368     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8369             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE), WithButtonState(0))));
8370 
8371     // Release touch.
8372     processId(mapper, -1);
8373     processSync(mapper);
8374     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8375             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP), WithButtonState(0))));
8376 }
8377 
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandleAllToolTypes)8378 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandleAllToolTypes) {
8379     addConfigurationProperty("touch.deviceType", "touchScreen");
8380     prepareDisplay(ui::ROTATION_0);
8381     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE);
8382     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8383 
8384     NotifyMotionArgs motionArgs;
8385 
8386     // default tool type is finger
8387     processId(mapper, 1);
8388     processPosition(mapper, 100, 200);
8389     processSync(mapper);
8390     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8391     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
8392     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8393 
8394     // eraser
8395     processKey(mapper, BTN_TOOL_RUBBER, 1);
8396     processSync(mapper);
8397     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8398     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8399     ASSERT_EQ(ToolType::ERASER, motionArgs.pointerProperties[0].toolType);
8400 
8401     // stylus
8402     processKey(mapper, BTN_TOOL_RUBBER, 0);
8403     processKey(mapper, BTN_TOOL_PEN, 1);
8404     processSync(mapper);
8405     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8406     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8407     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
8408 
8409     // brush
8410     processKey(mapper, BTN_TOOL_PEN, 0);
8411     processKey(mapper, BTN_TOOL_BRUSH, 1);
8412     processSync(mapper);
8413     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8414     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8415     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
8416 
8417     // pencil
8418     processKey(mapper, BTN_TOOL_BRUSH, 0);
8419     processKey(mapper, BTN_TOOL_PENCIL, 1);
8420     processSync(mapper);
8421     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8422     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8423     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
8424 
8425     // air-brush
8426     processKey(mapper, BTN_TOOL_PENCIL, 0);
8427     processKey(mapper, BTN_TOOL_AIRBRUSH, 1);
8428     processSync(mapper);
8429     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8430     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8431     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
8432 
8433     // mouse
8434     processKey(mapper, BTN_TOOL_AIRBRUSH, 0);
8435     processKey(mapper, BTN_TOOL_MOUSE, 1);
8436     processSync(mapper);
8437     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8438     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8439     ASSERT_EQ(ToolType::MOUSE, motionArgs.pointerProperties[0].toolType);
8440 
8441     // lens
8442     processKey(mapper, BTN_TOOL_MOUSE, 0);
8443     processKey(mapper, BTN_TOOL_LENS, 1);
8444     processSync(mapper);
8445     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8446     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8447     ASSERT_EQ(ToolType::MOUSE, motionArgs.pointerProperties[0].toolType);
8448 
8449     // double-tap
8450     processKey(mapper, BTN_TOOL_LENS, 0);
8451     processKey(mapper, BTN_TOOL_DOUBLETAP, 1);
8452     processSync(mapper);
8453     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8454     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8455     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8456 
8457     // triple-tap
8458     processKey(mapper, BTN_TOOL_DOUBLETAP, 0);
8459     processKey(mapper, BTN_TOOL_TRIPLETAP, 1);
8460     processSync(mapper);
8461     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8462     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8463     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8464 
8465     // quad-tap
8466     processKey(mapper, BTN_TOOL_TRIPLETAP, 0);
8467     processKey(mapper, BTN_TOOL_QUADTAP, 1);
8468     processSync(mapper);
8469     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8470     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8471     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8472 
8473     // finger
8474     processKey(mapper, BTN_TOOL_QUADTAP, 0);
8475     processKey(mapper, BTN_TOOL_FINGER, 1);
8476     processSync(mapper);
8477     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8478     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8479     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8480 
8481     // stylus trumps finger
8482     processKey(mapper, BTN_TOOL_PEN, 1);
8483     processSync(mapper);
8484     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8485     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8486     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
8487 
8488     // eraser trumps stylus
8489     processKey(mapper, BTN_TOOL_RUBBER, 1);
8490     processSync(mapper);
8491     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8492     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8493     ASSERT_EQ(ToolType::ERASER, motionArgs.pointerProperties[0].toolType);
8494 
8495     // mouse trumps eraser
8496     processKey(mapper, BTN_TOOL_MOUSE, 1);
8497     processSync(mapper);
8498     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8499     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8500     ASSERT_EQ(ToolType::MOUSE, motionArgs.pointerProperties[0].toolType);
8501 
8502     // MT tool type trumps BTN tool types: MT_TOOL_FINGER
8503     processToolType(mapper, MT_TOOL_FINGER); // this is the first time we send MT_TOOL_TYPE
8504     processSync(mapper);
8505     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8506     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8507     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8508 
8509     // MT tool type trumps BTN tool types: MT_TOOL_PEN
8510     processToolType(mapper, MT_TOOL_PEN);
8511     processSync(mapper);
8512     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8513     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8514     ASSERT_EQ(ToolType::STYLUS, motionArgs.pointerProperties[0].toolType);
8515 
8516     // back to default tool type
8517     processToolType(mapper, -1); // use a deliberately undefined tool type, for testing
8518     processKey(mapper, BTN_TOOL_MOUSE, 0);
8519     processKey(mapper, BTN_TOOL_RUBBER, 0);
8520     processKey(mapper, BTN_TOOL_PEN, 0);
8521     processKey(mapper, BTN_TOOL_FINGER, 0);
8522     processSync(mapper);
8523     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8524     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
8525     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
8526 }
8527 
TEST_F(MultiTouchInputMapperTest,Process_WhenBtnTouchPresent_HoversIfItsValueIsZero)8528 TEST_F(MultiTouchInputMapperTest, Process_WhenBtnTouchPresent_HoversIfItsValueIsZero) {
8529     addConfigurationProperty("touch.deviceType", "touchScreen");
8530     prepareDisplay(ui::ROTATION_0);
8531     prepareAxes(POSITION | ID | SLOT);
8532     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOUCH, 0, AKEYCODE_UNKNOWN, 0);
8533     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8534 
8535     NotifyMotionArgs motionArgs;
8536 
8537     // initially hovering because BTN_TOUCH not sent yet, pressure defaults to 0
8538     processId(mapper, 1);
8539     processPosition(mapper, 100, 200);
8540     processSync(mapper);
8541     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8542     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
8543     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8544             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
8545 
8546     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8547     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
8548     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8549             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
8550 
8551     // move a little
8552     processPosition(mapper, 150, 250);
8553     processSync(mapper);
8554     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8555     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
8556     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8557             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
8558 
8559     // down when BTN_TOUCH is pressed, pressure defaults to 1
8560     processKey(mapper, BTN_TOUCH, 1);
8561     processSync(mapper);
8562     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8563     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
8564     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8565             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
8566 
8567     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8568     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
8569     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8570             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
8571 
8572     // up when BTN_TOUCH is released, hover restored
8573     processKey(mapper, BTN_TOUCH, 0);
8574     processSync(mapper);
8575     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8576     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
8577     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8578             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
8579 
8580     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8581     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
8582     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8583             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
8584 
8585     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8586     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
8587     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8588             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
8589 
8590     // exit hover when pointer goes away
8591     processId(mapper, -1);
8592     processSync(mapper);
8593     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8594     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
8595     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8596             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
8597 }
8598 
TEST_F(MultiTouchInputMapperTest,Process_WhenAbsMTPressureIsPresent_HoversIfItsValueIsZero)8599 TEST_F(MultiTouchInputMapperTest, Process_WhenAbsMTPressureIsPresent_HoversIfItsValueIsZero) {
8600     addConfigurationProperty("touch.deviceType", "touchScreen");
8601     prepareDisplay(ui::ROTATION_0);
8602     prepareAxes(POSITION | ID | SLOT | PRESSURE);
8603     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8604 
8605     NotifyMotionArgs motionArgs;
8606 
8607     // initially hovering because pressure is 0
8608     processId(mapper, 1);
8609     processPosition(mapper, 100, 200);
8610     processPressure(mapper, 0);
8611     processSync(mapper);
8612     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8613     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
8614     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8615             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
8616 
8617     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8618     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
8619     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8620             toDisplayX(100), toDisplayY(200), 0, 0, 0, 0, 0, 0, 0, 0));
8621 
8622     // move a little
8623     processPosition(mapper, 150, 250);
8624     processSync(mapper);
8625     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8626     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
8627     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8628             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
8629 
8630     // down when pressure becomes non-zero
8631     processPressure(mapper, RAW_PRESSURE_MAX);
8632     processSync(mapper);
8633     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8634     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
8635     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8636             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
8637 
8638     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8639     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
8640     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8641             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
8642 
8643     // up when pressure becomes 0, hover restored
8644     processPressure(mapper, 0);
8645     processSync(mapper);
8646     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8647     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
8648     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8649             toDisplayX(150), toDisplayY(250), 1, 0, 0, 0, 0, 0, 0, 0));
8650 
8651     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8652     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_ENTER, motionArgs.action);
8653     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8654             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
8655 
8656     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8657     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
8658     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8659             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
8660 
8661     // exit hover when pointer goes away
8662     processId(mapper, -1);
8663     processSync(mapper);
8664     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8665     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_EXIT, motionArgs.action);
8666     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0],
8667             toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0));
8668 }
8669 
8670 /**
8671  * Set the input device port <--> display port associations, and check that the
8672  * events are routed to the display that matches the display port.
8673  * This can be checked by looking at the displayId of the resulting NotifyMotionArgs.
8674  */
TEST_F(MultiTouchInputMapperTest,Configure_AssignsDisplayPort)8675 TEST_F(MultiTouchInputMapperTest, Configure_AssignsDisplayPort) {
8676     const std::string usb2 = "USB2";
8677     const uint8_t hdmi1 = 0;
8678     const uint8_t hdmi2 = 1;
8679     const std::string secondaryUniqueId = "uniqueId2";
8680     constexpr ViewportType type = ViewportType::EXTERNAL;
8681 
8682     addConfigurationProperty("touch.deviceType", "touchScreen");
8683     prepareAxes(POSITION);
8684     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8685 
8686     mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi1);
8687     mFakePolicy->addInputPortAssociation(usb2, hdmi2);
8688 
8689     // We are intentionally not adding the viewport for display 1 yet. Since the port association
8690     // for this input device is specified, and the matching viewport is not present,
8691     // the input device should be disabled (at the mapper level).
8692 
8693     // Add viewport for display 2 on hdmi2
8694     prepareSecondaryDisplay(type, hdmi2);
8695     // Send a touch event
8696     processPosition(mapper, 100, 100);
8697     processSync(mapper);
8698     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
8699 
8700     // Add viewport for display 1 on hdmi1
8701     prepareDisplay(ui::ROTATION_0, hdmi1);
8702     // Send a touch event again
8703     processPosition(mapper, 100, 100);
8704     processSync(mapper);
8705 
8706     NotifyMotionArgs args;
8707     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8708     ASSERT_EQ(DISPLAY_ID, args.displayId);
8709 }
8710 
TEST_F(MultiTouchInputMapperTest,Configure_AssignsDisplayUniqueId)8711 TEST_F(MultiTouchInputMapperTest, Configure_AssignsDisplayUniqueId) {
8712     addConfigurationProperty("touch.deviceType", "touchScreen");
8713     prepareAxes(POSITION);
8714     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8715 
8716     mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, VIRTUAL_DISPLAY_UNIQUE_ID);
8717 
8718     prepareDisplay(ui::ROTATION_0);
8719     prepareVirtualDisplay(ui::ROTATION_0);
8720 
8721     // Send a touch event
8722     processPosition(mapper, 100, 100);
8723     processSync(mapper);
8724 
8725     NotifyMotionArgs args;
8726     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8727     ASSERT_EQ(VIRTUAL_DISPLAY_ID, args.displayId);
8728 }
8729 
TEST_F(MultiTouchInputMapperTest,Process_Pointer_ShouldHandleDisplayId)8730 TEST_F(MultiTouchInputMapperTest, Process_Pointer_ShouldHandleDisplayId) {
8731     prepareSecondaryDisplay(ViewportType::EXTERNAL);
8732 
8733     prepareDisplay(ui::ROTATION_0);
8734     prepareAxes(POSITION);
8735     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8736 
8737     ASSERT_EQ(AINPUT_SOURCE_MOUSE, mapper.getSources());
8738 
8739     NotifyMotionArgs motionArgs;
8740     processPosition(mapper, 100, 100);
8741     processSync(mapper);
8742 
8743     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8744     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action);
8745     ASSERT_EQ(ui::LogicalDisplayId::INVALID, motionArgs.displayId);
8746 }
8747 
8748 /**
8749  * Ensure that the readTime is set to the SYN_REPORT value when processing touch events.
8750  */
TEST_F(MultiTouchInputMapperTest,Process_SendsReadTime)8751 TEST_F(MultiTouchInputMapperTest, Process_SendsReadTime) {
8752     addConfigurationProperty("touch.deviceType", "touchScreen");
8753     prepareAxes(POSITION);
8754     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8755 
8756     prepareDisplay(ui::ROTATION_0);
8757     process(mapper, 10, /*readTime=*/11, EV_ABS, ABS_MT_TRACKING_ID, 1);
8758     process(mapper, 15, /*readTime=*/16, EV_ABS, ABS_MT_POSITION_X, 100);
8759     process(mapper, 20, /*readTime=*/21, EV_ABS, ABS_MT_POSITION_Y, 100);
8760     process(mapper, 25, /*readTime=*/26, EV_SYN, SYN_REPORT, 0);
8761 
8762     NotifyMotionArgs args;
8763     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8764     ASSERT_EQ(26, args.readTime);
8765 
8766     process(mapper, 30, /*readTime=*/31, EV_ABS, ABS_MT_POSITION_X, 110);
8767     process(mapper, 30, /*readTime=*/32, EV_ABS, ABS_MT_POSITION_Y, 220);
8768     process(mapper, 30, /*readTime=*/33, EV_SYN, SYN_REPORT, 0);
8769 
8770     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
8771     ASSERT_EQ(33, args.readTime);
8772 }
8773 
8774 /**
8775  * When the viewport is not active (isActive=false), the touch mapper should be disabled and the
8776  * events should not be delivered to the listener.
8777  */
TEST_F(MultiTouchInputMapperTest,WhenViewportIsNotActive_TouchesAreDropped)8778 TEST_F(MultiTouchInputMapperTest, WhenViewportIsNotActive_TouchesAreDropped) {
8779     addConfigurationProperty("touch.deviceType", "touchScreen");
8780     // Don't set touch.enableForInactiveViewport to verify the default behavior.
8781     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
8782                                     /*isActive=*/false, UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
8783     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
8784     prepareAxes(POSITION);
8785     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8786 
8787     NotifyMotionArgs motionArgs;
8788     processPosition(mapper, 100, 100);
8789     processSync(mapper);
8790 
8791     mFakeListener->assertNotifyMotionWasNotCalled();
8792 }
8793 
8794 /**
8795  * When the viewport is not active (isActive=false) and touch.enableForInactiveViewport is true,
8796  * the touch mapper can process the events and the events can be delivered to the listener.
8797  */
TEST_F(MultiTouchInputMapperTest,WhenViewportIsNotActive_TouchesAreProcessed)8798 TEST_F(MultiTouchInputMapperTest, WhenViewportIsNotActive_TouchesAreProcessed) {
8799     addConfigurationProperty("touch.deviceType", "touchScreen");
8800     addConfigurationProperty("touch.enableForInactiveViewport", "1");
8801     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
8802                                     /*isActive=*/false, UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
8803     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
8804     prepareAxes(POSITION);
8805     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8806 
8807     NotifyMotionArgs motionArgs;
8808     processPosition(mapper, 100, 100);
8809     processSync(mapper);
8810 
8811     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8812     EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
8813 }
8814 
8815 /**
8816  * When the viewport is deactivated (isActive transitions from true to false),
8817  * and touch.enableForInactiveViewport is false, touches prior to the transition
8818  * should be cancelled.
8819  */
TEST_F(MultiTouchInputMapperTest,Process_DeactivateViewport_AbortTouches)8820 TEST_F(MultiTouchInputMapperTest, Process_DeactivateViewport_AbortTouches) {
8821     addConfigurationProperty("touch.deviceType", "touchScreen");
8822     addConfigurationProperty("touch.enableForInactiveViewport", "0");
8823     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
8824                                     /*isActive=*/true, UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
8825     std::optional<DisplayViewport> optionalDisplayViewport =
8826             mFakePolicy->getDisplayViewportByUniqueId(UNIQUE_ID);
8827     ASSERT_TRUE(optionalDisplayViewport.has_value());
8828     DisplayViewport displayViewport = *optionalDisplayViewport;
8829 
8830     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
8831     prepareAxes(POSITION);
8832     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8833 
8834     // Finger down
8835     int32_t x = 100, y = 100;
8836     processPosition(mapper, x, y);
8837     processSync(mapper);
8838 
8839     NotifyMotionArgs motionArgs;
8840     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8841     EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
8842 
8843     // Deactivate display viewport
8844     displayViewport.isActive = false;
8845     ASSERT_TRUE(mFakePolicy->updateViewport(displayViewport));
8846     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
8847 
8848     // The ongoing touch should be canceled immediately
8849     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8850     EXPECT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionArgs.action);
8851 
8852     // Finger move is ignored
8853     x += 10, y += 10;
8854     processPosition(mapper, x, y);
8855     processSync(mapper);
8856     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
8857 
8858     // Reactivate display viewport
8859     displayViewport.isActive = true;
8860     ASSERT_TRUE(mFakePolicy->updateViewport(displayViewport));
8861     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
8862 
8863     // Finger move again starts new gesture
8864     x += 10, y += 10;
8865     processPosition(mapper, x, y);
8866     processSync(mapper);
8867     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8868     EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
8869 }
8870 
8871 /**
8872  * When the viewport is deactivated (isActive transitions from true to false),
8873  * and touch.enableForInactiveViewport is true, touches prior to the transition
8874  * should not be cancelled.
8875  */
TEST_F(MultiTouchInputMapperTest,Process_DeactivateViewport_TouchesNotAborted)8876 TEST_F(MultiTouchInputMapperTest, Process_DeactivateViewport_TouchesNotAborted) {
8877     addConfigurationProperty("touch.deviceType", "touchScreen");
8878     addConfigurationProperty("touch.enableForInactiveViewport", "1");
8879     mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, ui::ROTATION_0,
8880                                     /*isActive=*/true, UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
8881     std::optional<DisplayViewport> optionalDisplayViewport =
8882             mFakePolicy->getDisplayViewportByUniqueId(UNIQUE_ID);
8883     ASSERT_TRUE(optionalDisplayViewport.has_value());
8884     DisplayViewport displayViewport = *optionalDisplayViewport;
8885 
8886     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
8887     prepareAxes(POSITION);
8888     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8889 
8890     // Finger down
8891     int32_t x = 100, y = 100;
8892     processPosition(mapper, x, y);
8893     processSync(mapper);
8894     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8895             WithMotionAction(AMOTION_EVENT_ACTION_DOWN)));
8896 
8897     // Deactivate display viewport
8898     displayViewport.isActive = false;
8899     ASSERT_TRUE(mFakePolicy->updateViewport(displayViewport));
8900     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
8901 
8902     // The ongoing touch should not be canceled
8903     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
8904 
8905     // Finger move is not ignored
8906     x += 10, y += 10;
8907     processPosition(mapper, x, y);
8908     processSync(mapper);
8909     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8910             WithMotionAction(AMOTION_EVENT_ACTION_MOVE)));
8911 
8912     // Reactivate display viewport
8913     displayViewport.isActive = true;
8914     ASSERT_TRUE(mFakePolicy->updateViewport(displayViewport));
8915     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
8916 
8917     // Finger move continues and does not start new gesture
8918     x += 10, y += 10;
8919     processPosition(mapper, x, y);
8920     processSync(mapper);
8921     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
8922             WithMotionAction(AMOTION_EVENT_ACTION_MOVE)));
8923 }
8924 
TEST_F(MultiTouchInputMapperTest,VideoFrames_ReceivedByListener)8925 TEST_F(MultiTouchInputMapperTest, VideoFrames_ReceivedByListener) {
8926     prepareAxes(POSITION);
8927     addConfigurationProperty("touch.deviceType", "touchScreen");
8928     prepareDisplay(ui::ROTATION_0);
8929     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8930 
8931     NotifyMotionArgs motionArgs;
8932     // Unrotated video frame
8933     TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, {1, 2});
8934     std::vector<TouchVideoFrame> frames{frame};
8935     mFakeEventHub->setVideoFrames({{EVENTHUB_ID, frames}});
8936     processPosition(mapper, 100, 200);
8937     processSync(mapper);
8938     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8939     ASSERT_EQ(frames, motionArgs.videoFrames);
8940 
8941     // Subsequent touch events should not have any videoframes
8942     // This is implemented separately in FakeEventHub,
8943     // but that should match the behaviour of TouchVideoDevice.
8944     processPosition(mapper, 200, 200);
8945     processSync(mapper);
8946     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8947     ASSERT_EQ(std::vector<TouchVideoFrame>(), motionArgs.videoFrames);
8948 }
8949 
TEST_F(MultiTouchInputMapperTest,VideoFrames_AreNotRotated)8950 TEST_F(MultiTouchInputMapperTest, VideoFrames_AreNotRotated) {
8951     prepareAxes(POSITION);
8952     addConfigurationProperty("touch.deviceType", "touchScreen");
8953     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8954     // Unrotated video frame
8955     TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, {1, 2});
8956     NotifyMotionArgs motionArgs;
8957 
8958     // Test all 4 orientations
8959     for (ui::Rotation orientation : ftl::enum_range<ui::Rotation>()) {
8960         SCOPED_TRACE(StringPrintf("Orientation %s", ftl::enum_string(orientation).c_str()));
8961         clearViewports();
8962         prepareDisplay(orientation);
8963         std::vector<TouchVideoFrame> frames{frame};
8964         mFakeEventHub->setVideoFrames({{EVENTHUB_ID, frames}});
8965         processPosition(mapper, 100, 200);
8966         processSync(mapper);
8967         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8968         ASSERT_EQ(frames, motionArgs.videoFrames);
8969     }
8970 }
8971 
TEST_F(MultiTouchInputMapperTest,VideoFrames_WhenNotOrientationAware_AreRotated)8972 TEST_F(MultiTouchInputMapperTest, VideoFrames_WhenNotOrientationAware_AreRotated) {
8973     prepareAxes(POSITION);
8974     addConfigurationProperty("touch.deviceType", "touchScreen");
8975     // Since InputReader works in the un-rotated coordinate space, only devices that are not
8976     // orientation-aware are affected by display rotation.
8977     addConfigurationProperty("touch.orientationAware", "0");
8978     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
8979     // Unrotated video frame
8980     TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, {1, 2});
8981     NotifyMotionArgs motionArgs;
8982 
8983     // Test all 4 orientations
8984     for (ui::Rotation orientation : ftl::enum_range<ui::Rotation>()) {
8985         SCOPED_TRACE(StringPrintf("Orientation %s", ftl::enum_string(orientation).c_str()));
8986         clearViewports();
8987         prepareDisplay(orientation);
8988         std::vector<TouchVideoFrame> frames{frame};
8989         mFakeEventHub->setVideoFrames({{EVENTHUB_ID, frames}});
8990         processPosition(mapper, 100, 200);
8991         processSync(mapper);
8992         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
8993         // We expect the raw coordinates of the MotionEvent to be rotated in the inverse direction
8994         // compared to the display. This is so that when the window transform (which contains the
8995         // display rotation) is applied later by InputDispatcher, the coordinates end up in the
8996         // window's coordinate space.
8997         frames[0].rotate(getInverseRotation(orientation));
8998         ASSERT_EQ(frames, motionArgs.videoFrames);
8999 
9000         // Release finger.
9001         processSync(mapper);
9002         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9003     }
9004 }
9005 
TEST_F(MultiTouchInputMapperTest,VideoFrames_MultipleFramesAreNotRotated)9006 TEST_F(MultiTouchInputMapperTest, VideoFrames_MultipleFramesAreNotRotated) {
9007     prepareAxes(POSITION);
9008     addConfigurationProperty("touch.deviceType", "touchScreen");
9009     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9010     // Unrotated video frames. There's no rule that they must all have the same dimensions,
9011     // so mix these.
9012     TouchVideoFrame frame1(3, 2, {1, 2, 3, 4, 5, 6}, {1, 2});
9013     TouchVideoFrame frame2(3, 3, {0, 1, 2, 3, 4, 5, 6, 7, 8}, {1, 3});
9014     TouchVideoFrame frame3(2, 2, {10, 20, 10, 0}, {1, 4});
9015     std::vector<TouchVideoFrame> frames{frame1, frame2, frame3};
9016     NotifyMotionArgs motionArgs;
9017 
9018     prepareDisplay(ui::ROTATION_90);
9019     mFakeEventHub->setVideoFrames({{EVENTHUB_ID, frames}});
9020     processPosition(mapper, 100, 200);
9021     processSync(mapper);
9022     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9023     ASSERT_EQ(frames, motionArgs.videoFrames);
9024 }
9025 
TEST_F(MultiTouchInputMapperTest,VideoFrames_WhenNotOrientationAware_MultipleFramesAreRotated)9026 TEST_F(MultiTouchInputMapperTest, VideoFrames_WhenNotOrientationAware_MultipleFramesAreRotated) {
9027     prepareAxes(POSITION);
9028     addConfigurationProperty("touch.deviceType", "touchScreen");
9029     // Since InputReader works in the un-rotated coordinate space, only devices that are not
9030     // orientation-aware are affected by display rotation.
9031     addConfigurationProperty("touch.orientationAware", "0");
9032     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9033     // Unrotated video frames. There's no rule that they must all have the same dimensions,
9034     // so mix these.
9035     TouchVideoFrame frame1(3, 2, {1, 2, 3, 4, 5, 6}, {1, 2});
9036     TouchVideoFrame frame2(3, 3, {0, 1, 2, 3, 4, 5, 6, 7, 8}, {1, 3});
9037     TouchVideoFrame frame3(2, 2, {10, 20, 10, 0}, {1, 4});
9038     std::vector<TouchVideoFrame> frames{frame1, frame2, frame3};
9039     NotifyMotionArgs motionArgs;
9040 
9041     prepareDisplay(ui::ROTATION_90);
9042     mFakeEventHub->setVideoFrames({{EVENTHUB_ID, frames}});
9043     processPosition(mapper, 100, 200);
9044     processSync(mapper);
9045     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9046     std::for_each(frames.begin(), frames.end(), [](TouchVideoFrame& frame) {
9047         // We expect the raw coordinates of the MotionEvent to be rotated in the inverse direction
9048         // compared to the display. This is so that when the window transform (which contains the
9049         // display rotation) is applied later by InputDispatcher, the coordinates end up in the
9050         // window's coordinate space.
9051         frame.rotate(getInverseRotation(ui::ROTATION_90));
9052     });
9053     ASSERT_EQ(frames, motionArgs.videoFrames);
9054 }
9055 
9056 /**
9057  * If we had defined port associations, but the viewport is not ready, the touch device would be
9058  * expected to be disabled, and it should be enabled after the viewport has found.
9059  */
TEST_F(MultiTouchInputMapperTest,Configure_EnabledForAssociatedDisplay)9060 TEST_F(MultiTouchInputMapperTest, Configure_EnabledForAssociatedDisplay) {
9061     constexpr uint8_t hdmi2 = 1;
9062     const std::string secondaryUniqueId = "uniqueId2";
9063     constexpr ViewportType type = ViewportType::EXTERNAL;
9064 
9065     mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi2);
9066 
9067     addConfigurationProperty("touch.deviceType", "touchScreen");
9068     prepareAxes(POSITION);
9069     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9070 
9071     ASSERT_EQ(mDevice->isEnabled(), false);
9072 
9073     // Add display on hdmi2, the device should be enabled and can receive touch event.
9074     prepareSecondaryDisplay(type, hdmi2);
9075     ASSERT_EQ(mDevice->isEnabled(), true);
9076 
9077     // Send a touch event.
9078     processPosition(mapper, 100, 100);
9079     processSync(mapper);
9080 
9081     NotifyMotionArgs args;
9082     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
9083     ASSERT_EQ(SECONDARY_DISPLAY_ID, args.displayId);
9084 }
9085 
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandleSingleTouch)9086 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandleSingleTouch) {
9087     addConfigurationProperty("touch.deviceType", "touchScreen");
9088     prepareDisplay(ui::ROTATION_0);
9089     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE);
9090     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9091 
9092     NotifyMotionArgs motionArgs;
9093 
9094     constexpr int32_t x1 = 100, y1 = 200, x2 = 120, y2 = 220, x3 = 140, y3 = 240;
9095     // finger down
9096     processId(mapper, 1);
9097     processPosition(mapper, x1, y1);
9098     processSync(mapper);
9099     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9100     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9101     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9102 
9103     // finger move
9104     processId(mapper, 1);
9105     processPosition(mapper, x2, y2);
9106     processSync(mapper);
9107     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9108     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9109     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9110 
9111     // finger up.
9112     processId(mapper, -1);
9113     processSync(mapper);
9114     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9115     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
9116     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9117 
9118     // new finger down
9119     processId(mapper, 1);
9120     processPosition(mapper, x3, y3);
9121     processSync(mapper);
9122     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9123     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9124     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9125 }
9126 
9127 /**
9128  * Test single touch should be canceled when received the MT_TOOL_PALM event, and the following
9129  * MOVE and UP events should be ignored.
9130  */
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandlePalmToolType_SinglePointer)9131 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandlePalmToolType_SinglePointer) {
9132     addConfigurationProperty("touch.deviceType", "touchScreen");
9133     prepareDisplay(ui::ROTATION_0);
9134     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE);
9135     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9136 
9137     NotifyMotionArgs motionArgs;
9138 
9139     // default tool type is finger
9140     constexpr int32_t x1 = 100, y1 = 200, x2 = 120, y2 = 220, x3 = 140, y3 = 240;
9141     processId(mapper, FIRST_TRACKING_ID);
9142     processPosition(mapper, x1, y1);
9143     processSync(mapper);
9144     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9145     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9146     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9147 
9148     // Tool changed to MT_TOOL_PALM expect sending the cancel event.
9149     processToolType(mapper, MT_TOOL_PALM);
9150     processSync(mapper);
9151     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9152     ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionArgs.action);
9153 
9154     // Ignore the following MOVE and UP events if had detect a palm event.
9155     processId(mapper, FIRST_TRACKING_ID);
9156     processPosition(mapper, x2, y2);
9157     processSync(mapper);
9158     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
9159 
9160     // finger up.
9161     processId(mapper, INVALID_TRACKING_ID);
9162     processSync(mapper);
9163     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
9164 
9165     // new finger down
9166     processId(mapper, FIRST_TRACKING_ID);
9167     processToolType(mapper, MT_TOOL_FINGER);
9168     processPosition(mapper, x3, y3);
9169     processSync(mapper);
9170     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9171     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9172     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9173 }
9174 
9175 /**
9176  * Test multi-touch should sent POINTER_UP when received the MT_TOOL_PALM event from some finger,
9177  * and the rest active fingers could still be allowed to receive the events
9178  */
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandlePalmToolType_TwoPointers)9179 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandlePalmToolType_TwoPointers) {
9180     addConfigurationProperty("touch.deviceType", "touchScreen");
9181     prepareDisplay(ui::ROTATION_0);
9182     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE);
9183     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9184 
9185     NotifyMotionArgs motionArgs;
9186 
9187     // default tool type is finger
9188     constexpr int32_t x1 = 100, y1 = 200, x2 = 120, y2 = 220;
9189     processId(mapper, FIRST_TRACKING_ID);
9190     processPosition(mapper, x1, y1);
9191     processSync(mapper);
9192     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9193     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9194     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9195 
9196     // Second finger down.
9197     processSlot(mapper, SECOND_SLOT);
9198     processId(mapper, SECOND_TRACKING_ID);
9199     processPosition(mapper, x2, y2);
9200     processSync(mapper);
9201     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9202     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
9203     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[1].toolType);
9204 
9205     // If the tool type of the first finger changes to MT_TOOL_PALM,
9206     // we expect to receive ACTION_POINTER_UP with cancel flag.
9207     processSlot(mapper, FIRST_SLOT);
9208     processId(mapper, FIRST_TRACKING_ID);
9209     processToolType(mapper, MT_TOOL_PALM);
9210     processSync(mapper);
9211     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9212     ASSERT_EQ(ACTION_POINTER_0_UP, motionArgs.action);
9213     ASSERT_EQ(AMOTION_EVENT_FLAG_CANCELED, motionArgs.flags);
9214 
9215     // The following MOVE events of second finger should be processed.
9216     processSlot(mapper, SECOND_SLOT);
9217     processId(mapper, SECOND_TRACKING_ID);
9218     processPosition(mapper, x2 + 1, y2 + 1);
9219     processSync(mapper);
9220     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9221     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9222     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9223 
9224     // First finger up. It used to be in palm mode, and we already generated ACTION_POINTER_UP for
9225     // it. Second finger receive move.
9226     processSlot(mapper, FIRST_SLOT);
9227     processId(mapper, INVALID_TRACKING_ID);
9228     processSync(mapper);
9229     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9230     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9231     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9232 
9233     // Second finger keeps moving.
9234     processSlot(mapper, SECOND_SLOT);
9235     processId(mapper, SECOND_TRACKING_ID);
9236     processPosition(mapper, x2 + 2, y2 + 2);
9237     processSync(mapper);
9238     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9239     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9240     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9241 
9242     // Second finger up.
9243     processId(mapper, INVALID_TRACKING_ID);
9244     processSync(mapper);
9245     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9246     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
9247     ASSERT_NE(AMOTION_EVENT_FLAG_CANCELED, motionArgs.flags);
9248 }
9249 
9250 /**
9251  * Test multi-touch should sent POINTER_UP when received the MT_TOOL_PALM event, if only 1 finger
9252  * is active, it should send CANCEL after receiving the MT_TOOL_PALM event.
9253  */
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandlePalmToolType_ShouldCancelWhenAllTouchIsPalm)9254 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandlePalmToolType_ShouldCancelWhenAllTouchIsPalm) {
9255     addConfigurationProperty("touch.deviceType", "touchScreen");
9256     prepareDisplay(ui::ROTATION_0);
9257     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE);
9258     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9259 
9260     NotifyMotionArgs motionArgs;
9261 
9262     constexpr int32_t x1 = 100, y1 = 200, x2 = 120, y2 = 220, x3 = 140, y3 = 240;
9263     // First finger down.
9264     processId(mapper, FIRST_TRACKING_ID);
9265     processPosition(mapper, x1, y1);
9266     processSync(mapper);
9267     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9268     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9269     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9270 
9271     // Second finger down.
9272     processSlot(mapper, SECOND_SLOT);
9273     processId(mapper, SECOND_TRACKING_ID);
9274     processPosition(mapper, x2, y2);
9275     processSync(mapper);
9276     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9277     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
9278     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9279 
9280     // If the tool type of the first finger changes to MT_TOOL_PALM,
9281     // we expect to receive ACTION_POINTER_UP with cancel flag.
9282     processSlot(mapper, FIRST_SLOT);
9283     processId(mapper, FIRST_TRACKING_ID);
9284     processToolType(mapper, MT_TOOL_PALM);
9285     processSync(mapper);
9286     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9287     ASSERT_EQ(ACTION_POINTER_0_UP, motionArgs.action);
9288     ASSERT_EQ(AMOTION_EVENT_FLAG_CANCELED, motionArgs.flags);
9289 
9290     // Second finger keeps moving.
9291     processSlot(mapper, SECOND_SLOT);
9292     processId(mapper, SECOND_TRACKING_ID);
9293     processPosition(mapper, x2 + 1, y2 + 1);
9294     processSync(mapper);
9295     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9296     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9297 
9298     // second finger becomes palm, receive cancel due to only 1 finger is active.
9299     processId(mapper, SECOND_TRACKING_ID);
9300     processToolType(mapper, MT_TOOL_PALM);
9301     processSync(mapper);
9302     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9303     ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionArgs.action);
9304 
9305     // third finger down.
9306     processSlot(mapper, THIRD_SLOT);
9307     processId(mapper, THIRD_TRACKING_ID);
9308     processToolType(mapper, MT_TOOL_FINGER);
9309     processPosition(mapper, x3, y3);
9310     processSync(mapper);
9311     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9312     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9313     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9314     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9315 
9316     // third finger move
9317     processId(mapper, THIRD_TRACKING_ID);
9318     processPosition(mapper, x3 + 1, y3 + 1);
9319     processSync(mapper);
9320     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9321     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9322 
9323     // first finger up, third finger receive move.
9324     processSlot(mapper, FIRST_SLOT);
9325     processId(mapper, INVALID_TRACKING_ID);
9326     processSync(mapper);
9327     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9328     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9329     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9330 
9331     // second finger up, third finger receive move.
9332     processSlot(mapper, SECOND_SLOT);
9333     processId(mapper, INVALID_TRACKING_ID);
9334     processSync(mapper);
9335     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9336     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9337     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9338 
9339     // third finger up.
9340     processSlot(mapper, THIRD_SLOT);
9341     processId(mapper, INVALID_TRACKING_ID);
9342     processSync(mapper);
9343     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9344     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
9345     ASSERT_NE(AMOTION_EVENT_FLAG_CANCELED, motionArgs.flags);
9346 }
9347 
9348 /**
9349  * Test multi-touch should sent POINTER_UP when received the MT_TOOL_PALM event from some finger,
9350  * and the active finger could still be allowed to receive the events
9351  */
TEST_F(MultiTouchInputMapperTest,Process_ShouldHandlePalmToolType_KeepFirstPointer)9352 TEST_F(MultiTouchInputMapperTest, Process_ShouldHandlePalmToolType_KeepFirstPointer) {
9353     addConfigurationProperty("touch.deviceType", "touchScreen");
9354     prepareDisplay(ui::ROTATION_0);
9355     prepareAxes(POSITION | ID | SLOT | TOOL_TYPE);
9356     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9357 
9358     NotifyMotionArgs motionArgs;
9359 
9360     // default tool type is finger
9361     constexpr int32_t x1 = 100, y1 = 200, x2 = 120, y2 = 220;
9362     processId(mapper, FIRST_TRACKING_ID);
9363     processPosition(mapper, x1, y1);
9364     processSync(mapper);
9365     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9366     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9367     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9368 
9369     // Second finger down.
9370     processSlot(mapper, SECOND_SLOT);
9371     processId(mapper, SECOND_TRACKING_ID);
9372     processPosition(mapper, x2, y2);
9373     processSync(mapper);
9374     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9375     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
9376     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9377 
9378     // If the tool type of the second finger changes to MT_TOOL_PALM,
9379     // we expect to receive ACTION_POINTER_UP with cancel flag.
9380     processId(mapper, SECOND_TRACKING_ID);
9381     processToolType(mapper, MT_TOOL_PALM);
9382     processSync(mapper);
9383     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9384     ASSERT_EQ(ACTION_POINTER_1_UP, motionArgs.action);
9385     ASSERT_EQ(AMOTION_EVENT_FLAG_CANCELED, motionArgs.flags);
9386 
9387     // The following MOVE event should be processed.
9388     processSlot(mapper, FIRST_SLOT);
9389     processId(mapper, FIRST_TRACKING_ID);
9390     processPosition(mapper, x1 + 1, y1 + 1);
9391     processSync(mapper);
9392     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9393     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9394     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9395 
9396     // second finger up.
9397     processSlot(mapper, SECOND_SLOT);
9398     processId(mapper, INVALID_TRACKING_ID);
9399     processSync(mapper);
9400     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9401     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9402 
9403     // first finger keep moving
9404     processSlot(mapper, FIRST_SLOT);
9405     processId(mapper, FIRST_TRACKING_ID);
9406     processPosition(mapper, x1 + 2, y1 + 2);
9407     processSync(mapper);
9408     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9409     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9410 
9411     // first finger up.
9412     processId(mapper, INVALID_TRACKING_ID);
9413     processSync(mapper);
9414     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9415     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
9416     ASSERT_NE(AMOTION_EVENT_FLAG_CANCELED, motionArgs.flags);
9417 }
9418 
9419 /**
9420  * Test multi-touch should sent ACTION_POINTER_UP/ACTION_UP when received the INVALID_TRACKING_ID,
9421  * to prevent the driver side may send unexpected data after set tracking id as INVALID_TRACKING_ID
9422  * cause slot be valid again.
9423  */
TEST_F(MultiTouchInputMapperTest,Process_MultiTouch_WithInvalidTrackingId)9424 TEST_F(MultiTouchInputMapperTest, Process_MultiTouch_WithInvalidTrackingId) {
9425     addConfigurationProperty("touch.deviceType", "touchScreen");
9426     prepareDisplay(ui::ROTATION_0);
9427     prepareAxes(POSITION | ID | SLOT | PRESSURE);
9428     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9429 
9430     NotifyMotionArgs motionArgs;
9431 
9432     constexpr int32_t x1 = 100, y1 = 200, x2 = 0, y2 = 0;
9433     // First finger down.
9434     processId(mapper, FIRST_TRACKING_ID);
9435     processPosition(mapper, x1, y1);
9436     processPressure(mapper, RAW_PRESSURE_MAX);
9437     processSync(mapper);
9438     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9439     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9440     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9441 
9442     // First finger move.
9443     processId(mapper, FIRST_TRACKING_ID);
9444     processPosition(mapper, x1 + 1, y1 + 1);
9445     processPressure(mapper, RAW_PRESSURE_MAX);
9446     processSync(mapper);
9447     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9448     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9449     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9450 
9451     // Second finger down.
9452     processSlot(mapper, SECOND_SLOT);
9453     processId(mapper, SECOND_TRACKING_ID);
9454     processPosition(mapper, x2, y2);
9455     processPressure(mapper, RAW_PRESSURE_MAX);
9456     processSync(mapper);
9457     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9458     ASSERT_EQ(ACTION_POINTER_1_DOWN, motionArgs.action);
9459     ASSERT_EQ(uint32_t(2), motionArgs.getPointerCount());
9460 
9461     // second finger up with some unexpected data.
9462     processSlot(mapper, SECOND_SLOT);
9463     processId(mapper, INVALID_TRACKING_ID);
9464     processPosition(mapper, x2, y2);
9465     processSync(mapper);
9466     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9467     ASSERT_EQ(ACTION_POINTER_1_UP, motionArgs.action);
9468     ASSERT_EQ(uint32_t(2), motionArgs.getPointerCount());
9469 
9470     // first finger up with some unexpected data.
9471     processSlot(mapper, FIRST_SLOT);
9472     processId(mapper, INVALID_TRACKING_ID);
9473     processPosition(mapper, x2, y2);
9474     processPressure(mapper, RAW_PRESSURE_MAX);
9475     processSync(mapper);
9476     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9477     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, motionArgs.action);
9478     ASSERT_EQ(uint32_t(1), motionArgs.getPointerCount());
9479 }
9480 
TEST_F(MultiTouchInputMapperTest,Reset_RepopulatesMultiTouchState)9481 TEST_F(MultiTouchInputMapperTest, Reset_RepopulatesMultiTouchState) {
9482     addConfigurationProperty("touch.deviceType", "touchScreen");
9483     prepareDisplay(ui::ROTATION_0);
9484     prepareAxes(POSITION | ID | SLOT | PRESSURE);
9485     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9486 
9487     // First finger down.
9488     constexpr int32_t x1 = 100, y1 = 200, x2 = 300, y2 = 400;
9489     processId(mapper, FIRST_TRACKING_ID);
9490     processPosition(mapper, x1, y1);
9491     processPressure(mapper, RAW_PRESSURE_MAX);
9492     processSync(mapper);
9493     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9494             WithMotionAction(AMOTION_EVENT_ACTION_DOWN)));
9495 
9496     // Second finger down.
9497     processSlot(mapper, SECOND_SLOT);
9498     processId(mapper, SECOND_TRACKING_ID);
9499     processPosition(mapper, x2, y2);
9500     processPressure(mapper, RAW_PRESSURE_MAX);
9501     processSync(mapper);
9502     ASSERT_NO_FATAL_FAILURE(
9503             mFakeListener->assertNotifyMotionWasCalled(WithMotionAction(ACTION_POINTER_1_DOWN)));
9504 
9505     // Set MT Slot state to be repopulated for the required slots
9506     std::vector<int32_t> mtSlotValues(RAW_SLOT_MAX + 1, -1);
9507     mtSlotValues[0] = FIRST_TRACKING_ID;
9508     mtSlotValues[1] = SECOND_TRACKING_ID;
9509     mFakeEventHub->setMtSlotValues(EVENTHUB_ID, ABS_MT_TRACKING_ID, mtSlotValues);
9510 
9511     mtSlotValues[0] = x1;
9512     mtSlotValues[1] = x2;
9513     mFakeEventHub->setMtSlotValues(EVENTHUB_ID, ABS_MT_POSITION_X, mtSlotValues);
9514 
9515     mtSlotValues[0] = y1;
9516     mtSlotValues[1] = y2;
9517     mFakeEventHub->setMtSlotValues(EVENTHUB_ID, ABS_MT_POSITION_Y, mtSlotValues);
9518 
9519     mtSlotValues[0] = RAW_PRESSURE_MAX;
9520     mtSlotValues[1] = RAW_PRESSURE_MAX;
9521     mFakeEventHub->setMtSlotValues(EVENTHUB_ID, ABS_MT_PRESSURE, mtSlotValues);
9522 
9523     // Reset the mapper. When the mapper is reset, we expect the current multi-touch state to be
9524     // repopulated. Resetting should cancel the ongoing gesture.
9525     resetMapper(mapper, ARBITRARY_TIME);
9526     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9527             WithMotionAction(AMOTION_EVENT_ACTION_CANCEL)));
9528 
9529     // Send a sync to simulate an empty touch frame where nothing changes. The mapper should use
9530     // the existing touch state to generate a down event.
9531     processPosition(mapper, 301, 302);
9532     processSync(mapper);
9533     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9534             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithPressure(1.f))));
9535     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9536             AllOf(WithMotionAction(ACTION_POINTER_1_DOWN), WithPressure(1.f))));
9537 
9538     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
9539 }
9540 
TEST_F(MultiTouchInputMapperTest,Reset_PreservesLastTouchState_NoPointersDown)9541 TEST_F(MultiTouchInputMapperTest, Reset_PreservesLastTouchState_NoPointersDown) {
9542     addConfigurationProperty("touch.deviceType", "touchScreen");
9543     prepareDisplay(ui::ROTATION_0);
9544     prepareAxes(POSITION | ID | SLOT | PRESSURE);
9545     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9546 
9547     // First finger touches down and releases.
9548     processId(mapper, FIRST_TRACKING_ID);
9549     processPosition(mapper, 100, 200);
9550     processPressure(mapper, RAW_PRESSURE_MAX);
9551     processSync(mapper);
9552     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9553             WithMotionAction(AMOTION_EVENT_ACTION_DOWN)));
9554     processId(mapper, INVALID_TRACKING_ID);
9555     processSync(mapper);
9556     ASSERT_NO_FATAL_FAILURE(
9557             mFakeListener->assertNotifyMotionWasCalled(WithMotionAction(AMOTION_EVENT_ACTION_UP)));
9558 
9559     // Reset the mapper. When the mapper is reset, we expect it to restore the latest
9560     // raw state where no pointers are down.
9561     resetMapper(mapper, ARBITRARY_TIME);
9562     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
9563 
9564     // Send an empty sync frame. Since there are no pointers, no events are generated.
9565     processSync(mapper);
9566     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
9567 }
9568 
TEST_F(MultiTouchInputMapperTest,StylusSourceIsAddedDynamicallyFromToolType)9569 TEST_F(MultiTouchInputMapperTest, StylusSourceIsAddedDynamicallyFromToolType) {
9570     addConfigurationProperty("touch.deviceType", "touchScreen");
9571     prepareDisplay(ui::ROTATION_0);
9572     prepareAxes(POSITION | ID | SLOT | PRESSURE | TOOL_TYPE);
9573     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9574     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
9575 
9576     // Even if the device supports reporting the ABS_MT_TOOL_TYPE axis, which could give it the
9577     // ability to report MT_TOOL_PEN, we do not report the device as coming from a stylus source.
9578     // Due to limitations in the evdev protocol, we cannot say for certain that a device is capable
9579     // of reporting stylus events just because it supports ABS_MT_TOOL_TYPE.
9580     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, mapper.getSources());
9581 
9582     // However, if the device ever ends up reporting an event with MT_TOOL_PEN, it should be
9583     // reported with the stylus source.
9584     processId(mapper, FIRST_TRACKING_ID);
9585     processToolType(mapper, MT_TOOL_PEN);
9586     processPosition(mapper, 100, 200);
9587     processPressure(mapper, RAW_PRESSURE_MAX);
9588     processSync(mapper);
9589     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9590             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
9591                   WithSource(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS),
9592                   WithToolType(ToolType::STYLUS))));
9593 
9594     // Now that we know the device supports styluses, ensure that the device is re-configured with
9595     // the stylus source.
9596     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS, mapper.getSources());
9597     {
9598         const auto& devices = mReader->getInputDevices();
9599         auto deviceInfo =
9600                 std::find_if(devices.begin(), devices.end(),
9601                              [](const InputDeviceInfo& info) { return info.getId() == DEVICE_ID; });
9602         LOG_ALWAYS_FATAL_IF(deviceInfo == devices.end(), "Cannot find InputDevice");
9603         ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS, deviceInfo->getSources());
9604     }
9605 
9606     // Ensure the device was not reset to prevent interruptions of any ongoing gestures.
9607     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasNotCalled());
9608 
9609     processId(mapper, INVALID_TRACKING_ID);
9610     processSync(mapper);
9611     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9612             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
9613                   WithSource(AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS),
9614                   WithToolType(ToolType::STYLUS))));
9615 }
9616 
9617 // --- MultiTouchInputMapperTest_ExternalDevice ---
9618 
9619 class MultiTouchInputMapperTest_ExternalDevice : public MultiTouchInputMapperTest {
9620 protected:
SetUp()9621     void SetUp() override { InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::EXTERNAL); }
9622 };
9623 
9624 /**
9625  * Expect fallback to internal viewport if device is external and external viewport is not present.
9626  */
TEST_F(MultiTouchInputMapperTest_ExternalDevice,Viewports_Fallback)9627 TEST_F(MultiTouchInputMapperTest_ExternalDevice, Viewports_Fallback) {
9628     prepareAxes(POSITION);
9629     addConfigurationProperty("touch.deviceType", "touchScreen");
9630     prepareDisplay(ui::ROTATION_0);
9631     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9632 
9633     ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, mapper.getSources());
9634 
9635     NotifyMotionArgs motionArgs;
9636 
9637     // Expect the event to be sent to the internal viewport,
9638     // because an external viewport is not present.
9639     processPosition(mapper, 100, 100);
9640     processSync(mapper);
9641     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9642     ASSERT_EQ(ui::LogicalDisplayId::DEFAULT, motionArgs.displayId);
9643 
9644     // Expect the event to be sent to the external viewport if it is present.
9645     prepareSecondaryDisplay(ViewportType::EXTERNAL);
9646     processPosition(mapper, 100, 100);
9647     processSync(mapper);
9648     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9649     ASSERT_EQ(SECONDARY_DISPLAY_ID, motionArgs.displayId);
9650 }
9651 
9652 // TODO(b/281840344): Remove the test when the old touchpad stack is removed. It is currently
9653 //  unclear what the behavior of the touchpad logic in TouchInputMapper should do after the
9654 //  PointerChoreographer refactor.
TEST_F(MultiTouchInputMapperTest,DISABLED_Process_TouchpadPointer)9655 TEST_F(MultiTouchInputMapperTest, DISABLED_Process_TouchpadPointer) {
9656     // prepare device
9657     prepareDisplay(ui::ROTATION_0);
9658     prepareAxes(POSITION | ID | SLOT);
9659     mFakeEventHub->addKey(EVENTHUB_ID, BTN_LEFT, 0, AKEYCODE_UNKNOWN, 0);
9660     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOUCH, 0, AKEYCODE_UNKNOWN, 0);
9661     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9662     // run uncaptured pointer tests - pushes out generic events
9663     // FINGER 0 DOWN
9664     processId(mapper, 3);
9665     processPosition(mapper, 100, 100);
9666     processKey(mapper, BTN_TOUCH, 1);
9667     processSync(mapper);
9668 
9669     // start at (100,100), cursor should be at (0,0) * scale
9670     NotifyMotionArgs args;
9671     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
9672     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, args.action);
9673     ASSERT_NO_FATAL_FAILURE(
9674             assertPointerCoords(args.pointerCoords[0], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
9675 
9676     // FINGER 0 MOVE
9677     processPosition(mapper, 200, 200);
9678     processSync(mapper);
9679 
9680     // compute scaling to help with touch position checking
9681     float rawDiagonal = hypotf(RAW_X_MAX - RAW_X_MIN, RAW_Y_MAX - RAW_Y_MIN);
9682     float displayDiagonal = hypotf(DISPLAY_WIDTH, DISPLAY_HEIGHT);
9683     float scale =
9684             mFakePolicy->getPointerGestureMovementSpeedRatio() * displayDiagonal / rawDiagonal;
9685 
9686     // translate from (100,100) -> (200,200), cursor should have changed to (100,100) * scale)
9687     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
9688     ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, args.action);
9689     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0], 100 * scale, 100 * scale, 0,
9690                                                 0, 0, 0, 0, 0, 0, 0));
9691 
9692     // BUTTON DOWN
9693     processKey(mapper, BTN_LEFT, 1);
9694     processSync(mapper);
9695 
9696     // touchinputmapper design sends a move before button press
9697     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
9698     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
9699     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
9700     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_PRESS, args.action);
9701 
9702     // BUTTON UP
9703     processKey(mapper, BTN_LEFT, 0);
9704     processSync(mapper);
9705 
9706     // touchinputmapper design sends a move after button release
9707     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
9708     ASSERT_EQ(AMOTION_EVENT_ACTION_BUTTON_RELEASE, args.action);
9709     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
9710     ASSERT_EQ(AMOTION_EVENT_ACTION_UP, args.action);
9711 }
9712 
TEST_F(MultiTouchInputMapperTest,Touchpad_GetSources)9713 TEST_F(MultiTouchInputMapperTest, Touchpad_GetSources) {
9714     prepareDisplay(ui::ROTATION_0);
9715     prepareAxes(POSITION | ID | SLOT);
9716     mFakeEventHub->addKey(EVENTHUB_ID, BTN_LEFT, 0, AKEYCODE_UNKNOWN, 0);
9717     mFakePolicy->setPointerCapture(/*window=*/nullptr);
9718     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9719 
9720     // uncaptured touchpad should be a pointer device
9721     ASSERT_EQ(AINPUT_SOURCE_MOUSE, mapper.getSources());
9722 }
9723 
9724 // --- BluetoothMultiTouchInputMapperTest ---
9725 
9726 class BluetoothMultiTouchInputMapperTest : public MultiTouchInputMapperTest {
9727 protected:
SetUp()9728     void SetUp() override {
9729         InputMapperTest::SetUp(DEVICE_CLASSES | InputDeviceClass::EXTERNAL, BUS_BLUETOOTH);
9730     }
9731 };
9732 
TEST_F(BluetoothMultiTouchInputMapperTest,TimestampSmoothening)9733 TEST_F(BluetoothMultiTouchInputMapperTest, TimestampSmoothening) {
9734     addConfigurationProperty("touch.deviceType", "touchScreen");
9735     prepareDisplay(ui::ROTATION_0);
9736     prepareAxes(POSITION | ID | SLOT | PRESSURE);
9737     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9738 
9739     nsecs_t kernelEventTime = ARBITRARY_TIME;
9740     nsecs_t expectedEventTime = ARBITRARY_TIME;
9741     // Touch down.
9742     processId(mapper, FIRST_TRACKING_ID);
9743     processPosition(mapper, 100, 200);
9744     processPressure(mapper, RAW_PRESSURE_MAX);
9745     processSync(mapper, ARBITRARY_TIME);
9746     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9747             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN), WithEventTime(ARBITRARY_TIME))));
9748 
9749     // Process several events that come in quick succession, according to their timestamps.
9750     for (int i = 0; i < 3; i++) {
9751         constexpr static nsecs_t delta = ms2ns(1);
9752         static_assert(delta < MIN_BLUETOOTH_TIMESTAMP_DELTA);
9753         kernelEventTime += delta;
9754         expectedEventTime += MIN_BLUETOOTH_TIMESTAMP_DELTA;
9755 
9756         processPosition(mapper, 101 + i, 201 + i);
9757         processSync(mapper, kernelEventTime);
9758         ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9759                 AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
9760                       WithEventTime(expectedEventTime))));
9761     }
9762 
9763     // Release the touch.
9764     processId(mapper, INVALID_TRACKING_ID);
9765     processPressure(mapper, RAW_PRESSURE_MIN);
9766     processSync(mapper, ARBITRARY_TIME + ms2ns(50));
9767     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
9768             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP),
9769                   WithEventTime(ARBITRARY_TIME + ms2ns(50)))));
9770 }
9771 
9772 // --- MultiTouchPointerModeTest ---
9773 
9774 class MultiTouchPointerModeTest : public MultiTouchInputMapperTest {
9775 protected:
9776     float mPointerMovementScale;
9777     float mPointerXZoomScale;
preparePointerMode(int xAxisResolution,int yAxisResolution)9778     void preparePointerMode(int xAxisResolution, int yAxisResolution) {
9779         addConfigurationProperty("touch.deviceType", "pointer");
9780         prepareDisplay(ui::ROTATION_0);
9781 
9782         prepareAxes(POSITION);
9783         prepareAbsoluteAxisResolution(xAxisResolution, yAxisResolution);
9784         // In order to enable swipe and freeform gesture in pointer mode, pointer capture
9785         // needs to be disabled, and the pointer gesture needs to be enabled.
9786         mFakePolicy->setPointerCapture(/*window=*/nullptr);
9787         mFakePolicy->setPointerGestureEnabled(true);
9788 
9789         float rawDiagonal = hypotf(RAW_X_MAX - RAW_X_MIN, RAW_Y_MAX - RAW_Y_MIN);
9790         float displayDiagonal = hypotf(DISPLAY_WIDTH, DISPLAY_HEIGHT);
9791         mPointerMovementScale =
9792                 mFakePolicy->getPointerGestureMovementSpeedRatio() * displayDiagonal / rawDiagonal;
9793         mPointerXZoomScale =
9794                 mFakePolicy->getPointerGestureZoomSpeedRatio() * displayDiagonal / rawDiagonal;
9795     }
9796 
prepareAbsoluteAxisResolution(int xAxisResolution,int yAxisResolution)9797     void prepareAbsoluteAxisResolution(int xAxisResolution, int yAxisResolution) {
9798         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_X, RAW_X_MIN, RAW_X_MAX,
9799                                        /*flat*/ 0,
9800                                        /*fuzz*/ 0, /*resolution*/ xAxisResolution);
9801         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_POSITION_Y, RAW_Y_MIN, RAW_Y_MAX,
9802                                        /*flat*/ 0,
9803                                        /*fuzz*/ 0, /*resolution*/ yAxisResolution);
9804     }
9805 };
9806 
9807 /**
9808  * Two fingers down on a pointer mode touch pad. The width
9809  * of the two finger is larger than 1/4 of the touch pack diagnal length. However, it
9810  * is smaller than the fixed min physical length 30mm. Two fingers' distance must
9811  * be greater than the both value to be freeform gesture, so that after two
9812  * fingers start to move downwards, the gesture should be swipe.
9813  */
TEST_F(MultiTouchPointerModeTest,PointerGestureMaxSwipeWidthSwipe)9814 TEST_F(MultiTouchPointerModeTest, PointerGestureMaxSwipeWidthSwipe) {
9815     // The min freeform gesture width is 25units/mm x 30mm = 750
9816     // which is greater than fraction of the diagnal length of the touchpad (349).
9817     // Thus, MaxSwipWidth is 750.
9818     preparePointerMode(/*xResolution=*/25, /*yResolution=*/25);
9819     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9820     NotifyMotionArgs motionArgs;
9821 
9822     // Two fingers down at once.
9823     // The two fingers are 450 units apart, expects the current gesture to be PRESS
9824     // Pointer's initial position is used the [0,0] coordinate.
9825     int32_t x1 = 100, y1 = 125, x2 = 550, y2 = 125;
9826 
9827     processId(mapper, FIRST_TRACKING_ID);
9828     processPosition(mapper, x1, y1);
9829     processMTSync(mapper);
9830     processId(mapper, SECOND_TRACKING_ID);
9831     processPosition(mapper, x2, y2);
9832     processMTSync(mapper);
9833     processSync(mapper);
9834 
9835     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9836     ASSERT_EQ(1U, motionArgs.getPointerCount());
9837     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9838     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9839     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
9840     ASSERT_NO_FATAL_FAILURE(
9841             assertPointerCoords(motionArgs.pointerCoords[0], 0, 0, 1, 0, 0, 0, 0, 0, 0, 0));
9842 
9843     // It should be recognized as a SWIPE gesture when two fingers start to move down,
9844     // that there should be 1 pointer.
9845     int32_t movingDistance = 200;
9846     y1 += movingDistance;
9847     y2 += movingDistance;
9848 
9849     processId(mapper, FIRST_TRACKING_ID);
9850     processPosition(mapper, x1, y1);
9851     processMTSync(mapper);
9852     processId(mapper, SECOND_TRACKING_ID);
9853     processPosition(mapper, x2, y2);
9854     processMTSync(mapper);
9855     processSync(mapper);
9856 
9857     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9858     ASSERT_EQ(1U, motionArgs.getPointerCount());
9859     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9860     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9861     ASSERT_EQ(MotionClassification::TWO_FINGER_SWIPE, motionArgs.classification);
9862     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0], 0,
9863                                                 movingDistance * mPointerMovementScale, 1, 0, 0, 0,
9864                                                 0, 0, 0, 0));
9865 }
9866 
9867 /**
9868  * Two fingers down on a pointer mode touch pad. The width of the two finger is larger
9869  * than the minimum freeform gesture width, 30mm. However, it is smaller than 1/4 of
9870  * the touch pack diagnal length. Two fingers' distance must be greater than the both
9871  * value to be freeform gesture, so that after two fingers start to move downwards,
9872  * the gesture should be swipe.
9873  */
TEST_F(MultiTouchPointerModeTest,PointerGestureMaxSwipeWidthLowResolutionSwipe)9874 TEST_F(MultiTouchPointerModeTest, PointerGestureMaxSwipeWidthLowResolutionSwipe) {
9875     // The min freeform gesture width is 5units/mm x 30mm = 150
9876     // which is greater than fraction of the diagnal length of the touchpad (349).
9877     // Thus, MaxSwipWidth is the fraction of the diagnal length, 349.
9878     preparePointerMode(/*xResolution=*/5, /*yResolution=*/5);
9879     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9880     NotifyMotionArgs motionArgs;
9881 
9882     // Two fingers down at once.
9883     // The two fingers are 250 units apart, expects the current gesture to be PRESS
9884     // Pointer's initial position is used the [0,0] coordinate.
9885     int32_t x1 = 100, y1 = 125, x2 = 350, y2 = 125;
9886 
9887     processId(mapper, FIRST_TRACKING_ID);
9888     processPosition(mapper, x1, y1);
9889     processMTSync(mapper);
9890     processId(mapper, SECOND_TRACKING_ID);
9891     processPosition(mapper, x2, y2);
9892     processMTSync(mapper);
9893     processSync(mapper);
9894 
9895     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9896     ASSERT_EQ(1U, motionArgs.getPointerCount());
9897     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9898     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9899     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
9900     ASSERT_NO_FATAL_FAILURE(
9901             assertPointerCoords(motionArgs.pointerCoords[0], 0, 0, 1, 0, 0, 0, 0, 0, 0, 0));
9902 
9903     // It should be recognized as a SWIPE gesture when two fingers start to move down,
9904     // and there should be 1 pointer.
9905     int32_t movingDistance = 200;
9906     y1 += movingDistance;
9907     y2 += movingDistance;
9908 
9909     processId(mapper, FIRST_TRACKING_ID);
9910     processPosition(mapper, x1, y1);
9911     processMTSync(mapper);
9912     processId(mapper, SECOND_TRACKING_ID);
9913     processPosition(mapper, x2, y2);
9914     processMTSync(mapper);
9915     processSync(mapper);
9916 
9917     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9918     ASSERT_EQ(1U, motionArgs.getPointerCount());
9919     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
9920     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9921     ASSERT_EQ(MotionClassification::TWO_FINGER_SWIPE, motionArgs.classification);
9922     // New coordinate is the scaled relative coordinate from the initial coordinate.
9923     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0], 0,
9924                                                 movingDistance * mPointerMovementScale, 1, 0, 0, 0,
9925                                                 0, 0, 0, 0));
9926 }
9927 
9928 /**
9929  * Touch the touch pad with two fingers with a distance wider than the minimum freeform
9930  * gesture width and 1/4 of the diagnal length of the touchpad. Expect to receive
9931  * freeform gestures after two fingers start to move downwards.
9932  */
TEST_F(MultiTouchPointerModeTest,PointerGestureMaxSwipeWidthFreeform)9933 TEST_F(MultiTouchPointerModeTest, PointerGestureMaxSwipeWidthFreeform) {
9934     preparePointerMode(/*xResolution=*/25, /*yResolution=*/25);
9935     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
9936 
9937     NotifyMotionArgs motionArgs;
9938 
9939     // Two fingers down at once. Wider than the max swipe width.
9940     // The gesture is expected to be PRESS, then transformed to FREEFORM
9941     int32_t x1 = 100, y1 = 125, x2 = 900, y2 = 125;
9942 
9943     processId(mapper, FIRST_TRACKING_ID);
9944     processPosition(mapper, x1, y1);
9945     processMTSync(mapper);
9946     processId(mapper, SECOND_TRACKING_ID);
9947     processPosition(mapper, x2, y2);
9948     processMTSync(mapper);
9949     processSync(mapper);
9950 
9951     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9952     ASSERT_EQ(1U, motionArgs.getPointerCount());
9953     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9954     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9955     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
9956     // One pointer for PRESS, and its coordinate is used as the origin for pointer coordinates.
9957     ASSERT_NO_FATAL_FAILURE(
9958             assertPointerCoords(motionArgs.pointerCoords[0], 0, 0, 1, 0, 0, 0, 0, 0, 0, 0));
9959 
9960     int32_t movingDistance = 200;
9961 
9962     // Move two fingers down, expect a cancel event because gesture is changing to freeform,
9963     // then two down events for two pointers.
9964     y1 += movingDistance;
9965     y2 += movingDistance;
9966 
9967     processId(mapper, FIRST_TRACKING_ID);
9968     processPosition(mapper, x1, y1);
9969     processMTSync(mapper);
9970     processId(mapper, SECOND_TRACKING_ID);
9971     processPosition(mapper, x2, y2);
9972     processMTSync(mapper);
9973     processSync(mapper);
9974 
9975     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9976     // The previous PRESS gesture is cancelled, because it is transformed to freeform
9977     ASSERT_EQ(1U, motionArgs.getPointerCount());
9978     ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionArgs.action);
9979     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9980     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9981     ASSERT_EQ(1U, motionArgs.getPointerCount());
9982     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
9983     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
9984     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9985     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
9986     ASSERT_EQ(2U, motionArgs.getPointerCount());
9987     ASSERT_EQ(AMOTION_EVENT_ACTION_POINTER_DOWN, motionArgs.action & AMOTION_EVENT_ACTION_MASK);
9988     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
9989     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
9990     // Two pointers' scaled relative coordinates from their initial centroid.
9991     // Initial y coordinates are 0 as y1 and y2 have the same value.
9992     float cookedX1 = (x1 - x2) / 2 * mPointerXZoomScale;
9993     float cookedX2 = (x2 - x1) / 2 * mPointerXZoomScale;
9994     // When pointers move,  the new coordinates equal to the initial coordinates plus
9995     // scaled moving distance.
9996     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0], cookedX1,
9997                                                 movingDistance * mPointerMovementScale, 1, 0, 0, 0,
9998                                                 0, 0, 0, 0));
9999     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1], cookedX2,
10000                                                 movingDistance * mPointerMovementScale, 1, 0, 0, 0,
10001                                                 0, 0, 0, 0));
10002 
10003     // Move two fingers down again, expect one MOVE motion event.
10004     y1 += movingDistance;
10005     y2 += movingDistance;
10006 
10007     processId(mapper, FIRST_TRACKING_ID);
10008     processPosition(mapper, x1, y1);
10009     processMTSync(mapper);
10010     processId(mapper, SECOND_TRACKING_ID);
10011     processPosition(mapper, x2, y2);
10012     processMTSync(mapper);
10013     processSync(mapper);
10014 
10015     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10016     ASSERT_EQ(2U, motionArgs.getPointerCount());
10017     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10018     ASSERT_EQ(ToolType::FINGER, motionArgs.pointerProperties[0].toolType);
10019     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
10020     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[0], cookedX1,
10021                                                 movingDistance * 2 * mPointerMovementScale, 1, 0, 0,
10022                                                 0, 0, 0, 0, 0));
10023     ASSERT_NO_FATAL_FAILURE(assertPointerCoords(motionArgs.pointerCoords[1], cookedX2,
10024                                                 movingDistance * 2 * mPointerMovementScale, 1, 0, 0,
10025                                                 0, 0, 0, 0, 0));
10026 }
10027 
TEST_F(MultiTouchPointerModeTest,TwoFingerSwipeOffsets)10028 TEST_F(MultiTouchPointerModeTest, TwoFingerSwipeOffsets) {
10029     preparePointerMode(/*xResolution=*/25, /*yResolution=*/25);
10030     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10031     NotifyMotionArgs motionArgs;
10032 
10033     // Place two fingers down.
10034     int32_t x1 = 100, y1 = 125, x2 = 550, y2 = 125;
10035 
10036     processId(mapper, FIRST_TRACKING_ID);
10037     processPosition(mapper, x1, y1);
10038     processMTSync(mapper);
10039     processId(mapper, SECOND_TRACKING_ID);
10040     processPosition(mapper, x2, y2);
10041     processMTSync(mapper);
10042     processSync(mapper);
10043 
10044     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10045     ASSERT_EQ(1U, motionArgs.getPointerCount());
10046     ASSERT_EQ(AMOTION_EVENT_ACTION_DOWN, motionArgs.action);
10047     ASSERT_EQ(MotionClassification::NONE, motionArgs.classification);
10048     ASSERT_EQ(0, motionArgs.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET));
10049     ASSERT_EQ(0, motionArgs.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET));
10050 
10051     // Move the two fingers down and to the left.
10052     int32_t movingDistance = 200;
10053     x1 -= movingDistance;
10054     y1 += movingDistance;
10055     x2 -= movingDistance;
10056     y2 += movingDistance;
10057 
10058     processId(mapper, FIRST_TRACKING_ID);
10059     processPosition(mapper, x1, y1);
10060     processMTSync(mapper);
10061     processId(mapper, SECOND_TRACKING_ID);
10062     processPosition(mapper, x2, y2);
10063     processMTSync(mapper);
10064     processSync(mapper);
10065 
10066     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
10067     ASSERT_EQ(1U, motionArgs.getPointerCount());
10068     ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action);
10069     ASSERT_EQ(MotionClassification::TWO_FINGER_SWIPE, motionArgs.classification);
10070     ASSERT_LT(motionArgs.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET), 0);
10071     ASSERT_GT(motionArgs.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET), 0);
10072 }
10073 
TEST_F(MultiTouchPointerModeTest,WhenViewportActiveStatusChanged_PointerGestureIsReset)10074 TEST_F(MultiTouchPointerModeTest, WhenViewportActiveStatusChanged_PointerGestureIsReset) {
10075     preparePointerMode(/*xResolution=*/25, /*yResolution=*/25);
10076     mFakeEventHub->addKey(EVENTHUB_ID, BTN_TOOL_PEN, 0, AKEYCODE_UNKNOWN, 0);
10077     MultiTouchInputMapper& mapper = constructAndAddMapper<MultiTouchInputMapper>();
10078     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
10079 
10080     // Start a stylus gesture.
10081     processKey(mapper, BTN_TOOL_PEN, 1);
10082     processId(mapper, FIRST_TRACKING_ID);
10083     processPosition(mapper, 100, 200);
10084     processSync(mapper);
10085     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10086             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
10087                   WithSource(AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_STYLUS),
10088                   WithToolType(ToolType::STYLUS))));
10089     // TODO(b/257078296): Pointer mode generates extra event.
10090     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10091             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
10092                   WithSource(AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_STYLUS),
10093                   WithToolType(ToolType::STYLUS))));
10094     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
10095 
10096     // Make the viewport inactive. This will put the device in disabled mode, and the ongoing stylus
10097     // gesture should be disabled.
10098     auto viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
10099     viewport->isActive = false;
10100     mFakePolicy->updateViewport(*viewport);
10101     configureDevice(InputReaderConfiguration::Change::DISPLAY_INFO);
10102     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10103             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
10104                   WithSource(AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_STYLUS),
10105                   WithToolType(ToolType::STYLUS))));
10106     // TODO(b/257078296): Pointer mode generates extra event.
10107     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
10108             AllOf(WithMotionAction(AMOTION_EVENT_ACTION_CANCEL),
10109                   WithSource(AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_STYLUS),
10110                   WithToolType(ToolType::STYLUS))));
10111     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
10112 }
10113 
10114 // --- JoystickInputMapperTest ---
10115 
10116 class JoystickInputMapperTest : public InputMapperTest {
10117 protected:
10118     static const int32_t RAW_X_MIN;
10119     static const int32_t RAW_X_MAX;
10120     static const int32_t RAW_Y_MIN;
10121     static const int32_t RAW_Y_MAX;
10122 
SetUp()10123     void SetUp() override {
10124         InputMapperTest::SetUp(InputDeviceClass::JOYSTICK | InputDeviceClass::EXTERNAL);
10125     }
prepareAxes()10126     void prepareAxes() {
10127         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_X, RAW_X_MIN, RAW_X_MAX, 0, 0);
10128         mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_Y, RAW_Y_MIN, RAW_Y_MAX, 0, 0);
10129     }
10130 
processAxis(JoystickInputMapper & mapper,int32_t axis,int32_t value)10131     void processAxis(JoystickInputMapper& mapper, int32_t axis, int32_t value) {
10132         process(mapper, ARBITRARY_TIME, READ_TIME, EV_ABS, axis, value);
10133     }
10134 
processSync(JoystickInputMapper & mapper)10135     void processSync(JoystickInputMapper& mapper) {
10136         process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
10137     }
10138 
prepareVirtualDisplay(ui::Rotation orientation)10139     void prepareVirtualDisplay(ui::Rotation orientation) {
10140         setDisplayInfoAndReconfigure(VIRTUAL_DISPLAY_ID, VIRTUAL_DISPLAY_WIDTH,
10141                                      VIRTUAL_DISPLAY_HEIGHT, orientation, VIRTUAL_DISPLAY_UNIQUE_ID,
10142                                      NO_PORT, ViewportType::VIRTUAL);
10143     }
10144 };
10145 
10146 const int32_t JoystickInputMapperTest::RAW_X_MIN = -32767;
10147 const int32_t JoystickInputMapperTest::RAW_X_MAX = 32767;
10148 const int32_t JoystickInputMapperTest::RAW_Y_MIN = -32767;
10149 const int32_t JoystickInputMapperTest::RAW_Y_MAX = 32767;
10150 
TEST_F(JoystickInputMapperTest,Configure_AssignsDisplayUniqueId)10151 TEST_F(JoystickInputMapperTest, Configure_AssignsDisplayUniqueId) {
10152     prepareAxes();
10153     JoystickInputMapper& mapper = constructAndAddMapper<JoystickInputMapper>();
10154 
10155     mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, VIRTUAL_DISPLAY_UNIQUE_ID);
10156 
10157     prepareVirtualDisplay(ui::ROTATION_0);
10158 
10159     // Send an axis event
10160     processAxis(mapper, ABS_X, 100);
10161     processSync(mapper);
10162 
10163     NotifyMotionArgs args;
10164     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10165     ASSERT_EQ(VIRTUAL_DISPLAY_ID, args.displayId);
10166 
10167     // Send another axis event
10168     processAxis(mapper, ABS_Y, 100);
10169     processSync(mapper);
10170 
10171     ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
10172     ASSERT_EQ(VIRTUAL_DISPLAY_ID, args.displayId);
10173 }
10174 
10175 // --- PeripheralControllerTest ---
10176 
10177 class PeripheralControllerTest : public testing::Test {
10178 protected:
10179     static const char* DEVICE_NAME;
10180     static const char* DEVICE_LOCATION;
10181     static const int32_t DEVICE_ID;
10182     static const int32_t DEVICE_GENERATION;
10183     static const int32_t DEVICE_CONTROLLER_NUMBER;
10184     static const ftl::Flags<InputDeviceClass> DEVICE_CLASSES;
10185     static const int32_t EVENTHUB_ID;
10186 
10187     std::shared_ptr<FakeEventHub> mFakeEventHub;
10188     sp<FakeInputReaderPolicy> mFakePolicy;
10189     std::unique_ptr<TestInputListener> mFakeListener;
10190     std::unique_ptr<InstrumentedInputReader> mReader;
10191     std::shared_ptr<InputDevice> mDevice;
10192 
SetUp(ftl::Flags<InputDeviceClass> classes)10193     virtual void SetUp(ftl::Flags<InputDeviceClass> classes) {
10194         mFakeEventHub = std::make_unique<FakeEventHub>();
10195         mFakePolicy = sp<FakeInputReaderPolicy>::make();
10196         mFakeListener = std::make_unique<TestInputListener>();
10197         mReader = std::make_unique<InstrumentedInputReader>(mFakeEventHub, mFakePolicy,
10198                                                             *mFakeListener);
10199         mDevice = newDevice(DEVICE_ID, DEVICE_NAME, DEVICE_LOCATION, EVENTHUB_ID, classes);
10200     }
10201 
SetUp()10202     void SetUp() override { SetUp(DEVICE_CLASSES); }
10203 
TearDown()10204     void TearDown() override {
10205         mFakeListener.reset();
10206         mFakePolicy.clear();
10207     }
10208 
newDevice(int32_t deviceId,const std::string & name,const std::string & location,int32_t eventHubId,ftl::Flags<InputDeviceClass> classes)10209     std::shared_ptr<InputDevice> newDevice(int32_t deviceId, const std::string& name,
10210                                            const std::string& location, int32_t eventHubId,
10211                                            ftl::Flags<InputDeviceClass> classes) {
10212         InputDeviceIdentifier identifier;
10213         identifier.name = name;
10214         identifier.location = location;
10215         std::shared_ptr<InputDevice> device =
10216                 std::make_shared<InputDevice>(mReader->getContext(), deviceId, DEVICE_GENERATION,
10217                                               identifier);
10218         mReader->pushNextDevice(device);
10219         mFakeEventHub->addDevice(eventHubId, name, classes);
10220         mReader->loopOnce();
10221         return device;
10222     }
10223 
10224     template <class T, typename... Args>
addControllerAndConfigure(Args...args)10225     T& addControllerAndConfigure(Args... args) {
10226         T& controller = mDevice->addController<T>(EVENTHUB_ID, args...);
10227 
10228         return controller;
10229     }
10230 };
10231 
10232 const char* PeripheralControllerTest::DEVICE_NAME = "device";
10233 const char* PeripheralControllerTest::DEVICE_LOCATION = "BLUETOOTH";
10234 const int32_t PeripheralControllerTest::DEVICE_ID = END_RESERVED_ID + 1000;
10235 const int32_t PeripheralControllerTest::DEVICE_GENERATION = 2;
10236 const int32_t PeripheralControllerTest::DEVICE_CONTROLLER_NUMBER = 0;
10237 const ftl::Flags<InputDeviceClass> PeripheralControllerTest::DEVICE_CLASSES =
10238         ftl::Flags<InputDeviceClass>(0); // not needed for current tests
10239 const int32_t PeripheralControllerTest::EVENTHUB_ID = 1;
10240 
10241 // --- BatteryControllerTest ---
10242 class BatteryControllerTest : public PeripheralControllerTest {
10243 protected:
SetUp()10244     void SetUp() override {
10245         PeripheralControllerTest::SetUp(DEVICE_CLASSES | InputDeviceClass::BATTERY);
10246     }
10247 };
10248 
TEST_F(BatteryControllerTest,GetBatteryCapacity)10249 TEST_F(BatteryControllerTest, GetBatteryCapacity) {
10250     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10251 
10252     ASSERT_TRUE(controller.getBatteryCapacity(FakeEventHub::DEFAULT_BATTERY));
10253     ASSERT_EQ(controller.getBatteryCapacity(FakeEventHub::DEFAULT_BATTERY).value_or(-1),
10254               FakeEventHub::BATTERY_CAPACITY);
10255 }
10256 
TEST_F(BatteryControllerTest,GetBatteryStatus)10257 TEST_F(BatteryControllerTest, GetBatteryStatus) {
10258     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10259 
10260     ASSERT_TRUE(controller.getBatteryStatus(FakeEventHub::DEFAULT_BATTERY));
10261     ASSERT_EQ(controller.getBatteryStatus(FakeEventHub::DEFAULT_BATTERY).value_or(-1),
10262               FakeEventHub::BATTERY_STATUS);
10263 }
10264 
10265 // --- LightControllerTest ---
10266 class LightControllerTest : public PeripheralControllerTest {
10267 protected:
SetUp()10268     void SetUp() override {
10269         PeripheralControllerTest::SetUp(DEVICE_CLASSES | InputDeviceClass::LIGHT);
10270     }
10271 };
10272 
TEST_F(LightControllerTest,MonoLight)10273 TEST_F(LightControllerTest, MonoLight) {
10274     RawLightInfo infoMono = {.id = 1,
10275                              .name = "mono_light",
10276                              .maxBrightness = 255,
10277                              .flags = InputLightClass::BRIGHTNESS,
10278                              .path = ""};
10279     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
10280 
10281     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10282     InputDeviceInfo info;
10283     controller.populateDeviceInfo(&info);
10284     std::vector<InputDeviceLightInfo> lights = info.getLights();
10285     ASSERT_EQ(1U, lights.size());
10286     ASSERT_EQ(InputDeviceLightType::INPUT, lights[0].type);
10287     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
10288 
10289     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_BRIGHTNESS));
10290     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_BRIGHTNESS);
10291 }
10292 
TEST_F(LightControllerTest,MonoKeyboardMuteLight)10293 TEST_F(LightControllerTest, MonoKeyboardMuteLight) {
10294     RawLightInfo infoMono = {.id = 1,
10295                              .name = "mono_keyboard_mute",
10296                              .maxBrightness = 255,
10297                              .flags = InputLightClass::BRIGHTNESS |
10298                                      InputLightClass::KEYBOARD_MIC_MUTE,
10299                              .path = ""};
10300     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
10301 
10302     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10303     std::list<NotifyArgs> unused =
10304             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
10305                                /*changes=*/{});
10306 
10307     InputDeviceInfo info;
10308     controller.populateDeviceInfo(&info);
10309     std::vector<InputDeviceLightInfo> lights = info.getLights();
10310     ASSERT_EQ(1U, lights.size());
10311     ASSERT_EQ(InputDeviceLightType::KEYBOARD_MIC_MUTE, lights[0].type);
10312     ASSERT_EQ(0U, lights[0].preferredBrightnessLevels.size());
10313 }
10314 
TEST_F(LightControllerTest,MonoKeyboardBacklight)10315 TEST_F(LightControllerTest, MonoKeyboardBacklight) {
10316     RawLightInfo infoMono = {.id = 1,
10317                              .name = "mono_keyboard_backlight",
10318                              .maxBrightness = 255,
10319                              .flags = InputLightClass::BRIGHTNESS |
10320                                      InputLightClass::KEYBOARD_BACKLIGHT,
10321                              .path = ""};
10322     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
10323 
10324     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10325     InputDeviceInfo info;
10326     controller.populateDeviceInfo(&info);
10327     std::vector<InputDeviceLightInfo> lights = info.getLights();
10328     ASSERT_EQ(1U, lights.size());
10329     ASSERT_EQ(InputDeviceLightType::KEYBOARD_BACKLIGHT, lights[0].type);
10330     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
10331 
10332     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_BRIGHTNESS));
10333     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_BRIGHTNESS);
10334 }
10335 
TEST_F(LightControllerTest,Ignore_MonoLight_WithPreferredBacklightLevels)10336 TEST_F(LightControllerTest, Ignore_MonoLight_WithPreferredBacklightLevels) {
10337     RawLightInfo infoMono = {.id = 1,
10338                              .name = "mono_light",
10339                              .maxBrightness = 255,
10340                              .flags = InputLightClass::BRIGHTNESS,
10341                              .path = ""};
10342     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
10343     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "keyboard.backlight.brightnessLevels",
10344                                             "0,100,200");
10345 
10346     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10347     std::list<NotifyArgs> unused =
10348             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
10349                                /*changes=*/{});
10350 
10351     InputDeviceInfo info;
10352     controller.populateDeviceInfo(&info);
10353     std::vector<InputDeviceLightInfo> lights = info.getLights();
10354     ASSERT_EQ(1U, lights.size());
10355     ASSERT_EQ(0U, lights[0].preferredBrightnessLevels.size());
10356 }
10357 
TEST_F(LightControllerTest,KeyboardBacklight_WithNoPreferredBacklightLevels)10358 TEST_F(LightControllerTest, KeyboardBacklight_WithNoPreferredBacklightLevels) {
10359     RawLightInfo infoMono = {.id = 1,
10360                              .name = "mono_keyboard_backlight",
10361                              .maxBrightness = 255,
10362                              .flags = InputLightClass::BRIGHTNESS |
10363                                      InputLightClass::KEYBOARD_BACKLIGHT,
10364                              .path = ""};
10365     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
10366 
10367     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10368     std::list<NotifyArgs> unused =
10369             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
10370                                /*changes=*/{});
10371 
10372     InputDeviceInfo info;
10373     controller.populateDeviceInfo(&info);
10374     std::vector<InputDeviceLightInfo> lights = info.getLights();
10375     ASSERT_EQ(1U, lights.size());
10376     ASSERT_EQ(0U, lights[0].preferredBrightnessLevels.size());
10377 }
10378 
TEST_F(LightControllerTest,KeyboardBacklight_WithPreferredBacklightLevels)10379 TEST_F(LightControllerTest, KeyboardBacklight_WithPreferredBacklightLevels) {
10380     RawLightInfo infoMono = {.id = 1,
10381                              .name = "mono_keyboard_backlight",
10382                              .maxBrightness = 255,
10383                              .flags = InputLightClass::BRIGHTNESS |
10384                                      InputLightClass::KEYBOARD_BACKLIGHT,
10385                              .path = ""};
10386     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
10387     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "keyboard.backlight.brightnessLevels",
10388                                             "0,100,200");
10389 
10390     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10391     std::list<NotifyArgs> unused =
10392             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
10393                                /*changes=*/{});
10394 
10395     InputDeviceInfo info;
10396     controller.populateDeviceInfo(&info);
10397     std::vector<InputDeviceLightInfo> lights = info.getLights();
10398     ASSERT_EQ(1U, lights.size());
10399     ASSERT_EQ(3U, lights[0].preferredBrightnessLevels.size());
10400     std::set<BrightnessLevel>::iterator it = lights[0].preferredBrightnessLevels.begin();
10401     ASSERT_EQ(BrightnessLevel(0), *it);
10402     std::advance(it, 1);
10403     ASSERT_EQ(BrightnessLevel(100), *it);
10404     std::advance(it, 1);
10405     ASSERT_EQ(BrightnessLevel(200), *it);
10406 }
10407 
TEST_F(LightControllerTest,KeyboardBacklight_WithWrongPreferredBacklightLevels)10408 TEST_F(LightControllerTest, KeyboardBacklight_WithWrongPreferredBacklightLevels) {
10409     RawLightInfo infoMono = {.id = 1,
10410                              .name = "mono_keyboard_backlight",
10411                              .maxBrightness = 255,
10412                              .flags = InputLightClass::BRIGHTNESS |
10413                                      InputLightClass::KEYBOARD_BACKLIGHT,
10414                              .path = ""};
10415     mFakeEventHub->addRawLightInfo(infoMono.id, std::move(infoMono));
10416     mFakeEventHub->addConfigurationProperty(EVENTHUB_ID, "keyboard.backlight.brightnessLevels",
10417                                             "0,100,200,300,400,500");
10418 
10419     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10420     std::list<NotifyArgs> unused =
10421             mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
10422                                /*changes=*/{});
10423 
10424     InputDeviceInfo info;
10425     controller.populateDeviceInfo(&info);
10426     std::vector<InputDeviceLightInfo> lights = info.getLights();
10427     ASSERT_EQ(1U, lights.size());
10428     ASSERT_EQ(0U, lights[0].preferredBrightnessLevels.size());
10429 }
10430 
TEST_F(LightControllerTest,RGBLight)10431 TEST_F(LightControllerTest, RGBLight) {
10432     RawLightInfo infoRed = {.id = 1,
10433                             .name = "red",
10434                             .maxBrightness = 255,
10435                             .flags = InputLightClass::BRIGHTNESS | InputLightClass::RED,
10436                             .path = ""};
10437     RawLightInfo infoGreen = {.id = 2,
10438                               .name = "green",
10439                               .maxBrightness = 255,
10440                               .flags = InputLightClass::BRIGHTNESS | InputLightClass::GREEN,
10441                               .path = ""};
10442     RawLightInfo infoBlue = {.id = 3,
10443                              .name = "blue",
10444                              .maxBrightness = 255,
10445                              .flags = InputLightClass::BRIGHTNESS | InputLightClass::BLUE,
10446                              .path = ""};
10447     mFakeEventHub->addRawLightInfo(infoRed.id, std::move(infoRed));
10448     mFakeEventHub->addRawLightInfo(infoGreen.id, std::move(infoGreen));
10449     mFakeEventHub->addRawLightInfo(infoBlue.id, std::move(infoBlue));
10450 
10451     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10452     InputDeviceInfo info;
10453     controller.populateDeviceInfo(&info);
10454     std::vector<InputDeviceLightInfo> lights = info.getLights();
10455     ASSERT_EQ(1U, lights.size());
10456     ASSERT_EQ(InputDeviceLightType::INPUT, lights[0].type);
10457     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
10458     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
10459 
10460     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
10461     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_COLOR);
10462 }
10463 
TEST_F(LightControllerTest,CorrectRGBKeyboardBacklight)10464 TEST_F(LightControllerTest, CorrectRGBKeyboardBacklight) {
10465     RawLightInfo infoRed = {.id = 1,
10466                             .name = "red_keyboard_backlight",
10467                             .maxBrightness = 255,
10468                             .flags = InputLightClass::BRIGHTNESS | InputLightClass::RED |
10469                                     InputLightClass::KEYBOARD_BACKLIGHT,
10470                             .path = ""};
10471     RawLightInfo infoGreen = {.id = 2,
10472                               .name = "green_keyboard_backlight",
10473                               .maxBrightness = 255,
10474                               .flags = InputLightClass::BRIGHTNESS | InputLightClass::GREEN |
10475                                       InputLightClass::KEYBOARD_BACKLIGHT,
10476                               .path = ""};
10477     RawLightInfo infoBlue = {.id = 3,
10478                              .name = "blue_keyboard_backlight",
10479                              .maxBrightness = 255,
10480                              .flags = InputLightClass::BRIGHTNESS | InputLightClass::BLUE |
10481                                      InputLightClass::KEYBOARD_BACKLIGHT,
10482                              .path = ""};
10483     mFakeEventHub->addRawLightInfo(infoRed.id, std::move(infoRed));
10484     mFakeEventHub->addRawLightInfo(infoGreen.id, std::move(infoGreen));
10485     mFakeEventHub->addRawLightInfo(infoBlue.id, std::move(infoBlue));
10486 
10487     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10488     InputDeviceInfo info;
10489     controller.populateDeviceInfo(&info);
10490     std::vector<InputDeviceLightInfo> lights = info.getLights();
10491     ASSERT_EQ(1U, lights.size());
10492     ASSERT_EQ(InputDeviceLightType::KEYBOARD_BACKLIGHT, lights[0].type);
10493     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
10494     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
10495 
10496     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
10497     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_COLOR);
10498 }
10499 
TEST_F(LightControllerTest,IncorrectRGBKeyboardBacklight)10500 TEST_F(LightControllerTest, IncorrectRGBKeyboardBacklight) {
10501     RawLightInfo infoRed = {.id = 1,
10502                             .name = "red",
10503                             .maxBrightness = 255,
10504                             .flags = InputLightClass::BRIGHTNESS | InputLightClass::RED,
10505                             .path = ""};
10506     RawLightInfo infoGreen = {.id = 2,
10507                               .name = "green",
10508                               .maxBrightness = 255,
10509                               .flags = InputLightClass::BRIGHTNESS | InputLightClass::GREEN,
10510                               .path = ""};
10511     RawLightInfo infoBlue = {.id = 3,
10512                              .name = "blue",
10513                              .maxBrightness = 255,
10514                              .flags = InputLightClass::BRIGHTNESS | InputLightClass::BLUE,
10515                              .path = ""};
10516     RawLightInfo infoGlobal = {.id = 3,
10517                                .name = "global_keyboard_backlight",
10518                                .maxBrightness = 255,
10519                                .flags = InputLightClass::BRIGHTNESS | InputLightClass::GLOBAL |
10520                                        InputLightClass::KEYBOARD_BACKLIGHT,
10521                                .path = ""};
10522     mFakeEventHub->addRawLightInfo(infoRed.id, std::move(infoRed));
10523     mFakeEventHub->addRawLightInfo(infoGreen.id, std::move(infoGreen));
10524     mFakeEventHub->addRawLightInfo(infoBlue.id, std::move(infoBlue));
10525     mFakeEventHub->addRawLightInfo(infoBlue.id, std::move(infoGlobal));
10526 
10527     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10528     InputDeviceInfo info;
10529     controller.populateDeviceInfo(&info);
10530     std::vector<InputDeviceLightInfo> lights = info.getLights();
10531     ASSERT_EQ(1U, lights.size());
10532     ASSERT_EQ(InputDeviceLightType::INPUT, lights[0].type);
10533     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
10534     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
10535 
10536     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
10537     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_COLOR);
10538 }
10539 
TEST_F(LightControllerTest,MultiColorRGBLight)10540 TEST_F(LightControllerTest, MultiColorRGBLight) {
10541     RawLightInfo infoColor = {.id = 1,
10542                               .name = "multi_color",
10543                               .maxBrightness = 255,
10544                               .flags = InputLightClass::BRIGHTNESS |
10545                                       InputLightClass::MULTI_INTENSITY |
10546                                       InputLightClass::MULTI_INDEX,
10547                               .path = ""};
10548 
10549     mFakeEventHub->addRawLightInfo(infoColor.id, std::move(infoColor));
10550 
10551     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10552     InputDeviceInfo info;
10553     controller.populateDeviceInfo(&info);
10554     std::vector<InputDeviceLightInfo> lights = info.getLights();
10555     ASSERT_EQ(1U, lights.size());
10556     ASSERT_EQ(InputDeviceLightType::INPUT, lights[0].type);
10557     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
10558     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
10559 
10560     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
10561     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_COLOR);
10562 }
10563 
TEST_F(LightControllerTest,MultiColorRGBKeyboardBacklight)10564 TEST_F(LightControllerTest, MultiColorRGBKeyboardBacklight) {
10565     RawLightInfo infoColor = {.id = 1,
10566                               .name = "multi_color_keyboard_backlight",
10567                               .maxBrightness = 255,
10568                               .flags = InputLightClass::BRIGHTNESS |
10569                                       InputLightClass::MULTI_INTENSITY |
10570                                       InputLightClass::MULTI_INDEX |
10571                                       InputLightClass::KEYBOARD_BACKLIGHT,
10572                               .path = ""};
10573 
10574     mFakeEventHub->addRawLightInfo(infoColor.id, std::move(infoColor));
10575 
10576     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10577     InputDeviceInfo info;
10578     controller.populateDeviceInfo(&info);
10579     std::vector<InputDeviceLightInfo> lights = info.getLights();
10580     ASSERT_EQ(1U, lights.size());
10581     ASSERT_EQ(InputDeviceLightType::KEYBOARD_BACKLIGHT, lights[0].type);
10582     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
10583     ASSERT_TRUE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
10584 
10585     ASSERT_TRUE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
10586     ASSERT_EQ(controller.getLightColor(lights[0].id).value_or(-1), LIGHT_COLOR);
10587 }
10588 
TEST_F(LightControllerTest,SonyPlayerIdLight)10589 TEST_F(LightControllerTest, SonyPlayerIdLight) {
10590     RawLightInfo info1 = {.id = 1,
10591                           .name = "sony1",
10592                           .maxBrightness = 255,
10593                           .flags = InputLightClass::BRIGHTNESS,
10594                           .path = ""};
10595     RawLightInfo info2 = {.id = 2,
10596                           .name = "sony2",
10597                           .maxBrightness = 255,
10598                           .flags = InputLightClass::BRIGHTNESS,
10599                           .path = ""};
10600     RawLightInfo info3 = {.id = 3,
10601                           .name = "sony3",
10602                           .maxBrightness = 255,
10603                           .flags = InputLightClass::BRIGHTNESS,
10604                           .path = ""};
10605     RawLightInfo info4 = {.id = 4,
10606                           .name = "sony4",
10607                           .maxBrightness = 255,
10608                           .flags = InputLightClass::BRIGHTNESS,
10609                           .path = ""};
10610     mFakeEventHub->addRawLightInfo(info1.id, std::move(info1));
10611     mFakeEventHub->addRawLightInfo(info2.id, std::move(info2));
10612     mFakeEventHub->addRawLightInfo(info3.id, std::move(info3));
10613     mFakeEventHub->addRawLightInfo(info4.id, std::move(info4));
10614 
10615     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10616     InputDeviceInfo info;
10617     controller.populateDeviceInfo(&info);
10618     std::vector<InputDeviceLightInfo> lights = info.getLights();
10619     ASSERT_EQ(1U, lights.size());
10620     ASSERT_STREQ("sony", lights[0].name.c_str());
10621     ASSERT_EQ(InputDeviceLightType::PLAYER_ID, lights[0].type);
10622     ASSERT_FALSE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
10623     ASSERT_FALSE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
10624 
10625     ASSERT_FALSE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
10626     ASSERT_TRUE(controller.setLightPlayerId(lights[0].id, LIGHT_PLAYER_ID));
10627     ASSERT_EQ(controller.getLightPlayerId(lights[0].id).value_or(-1), LIGHT_PLAYER_ID);
10628     ASSERT_STREQ("sony", lights[0].name.c_str());
10629 }
10630 
TEST_F(LightControllerTest,PlayerIdLight)10631 TEST_F(LightControllerTest, PlayerIdLight) {
10632     RawLightInfo info1 = {.id = 1,
10633                           .name = "player-1",
10634                           .maxBrightness = 255,
10635                           .flags = InputLightClass::BRIGHTNESS,
10636                           .path = ""};
10637     RawLightInfo info2 = {.id = 2,
10638                           .name = "player-2",
10639                           .maxBrightness = 255,
10640                           .flags = InputLightClass::BRIGHTNESS,
10641                           .path = ""};
10642     RawLightInfo info3 = {.id = 3,
10643                           .name = "player-3",
10644                           .maxBrightness = 255,
10645                           .flags = InputLightClass::BRIGHTNESS,
10646                           .path = ""};
10647     RawLightInfo info4 = {.id = 4,
10648                           .name = "player-4",
10649                           .maxBrightness = 255,
10650                           .flags = InputLightClass::BRIGHTNESS,
10651                           .path = ""};
10652     mFakeEventHub->addRawLightInfo(info1.id, std::move(info1));
10653     mFakeEventHub->addRawLightInfo(info2.id, std::move(info2));
10654     mFakeEventHub->addRawLightInfo(info3.id, std::move(info3));
10655     mFakeEventHub->addRawLightInfo(info4.id, std::move(info4));
10656 
10657     PeripheralController& controller = addControllerAndConfigure<PeripheralController>();
10658     InputDeviceInfo info;
10659     controller.populateDeviceInfo(&info);
10660     std::vector<InputDeviceLightInfo> lights = info.getLights();
10661     ASSERT_EQ(1U, lights.size());
10662     ASSERT_STREQ("player", lights[0].name.c_str());
10663     ASSERT_EQ(InputDeviceLightType::PLAYER_ID, lights[0].type);
10664     ASSERT_FALSE(lights[0].capabilityFlags.test(InputDeviceLightCapability::BRIGHTNESS));
10665     ASSERT_FALSE(lights[0].capabilityFlags.test(InputDeviceLightCapability::RGB));
10666 
10667     ASSERT_FALSE(controller.setLightColor(lights[0].id, LIGHT_COLOR));
10668     ASSERT_TRUE(controller.setLightPlayerId(lights[0].id, LIGHT_PLAYER_ID));
10669     ASSERT_EQ(controller.getLightPlayerId(lights[0].id).value_or(-1), LIGHT_PLAYER_ID);
10670 }
10671 
10672 } // namespace android
10673