From 777a10ba60e1b23a2d0d7f91ab3a9596cd2552d5 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Wed, 31 Jan 2018 16:45:06 -0800 Subject: Move display id into MotionEvent Display id is now part of MotionEvent. Test: m -j inputflinger_tests_InputReader_test inputflinger_tests_InputDispatcher_test libinput_tests_InputChannel_test libinput_tests_InputEvent_test libinput_tests_InputPublisherAndConsumer_test libinput_tests_VelocityTracker_test StructLayout_test && adb push out/target/product/$TARGET_PRODUCT/data/nativetest64/* /data/nativetest64/ then run all native tests on the device Bug: 64258305 Change-Id: I55afcbbc25b67afe6f7cc3457a1eca4b32651e4b --- services/inputflinger/InputReader.cpp | 75 ++++++++++++++++------------------- 1 file changed, 35 insertions(+), 40 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index e0cd8a005a..50229cbaab 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -2279,15 +2279,12 @@ void KeyboardInputMapper::configure(nsecs_t when, } if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { + mOrientation = DISPLAY_ORIENTATION_0; if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { DisplayViewport v; if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) { mOrientation = v.orientation; - } else { - mOrientation = DISPLAY_ORIENTATION_0; } - } else { - mOrientation = DISPLAY_ORIENTATION_0; } } } @@ -2699,15 +2696,12 @@ void CursorInputMapper::configure(nsecs_t when, } if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { + mOrientation = DISPLAY_ORIENTATION_0; if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { DisplayViewport v; if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) { mOrientation = v.orientation; - } else { - mOrientation = DISPLAY_ORIENTATION_0; } - } else { - mOrientation = DISPLAY_ORIENTATION_0; } bumpGeneration(); } @@ -2894,19 +2888,19 @@ void CursorInputMapper::sync(nsecs_t when) { while (!released.isEmpty()) { int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit()); buttonState &= ~actionButton; - NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, - displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, + /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&releaseArgs); } } - NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, - displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, + /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&args); @@ -2915,10 +2909,10 @@ void CursorInputMapper::sync(nsecs_t when) { while (!pressed.isEmpty()) { int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit()); buttonState |= actionButton; - NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, - displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, + /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&pressArgs); } @@ -2929,10 +2923,10 @@ void CursorInputMapper::sync(nsecs_t when) { // Send hover move after UP to tell the application that the mouse is hovering now. if (motionEventAction == AMOTION_EVENT_ACTION_UP && (mSource == AINPUT_SOURCE_MOUSE)) { - NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, - displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, + /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&hoverArgs); } @@ -2942,10 +2936,10 @@ void CursorInputMapper::sync(nsecs_t when) { pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); - NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, - displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, + /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&scrollArgs); } @@ -3072,10 +3066,10 @@ void RotaryEncoderInputMapper::sync(nsecs_t when) { int32_t metaState = mContext->getGlobalMetaState(); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor); - NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0, AMOTION_EVENT_EDGE_FLAG_NONE, - displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, + /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, 0, 0, 0); getListener()->notifyMotion(&scrollArgs); } @@ -5413,10 +5407,10 @@ void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlag pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); - NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, - mViewport.displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, + /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, 0, 0, mPointerGesture.downTime); getListener()->notifyMotion(&args); } @@ -6336,9 +6330,9 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.down = false; // Send up. - NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0, - mViewport.displayId, /* deviceTimestamp */ 0, + /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); @@ -6349,9 +6343,9 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.hovering = false; // Send hover exit. - NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0, - mViewport.displayId, /* deviceTimestamp */ 0, + /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); @@ -6364,9 +6358,9 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.downTime = when; // Send down. - NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0, - mViewport.displayId, /* deviceTimestamp */ 0, + /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); @@ -6374,9 +6368,9 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } // Send move. - NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, - mViewport.displayId, /* deviceTimestamp */ 0, + /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); @@ -6388,10 +6382,10 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.hovering = true; // Send hover enter. - NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState, mCurrentRawState.buttonState, 0, - mViewport.displayId, /* deviceTimestamp */ 0, + /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); @@ -6399,10 +6393,10 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } // Send hover move. - NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, - mViewport.displayId, /* deviceTimestamp */ 0, + /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); @@ -6421,9 +6415,9 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); - NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0, - mViewport.displayId, /* deviceTimestamp */ 0, + /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &pointerCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); @@ -6484,9 +6478,9 @@ void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32 } } - NotifyMotionArgs args(when, getDeviceId(), source, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), source, mViewport.displayId, policyFlags, action, actionButton, flags, metaState, buttonState, edgeFlags, - mViewport.displayId, deviceTimestamp, pointerCount, pointerProperties, pointerCoords, + deviceTimestamp, pointerCount, pointerProperties, pointerCoords, xPrecision, yPrecision, downTime); getListener()->notifyMotion(&args); } @@ -7404,9 +7398,10 @@ void JoystickInputMapper::sync(nsecs_t when, bool force) { // TODO: Use the input device configuration to control this behavior more finely. uint32_t policyFlags = 0; - NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, + policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, - ADISPLAY_ID_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, + /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, 0, 0, 0); getListener()->notifyMotion(&args); } -- cgit v1.2.3-59-g8ed1b From a62a8dd15e3deb4622e3ee8fd844999cf4fafc41 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Fri, 8 Jun 2018 21:17:33 +0100 Subject: Move displayid into InputEvent There are certain use cases where key events should be associated with a particular display. Refactor KeyEvent and MotionEvent to have an associated display id. Remove "hasAssociatedDisplay" variable from KeyboardInputMapper, it just used to mirror "isOrientationAware". If the keyboard is orientation aware (= it is physically attached to a display, and therefore rotates together with that display), then associate that keyboard with the internal viewport. Otherwise, the key events are not associated with any particular display. Remaining to do: - make mInternalDisplay, mExternalDisplay, mVirtualDisplays into a single vector with type (internal, external, virtual) - have getDisplayViewport return std::optional (will require deep changes) Bug: 64258305 Test: atest inputflinger_tests libinput_tests Change-Id: I4fe145e74cb59310efaa55bfc9dc3c2b3bd997e3 --- include/input/Input.h | 14 +++-- include/input/InputTransport.h | 2 + libs/input/Input.cpp | 13 +++-- libs/input/InputTransport.cpp | 3 + libs/input/KeyCharacterMap.cpp | 2 +- libs/input/tests/InputEvent_test.cpp | 8 ++- .../input/tests/InputPublisherAndConsumer_test.cpp | 30 +++++----- libs/input/tests/StructLayout_test.cpp | 15 ++--- services/inputflinger/Android.bp | 2 + services/inputflinger/InputDispatcher.cpp | 45 ++++++++------- services/inputflinger/InputDispatcher.h | 6 +- services/inputflinger/InputListener.cpp | 7 ++- services/inputflinger/InputListener.h | 5 +- services/inputflinger/InputReader.cpp | 64 ++++++++++++---------- services/inputflinger/InputReader.h | 10 +++- services/inputflinger/tests/Android.bp | 1 + .../inputflinger/tests/InputDispatcher_test.cpp | 4 +- services/inputflinger/tests/InputReader_test.cpp | 58 ++++++++++++++++++++ 18 files changed, 193 insertions(+), 96 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/include/input/Input.h b/include/input/Input.h index 15c86ebd85..7c4379eda1 100644 --- a/include/input/Input.h +++ b/include/input/Input.h @@ -302,12 +302,18 @@ public: inline void setSource(int32_t source) { mSource = source; } + inline int32_t getDisplayId() const { return mDisplayId; } + + inline void setDisplayId(int32_t displayId) { mDisplayId = displayId; } + + protected: - void initialize(int32_t deviceId, int32_t source); + void initialize(int32_t deviceId, int32_t source, int32_t displayId); void initialize(const InputEvent& from); int32_t mDeviceId; int32_t mSource; + int32_t mDisplayId; }; /* @@ -343,6 +349,7 @@ public: void initialize( int32_t deviceId, int32_t source, + int32_t displayId, int32_t action, int32_t flags, int32_t keyCode, @@ -373,10 +380,6 @@ public: virtual int32_t getType() const { return AINPUT_EVENT_TYPE_MOTION; } - inline int32_t getDisplayId() const { return mDisplayId; } - - inline void setDisplayId(int32_t displayId) { mDisplayId = displayId; } - inline int32_t getAction() const { return mAction; } inline int32_t getActionMasked() const { return mAction & AMOTION_EVENT_ACTION_MASK; } @@ -614,7 +617,6 @@ public: static int32_t getAxisFromLabel(const char* label); protected: - int32_t mDisplayId; int32_t mAction; int32_t mActionButton; int32_t mFlags; diff --git a/include/input/InputTransport.h b/include/input/InputTransport.h index ee5266108b..e8d1345096 100644 --- a/include/input/InputTransport.h +++ b/include/input/InputTransport.h @@ -64,6 +64,7 @@ struct InputMessage { nsecs_t eventTime __attribute__((aligned(8))); int32_t deviceId; int32_t source; + int32_t displayId; int32_t action; int32_t flags; int32_t keyCode; @@ -211,6 +212,7 @@ public: uint32_t seq, int32_t deviceId, int32_t source, + int32_t displayId, int32_t action, int32_t flags, int32_t keyCode, diff --git a/libs/input/Input.cpp b/libs/input/Input.cpp index db27e11e24..8a15e2f40f 100644 --- a/libs/input/Input.cpp +++ b/libs/input/Input.cpp @@ -31,14 +31,16 @@ namespace android { // --- InputEvent --- -void InputEvent::initialize(int32_t deviceId, int32_t source) { +void InputEvent::initialize(int32_t deviceId, int32_t source, int32_t displayId) { mDeviceId = deviceId; mSource = source; + mDisplayId = displayId; } void InputEvent::initialize(const InputEvent& from) { mDeviceId = from.mDeviceId; mSource = from.mSource; + mDisplayId = from.mDisplayId; } // --- KeyEvent --- @@ -54,6 +56,7 @@ int32_t KeyEvent::getKeyCodeFromLabel(const char* label) { void KeyEvent::initialize( int32_t deviceId, int32_t source, + int32_t displayId, int32_t action, int32_t flags, int32_t keyCode, @@ -62,7 +65,7 @@ void KeyEvent::initialize( int32_t repeatCount, nsecs_t downTime, nsecs_t eventTime) { - InputEvent::initialize(deviceId, source); + InputEvent::initialize(deviceId, source, displayId); mAction = action; mFlags = flags; mKeyCode = keyCode; @@ -231,8 +234,7 @@ void MotionEvent::initialize( size_t pointerCount, const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) { - InputEvent::initialize(deviceId, source); - mDisplayId = displayId; + InputEvent::initialize(deviceId, source, displayId); mAction = action; mActionButton = actionButton; mFlags = flags; @@ -252,8 +254,7 @@ void MotionEvent::initialize( } void MotionEvent::copyFrom(const MotionEvent* other, bool keepHistory) { - InputEvent::initialize(other->mDeviceId, other->mSource); - mDisplayId = other->mDisplayId; + InputEvent::initialize(other->mDeviceId, other->mSource, other->mDisplayId); mAction = other->mAction; mActionButton = other->mActionButton; mFlags = other->mFlags; diff --git a/libs/input/InputTransport.cpp b/libs/input/InputTransport.cpp index f1c3fea879..d192f63c56 100644 --- a/libs/input/InputTransport.cpp +++ b/libs/input/InputTransport.cpp @@ -243,6 +243,7 @@ status_t InputPublisher::publishKeyEvent( uint32_t seq, int32_t deviceId, int32_t source, + int32_t displayId, int32_t action, int32_t flags, int32_t keyCode, @@ -270,6 +271,7 @@ status_t InputPublisher::publishKeyEvent( msg.body.key.seq = seq; msg.body.key.deviceId = deviceId; msg.body.key.source = source; + msg.body.key.displayId = displayId; msg.body.key.action = action; msg.body.key.flags = flags; msg.body.key.keyCode = keyCode; @@ -926,6 +928,7 @@ void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) event->initialize( msg->body.key.deviceId, msg->body.key.source, + msg->body.key.displayId, msg->body.key.action, msg->body.key.flags, msg->body.key.keyCode, diff --git a/libs/input/KeyCharacterMap.cpp b/libs/input/KeyCharacterMap.cpp index cba1111606..b561b605b4 100644 --- a/libs/input/KeyCharacterMap.cpp +++ b/libs/input/KeyCharacterMap.cpp @@ -487,7 +487,7 @@ void KeyCharacterMap::addKey(Vector& outEvents, int32_t deviceId, int32_t keyCode, int32_t metaState, bool down, nsecs_t time) { outEvents.push(); KeyEvent& event = outEvents.editTop(); - event.initialize(deviceId, AINPUT_SOURCE_KEYBOARD, + event.initialize(deviceId, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP, 0, keyCode, 0, metaState, 0, time, time); } diff --git a/libs/input/tests/InputEvent_test.cpp b/libs/input/tests/InputEvent_test.cpp index c4b8fe328f..99f83ba7db 100644 --- a/libs/input/tests/InputEvent_test.cpp +++ b/libs/input/tests/InputEvent_test.cpp @@ -181,13 +181,14 @@ TEST_F(KeyEventTest, Properties) { // Initialize and get properties. const nsecs_t ARBITRARY_DOWN_TIME = 1; const nsecs_t ARBITRARY_EVENT_TIME = 2; - event.initialize(2, AINPUT_SOURCE_GAMEPAD, AKEY_EVENT_ACTION_DOWN, + event.initialize(2, AINPUT_SOURCE_GAMEPAD, DISPLAY_ID, AKEY_EVENT_ACTION_DOWN, AKEY_EVENT_FLAG_FROM_SYSTEM, AKEYCODE_BUTTON_X, 121, AMETA_ALT_ON, 1, ARBITRARY_DOWN_TIME, ARBITRARY_EVENT_TIME); ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, event.getType()); ASSERT_EQ(2, event.getDeviceId()); ASSERT_EQ(static_cast(AINPUT_SOURCE_GAMEPAD), event.getSource()); + ASSERT_EQ(DISPLAY_ID, event.getDisplayId()); ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, event.getAction()); ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, event.getFlags()); ASSERT_EQ(AKEYCODE_BUTTON_X, event.getKeyCode()); @@ -200,6 +201,11 @@ TEST_F(KeyEventTest, Properties) { // Set source. event.setSource(AINPUT_SOURCE_JOYSTICK); ASSERT_EQ(static_cast(AINPUT_SOURCE_JOYSTICK), event.getSource()); + + // Set display id. + constexpr int32_t newDisplayId = 2; + event.setDisplayId(newDisplayId); + ASSERT_EQ(newDisplayId, event.getDisplayId()); } diff --git a/libs/input/tests/InputPublisherAndConsumer_test.cpp b/libs/input/tests/InputPublisherAndConsumer_test.cpp index 6c4faed2cc..13617bfd9b 100644 --- a/libs/input/tests/InputPublisherAndConsumer_test.cpp +++ b/libs/input/tests/InputPublisherAndConsumer_test.cpp @@ -70,19 +70,20 @@ TEST_F(InputPublisherAndConsumerTest, GetChannel_ReturnsTheChannel) { void InputPublisherAndConsumerTest::PublishAndConsumeKeyEvent() { status_t status; - const uint32_t seq = 15; - const int32_t deviceId = 1; - const int32_t source = AINPUT_SOURCE_KEYBOARD; - const int32_t action = AKEY_EVENT_ACTION_DOWN; - const int32_t flags = AKEY_EVENT_FLAG_FROM_SYSTEM; - const int32_t keyCode = AKEYCODE_ENTER; - const int32_t scanCode = 13; - const int32_t metaState = AMETA_ALT_LEFT_ON | AMETA_ALT_ON; - const int32_t repeatCount = 1; - const nsecs_t downTime = 3; - const nsecs_t eventTime = 4; - - status = mPublisher->publishKeyEvent(seq, deviceId, source, action, flags, + constexpr uint32_t seq = 15; + constexpr int32_t deviceId = 1; + constexpr int32_t source = AINPUT_SOURCE_KEYBOARD; + constexpr int32_t displayId = ADISPLAY_ID_DEFAULT; + constexpr int32_t action = AKEY_EVENT_ACTION_DOWN; + constexpr int32_t flags = AKEY_EVENT_FLAG_FROM_SYSTEM; + constexpr int32_t keyCode = AKEYCODE_ENTER; + constexpr int32_t scanCode = 13; + constexpr int32_t metaState = AMETA_ALT_LEFT_ON | AMETA_ALT_ON; + constexpr int32_t repeatCount = 1; + constexpr nsecs_t downTime = 3; + constexpr nsecs_t eventTime = 4; + + status = mPublisher->publishKeyEvent(seq, deviceId, source, displayId, action, flags, keyCode, scanCode, metaState, repeatCount, downTime, eventTime); ASSERT_EQ(OK, status) << "publisher publishKeyEvent should return OK"; @@ -102,6 +103,7 @@ void InputPublisherAndConsumerTest::PublishAndConsumeKeyEvent() { EXPECT_EQ(seq, consumeSeq); EXPECT_EQ(deviceId, keyEvent->getDeviceId()); EXPECT_EQ(source, keyEvent->getSource()); + EXPECT_EQ(displayId, keyEvent->getDisplayId()); EXPECT_EQ(action, keyEvent->getAction()); EXPECT_EQ(flags, keyEvent->getFlags()); EXPECT_EQ(keyCode, keyEvent->getKeyCode()); @@ -132,7 +134,7 @@ void InputPublisherAndConsumerTest::PublishAndConsumeMotionEvent() { constexpr uint32_t seq = 15; constexpr int32_t deviceId = 1; constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN; - constexpr int32_t displayId = 0; + constexpr int32_t displayId = ADISPLAY_ID_DEFAULT; constexpr int32_t action = AMOTION_EVENT_ACTION_MOVE; constexpr int32_t actionButton = 0; constexpr int32_t flags = AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED; diff --git a/libs/input/tests/StructLayout_test.cpp b/libs/input/tests/StructLayout_test.cpp index 77cce7ac18..d19f3b8066 100644 --- a/libs/input/tests/StructLayout_test.cpp +++ b/libs/input/tests/StructLayout_test.cpp @@ -38,13 +38,14 @@ void TestInputMessageAlignment() { CHECK_OFFSET(InputMessage::Body::Key, eventTime, 8); CHECK_OFFSET(InputMessage::Body::Key, deviceId, 16); CHECK_OFFSET(InputMessage::Body::Key, source, 20); - CHECK_OFFSET(InputMessage::Body::Key, action, 24); - CHECK_OFFSET(InputMessage::Body::Key, flags, 28); - CHECK_OFFSET(InputMessage::Body::Key, keyCode, 32); - CHECK_OFFSET(InputMessage::Body::Key, scanCode, 36); - CHECK_OFFSET(InputMessage::Body::Key, metaState, 40); - CHECK_OFFSET(InputMessage::Body::Key, repeatCount, 44); - CHECK_OFFSET(InputMessage::Body::Key, downTime, 48); + CHECK_OFFSET(InputMessage::Body::Key, displayId, 24); + CHECK_OFFSET(InputMessage::Body::Key, action, 28); + CHECK_OFFSET(InputMessage::Body::Key, flags, 32); + CHECK_OFFSET(InputMessage::Body::Key, keyCode, 36); + CHECK_OFFSET(InputMessage::Body::Key, scanCode, 40); + CHECK_OFFSET(InputMessage::Body::Key, metaState, 44); + CHECK_OFFSET(InputMessage::Body::Key, repeatCount, 48); + CHECK_OFFSET(InputMessage::Body::Key, downTime, 56); CHECK_OFFSET(InputMessage::Body::Motion, seq, 0); CHECK_OFFSET(InputMessage::Body::Motion, eventTime, 8); diff --git a/services/inputflinger/Android.bp b/services/inputflinger/Android.bp index a9e5a4339c..45efb9fc08 100644 --- a/services/inputflinger/Android.bp +++ b/services/inputflinger/Android.bp @@ -15,6 +15,8 @@ cc_library_shared { name: "libinputflinger", + cpp_std: "c++17", + srcs: [ "EventHub.cpp", "InputApplication.cpp", diff --git a/services/inputflinger/InputDispatcher.cpp b/services/inputflinger/InputDispatcher.cpp index 078fbca0d6..18744c3401 100644 --- a/services/inputflinger/InputDispatcher.cpp +++ b/services/inputflinger/InputDispatcher.cpp @@ -702,7 +702,7 @@ InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t cu entry->repeatCount += 1; } else { KeyEntry* newEntry = new KeyEntry(currentTime, - entry->deviceId, entry->source, policyFlags, + entry->deviceId, entry->source, entry->displayId, policyFlags, entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount + 1, entry->downTime); @@ -851,11 +851,11 @@ bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry, void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) { #if DEBUG_OUTBOUND_EVENT_DETAILS - ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, " - "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, " - "repeatCount=%d, downTime=%" PRId64, + ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", " + "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, " + "metaState=0x%x, repeatCount=%d, downTime=%" PRId64, prefix, - entry->eventTime, entry->deviceId, entry->source, entry->policyFlags, + entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags, entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount, entry->downTime); #endif @@ -2018,7 +2018,7 @@ void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime, // Publish the key event. status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq, - keyEntry->deviceId, keyEntry->source, + keyEntry->deviceId, keyEntry->source, keyEntry->displayId, dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags, keyEntry->keyCode, keyEntry->scanCode, keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime, @@ -2464,9 +2464,9 @@ void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int3 void InputDispatcher::notifyKey(const NotifyKeyArgs* args) { #if DEBUG_INBOUND_EVENT_DETAILS ALOGD("notifyKey - eventTime=%" PRId64 - ", deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, " + ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, " "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64, - args->eventTime, args->deviceId, args->source, args->policyFlags, + args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags, args->action, args->flags, args->keyCode, args->scanCode, args->metaState, args->downTime); #endif @@ -2491,7 +2491,7 @@ void InputDispatcher::notifyKey(const NotifyKeyArgs* args) { accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState); KeyEvent event; - event.initialize(args->deviceId, args->source, args->action, + event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode, args->scanCode, metaState, 0, args->downTime, args->eventTime); @@ -2519,7 +2519,7 @@ void InputDispatcher::notifyKey(const NotifyKeyArgs* args) { int32_t repeatCount = 0; KeyEntry* newEntry = new KeyEntry(args->eventTime, - args->deviceId, args->source, policyFlags, + args->deviceId, args->source, args->displayId, policyFlags, args->action, flags, keyCode, args->scanCode, metaState, repeatCount, args->downTime); @@ -2687,8 +2687,8 @@ int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t metaState = keyEvent.getMetaState(); accelerateMetaShortcuts(keyEvent.getDeviceId(), action, /*byref*/ keyCode, /*byref*/ metaState); - keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), action, - flags, keyCode, keyEvent.getScanCode(), metaState, 0, + keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(), + action, flags, keyCode, keyEvent.getScanCode(), metaState, 0, keyEvent.getDownTime(), keyEvent.getEventTime()); if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) { @@ -2706,7 +2706,7 @@ int32_t InputDispatcher::injectInputEvent(const InputEvent* event, mLock.lock(); firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(), - keyEvent.getDeviceId(), keyEvent.getSource(), + keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(), policyFlags, action, flags, keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(), keyEvent.getRepeatCount(), keyEvent.getDownTime()); @@ -3840,6 +3840,7 @@ bool InputDispatcher::afterKeyEventLockedInterruptible(const sp& con keyEntry->eventTime = event.getEventTime(); keyEntry->deviceId = event.getDeviceId(); keyEntry->source = event.getSource(); + keyEntry->displayId = event.getDisplayId(); keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK; keyEntry->keyCode = fallbackKeyCode; keyEntry->scanCode = event.getScanCode(); @@ -3878,7 +3879,7 @@ void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* comman } void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) { - event->initialize(entry->deviceId, entry->source, entry->action, entry->flags, + event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount, entry->downTime, entry->eventTime); } @@ -4014,11 +4015,11 @@ void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) cons // --- InputDispatcher::KeyEntry --- InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime, - int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, + int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, int32_t repeatCount, nsecs_t downTime) : EventEntry(TYPE_KEY, eventTime, policyFlags), - deviceId(deviceId), source(source), action(action), flags(flags), + deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags), keyCode(keyCode), scanCode(scanCode), metaState(metaState), repeatCount(repeatCount), downTime(downTime), syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN), @@ -4029,10 +4030,10 @@ InputDispatcher::KeyEntry::~KeyEntry() { } void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const { - msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, action=%s, " + msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, " "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, " "repeatCount=%d), policyFlags=0x%08x", - deviceId, source, keyActionToString(action).c_str(), flags, keyCode, + deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode, scanCode, metaState, repeatCount, policyFlags); } @@ -4302,6 +4303,7 @@ ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const const KeyMemento& memento = mKeyMementos.itemAt(i); if (memento.deviceId == entry->deviceId && memento.source == entry->source + && memento.displayId == entry->displayId && memento.keyCode == entry->keyCode && memento.scanCode == entry->scanCode) { return i; @@ -4329,6 +4331,7 @@ void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t f KeyMemento& memento = mKeyMementos.editTop(); memento.deviceId = entry->deviceId; memento.source = entry->source; + memento.displayId = entry->displayId; memento.keyCode = entry->keyCode; memento.scanCode = entry->scanCode; memento.metaState = entry->metaState; @@ -4367,7 +4370,7 @@ void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTim const KeyMemento& memento = mKeyMementos.itemAt(i); if (shouldCancelKey(memento, options)) { outEvents.push(new KeyEntry(currentTime, - memento.deviceId, memento.source, memento.policyFlags, + memento.deviceId, memento.source, memento.displayId, memento.policyFlags, AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED, memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime)); } @@ -4535,7 +4538,7 @@ InputDispatcher::CommandEntry::~CommandEntry() { // --- InputDispatcher::TouchState --- InputDispatcher::TouchState::TouchState() : - down(false), split(false), deviceId(-1), source(0), displayId(-1) { + down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) { } InputDispatcher::TouchState::~TouchState() { @@ -4546,7 +4549,7 @@ void InputDispatcher::TouchState::reset() { split = false; deviceId = -1; source = 0; - displayId = -1; + displayId = ADISPLAY_ID_NONE; windows.clear(); } diff --git a/services/inputflinger/InputDispatcher.h b/services/inputflinger/InputDispatcher.h index 82960b7779..1072eb655f 100644 --- a/services/inputflinger/InputDispatcher.h +++ b/services/inputflinger/InputDispatcher.h @@ -474,6 +474,7 @@ private: struct KeyEntry : EventEntry { int32_t deviceId; uint32_t source; + int32_t displayId; int32_t action; int32_t flags; int32_t keyCode; @@ -494,8 +495,8 @@ private: nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER KeyEntry(nsecs_t eventTime, - int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, - int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, + int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, + int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, int32_t repeatCount, nsecs_t downTime); virtual void appendDescription(std::string& msg) const; void recycle(); @@ -753,6 +754,7 @@ private: struct KeyMemento { int32_t deviceId; uint32_t source; + int32_t displayId; int32_t keyCode; int32_t scanCode; int32_t metaState; diff --git a/services/inputflinger/InputListener.cpp b/services/inputflinger/InputListener.cpp index c36d7cfb1a..25a39a8274 100644 --- a/services/inputflinger/InputListener.cpp +++ b/services/inputflinger/InputListener.cpp @@ -43,17 +43,18 @@ void NotifyConfigurationChangedArgs::notify(const sp& li // --- NotifyKeyArgs --- NotifyKeyArgs::NotifyKeyArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, - uint32_t policyFlags, + int32_t displayId, uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) : - eventTime(eventTime), deviceId(deviceId), source(source), policyFlags(policyFlags), + eventTime(eventTime), deviceId(deviceId), source(source), displayId(displayId), + policyFlags(policyFlags), action(action), flags(flags), keyCode(keyCode), scanCode(scanCode), metaState(metaState), downTime(downTime) { } NotifyKeyArgs::NotifyKeyArgs(const NotifyKeyArgs& other) : eventTime(other.eventTime), deviceId(other.deviceId), source(other.source), - policyFlags(other.policyFlags), + displayId(other.displayId), policyFlags(other.policyFlags), action(other.action), flags(other.flags), keyCode(other.keyCode), scanCode(other.scanCode), metaState(other.metaState), downTime(other.downTime) { diff --git a/services/inputflinger/InputListener.h b/services/inputflinger/InputListener.h index d24be4c677..a3d919bf5a 100644 --- a/services/inputflinger/InputListener.h +++ b/services/inputflinger/InputListener.h @@ -55,6 +55,7 @@ struct NotifyKeyArgs : public NotifyArgs { nsecs_t eventTime; int32_t deviceId; uint32_t source; + int32_t displayId; uint32_t policyFlags; int32_t action; int32_t flags; @@ -65,8 +66,8 @@ struct NotifyKeyArgs : public NotifyArgs { inline NotifyKeyArgs() { } - NotifyKeyArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, uint32_t policyFlags, - int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, + NotifyKeyArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, + uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime); NotifyKeyArgs(const NotifyKeyArgs& other); diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 50229cbaab..9a35510fe6 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -226,7 +226,7 @@ static float calculateCommonVector(float a, float b) { } static void synthesizeButtonKey(InputReaderContext* context, int32_t action, - nsecs_t when, int32_t deviceId, uint32_t source, + nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState, int32_t buttonState, int32_t keyCode) { if ( @@ -236,19 +236,19 @@ static void synthesizeButtonKey(InputReaderContext* context, int32_t action, || (action == AKEY_EVENT_ACTION_UP && (lastButtonState & buttonState) && !(currentButtonState & buttonState))) { - NotifyKeyArgs args(when, deviceId, source, policyFlags, + NotifyKeyArgs args(when, deviceId, source, displayId, policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when); context->getListener()->notifyKey(&args); } } static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, - nsecs_t when, int32_t deviceId, uint32_t source, + nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) { - synthesizeButtonKey(context, action, when, deviceId, source, policyFlags, + synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags, lastButtonState, currentButtonState, AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK); - synthesizeButtonKey(context, action, when, deviceId, source, policyFlags, + synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags, lastButtonState, currentButtonState, AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD); } @@ -2240,8 +2240,7 @@ void VibratorInputMapper::dump(std::string& dump) { KeyboardInputMapper::KeyboardInputMapper(InputDevice* device, uint32_t source, int32_t keyboardType) : - InputMapper(device), mSource(source), - mKeyboardType(keyboardType) { + InputMapper(device), mSource(source), mKeyboardType(keyboardType) { } KeyboardInputMapper::~KeyboardInputMapper() { @@ -2251,6 +2250,20 @@ uint32_t KeyboardInputMapper::getSources() { return mSource; } +int32_t KeyboardInputMapper::getOrientation() { + if (mViewport) { + return mViewport->orientation; + } + return DISPLAY_ORIENTATION_0; +} + +int32_t KeyboardInputMapper::getDisplayId() { + if (mViewport) { + return mViewport->displayId; + } + return ADISPLAY_ID_NONE; +} + void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); @@ -2262,7 +2275,7 @@ void KeyboardInputMapper::dump(std::string& dump) { dump += INDENT2 "Keyboard Input Mapper:\n"; dumpParameters(dump); dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType); - dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation); + dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation()); dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size()); dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState); dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime); @@ -2279,12 +2292,10 @@ void KeyboardInputMapper::configure(nsecs_t when, } if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { - mOrientation = DISPLAY_ORIENTATION_0; - if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { - DisplayViewport v; - if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) { - mOrientation = v.orientation; - } + if (mParameters.orientationAware) { + DisplayViewport dvp; + config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &dvp); + mViewport = dvp; } } } @@ -2307,10 +2318,7 @@ void KeyboardInputMapper::configureParameters() { config.tryGetProperty(String8("keyboard.orientationAware"), mParameters.orientationAware); - mParameters.hasAssociatedDisplay = false; if (mParameters.orientationAware) { - mParameters.hasAssociatedDisplay = true; - mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary"); mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1"); mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2"); @@ -2324,8 +2332,6 @@ void KeyboardInputMapper::configureParameters() { void KeyboardInputMapper::dumpParameters(std::string& dump) { dump += INDENT3 "Parameters:\n"; - dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n", - toString(mParameters.hasAssociatedDisplay)); dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware)); dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n", @@ -2420,8 +2426,8 @@ void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode, if (down) { // Rotate key codes according to orientation if needed. - if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { - keyCode = rotateKeyCode(keyCode, mOrientation); + if (mParameters.orientationAware) { + keyCode = rotateKeyCode(keyCode, getOrientation()); } // Add key down. @@ -2486,7 +2492,7 @@ void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode, policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT; } - NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags, + NotifyKeyArgs args(when, getDeviceId(), mSource, getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP, AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime); getListener()->notifyKey(&args); @@ -2868,7 +2874,7 @@ void CursorInputMapper::sync(nsecs_t when) { // Synthesize key down from buttons if needed. synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource, - policyFlags, lastButtonState, currentButtonState); + displayId, policyFlags, lastButtonState, currentButtonState); // Send motion event. if (downChanged || moved || scrolled || buttonsChanged) { @@ -2947,7 +2953,7 @@ void CursorInputMapper::sync(nsecs_t when) { // Synthesize key up from buttons if needed. synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource, - policyFlags, lastButtonState, currentButtonState); + displayId, policyFlags, lastButtonState, currentButtonState); mCursorMotionAccumulator.finishSync(); mCursorScrollAccumulator.finishSync(); @@ -4427,7 +4433,8 @@ void TouchInputMapper::cookAndDispatch(nsecs_t when) { // Synthesize key down from raw buttons if needed. synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource, - policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState); + mViewport.displayId, policyFlags, + mLastCookedState.buttonState, mCurrentCookedState.buttonState); // Dispatch the touches either directly or by translation through a pointer on screen. if (mDeviceMode == DEVICE_MODE_POINTER) { @@ -4499,7 +4506,8 @@ void TouchInputMapper::cookAndDispatch(nsecs_t when) { // Synthesize key up from raw buttons if needed. synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource, - policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState); + mViewport.displayId, policyFlags, + mLastCookedState.buttonState, mCurrentCookedState.buttonState); // Clear some transient state. mCurrentRawState.rawVScroll = 0; @@ -4714,8 +4722,8 @@ void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags, int32_t metaState = mContext->getGlobalMetaState(); policyFlags |= POLICY_FLAG_VIRTUAL; - NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags, - keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime); + NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId, + policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime); getListener()->notifyKey(&args); } diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h index cef3212684..89290a82e3 100644 --- a/services/inputflinger/InputReader.h +++ b/services/inputflinger/InputReader.h @@ -35,6 +35,7 @@ #include #include +#include #include #include @@ -1094,6 +1095,9 @@ public: virtual void updateMetaState(int32_t keyCode); private: + // The current viewport. + std::optional mViewport; + struct KeyDown { int32_t keyCode; int32_t scanCode; @@ -1102,8 +1106,6 @@ private: uint32_t mSource; int32_t mKeyboardType; - int32_t mOrientation; // orientation for dpad keys - Vector mKeyDowns; // keys that are down int32_t mMetaState; nsecs_t mDownTime; // time of most recent key down @@ -1120,7 +1122,6 @@ private: // Immutable configuration parameters. struct Parameters { - bool hasAssociatedDisplay; bool orientationAware; bool handlesKeyRepeat; } mParameters; @@ -1128,6 +1129,9 @@ private: void configureParameters(); void dumpParameters(std::string& dump); + int32_t getOrientation(); + int32_t getDisplayId(); + bool isKeyboardOrGamepadKey(int32_t scanCode); bool isMediaKey(int32_t keyCode); diff --git a/services/inputflinger/tests/Android.bp b/services/inputflinger/tests/Android.bp index 2faa7944c1..ccd14c93ae 100644 --- a/services/inputflinger/tests/Android.bp +++ b/services/inputflinger/tests/Android.bp @@ -2,6 +2,7 @@ cc_test { name: "inputflinger_tests", + cpp_std: "c++17", srcs: [ "InputReader_test.cpp", "InputDispatcher_test.cpp", diff --git a/services/inputflinger/tests/InputDispatcher_test.cpp b/services/inputflinger/tests/InputDispatcher_test.cpp index 9c72c77846..0e26d4a9ce 100644 --- a/services/inputflinger/tests/InputDispatcher_test.cpp +++ b/services/inputflinger/tests/InputDispatcher_test.cpp @@ -120,7 +120,7 @@ TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) { KeyEvent event; // Rejects undefined key actions. - event.initialize(DEVICE_ID, AINPUT_SOURCE_KEYBOARD, + event.initialize(DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE, /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME, ARBITRARY_TIME); ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED, mDispatcher->injectInputEvent( @@ -129,7 +129,7 @@ TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) { << "Should reject key events with undefined action."; // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API. - event.initialize(DEVICE_ID, AINPUT_SOURCE_KEYBOARD, + event.initialize(DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME, ARBITRARY_TIME); ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED, mDispatcher->injectInputEvent( diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index 22f15a05fe..4f29e3abf1 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -1996,6 +1996,64 @@ TEST_F(KeyboardInputMapperTest, Process_WhenOrientationAware_ShouldRotateDPad) { ASSERT_EQ(AKEYCODE_DPAD_RIGHT, args.keyCode); } +TEST_F(KeyboardInputMapperTest, DisplayIdConfigurationChange_NotOrientationAware) { + // If the keyboard is not orientation aware, + // key events should not be associated with a specific display id + mFakeEventHub->addKey(DEVICE_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0); + + KeyboardInputMapper* mapper = new KeyboardInputMapper(mDevice, + AINPUT_SOURCE_KEYBOARD, AINPUT_KEYBOARD_TYPE_ALPHABETIC); + addMapperAndConfigure(mapper); + NotifyKeyArgs args; + + // Display id should be ADISPLAY_ID_NONE without any display configuration. + process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 1); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); + process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 0); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); + ASSERT_EQ(ADISPLAY_ID_NONE, args.displayId); + + setDisplayInfoAndReconfigure(DISPLAY_ID, + DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0); + process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 1); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); + process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 0); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); + ASSERT_EQ(ADISPLAY_ID_NONE, args.displayId); +} + +TEST_F(KeyboardInputMapperTest, DisplayIdConfigurationChange_OrientationAware) { + // If the keyboard is orientation aware, + // key events should be associated with the internal viewport + mFakeEventHub->addKey(DEVICE_ID, KEY_UP, 0, AKEYCODE_DPAD_UP, 0); + + KeyboardInputMapper* mapper = new KeyboardInputMapper(mDevice, + AINPUT_SOURCE_KEYBOARD, AINPUT_KEYBOARD_TYPE_ALPHABETIC); + addConfigurationProperty("keyboard.orientationAware", "1"); + addMapperAndConfigure(mapper); + NotifyKeyArgs args; + + // Display id should be ADISPLAY_ID_NONE without any display configuration. + // ^--- already checked by the previous test + + setDisplayInfoAndReconfigure(DISPLAY_ID, + DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0); + process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 1); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); + process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 0); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); + ASSERT_EQ(DISPLAY_ID, args.displayId); + + constexpr int32_t newDisplayId = 2; + setDisplayInfoAndReconfigure(newDisplayId, + DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0); + process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 1); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); + process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 0); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); + ASSERT_EQ(newDisplayId, args.displayId); +} + TEST_F(KeyboardInputMapperTest, GetKeyCodeState) { KeyboardInputMapper* mapper = new KeyboardInputMapper(mDevice, AINPUT_SOURCE_KEYBOARD, AINPUT_KEYBOARD_TYPE_ALPHABETIC); -- cgit v1.2.3-59-g8ed1b From 9b14ac68219c997b5e253cd59f215b9c81cd6e9f Mon Sep 17 00:00:00 2001 From: Yi Kong Date: Tue, 17 Jul 2018 13:48:38 -0700 Subject: [inputflinger] Modernize codebase by replacing NULL with nullptr Fixes -Wzero-as-null-pointer-constant warning. Test: m Bug: 68236239 Change-Id: I0d06ab2a187e72bd893900355edad97caa684c7a --- services/inputflinger/EventHub.cpp | 42 ++++---- services/inputflinger/EventHub.h | 2 +- services/inputflinger/InputApplication.cpp | 4 +- services/inputflinger/InputDispatcher.cpp | 126 +++++++++++------------ services/inputflinger/InputDispatcher.h | 14 +-- services/inputflinger/InputReader.cpp | 42 ++++---- services/inputflinger/InputWindow.cpp | 4 +- services/inputflinger/InputWindow.h | 2 +- services/inputflinger/tests/InputReader_test.cpp | 64 ++++++------ 9 files changed, 150 insertions(+), 150 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/EventHub.cpp b/services/inputflinger/EventHub.cpp index 4d9a2a0254..77a474fa82 100644 --- a/services/inputflinger/EventHub.cpp +++ b/services/inputflinger/EventHub.cpp @@ -143,9 +143,9 @@ uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) { EventHub::Device::Device(int fd, int32_t id, const String8& path, const InputDeviceIdentifier& identifier) : - next(NULL), + next(nullptr), fd(fd), id(id), path(path), identifier(identifier), - classes(0), configuration(NULL), virtualKeyMap(NULL), + classes(0), configuration(nullptr), virtualKeyMap(nullptr), ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0), timestampOverrideSec(0), timestampOverrideUsec(0), enabled(true), isVirtual(fd < 0) { @@ -200,7 +200,7 @@ const int EventHub::EPOLL_MAX_EVENTS; EventHub::EventHub(void) : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(), - mOpeningDevices(0), mClosingDevices(0), + mOpeningDevices(nullptr), mClosingDevices(nullptr), mNeedToSendFinishedDeviceScan(false), mNeedToReopenDevices(false), mNeedToScanDevices(true), mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) { @@ -267,21 +267,21 @@ EventHub::~EventHub(void) { InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const { AutoMutex _l(mLock); Device* device = getDeviceLocked(deviceId); - if (device == NULL) return InputDeviceIdentifier(); + if (device == nullptr) return InputDeviceIdentifier(); return device->identifier; } uint32_t EventHub::getDeviceClasses(int32_t deviceId) const { AutoMutex _l(mLock); Device* device = getDeviceLocked(deviceId); - if (device == NULL) return 0; + if (device == nullptr) return 0; return device->classes; } int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const { AutoMutex _l(mLock); Device* device = getDeviceLocked(deviceId); - if (device == NULL) return 0; + if (device == nullptr) return 0; return device->controllerNumber; } @@ -465,7 +465,7 @@ status_t EventHub::mapKey(int32_t deviceId, if (device) { // Check the key character map first. sp kcm = device->getKeyCharacterMap(); - if (kcm != NULL) { + if (kcm != nullptr) { if (!kcm->mapKey(scanCode, usageCode, outKeycode)) { *outFlags = 0; status = NO_ERROR; @@ -481,7 +481,7 @@ status_t EventHub::mapKey(int32_t deviceId, } if (status == NO_ERROR) { - if (kcm != NULL) { + if (kcm != nullptr) { kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState); } else { *outMetaState = metaState; @@ -581,7 +581,7 @@ sp EventHub::getKeyCharacterMap(int32_t deviceId) const { if (device) { return device->getKeyCharacterMap(); } - return NULL; + return nullptr; } bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, @@ -641,7 +641,7 @@ void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) { if (identifier.uniqueId.isEmpty()) { // If it didn't have a unique id check for conflicts and enforce // uniqueness if necessary. - while(getDeviceByDescriptorLocked(identifier.descriptor) != NULL) { + while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) { identifier.nonce++; rawDescriptor = generateDescriptor(identifier); } @@ -714,7 +714,7 @@ EventHub::Device* EventHub::getDeviceByDescriptorLocked(String8& descriptor) con return device; } } - return NULL; + return nullptr; } EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const { @@ -732,7 +732,7 @@ EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const return device; } } - return NULL; + return nullptr; } size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) { @@ -782,7 +782,7 @@ size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSiz mNeedToSendFinishedDeviceScan = true; } - while (mOpeningDevices != NULL) { + while (mOpeningDevices != nullptr) { Device* device = mOpeningDevices; ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.string()); @@ -1099,7 +1099,7 @@ status_t EventHub::registerDeviceForEpollLocked(Device* device) { status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) { if (device->hasValidFd()) { - if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, NULL)) { + if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, nullptr)) { ALOGW("Could not remove device fd from epoll instance. errno=%d", errno); return -errno; } @@ -1423,7 +1423,7 @@ void EventHub::configureFd(Device* device) { bool EventHub::isDeviceEnabled(int32_t deviceId) { AutoMutex _l(mLock); Device* device = getDeviceLocked(deviceId); - if (device == NULL) { + if (device == nullptr) { ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__); return false; } @@ -1433,7 +1433,7 @@ bool EventHub::isDeviceEnabled(int32_t deviceId) { status_t EventHub::enableDevice(int32_t deviceId) { AutoMutex _l(mLock); Device* device = getDeviceLocked(deviceId); - if (device == NULL) { + if (device == nullptr) { ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__); return BAD_VALUE; } @@ -1455,7 +1455,7 @@ status_t EventHub::enableDevice(int32_t deviceId) { status_t EventHub::disableDevice(int32_t deviceId) { AutoMutex _l(mLock); Device* device = getDeviceLocked(deviceId); - if (device == NULL) { + if (device == nullptr) { ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__); return BAD_VALUE; } @@ -1634,9 +1634,9 @@ void EventHub::closeDeviceLocked(Device* device) { device->close(); // Unlink for opening devices list if it is present. - Device* pred = NULL; + Device* pred = nullptr; bool found = false; - for (Device* entry = mOpeningDevices; entry != NULL; ) { + for (Device* entry = mOpeningDevices; entry != nullptr; ) { if (entry == device) { found = true; break; @@ -1712,7 +1712,7 @@ status_t EventHub::scanDirLocked(const char *dirname) DIR *dir; struct dirent *de; dir = opendir(dirname); - if(dir == NULL) + if(dir == nullptr) return -1; strcpy(devname, dirname); filename = devname + strlen(devname); @@ -1773,7 +1773,7 @@ void EventHub::dump(std::string& dump) { dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n", device->configurationFile.string()); dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n", - toString(device->overlayKeyMap != NULL)); + toString(device->overlayKeyMap != nullptr)); } } // release lock } diff --git a/services/inputflinger/EventHub.h b/services/inputflinger/EventHub.h index 66bc29456b..dfe3defc73 100644 --- a/services/inputflinger/EventHub.h +++ b/services/inputflinger/EventHub.h @@ -385,7 +385,7 @@ private: const bool isVirtual; // set if fd < 0 is passed to constructor const sp& getKeyCharacterMap() const { - if (combinedKeyMap != NULL) { + if (combinedKeyMap != nullptr) { return combinedKeyMap; } return keyMap.keyCharacterMap; diff --git a/services/inputflinger/InputApplication.cpp b/services/inputflinger/InputApplication.cpp index 9e90631840..c56dfe6879 100644 --- a/services/inputflinger/InputApplication.cpp +++ b/services/inputflinger/InputApplication.cpp @@ -25,7 +25,7 @@ namespace android { // --- InputApplicationHandle --- InputApplicationHandle::InputApplicationHandle() : - mInfo(NULL) { + mInfo(nullptr) { } InputApplicationHandle::~InputApplicationHandle() { @@ -35,7 +35,7 @@ InputApplicationHandle::~InputApplicationHandle() { void InputApplicationHandle::releaseInfo() { if (mInfo) { delete mInfo; - mInfo = NULL; + mInfo = nullptr; } } diff --git a/services/inputflinger/InputDispatcher.cpp b/services/inputflinger/InputDispatcher.cpp index 18744c3401..c805805252 100644 --- a/services/inputflinger/InputDispatcher.cpp +++ b/services/inputflinger/InputDispatcher.cpp @@ -240,14 +240,14 @@ static void dumpRegion(std::string& dump, const Region& region) { InputDispatcher::InputDispatcher(const sp& policy) : mPolicy(policy), - mPendingEvent(NULL), mLastDropReason(DROP_REASON_NOT_DROPPED), + mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX), - mNextUnblockedEvent(NULL), + mNextUnblockedEvent(nullptr), mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false), mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) { mLooper = new Looper(false); - mKeyRepeatState.lastKeyEntry = NULL; + mKeyRepeatState.lastKeyEntry = nullptr; policy->getDispatcherConfiguration(&mConfig); } @@ -360,7 +360,7 @@ void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) { // Now we have an event to dispatch. // All events are eventually dequeued and processed this way, even if we intend to drop them. - ALOG_ASSERT(mPendingEvent != NULL); + ALOG_ASSERT(mPendingEvent != nullptr); bool done = false; DropReason dropReason = DROP_REASON_NOT_DROPPED; if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) { @@ -370,7 +370,7 @@ void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) { } if (mNextUnblockedEvent == mPendingEvent) { - mNextUnblockedEvent = NULL; + mNextUnblockedEvent = nullptr; } switch (mPendingEvent->type) { @@ -481,14 +481,14 @@ bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) { if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY - && mInputTargetWaitApplicationHandle != NULL) { + && mInputTargetWaitApplicationHandle != nullptr) { int32_t displayId = motionEntry->displayId; int32_t x = int32_t(motionEntry->pointerCoords[0]. getAxisValue(AMOTION_EVENT_AXIS_X)); int32_t y = int32_t(motionEntry->pointerCoords[0]. getAxisValue(AMOTION_EVENT_AXIS_Y)); sp touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y); - if (touchedWindowHandle != NULL + if (touchedWindowHandle != nullptr && touchedWindowHandle->inputApplicationHandle != mInputTargetWaitApplicationHandle) { // User touched a different application than the one we are waiting on. @@ -534,7 +534,7 @@ sp InputDispatcher::findTouchedWindowAtLocked(int32_t display } } } - return NULL; + return nullptr; } void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) { @@ -663,7 +663,7 @@ void InputDispatcher::releasePendingEventLocked() { if (mPendingEvent) { resetANRTimeoutsLocked(); releaseInboundEventLocked(mPendingEvent); - mPendingEvent = NULL; + mPendingEvent = nullptr; } } @@ -676,7 +676,7 @@ void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) { setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED); } if (entry == mNextUnblockedEvent) { - mNextUnblockedEvent = NULL; + mNextUnblockedEvent = nullptr; } addRecentEventLocked(entry); entry->release(); @@ -685,7 +685,7 @@ void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) { void InputDispatcher::resetKeyRepeatLocked() { if (mKeyRepeatState.lastKeyEntry) { mKeyRepeatState.lastKeyEntry->release(); - mKeyRepeatState.lastKeyEntry = NULL; + mKeyRepeatState.lastKeyEntry = nullptr; } } @@ -807,7 +807,7 @@ bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry, if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) { CommandEntry* commandEntry = postCommandLocked( & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible); - if (mFocusedWindowHandle != NULL) { + if (mFocusedWindowHandle != nullptr) { commandEntry->inputWindowHandle = mFocusedWindowHandle; } commandEntry->keyEntry = entry; @@ -988,7 +988,7 @@ int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime, const sp& applicationHandle, const sp& windowHandle, nsecs_t* nextWakeupTime, const char* reason) { - if (applicationHandle == NULL && windowHandle == NULL) { + if (applicationHandle == nullptr && windowHandle == nullptr) { if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) { #if DEBUG_FOCUS ALOGD("Waiting for system to become ready for input. Reason: %s", reason); @@ -1007,9 +1007,9 @@ int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime, reason); #endif nsecs_t timeout; - if (windowHandle != NULL) { + if (windowHandle != nullptr) { timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT); - } else if (applicationHandle != NULL) { + } else if (applicationHandle != nullptr) { timeout = applicationHandle->getDispatchingTimeout( DEFAULT_INPUT_DISPATCHING_TIMEOUT); } else { @@ -1022,10 +1022,10 @@ int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime, mInputTargetWaitTimeoutExpired = false; mInputTargetWaitApplicationHandle.clear(); - if (windowHandle != NULL) { + if (windowHandle != nullptr) { mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle; } - if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) { + if (mInputTargetWaitApplicationHandle == nullptr && applicationHandle != nullptr) { mInputTargetWaitApplicationHandle = applicationHandle; } } @@ -1068,7 +1068,7 @@ void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout sp connection = mConnectionsByFd.valueAt(connectionIndex); sp windowHandle = connection->inputWindowHandle; - if (windowHandle != NULL) { + if (windowHandle != nullptr) { const InputWindowInfo* info = windowHandle->getInfo(); if (info) { ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId); @@ -1114,10 +1114,10 @@ int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime, // If there is no currently focused window and no focused application // then drop the event. - if (mFocusedWindowHandle == NULL) { - if (mFocusedApplicationHandle != NULL) { + if (mFocusedWindowHandle == nullptr) { + if (mFocusedApplicationHandle != nullptr) { injectionResult = handleTargetsNotReadyLocked(currentTime, entry, - mFocusedApplicationHandle, NULL, nextWakeupTime, + mFocusedApplicationHandle, nullptr, nextWakeupTime, "Waiting because no window has focus but there is a " "focused application that may eventually add a window " "when it finishes starting up."); @@ -1187,7 +1187,7 @@ int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, // Copy current touch state into mTempTouchState. // This state is always reset at the end of this function, so if we don't find state // for the specified display then our initial state will be empty. - const TouchState* oldState = NULL; + const TouchState* oldState = nullptr; ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId); if (oldStateIndex >= 0) { oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex); @@ -1275,21 +1275,21 @@ int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, } // Figure out whether splitting will be allowed for this window. - if (newTouchedWindowHandle != NULL + if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) { // New window supports splitting. isSplit = true; } else if (isSplit) { // New window does not support splitting but we have already split events. // Ignore the new window. - newTouchedWindowHandle = NULL; + newTouchedWindowHandle = nullptr; } // Handle the case where we did not find a window. - if (newTouchedWindowHandle == NULL) { + if (newTouchedWindowHandle == nullptr) { // Try to assign the pointer to the first foreground window we find, if there is one. newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); - if (newTouchedWindowHandle == NULL) { + if (newTouchedWindowHandle == nullptr) { ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y); injectionResult = INPUT_EVENT_INJECTION_FAILED; goto Failed; @@ -1346,7 +1346,7 @@ int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, sp newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y); if (oldTouchedWindowHandle != newTouchedWindowHandle - && newTouchedWindowHandle != NULL) { + && newTouchedWindowHandle != nullptr) { #if DEBUG_FOCUS ALOGD("Touch is slipping out of window %s into window %s.", oldTouchedWindowHandle->getName().c_str(), @@ -1381,7 +1381,7 @@ int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, if (newHoverWindowHandle != mLastHoverWindowHandle) { // Let the previous window know that the hover sequence is over. - if (mLastHoverWindowHandle != NULL) { + if (mLastHoverWindowHandle != nullptr) { #if DEBUG_HOVER ALOGD("Sending hover exit event to window %s.", mLastHoverWindowHandle->getName().c_str()); @@ -1391,7 +1391,7 @@ int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, } // Let the new window know that the hover sequence is starting. - if (newHoverWindowHandle != NULL) { + if (newHoverWindowHandle != nullptr) { #if DEBUG_HOVER ALOGD("Sending hover enter event to window %s.", newHoverWindowHandle->getName().c_str()); @@ -1456,7 +1456,7 @@ int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, touchedWindow.windowHandle, entry, "touched"); if (!reason.empty()) { injectionResult = handleTargetsNotReadyLocked(currentTime, entry, - NULL, touchedWindow.windowHandle, nextWakeupTime, reason.c_str()); + nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str()); goto Unresponsive; } } @@ -1504,7 +1504,7 @@ int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, Failed: // Check injection permission once and for all. if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) { - if (checkInjectionPermission(NULL, entry->injectionState)) { + if (checkInjectionPermission(nullptr, entry->injectionState)) { injectionPermission = INJECTION_PERMISSION_GRANTED; } else { injectionPermission = INJECTION_PERMISSION_DENIED; @@ -1637,10 +1637,10 @@ void InputDispatcher::addMonitoringTargetsLocked(Vector& inputTarge bool InputDispatcher::checkInjectionPermission(const sp& windowHandle, const InjectionState* injectionState) { if (injectionState - && (windowHandle == NULL + && (windowHandle == nullptr || windowHandle->getInfo()->ownerUid != injectionState->injectorUid) && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) { - if (windowHandle != NULL) { + if (windowHandle != nullptr) { ALOGW("Permission denied: injecting event from pid %d uid %d to window %s " "owned by uid %d", injectionState->injectorPid, injectionState->injectorUid, @@ -1779,8 +1779,8 @@ std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentT std::string InputDispatcher::getApplicationWindowLabelLocked( const sp& applicationHandle, const sp& windowHandle) { - if (applicationHandle != NULL) { - if (windowHandle != NULL) { + if (applicationHandle != nullptr) { + if (windowHandle != nullptr) { std::string label(applicationHandle->getName()); label += " - "; label += windowHandle->getName(); @@ -1788,7 +1788,7 @@ std::string InputDispatcher::getApplicationWindowLabelLocked( } else { return applicationHandle->getName(); } - } else if (windowHandle != NULL) { + } else if (windowHandle != nullptr) { return windowHandle->getName(); } else { return ""; @@ -1796,7 +1796,7 @@ std::string InputDispatcher::getApplicationWindowLabelLocked( } void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) { - if (mFocusedWindowHandle != NULL) { + if (mFocusedWindowHandle != nullptr) { const InputWindowInfo* info = mFocusedWindowHandle->getInfo(); if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) { #if DEBUG_DISPATCH_CYCLE @@ -2292,7 +2292,7 @@ void InputDispatcher::synthesizeCancelationEventsForConnectionLocked( InputTarget target; sp windowHandle = getWindowHandleLocked(connection->inputChannel); - if (windowHandle != NULL) { + if (windowHandle != nullptr) { const InputWindowInfo* windowInfo = windowHandle->getInfo(); target.xOffset = -windowInfo->frameLeft; target.yOffset = -windowInfo->frameTop; @@ -2350,7 +2350,7 @@ InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet "we expected there to be %d pointers. This probably means we received " "a broken sequence of pointer ids from the input device.", splitPointerCount, pointerIds.count()); - return NULL; + return nullptr; } int32_t action = originalMotionEntry->action; @@ -2781,7 +2781,7 @@ int32_t InputDispatcher::injectInputEvent(const InputEvent* event, lastInjectedEntry->injectionState = injectionState; bool needWake = false; - for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) { + for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) { EventEntry* nextEntry = entry->next; needWake |= enqueueInboundEventLocked(entry); entry = nextEntry; @@ -2918,7 +2918,7 @@ sp InputDispatcher::getWindowHandleLocked( return windowHandle; } } - return NULL; + return nullptr; } bool InputDispatcher::hasWindowHandleLocked( @@ -2946,7 +2946,7 @@ void InputDispatcher::setInputWindows(const Vector >& inpu bool foundHoveredWindow = false; for (size_t i = 0; i < mWindowHandles.size(); i++) { const sp& windowHandle = mWindowHandles.itemAt(i); - if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) { + if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == nullptr) { mWindowHandles.removeAt(i--); continue; } @@ -2959,24 +2959,24 @@ void InputDispatcher::setInputWindows(const Vector >& inpu } if (!foundHoveredWindow) { - mLastHoverWindowHandle = NULL; + mLastHoverWindowHandle = nullptr; } if (mFocusedWindowHandle != newFocusedWindowHandle) { - if (mFocusedWindowHandle != NULL) { + if (mFocusedWindowHandle != nullptr) { #if DEBUG_FOCUS ALOGD("Focus left window: %s", mFocusedWindowHandle->getName().c_str()); #endif sp focusedInputChannel = mFocusedWindowHandle->getInputChannel(); - if (focusedInputChannel != NULL) { + if (focusedInputChannel != nullptr) { CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, "focus left window"); synthesizeCancelationEventsForInputChannelLocked( focusedInputChannel, options); } } - if (newFocusedWindowHandle != NULL) { + if (newFocusedWindowHandle != nullptr) { #if DEBUG_FOCUS ALOGD("Focus entered window: %s", newFocusedWindowHandle->getName().c_str()); @@ -2996,7 +2996,7 @@ void InputDispatcher::setInputWindows(const Vector >& inpu #endif sp touchedInputChannel = touchedWindow.windowHandle->getInputChannel(); - if (touchedInputChannel != NULL) { + if (touchedInputChannel != nullptr) { CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, "touched window was removed"); synthesizeCancelationEventsForInputChannelLocked( @@ -3036,15 +3036,15 @@ void InputDispatcher::setFocusedApplication( { // acquire lock AutoMutex _l(mLock); - if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) { + if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) { if (mFocusedApplicationHandle != inputApplicationHandle) { - if (mFocusedApplicationHandle != NULL) { + if (mFocusedApplicationHandle != nullptr) { resetANRTimeoutsLocked(); mFocusedApplicationHandle->releaseInfo(); } mFocusedApplicationHandle = inputApplicationHandle; } - } else if (mFocusedApplicationHandle != NULL) { + } else if (mFocusedApplicationHandle != nullptr) { resetANRTimeoutsLocked(); mFocusedApplicationHandle->releaseInfo(); mFocusedApplicationHandle.clear(); @@ -3126,7 +3126,7 @@ bool InputDispatcher::transferTouchFocus(const sp& fromChannel, sp fromWindowHandle = getWindowHandleLocked(fromChannel); sp toWindowHandle = getWindowHandleLocked(toChannel); - if (fromWindowHandle == NULL || toWindowHandle == NULL) { + if (fromWindowHandle == nullptr || toWindowHandle == nullptr) { #if DEBUG_FOCUS ALOGD("Cannot transfer focus because from or to window not found."); #endif @@ -3231,7 +3231,7 @@ void InputDispatcher::dumpDispatchStateLocked(std::string& dump) { dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled); dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen); - if (mFocusedApplicationHandle != NULL) { + if (mFocusedApplicationHandle != nullptr) { dump += StringPrintf(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n", mFocusedApplicationHandle->getName().c_str(), mFocusedApplicationHandle->getDispatchingTimeout( @@ -3240,7 +3240,7 @@ void InputDispatcher::dumpDispatchStateLocked(std::string& dump) { dump += StringPrintf(INDENT "FocusedApplication: \n"); } dump += StringPrintf(INDENT "FocusedWindow: name='%s'\n", - mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().c_str() : ""); + mFocusedWindowHandle != nullptr ? mFocusedWindowHandle->getName().c_str() : ""); if (!mTouchStatesByDisplay.isEmpty()) { dump += StringPrintf(INDENT "TouchStatesByDisplay:\n"); @@ -3551,7 +3551,7 @@ void InputDispatcher::onANRLocked( dispatchLatency, waitDuration, reason); // Capture a record of the InputDispatcher state at the time of the ANR. - time_t t = time(NULL); + time_t t = time(nullptr); struct tm tm; localtime_r(&t, &tm); char timestr[64]; @@ -3606,8 +3606,8 @@ void InputDispatcher::doNotifyANRLockedInterruptible( mLock.lock(); resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, - commandEntry->inputWindowHandle != NULL - ? commandEntry->inputWindowHandle->getInputChannel() : NULL); + commandEntry->inputWindowHandle != nullptr + ? commandEntry->inputWindowHandle->getInputChannel() : nullptr); } void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible( @@ -3958,7 +3958,7 @@ void InputDispatcher::InjectionState::release() { InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) : refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags), - injectionState(NULL), dispatchInProgress(false) { + injectionState(nullptr), dispatchInProgress(false) { } InputDispatcher::EventEntry::~EventEntry() { @@ -3977,7 +3977,7 @@ void InputDispatcher::EventEntry::release() { void InputDispatcher::EventEntry::releaseInjectionState() { if (injectionState) { injectionState->release(); - injectionState = NULL; + injectionState = nullptr; } } @@ -4489,7 +4489,7 @@ InputDispatcher::Connection::~Connection() { } const std::string InputDispatcher::Connection::getWindowName() const { - if (inputWindowHandle != NULL) { + if (inputWindowHandle != nullptr) { return inputWindowHandle->getName(); } if (monitor) { @@ -4515,19 +4515,19 @@ const char* InputDispatcher::Connection::getStatusLabel() const { } InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) { - for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) { + for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) { if (entry->seq == seq) { return entry; } } - return NULL; + return nullptr; } // --- InputDispatcher::CommandEntry --- InputDispatcher::CommandEntry::CommandEntry(Command command) : - command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), + command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0), seq(0), handled(false) { } @@ -4618,7 +4618,7 @@ sp InputDispatcher::TouchState::getFirstForegroundWindowHandl return window.windowHandle; } } - return NULL; + return nullptr; } bool InputDispatcher::TouchState::isSlippery() const { diff --git a/services/inputflinger/InputDispatcher.h b/services/inputflinger/InputDispatcher.h index 1072eb655f..31ab339421 100644 --- a/services/inputflinger/InputDispatcher.h +++ b/services/inputflinger/InputDispatcher.h @@ -406,7 +406,7 @@ private: T* prev; protected: - inline Link() : next(NULL), prev(NULL) { } + inline Link() : next(nullptr), prev(nullptr) { } }; struct InjectionState { @@ -441,7 +441,7 @@ private: bool dispatchInProgress; // initially false, set to true while dispatching - inline bool isInjected() const { return injectionState != NULL; } + inline bool isInjected() const { return injectionState != nullptr; } void release(); @@ -614,7 +614,7 @@ private: T* tail; uint32_t entryCount; - inline Queue() : head(NULL), tail(NULL), entryCount(0) { + inline Queue() : head(nullptr), tail(nullptr), entryCount(0) { } inline bool isEmpty() const { @@ -629,7 +629,7 @@ private: } else { head = entry; } - entry->next = NULL; + entry->next = nullptr; tail = entry; } @@ -641,7 +641,7 @@ private: } else { tail = entry; } - entry->prev = NULL; + entry->prev = nullptr; head = entry; } @@ -664,9 +664,9 @@ private: T* entry = head; head = entry->next; if (head) { - head->prev = NULL; + head->prev = nullptr; } else { - tail = NULL; + tail = nullptr; } return entry; } diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 9a35510fe6..5adb75ce1b 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -258,8 +258,8 @@ static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType, const String8* uniqueDisplayId, DisplayViewport* outViewport) const { - const DisplayViewport* viewport = NULL; - if (viewportType == ViewportType::VIEWPORT_VIRTUAL && uniqueDisplayId != NULL) { + const DisplayViewport* viewport = nullptr; + if (viewportType == ViewportType::VIEWPORT_VIRTUAL && uniqueDisplayId != nullptr) { for (const DisplayViewport& currentViewport : mVirtualDisplays) { if (currentViewport.uniqueId == *uniqueDisplayId) { viewport = ¤tViewport; @@ -272,7 +272,7 @@ bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType, viewport = &mInternalDisplay; } - if (viewport != NULL && viewport->displayId >= 0) { + if (viewport != nullptr && viewport->displayId >= 0) { *outViewport = *viewport; return true; } @@ -488,7 +488,7 @@ void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) { } void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) { - InputDevice* device = NULL; + InputDevice* device = nullptr; ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex < 0) { ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId); @@ -1786,7 +1786,7 @@ void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) { // --- MultiTouchMotionAccumulator --- MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() : - mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false), + mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false), mHaveStylus(false), mDeviceTimestamp(0) { } @@ -2294,7 +2294,7 @@ void KeyboardInputMapper::configure(nsecs_t when, if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { if (mParameters.orientationAware) { DisplayViewport dvp; - config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &dvp); + config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, nullptr, &dvp); mViewport = dvp; } } @@ -2705,7 +2705,7 @@ void CursorInputMapper::configure(nsecs_t when, mOrientation = DISPLAY_ORIENTATION_0; if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { DisplayViewport v; - if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) { + if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, nullptr, &v)) { mOrientation = v.orientation; } } @@ -2826,8 +2826,8 @@ void CursorInputMapper::sync(nsecs_t when) { float hscroll = mCursorScrollAccumulator.getRelativeHWheel(); bool scrolled = vscroll != 0 || hscroll != 0; - mWheelYVelocityControl.move(when, NULL, &vscroll); - mWheelXVelocityControl.move(when, &hscroll, NULL); + mWheelYVelocityControl.move(when, nullptr, &vscroll); + mWheelXVelocityControl.move(when, &hscroll, nullptr); mPointerVelocityControl.move(when, &deltaX, &deltaY); @@ -2968,7 +2968,7 @@ int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCod } void CursorInputMapper::fadePointer() { - if (mPointerController != NULL) { + if (mPointerController != nullptr) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } } @@ -3020,7 +3020,7 @@ void RotaryEncoderInputMapper::configure(nsecs_t when, } if (!changes || (InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { DisplayViewport v; - if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) { + if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, nullptr, &v)) { mOrientation = v.orientation; } else { mOrientation = DISPLAY_ORIENTATION_0; @@ -3517,7 +3517,7 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { // Get associated display dimensions. DisplayViewport newViewport; if (mParameters.hasAssociatedDisplay) { - const String8* uniqueDisplayId = NULL; + const String8* uniqueDisplayId = nullptr; ViewportType viewportTypeToUse; if (mParameters.associatedDisplayIsExternal) { @@ -3621,7 +3621,7 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { // Create pointer controller if needed. if (mDeviceMode == DEVICE_MODE_POINTER || (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) { - if (mPointerController == NULL) { + if (mPointerController == nullptr) { mPointerController = getPolicy()->obtainPointerController(getDeviceId()); } } else { @@ -4271,7 +4271,7 @@ void TouchInputMapper::reset(nsecs_t when) { mPointerSimple.reset(); resetExternalStylus(); - if (mPointerController != NULL) { + if (mPointerController != nullptr) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); mPointerController->clearSpots(); } @@ -4481,7 +4481,7 @@ void TouchInputMapper::cookAndDispatch(nsecs_t when) { dispatchPointerUsage(when, policyFlags, pointerUsage); } else { if (mDeviceMode == DEVICE_MODE_DIRECT - && mConfig.showTouches && mPointerController != NULL) { + && mConfig.showTouches && mPointerController != nullptr) { mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT); mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); @@ -5460,7 +5460,7 @@ void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) mPointerVelocityControl.reset(); // Remove any current spots. - if (mPointerController != NULL) { + if (mPointerController != nullptr) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); mPointerController->clearSpots(); } @@ -6323,7 +6323,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down, bool hovering) { int32_t metaState = getContext()->getGlobalMetaState(); - if (mPointerController != NULL) { + if (mPointerController != nullptr) { if (down || hovering) { mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER); mPointerController->clearSpots(); @@ -6414,8 +6414,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) { float vscroll = mCurrentRawState.rawVScroll; float hscroll = mCurrentRawState.rawHScroll; - mWheelYVelocityControl.move(when, NULL, &vscroll); - mWheelXVelocityControl.move(when, &hscroll, NULL); + mWheelYVelocityControl.move(when, nullptr, &vscroll); + mWheelXVelocityControl.move(when, &hscroll, nullptr); // Send scroll. PointerCoords pointerCoords; @@ -6522,7 +6522,7 @@ bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties } void TouchInputMapper::fadePointer() { - if (mPointerController != NULL) { + if (mPointerController != nullptr) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } } @@ -6557,7 +6557,7 @@ const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit( } } - return NULL; + return nullptr; } void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) { diff --git a/services/inputflinger/InputWindow.cpp b/services/inputflinger/InputWindow.cpp index 3ae7972779..0d1dfddb07 100644 --- a/services/inputflinger/InputWindow.cpp +++ b/services/inputflinger/InputWindow.cpp @@ -66,7 +66,7 @@ bool InputWindowInfo::overlaps(const InputWindowInfo* other) const { // --- InputWindowHandle --- InputWindowHandle::InputWindowHandle(const sp& inputApplicationHandle) : - inputApplicationHandle(inputApplicationHandle), mInfo(NULL) { + inputApplicationHandle(inputApplicationHandle), mInfo(nullptr) { } InputWindowHandle::~InputWindowHandle() { @@ -76,7 +76,7 @@ InputWindowHandle::~InputWindowHandle() { void InputWindowHandle::releaseInfo() { if (mInfo) { delete mInfo; - mInfo = NULL; + mInfo = nullptr; } } diff --git a/services/inputflinger/InputWindow.h b/services/inputflinger/InputWindow.h index 5a48375910..c481853e2c 100644 --- a/services/inputflinger/InputWindow.h +++ b/services/inputflinger/InputWindow.h @@ -169,7 +169,7 @@ public: } inline sp getInputChannel() const { - return mInfo ? mInfo->inputChannel : NULL; + return mInfo ? mInfo->inputChannel : nullptr; } inline std::string getName() const { diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index 4f29e3abf1..286cf880f1 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -236,7 +236,7 @@ private: } virtual sp getKeyboardLayoutOverlay(const InputDeviceIdentifier&) { - return NULL; + return nullptr; } virtual String8 getDeviceAlias(const InputDeviceIdentifier&) { @@ -263,7 +263,7 @@ public: } void assertNotifyConfigurationChangedWasCalled( - NotifyConfigurationChangedArgs* outEventArgs = NULL) { + NotifyConfigurationChangedArgs* outEventArgs = nullptr) { ASSERT_FALSE(mNotifyConfigurationChangedArgsQueue.empty()) << "Expected notifyConfigurationChanged() to have been called."; if (outEventArgs) { @@ -278,7 +278,7 @@ public: } void assertNotifyDeviceResetWasCalled( - NotifyDeviceResetArgs* outEventArgs = NULL) { + NotifyDeviceResetArgs* outEventArgs = nullptr) { ASSERT_FALSE(mNotifyDeviceResetArgsQueue.empty()) << "Expected notifyDeviceReset() to have been called."; if (outEventArgs) { @@ -292,7 +292,7 @@ public: << "Expected notifyDeviceReset() to not have been called."; } - void assertNotifyKeyWasCalled(NotifyKeyArgs* outEventArgs = NULL) { + void assertNotifyKeyWasCalled(NotifyKeyArgs* outEventArgs = nullptr) { ASSERT_FALSE(mNotifyKeyArgsQueue.empty()) << "Expected notifyKey() to have been called."; if (outEventArgs) { @@ -306,7 +306,7 @@ public: << "Expected notifyKey() to not have been called."; } - void assertNotifyMotionWasCalled(NotifyMotionArgs* outEventArgs = NULL) { + void assertNotifyMotionWasCalled(NotifyMotionArgs* outEventArgs = nullptr) { ASSERT_FALSE(mNotifyMotionArgsQueue.empty()) << "Expected notifyMotion() to have been called."; if (outEventArgs) { @@ -320,7 +320,7 @@ public: << "Expected notifyMotion() to not have been called."; } - void assertNotifySwitchWasCalled(NotifySwitchArgs* outEventArgs = NULL) { + void assertNotifySwitchWasCalled(NotifySwitchArgs* outEventArgs = nullptr) { ASSERT_FALSE(mNotifySwitchArgsQueue.empty()) << "Expected notifySwitch() to have been called."; if (outEventArgs) { @@ -422,7 +422,7 @@ public: bool isDeviceEnabled(int32_t deviceId) { Device* device = getDevice(deviceId); - if (device == NULL) { + if (device == nullptr) { ALOGE("Incorrect device id=%" PRId32 " provided to %s", deviceId, __func__); return false; } @@ -432,7 +432,7 @@ public: status_t enableDevice(int32_t deviceId) { status_t result; Device* device = getDevice(deviceId); - if (device == NULL) { + if (device == nullptr) { ALOGE("Incorrect device id=%" PRId32 " provided to %s", deviceId, __func__); return BAD_VALUE; } @@ -446,7 +446,7 @@ public: status_t disableDevice(int32_t deviceId) { Device* device = getDevice(deviceId); - if (device == NULL) { + if (device == nullptr) { ALOGE("Incorrect device id=%" PRId32 " provided to %s", deviceId, __func__); return BAD_VALUE; } @@ -651,7 +651,7 @@ private: return &device->keysByScanCode.valueAt(index); } } - return NULL; + return nullptr; } virtual status_t mapAxis(int32_t, int32_t, AxisInfo*) const { @@ -781,7 +781,7 @@ private: } virtual sp getKeyCharacterMap(int32_t) const { - return NULL; + return nullptr; } virtual bool setKeyboardLayoutOverlay(int32_t, const sp&) { @@ -940,7 +940,7 @@ public: mResetWasCalled = false; } - void assertProcessWasCalled(RawEvent* outLastEvent = NULL) { + void assertProcessWasCalled(RawEvent* outLastEvent = nullptr) { ASSERT_TRUE(mProcessWasCalled) << "Expected process() to have been called."; if (outLastEvent) { @@ -1039,7 +1039,7 @@ public: const sp& policy, const sp& listener) : InputReader(eventHub, policy, listener), - mNextDevice(NULL) { + mNextDevice(nullptr) { } virtual ~InstrumentedInputReader() { @@ -1066,7 +1066,7 @@ protected: const InputDeviceIdentifier& identifier, uint32_t classes) { if (mNextDevice) { InputDevice* device = mNextDevice; - mNextDevice = NULL; + mNextDevice = nullptr; return device; } return InputReader::createDeviceLocked(deviceId, controllerNumber, identifier, classes); @@ -1142,9 +1142,9 @@ protected: TEST_F(InputReaderTest, GetInputDevices) { ASSERT_NO_FATAL_FAILURE(addDevice(1, String8("keyboard"), - INPUT_DEVICE_CLASS_KEYBOARD, NULL)); + INPUT_DEVICE_CLASS_KEYBOARD, nullptr)); ASSERT_NO_FATAL_FAILURE(addDevice(2, String8("ignored"), - 0, NULL)); // no classes so device will be ignored + 0, nullptr)); // no classes so device will be ignored Vector inputDevices; mReader->getInputDevices(inputDevices); @@ -1174,9 +1174,9 @@ TEST_F(InputReaderTest, WhenEnabledChanges_SendsDeviceResetNotification) { FakeInputMapper* mapper = new FakeInputMapper(device, AINPUT_SOURCE_KEYBOARD); device->addMapper(mapper); mReader->setNextDevice(device); - addDevice(deviceId, String8("fake"), deviceClass, NULL); + addDevice(deviceId, String8("fake"), deviceClass, nullptr); - ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasCalled(NULL)); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasCalled(nullptr)); NotifyDeviceResetArgs resetArgs; ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs)); @@ -1207,9 +1207,9 @@ TEST_F(InputReaderTest, WhenEnabledChanges_SendsDeviceResetNotification) { } TEST_F(InputReaderTest, GetKeyCodeState_ForwardsRequestsToMappers) { - FakeInputMapper* mapper = NULL; + FakeInputMapper* mapper = nullptr; ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, String8("fake"), - INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, NULL)); + INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, nullptr)); mapper->setKeyCodeState(AKEYCODE_A, AKEY_STATE_DOWN); ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getKeyCodeState(0, @@ -1234,9 +1234,9 @@ TEST_F(InputReaderTest, GetKeyCodeState_ForwardsRequestsToMappers) { } TEST_F(InputReaderTest, GetScanCodeState_ForwardsRequestsToMappers) { - FakeInputMapper* mapper = NULL; + FakeInputMapper* mapper = nullptr; ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, String8("fake"), - INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, NULL)); + INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, nullptr)); mapper->setScanCodeState(KEY_A, AKEY_STATE_DOWN); ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getScanCodeState(0, @@ -1261,9 +1261,9 @@ TEST_F(InputReaderTest, GetScanCodeState_ForwardsRequestsToMappers) { } TEST_F(InputReaderTest, GetSwitchState_ForwardsRequestsToMappers) { - FakeInputMapper* mapper = NULL; + FakeInputMapper* mapper = nullptr; ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, String8("fake"), - INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, NULL)); + INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, nullptr)); mapper->setSwitchState(SW_LID, AKEY_STATE_DOWN); ASSERT_EQ(AKEY_STATE_UNKNOWN, mReader->getSwitchState(0, @@ -1288,9 +1288,9 @@ TEST_F(InputReaderTest, GetSwitchState_ForwardsRequestsToMappers) { } TEST_F(InputReaderTest, MarkSupportedKeyCodes_ForwardsRequestsToMappers) { - FakeInputMapper* mapper = NULL; + FakeInputMapper* mapper = nullptr; ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, String8("fake"), - INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, NULL)); + INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, nullptr)); mapper->addSupportedKeyCode(AKEYCODE_A); mapper->addSupportedKeyCode(AKEYCODE_B); @@ -1323,7 +1323,7 @@ TEST_F(InputReaderTest, MarkSupportedKeyCodes_ForwardsRequestsToMappers) { } TEST_F(InputReaderTest, LoopOnce_WhenDeviceScanFinished_SendsConfigurationChanged) { - addDevice(1, String8("ignored"), INPUT_DEVICE_CLASS_KEYBOARD, NULL); + addDevice(1, String8("ignored"), INPUT_DEVICE_CLASS_KEYBOARD, nullptr); NotifyConfigurationChangedArgs args; @@ -1332,9 +1332,9 @@ TEST_F(InputReaderTest, LoopOnce_WhenDeviceScanFinished_SendsConfigurationChange } TEST_F(InputReaderTest, LoopOnce_ForwardsRawEventsToMappers) { - FakeInputMapper* mapper = NULL; + FakeInputMapper* mapper = nullptr; ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, String8("fake"), - INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, NULL)); + INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, nullptr)); mFakeEventHub->enqueueEvent(0, 1, EV_KEY, KEY_A, 1); mReader->loopOnce(); @@ -1621,7 +1621,7 @@ protected: static void assertMotionRange(const InputDeviceInfo& info, int32_t axis, uint32_t source, float min, float max, float flat, float fuzz) { const InputDeviceInfo::MotionRange* range = info.getMotionRange(axis, source); - ASSERT_TRUE(range != NULL) << "Axis: " << axis << " Source: " << source; + ASSERT_TRUE(range != nullptr) << "Axis: " << axis << " Source: " << source; ASSERT_EQ(axis, range->axis) << "Axis: " << axis << " Source: " << source; ASSERT_EQ(source, range->source) << "Axis: " << axis << " Source: " << source; ASSERT_NEAR(min, range->min, EPSILON) << "Axis: " << axis << " Source: " << source; @@ -2232,8 +2232,8 @@ TEST_F(CursorInputMapperTest, WhenModeIsPointer_PopulateDeviceInfo_ReturnsRangeF mapper->populateDeviceInfo(&info); // Initially there may not be a valid motion range. - ASSERT_EQ(NULL, info.getMotionRange(AINPUT_MOTION_RANGE_X, AINPUT_SOURCE_MOUSE)); - ASSERT_EQ(NULL, info.getMotionRange(AINPUT_MOTION_RANGE_Y, AINPUT_SOURCE_MOUSE)); + ASSERT_EQ(nullptr, info.getMotionRange(AINPUT_MOTION_RANGE_X, AINPUT_SOURCE_MOUSE)); + ASSERT_EQ(nullptr, info.getMotionRange(AINPUT_MOTION_RANGE_Y, AINPUT_SOURCE_MOUSE)); ASSERT_NO_FATAL_FAILURE(assertMotionRange(info, AINPUT_MOTION_RANGE_PRESSURE, AINPUT_SOURCE_MOUSE, 0.0f, 1.0f, 0.0f, 0.0f)); -- cgit v1.2.3-59-g8ed1b From d00e78758bcb37f5194fcf672c4f48a9acc2778b Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Thu, 9 Aug 2018 09:22:45 -0700 Subject: Fix questionable condition Fix a typo in InputReader.cpp. Bug: 112154205 Test: None Change-Id: Ia8fa9062e0881ca8fca45353829ae0762dfdd389 --- services/inputflinger/InputReader.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 5adb75ce1b..beda75a2cb 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -3018,7 +3018,7 @@ void RotaryEncoderInputMapper::configure(nsecs_t when, if (!changes) { mRotaryEncoderScrollAccumulator.configure(getDevice()); } - if (!changes || (InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { + if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { DisplayViewport v; if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, nullptr, &v)) { mOrientation = v.orientation; -- cgit v1.2.3-59-g8ed1b From ec8f725bcc099ae63c95a5d725f3ccd63eb4ebe3 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Fri, 6 Jul 2018 11:19:32 +0100 Subject: Prefer std::string over String8 String8 is deprecated, so use proper C++ std::string instead. Change DisplayViewport.uniqueId to std::string. The current usage of String8 in DisplayViewport hinders refactoring of the code to use viewport types inside the viewports themselves. Most of the dependency on String8 is now removed. Once the xml for properties patch is added, almost all String8 should be gone from the input system. Test: atest libinput_tests inputflinger_tests Bug: 111108021 Change-Id: I580dc27b0449e664a7c9db2cdec1a0c18bf71a09 --- include/input/DisplayViewport.h | 4 +- include/input/Input.h | 1 - include/input/InputDevice.h | 24 ++-- include/input/InputTransport.h | 2 + include/input/KeyCharacterMap.h | 7 +- include/input/KeyLayoutMap.h | 2 +- include/input/Keyboard.h | 19 ++- include/input/VirtualKeyMap.h | 3 +- libs/input/InputDevice.cpp | 62 +++++---- libs/input/KeyCharacterMap.cpp | 18 +-- libs/input/KeyLayoutMap.cpp | 6 +- libs/input/Keyboard.cpp | 44 +++---- libs/input/VirtualKeyMap.cpp | 6 +- services/inputflinger/EventHub.cpp | 156 +++++++++++------------ services/inputflinger/EventHub.h | 18 +-- services/inputflinger/InputApplication.h | 2 + services/inputflinger/InputManager.h | 1 - services/inputflinger/InputReader.cpp | 59 +++++---- services/inputflinger/InputReader.h | 18 +-- services/inputflinger/host/InputDriver.cpp | 10 +- services/inputflinger/tests/InputReader_test.cpp | 74 +++++------ 21 files changed, 276 insertions(+), 260 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/include/input/DisplayViewport.h b/include/input/DisplayViewport.h index 86da4d38e8..0f336dd2b8 100644 --- a/include/input/DisplayViewport.h +++ b/include/input/DisplayViewport.h @@ -39,13 +39,13 @@ struct DisplayViewport { int32_t physicalBottom; int32_t deviceWidth; int32_t deviceHeight; - String8 uniqueId; + std::string uniqueId; DisplayViewport() : displayId(ADISPLAY_ID_NONE), orientation(DISPLAY_ORIENTATION_0), logicalLeft(0), logicalTop(0), logicalRight(0), logicalBottom(0), physicalLeft(0), physicalTop(0), physicalRight(0), physicalBottom(0), - deviceWidth(0), deviceHeight(0) { + deviceWidth(0), deviceHeight(0), uniqueId() { } bool operator==(const DisplayViewport& other) const { diff --git a/include/input/Input.h b/include/input/Input.h index 7c4379eda1..819a89f37c 100644 --- a/include/input/Input.h +++ b/include/input/Input.h @@ -25,7 +25,6 @@ #include #include #include -#include #include #include #include diff --git a/include/input/InputDevice.h b/include/input/InputDevice.h index 1ea69d352d..34d164c280 100644 --- a/include/input/InputDevice.h +++ b/include/input/InputDevice.h @@ -31,9 +31,9 @@ struct InputDeviceIdentifier { } // Information provided by the kernel. - String8 name; - String8 location; - String8 uniqueId; + std::string name; + std::string location; + std::string uniqueId; uint16_t bus; uint16_t vendor; uint16_t product; @@ -45,7 +45,7 @@ struct InputDeviceIdentifier { // It is hashed from whatever kernel provided information is available. // Ideally, the way this value is computed should not change between Android releases // because that would invalidate persistent settings that rely on it. - String8 descriptor; + std::string descriptor; // A value added to uniquely identify a device in the absence of a unique id. This // is intended to be a minimum way to distinguish from other active devices and may @@ -73,16 +73,16 @@ public: }; void initialize(int32_t id, int32_t generation, int32_t controllerNumber, - const InputDeviceIdentifier& identifier, const String8& alias, bool isExternal, + const InputDeviceIdentifier& identifier, const std::string& alias, bool isExternal, bool hasMic); inline int32_t getId() const { return mId; } inline int32_t getControllerNumber() const { return mControllerNumber; } inline int32_t getGeneration() const { return mGeneration; } inline const InputDeviceIdentifier& getIdentifier() const { return mIdentifier; } - inline const String8& getAlias() const { return mAlias; } - inline const String8& getDisplayName() const { - return mAlias.isEmpty() ? mIdentifier.name : mAlias; + inline const std::string& getAlias() const { return mAlias; } + inline const std::string& getDisplayName() const { + return mAlias.empty() ? mIdentifier.name : mAlias; } inline bool isExternal() const { return mIsExternal; } inline bool hasMic() const { return mHasMic; } @@ -121,7 +121,7 @@ private: int32_t mGeneration; int32_t mControllerNumber; InputDeviceIdentifier mIdentifier; - String8 mAlias; + std::string mAlias; bool mIsExternal; bool mHasMic; uint32_t mSources; @@ -149,7 +149,7 @@ enum InputDeviceConfigurationFileType { * * Returns an empty string if not found. */ -extern String8 getInputDeviceConfigurationFilePathByDeviceIdentifier( +extern std::string getInputDeviceConfigurationFilePathByDeviceIdentifier( const InputDeviceIdentifier& deviceIdentifier, InputDeviceConfigurationFileType type); @@ -162,8 +162,8 @@ extern String8 getInputDeviceConfigurationFilePathByDeviceIdentifier( * * Returns an empty string if not found. */ -extern String8 getInputDeviceConfigurationFilePathByName( - const String8& name, InputDeviceConfigurationFileType type); +extern std::string getInputDeviceConfigurationFilePathByName( + const std::string& name, InputDeviceConfigurationFileType type); } // namespace android diff --git a/include/input/InputTransport.h b/include/input/InputTransport.h index e8d1345096..5fd86b48f7 100644 --- a/include/input/InputTransport.h +++ b/include/input/InputTransport.h @@ -27,6 +27,8 @@ * The InputConsumer is used by the application to receive events from the input dispatcher. */ +#include + #include #include #include diff --git a/include/input/KeyCharacterMap.h b/include/input/KeyCharacterMap.h index 33d2757ec8..9f4559f53c 100644 --- a/include/input/KeyCharacterMap.h +++ b/include/input/KeyCharacterMap.h @@ -27,7 +27,6 @@ #include #include #include -#include #include #include @@ -75,10 +74,10 @@ public: }; /* Loads a key character map from a file. */ - static status_t load(const String8& filename, Format format, sp* outMap); + static status_t load(const std::string& filename, Format format, sp* outMap); /* Loads a key character map from its string contents. */ - static status_t loadContents(const String8& filename, + static status_t loadContents(const std::string& filename, const char* contents, Format format, sp* outMap); /* Combines a base key character map and an overlay. */ @@ -221,7 +220,7 @@ private: status_t parseKey(); status_t parseKeyProperty(); status_t finishKey(Key* key); - status_t parseModifier(const String8& token, int32_t* outMetaState); + status_t parseModifier(const std::string& token, int32_t* outMetaState); status_t parseCharacterLiteral(char16_t* outCharacter); }; diff --git a/include/input/KeyLayoutMap.h b/include/input/KeyLayoutMap.h index 1e8de7173b..73815fe8b4 100644 --- a/include/input/KeyLayoutMap.h +++ b/include/input/KeyLayoutMap.h @@ -62,7 +62,7 @@ struct AxisInfo { */ class KeyLayoutMap : public RefBase { public: - static status_t load(const String8& filename, sp* outMap); + static status_t load(const std::string& filename, sp* outMap); status_t mapKey(int32_t scanCode, int32_t usageCode, int32_t* outKeyCode, uint32_t* outFlags) const; diff --git a/include/input/Keyboard.h b/include/input/Keyboard.h index d4903e98df..8b66f693cc 100644 --- a/include/input/Keyboard.h +++ b/include/input/Keyboard.h @@ -21,7 +21,6 @@ #include #include #include -#include #include namespace android { @@ -43,10 +42,10 @@ class KeyCharacterMap; */ class KeyMap { public: - String8 keyLayoutFile; + std::string keyLayoutFile; sp keyLayoutMap; - String8 keyCharacterMapFile; + std::string keyCharacterMapFile; sp keyCharacterMap; KeyMap(); @@ -56,11 +55,11 @@ public: const PropertyMap* deviceConfiguration); inline bool haveKeyLayout() const { - return !keyLayoutFile.isEmpty(); + return !keyLayoutFile.empty(); } inline bool haveKeyCharacterMap() const { - return !keyCharacterMapFile.isEmpty(); + return !keyCharacterMapFile.empty(); } inline bool isComplete() const { @@ -68,12 +67,12 @@ public: } private: - bool probeKeyMap(const InputDeviceIdentifier& deviceIdentifier, const String8& name); - status_t loadKeyLayout(const InputDeviceIdentifier& deviceIdentifier, const String8& name); + bool probeKeyMap(const InputDeviceIdentifier& deviceIdentifier, const std::string& name); + status_t loadKeyLayout(const InputDeviceIdentifier& deviceIdentifier, const std::string& name); status_t loadKeyCharacterMap(const InputDeviceIdentifier& deviceIdentifier, - const String8& name); - String8 getPath(const InputDeviceIdentifier& deviceIdentifier, - const String8& name, InputDeviceConfigurationFileType type); + const std::string& name); + std::string getPath(const InputDeviceIdentifier& deviceIdentifier, + const std::string& name, InputDeviceConfigurationFileType type); }; /** diff --git a/include/input/VirtualKeyMap.h b/include/input/VirtualKeyMap.h index e245ead682..24e0e0ed9e 100644 --- a/include/input/VirtualKeyMap.h +++ b/include/input/VirtualKeyMap.h @@ -23,7 +23,6 @@ #include #include #include -#include #include namespace android { @@ -50,7 +49,7 @@ class VirtualKeyMap { public: ~VirtualKeyMap(); - static status_t load(const String8& filename, VirtualKeyMap** outMap); + static status_t load(const std::string& filename, VirtualKeyMap** outMap); inline const Vector& getVirtualKeys() const { return mVirtualKeys; diff --git a/libs/input/InputDevice.cpp b/libs/input/InputDevice.cpp index 5d27bf687d..778c4539fa 100644 --- a/libs/input/InputDevice.cpp +++ b/libs/input/InputDevice.cpp @@ -20,9 +20,12 @@ #include #include +#include #include #include +using android::base::StringPrintf; + namespace android { static const char* CONFIGURATION_FILE_DIR[] = { @@ -41,8 +44,8 @@ static bool isValidNameChar(char ch) { return isascii(ch) && (isdigit(ch) || isalpha(ch) || ch == '-' || ch == '_'); } -static void appendInputDeviceConfigurationFileRelativePath(String8& path, - const String8& name, InputDeviceConfigurationFileType type) { +static void appendInputDeviceConfigurationFileRelativePath(std::string& path, + const std::string& name, InputDeviceConfigurationFileType type) { path.append(CONFIGURATION_FILE_DIR[type]); for (size_t i = 0; i < name.length(); i++) { char ch = name[i]; @@ -54,28 +57,28 @@ static void appendInputDeviceConfigurationFileRelativePath(String8& path, path.append(CONFIGURATION_FILE_EXTENSION[type]); } -String8 getInputDeviceConfigurationFilePathByDeviceIdentifier( +std::string getInputDeviceConfigurationFilePathByDeviceIdentifier( const InputDeviceIdentifier& deviceIdentifier, InputDeviceConfigurationFileType type) { if (deviceIdentifier.vendor !=0 && deviceIdentifier.product != 0) { if (deviceIdentifier.version != 0) { // Try vendor product version. - String8 versionPath(getInputDeviceConfigurationFilePathByName( - String8::format("Vendor_%04x_Product_%04x_Version_%04x", + std::string versionPath = getInputDeviceConfigurationFilePathByName( + StringPrintf("Vendor_%04x_Product_%04x_Version_%04x", deviceIdentifier.vendor, deviceIdentifier.product, deviceIdentifier.version), - type)); - if (!versionPath.isEmpty()) { + type); + if (!versionPath.empty()) { return versionPath; } } // Try vendor product. - String8 productPath(getInputDeviceConfigurationFilePathByName( - String8::format("Vendor_%04x_Product_%04x", + std::string productPath = getInputDeviceConfigurationFilePathByName( + StringPrintf("Vendor_%04x_Product_%04x", deviceIdentifier.vendor, deviceIdentifier.product), - type)); - if (!productPath.isEmpty()) { + type); + if (!productPath.empty()) { return productPath; } } @@ -84,22 +87,25 @@ String8 getInputDeviceConfigurationFilePathByDeviceIdentifier( return getInputDeviceConfigurationFilePathByName(deviceIdentifier.name, type); } -String8 getInputDeviceConfigurationFilePathByName( - const String8& name, InputDeviceConfigurationFileType type) { +std::string getInputDeviceConfigurationFilePathByName( + const std::string& name, InputDeviceConfigurationFileType type) { // Search system repository. - String8 path; + std::string path; // Treblized input device config files will be located /odm/usr or /vendor/usr. const char *rootsForPartition[] {"/odm", "/vendor", getenv("ANDROID_ROOT")}; for (size_t i = 0; i < size(rootsForPartition); i++) { - path.setTo(rootsForPartition[i]); - path.append("/usr/"); + if (rootsForPartition[i] == nullptr) { + continue; + } + path = rootsForPartition[i]; + path += "/usr/"; appendInputDeviceConfigurationFileRelativePath(path, name, type); #if DEBUG_PROBE ALOGD("Probing for system provided input device configuration file: path='%s'", - path.string()); + path.c_str()); #endif - if (!access(path.string(), R_OK)) { + if (!access(path.c_str(), R_OK)) { #if DEBUG_PROBE ALOGD("Found"); #endif @@ -109,13 +115,17 @@ String8 getInputDeviceConfigurationFilePathByName( // Search user repository. // TODO Should only look here if not in safe mode. - path.setTo(getenv("ANDROID_DATA")); - path.append("/system/devices/"); + path = ""; + char *androidData = getenv("ANDROID_DATA"); + if (androidData != nullptr) { + path += androidData; + } + path += "/system/devices/"; appendInputDeviceConfigurationFileRelativePath(path, name, type); #if DEBUG_PROBE - ALOGD("Probing for system user input device configuration file: path='%s'", path.string()); + ALOGD("Probing for system user input device configuration file: path='%s'", path.c_str()); #endif - if (!access(path.string(), R_OK)) { + if (!access(path.c_str(), R_OK)) { #if DEBUG_PROBE ALOGD("Found"); #endif @@ -125,16 +135,16 @@ String8 getInputDeviceConfigurationFilePathByName( // Not found. #if DEBUG_PROBE ALOGD("Probe failed to find input device configuration file: name='%s', type=%d", - name.string(), type); + name.c_str(), type); #endif - return String8(); + return ""; } // --- InputDeviceInfo --- InputDeviceInfo::InputDeviceInfo() { - initialize(-1, 0, -1, InputDeviceIdentifier(), String8(), false, false); + initialize(-1, 0, -1, InputDeviceIdentifier(), "", false, false); } InputDeviceInfo::InputDeviceInfo(const InputDeviceInfo& other) : @@ -150,7 +160,7 @@ InputDeviceInfo::~InputDeviceInfo() { } void InputDeviceInfo::initialize(int32_t id, int32_t generation, int32_t controllerNumber, - const InputDeviceIdentifier& identifier, const String8& alias, bool isExternal, + const InputDeviceIdentifier& identifier, const std::string& alias, bool isExternal, bool hasMic) { mId = id; mGeneration = generation; diff --git a/libs/input/KeyCharacterMap.cpp b/libs/input/KeyCharacterMap.cpp index 26747bdbbc..e189d20e28 100644 --- a/libs/input/KeyCharacterMap.cpp +++ b/libs/input/KeyCharacterMap.cpp @@ -106,14 +106,14 @@ KeyCharacterMap::~KeyCharacterMap() { } } -status_t KeyCharacterMap::load(const String8& filename, +status_t KeyCharacterMap::load(const std::string& filename, Format format, sp* outMap) { outMap->clear(); Tokenizer* tokenizer; - status_t status = Tokenizer::open(filename, &tokenizer); + status_t status = Tokenizer::open(String8(filename.c_str()), &tokenizer); if (status) { - ALOGE("Error %d opening key character map file %s.", status, filename.string()); + ALOGE("Error %d opening key character map file %s.", status, filename.c_str()); } else { status = load(tokenizer, format, outMap); delete tokenizer; @@ -121,12 +121,12 @@ status_t KeyCharacterMap::load(const String8& filename, return status; } -status_t KeyCharacterMap::loadContents(const String8& filename, const char* contents, +status_t KeyCharacterMap::loadContents(const std::string& filename, const char* contents, Format format, sp* outMap) { outMap->clear(); Tokenizer* tokenizer; - status_t status = Tokenizer::fromContents(filename, contents, &tokenizer); + status_t status = Tokenizer::fromContents(String8(filename.c_str()), contents, &tokenizer); if (status) { ALOGE("Error %d opening key character map.", status); } else { @@ -944,7 +944,7 @@ status_t KeyCharacterMap::Parser::parseKeyProperty() { properties.add(Property(PROPERTY_NUMBER)); } else { int32_t metaState; - status_t status = parseModifier(token, &metaState); + status_t status = parseModifier(token.string(), &metaState); if (status) { ALOGE("%s: Expected a property name or modifier, got '%s'.", mTokenizer->getLocation().string(), token.string()); @@ -1137,7 +1137,7 @@ status_t KeyCharacterMap::Parser::finishKey(Key* key) { return NO_ERROR; } -status_t KeyCharacterMap::Parser::parseModifier(const String8& token, int32_t* outMetaState) { +status_t KeyCharacterMap::Parser::parseModifier(const std::string& token, int32_t* outMetaState) { if (token == "base") { *outMetaState = 0; return NO_ERROR; @@ -1145,7 +1145,7 @@ status_t KeyCharacterMap::Parser::parseModifier(const String8& token, int32_t* o int32_t combinedMeta = 0; - const char* str = token.string(); + const char* str = token.c_str(); const char* start = str; for (const char* cur = str; ; cur++) { char ch = *cur; @@ -1164,7 +1164,7 @@ status_t KeyCharacterMap::Parser::parseModifier(const String8& token, int32_t* o } if (combinedMeta & metaState) { ALOGE("%s: Duplicate modifier combination '%s'.", - mTokenizer->getLocation().string(), token.string()); + mTokenizer->getLocation().string(), token.c_str()); return BAD_VALUE; } diff --git a/libs/input/KeyLayoutMap.cpp b/libs/input/KeyLayoutMap.cpp index c440078666..88cb0dbdb4 100644 --- a/libs/input/KeyLayoutMap.cpp +++ b/libs/input/KeyLayoutMap.cpp @@ -49,13 +49,13 @@ KeyLayoutMap::KeyLayoutMap() { KeyLayoutMap::~KeyLayoutMap() { } -status_t KeyLayoutMap::load(const String8& filename, sp* outMap) { +status_t KeyLayoutMap::load(const std::string& filename, sp* outMap) { outMap->clear(); Tokenizer* tokenizer; - status_t status = Tokenizer::open(filename, &tokenizer); + status_t status = Tokenizer::open(String8(filename.c_str()), &tokenizer); if (status) { - ALOGE("Error %d opening key layout map file %s.", status, filename.string()); + ALOGE("Error %d opening key layout map file %s.", status, filename.c_str()); } else { sp map = new KeyLayoutMap(); if (!map.get()) { diff --git a/libs/input/Keyboard.cpp b/libs/input/Keyboard.cpp index 11842ee7ff..0c22bfefed 100644 --- a/libs/input/Keyboard.cpp +++ b/libs/input/Keyboard.cpp @@ -45,22 +45,22 @@ status_t KeyMap::load(const InputDeviceIdentifier& deviceIdenfifier, String8 keyLayoutName; if (deviceConfiguration->tryGetProperty(String8("keyboard.layout"), keyLayoutName)) { - status_t status = loadKeyLayout(deviceIdenfifier, keyLayoutName); + status_t status = loadKeyLayout(deviceIdenfifier, keyLayoutName.c_str()); if (status == NAME_NOT_FOUND) { ALOGE("Configuration for keyboard device '%s' requested keyboard layout '%s' but " "it was not found.", - deviceIdenfifier.name.string(), keyLayoutName.string()); + deviceIdenfifier.name.c_str(), keyLayoutName.string()); } } String8 keyCharacterMapName; if (deviceConfiguration->tryGetProperty(String8("keyboard.characterMap"), keyCharacterMapName)) { - status_t status = loadKeyCharacterMap(deviceIdenfifier, keyCharacterMapName); + status_t status = loadKeyCharacterMap(deviceIdenfifier, keyCharacterMapName.c_str()); if (status == NAME_NOT_FOUND) { ALOGE("Configuration for keyboard device '%s' requested keyboard character " "map '%s' but it was not found.", - deviceIdenfifier.name.string(), keyLayoutName.string()); + deviceIdenfifier.name.c_str(), keyLayoutName.string()); } } @@ -70,30 +70,30 @@ status_t KeyMap::load(const InputDeviceIdentifier& deviceIdenfifier, } // Try searching by device identifier. - if (probeKeyMap(deviceIdenfifier, String8::empty())) { + if (probeKeyMap(deviceIdenfifier, "")) { return OK; } // Fall back on the Generic key map. // TODO Apply some additional heuristics here to figure out what kind of // generic key map to use (US English, etc.) for typical external keyboards. - if (probeKeyMap(deviceIdenfifier, String8("Generic"))) { + if (probeKeyMap(deviceIdenfifier, "Generic")) { return OK; } // Try the Virtual key map as a last resort. - if (probeKeyMap(deviceIdenfifier, String8("Virtual"))) { + if (probeKeyMap(deviceIdenfifier, "Virtual")) { return OK; } // Give up! ALOGE("Could not determine key map for device '%s' and no default key maps were found!", - deviceIdenfifier.name.string()); + deviceIdenfifier.name.c_str()); return NAME_NOT_FOUND; } bool KeyMap::probeKeyMap(const InputDeviceIdentifier& deviceIdentifier, - const String8& keyMapName) { + const std::string& keyMapName) { if (!haveKeyLayout()) { loadKeyLayout(deviceIdentifier, keyMapName); } @@ -104,10 +104,10 @@ bool KeyMap::probeKeyMap(const InputDeviceIdentifier& deviceIdentifier, } status_t KeyMap::loadKeyLayout(const InputDeviceIdentifier& deviceIdentifier, - const String8& name) { - String8 path(getPath(deviceIdentifier, name, + const std::string& name) { + std::string path(getPath(deviceIdentifier, name, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_LAYOUT)); - if (path.isEmpty()) { + if (path.empty()) { return NAME_NOT_FOUND; } @@ -116,15 +116,15 @@ status_t KeyMap::loadKeyLayout(const InputDeviceIdentifier& deviceIdentifier, return status; } - keyLayoutFile.setTo(path); + keyLayoutFile = path; return OK; } status_t KeyMap::loadKeyCharacterMap(const InputDeviceIdentifier& deviceIdentifier, - const String8& name) { - String8 path(getPath(deviceIdentifier, name, - INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_CHARACTER_MAP)); - if (path.isEmpty()) { + const std::string& name) { + std::string path = getPath(deviceIdentifier, name, + INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_CHARACTER_MAP); + if (path.empty()) { return NAME_NOT_FOUND; } @@ -134,13 +134,13 @@ status_t KeyMap::loadKeyCharacterMap(const InputDeviceIdentifier& deviceIdentifi return status; } - keyCharacterMapFile.setTo(path); + keyCharacterMapFile = path; return OK; } -String8 KeyMap::getPath(const InputDeviceIdentifier& deviceIdentifier, - const String8& name, InputDeviceConfigurationFileType type) { - return name.isEmpty() +std::string KeyMap::getPath(const InputDeviceIdentifier& deviceIdentifier, + const std::string& name, InputDeviceConfigurationFileType type) { + return name.empty() ? getInputDeviceConfigurationFilePathByDeviceIdentifier(deviceIdentifier, type) : getInputDeviceConfigurationFilePathByName(name, type); } @@ -174,7 +174,7 @@ bool isEligibleBuiltInKeyboard(const InputDeviceIdentifier& deviceIdentifier, } } - return strstr(deviceIdentifier.name.string(), "-keypad"); + return strstr(deviceIdentifier.name.c_str(), "-keypad"); } static int32_t setEphemeralMetaState(int32_t mask, bool down, int32_t oldMetaState) { diff --git a/libs/input/VirtualKeyMap.cpp b/libs/input/VirtualKeyMap.cpp index 993297319e..3ec53bf5a0 100644 --- a/libs/input/VirtualKeyMap.cpp +++ b/libs/input/VirtualKeyMap.cpp @@ -46,13 +46,13 @@ VirtualKeyMap::VirtualKeyMap() { VirtualKeyMap::~VirtualKeyMap() { } -status_t VirtualKeyMap::load(const String8& filename, VirtualKeyMap** outMap) { +status_t VirtualKeyMap::load(const std::string& filename, VirtualKeyMap** outMap) { *outMap = nullptr; Tokenizer* tokenizer; - status_t status = Tokenizer::open(filename, &tokenizer); + status_t status = Tokenizer::open(String8(filename.c_str()), &tokenizer); if (status) { - ALOGE("Error %d opening virtual key map file %s.", status, filename.string()); + ALOGE("Error %d opening virtual key map file %s.", status, filename.c_str()); } else { VirtualKeyMap* map = new VirtualKeyMap(); if (!map) { diff --git a/services/inputflinger/EventHub.cpp b/services/inputflinger/EventHub.cpp index 77a474fa82..a964d29489 100644 --- a/services/inputflinger/EventHub.cpp +++ b/services/inputflinger/EventHub.cpp @@ -76,16 +76,16 @@ static inline const char* toString(bool value) { return value ? "true" : "false"; } -static String8 sha1(const String8& in) { +static std::string sha1(const std::string& in) { SHA_CTX ctx; SHA1_Init(&ctx); - SHA1_Update(&ctx, reinterpret_cast(in.string()), in.size()); + SHA1_Update(&ctx, reinterpret_cast(in.c_str()), in.size()); u_char digest[SHA_DIGEST_LENGTH]; SHA1_Final(digest, &ctx); - String8 out; + std::string out; for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) { - out.appendFormat("%02x", digest[i]); + out += StringPrintf("%02x", digest[i]); } return out; } @@ -141,7 +141,7 @@ uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) { // --- EventHub::Device --- -EventHub::Device::Device(int fd, int32_t id, const String8& path, +EventHub::Device::Device(int fd, int32_t id, const std::string& path, const InputDeviceIdentifier& identifier) : next(nullptr), fd(fd), id(id), path(path), identifier(identifier), @@ -172,9 +172,9 @@ void EventHub::Device::close() { } status_t EventHub::Device::enable() { - fd = open(path, O_RDWR | O_CLOEXEC | O_NONBLOCK); + fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK); if(fd < 0) { - ALOGE("could not open %s, %s\n", path.string(), strerror(errno)); + ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno)); return -errno; } enabled = true; @@ -307,7 +307,7 @@ status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis, struct input_absinfo info; if(ioctl(device->fd, EVIOCGABS(axis), &info)) { ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", - axis, device->identifier.name.string(), device->fd, errno); + axis, device->identifier.name.c_str(), device->fd, errno); return -errno; } @@ -416,7 +416,7 @@ status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* struct input_absinfo info; if(ioctl(device->fd, EVIOCGABS(axis), &info)) { ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", - axis, device->identifier.name.string(), device->fd, errno); + axis, device->identifier.name.c_str(), device->fd, errno); return -errno; } @@ -512,7 +512,7 @@ status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxis return NAME_NOT_FOUND; } -void EventHub::setExcludedDevices(const Vector& devices) { +void EventHub::setExcludedDevices(const std::vector& devices) { AutoMutex _l(mLock); mExcludedDevices = devices; @@ -599,16 +599,16 @@ bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, return false; } -static String8 generateDescriptor(InputDeviceIdentifier& identifier) { - String8 rawDescriptor; - rawDescriptor.appendFormat(":%04x:%04x:", identifier.vendor, +static std::string generateDescriptor(InputDeviceIdentifier& identifier) { + std::string rawDescriptor; + rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product); // TODO add handling for USB devices to not uniqueify kbs that show up twice - if (!identifier.uniqueId.isEmpty()) { - rawDescriptor.append("uniqueId:"); - rawDescriptor.append(identifier.uniqueId); + if (!identifier.uniqueId.empty()) { + rawDescriptor += "uniqueId:"; + rawDescriptor += identifier.uniqueId; } else if (identifier.nonce != 0) { - rawDescriptor.appendFormat("nonce:%04x", identifier.nonce); + rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce); } if (identifier.vendor == 0 && identifier.product == 0) { @@ -616,12 +616,12 @@ static String8 generateDescriptor(InputDeviceIdentifier& identifier) { // built-in so we need to rely on other information to uniquely identify // the input device. Usually we try to avoid relying on the device name or // location but for built-in input device, they are unlikely to ever change. - if (!identifier.name.isEmpty()) { - rawDescriptor.append("name:"); - rawDescriptor.append(identifier.name); - } else if (!identifier.location.isEmpty()) { - rawDescriptor.append("location:"); - rawDescriptor.append(identifier.location); + if (!identifier.name.empty()) { + rawDescriptor += "name:"; + rawDescriptor += identifier.name; + } else if (!identifier.location.empty()) { + rawDescriptor += "location:"; + rawDescriptor += identifier.location; } } identifier.descriptor = sha1(rawDescriptor); @@ -637,8 +637,8 @@ void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) { // Ideally, we also want the descriptor to be short and relatively opaque. identifier.nonce = 0; - String8 rawDescriptor = generateDescriptor(identifier); - if (identifier.uniqueId.isEmpty()) { + std::string rawDescriptor = generateDescriptor(identifier); + if (identifier.uniqueId.empty()) { // If it didn't have a unique id check for conflicts and enforce // uniqueness if necessary. while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) { @@ -646,8 +646,8 @@ void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) { rawDescriptor = generateDescriptor(identifier); } } - ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.string(), - identifier.descriptor.string()); + ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(), + identifier.descriptor.c_str()); } void EventHub::vibrate(int32_t deviceId, nsecs_t duration) { @@ -664,7 +664,7 @@ void EventHub::vibrate(int32_t deviceId, nsecs_t duration) { effect.replay.delay = 0; if (ioctl(device->fd, EVIOCSFF, &effect)) { ALOGW("Could not upload force feedback effect to device %s due to error %d.", - device->identifier.name.string(), errno); + device->identifier.name.c_str(), errno); return; } device->ffEffectId = effect.id; @@ -677,7 +677,7 @@ void EventHub::vibrate(int32_t deviceId, nsecs_t duration) { ev.value = 1; if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) { ALOGW("Could not start force feedback effect on device %s due to error %d.", - device->identifier.name.string(), errno); + device->identifier.name.c_str(), errno); return; } device->ffEffectPlaying = true; @@ -699,18 +699,18 @@ void EventHub::cancelVibrate(int32_t deviceId) { ev.value = 0; if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) { ALOGW("Could not stop force feedback effect on device %s due to error %d.", - device->identifier.name.string(), errno); + device->identifier.name.c_str(), errno); return; } } } } -EventHub::Device* EventHub::getDeviceByDescriptorLocked(String8& descriptor) const { +EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const { size_t size = mDevices.size(); for (size_t i = 0; i < size; i++) { Device* device = mDevices.valueAt(i); - if (descriptor.compare(device->identifier.descriptor) == 0) { + if (descriptor == device->identifier.descriptor) { return device; } } @@ -763,7 +763,7 @@ size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSiz while (mClosingDevices) { Device* device = mClosingDevices; ALOGV("Reporting device closed: id=%d, name=%s\n", - device->id, device->path.string()); + device->id, device->path.c_str()); mClosingDevices = device->next; event->when = now; event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id; @@ -785,7 +785,7 @@ size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSiz while (mOpeningDevices != nullptr) { Device* device = mOpeningDevices; ALOGV("Reporting device opened: id=%d, name=%s\n", - device->id, device->path.string()); + device->id, device->path.c_str()); mOpeningDevices = device->next; event->when = now; event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id; @@ -867,7 +867,7 @@ size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSiz for (size_t i = 0; i < count; i++) { struct input_event& iev = readBuffer[i]; ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d", - device->path.string(), + device->path.c_str(), (int) iev.time.tv_sec, (int) iev.time.tv_usec, iev.type, iev.code, iev.value); @@ -936,7 +936,7 @@ size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSiz "event time %" PRId64 ", current time %" PRId64 ", call time %" PRId64 ". " "Using current time instead.", - device->path.string(), event->when, time, now); + device->path.c_str(), event->when, time, now); event->when = time; } else { ALOGV("Event time is ok but failed the fast path and required " @@ -962,12 +962,12 @@ size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSiz } } else if (eventItem.events & EPOLLHUP) { ALOGI("Removing device %s due to epoll hang-up event.", - device->identifier.name.string()); + device->identifier.name.c_str()); deviceChanged = true; closeDeviceLocked(device); } else { ALOGW("Received unexpected epoll event 0x%08x for device %s.", - eventItem.events, device->identifier.name.string()); + eventItem.events, device->identifier.name.c_str()); } } @@ -1125,14 +1125,14 @@ status_t EventHub::openDeviceLocked(const char *devicePath) { //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno)); } else { buffer[sizeof(buffer) - 1] = '\0'; - identifier.name.setTo(buffer); + identifier.name = buffer; } // Check to see if the device is on our excluded list for (size_t i = 0; i < mExcludedDevices.size(); i++) { - const String8& item = mExcludedDevices.itemAt(i); + const std::string& item = mExcludedDevices[i]; if (identifier.name == item) { - ALOGI("ignoring event id %s driver %s\n", devicePath, item.string()); + ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str()); close(fd); return -1; } @@ -1163,7 +1163,7 @@ status_t EventHub::openDeviceLocked(const char *devicePath) { //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno)); } else { buffer[sizeof(buffer) - 1] = '\0'; - identifier.location.setTo(buffer); + identifier.location = buffer; } // Get device unique id. @@ -1171,7 +1171,7 @@ status_t EventHub::openDeviceLocked(const char *devicePath) { //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno)); } else { buffer[sizeof(buffer) - 1] = '\0'; - identifier.uniqueId.setTo(buffer); + identifier.uniqueId = buffer; } // Fill in the descriptor. @@ -1179,7 +1179,7 @@ status_t EventHub::openDeviceLocked(const char *devicePath) { // Allocate device. (The device object takes ownership of the fd at this point.) int32_t deviceId = mNextDeviceId++; - Device* device = new Device(fd, deviceId, String8(devicePath), identifier); + Device* device = new Device(fd, deviceId, devicePath, identifier); ALOGV("add device %d: %s\n", deviceId, devicePath); ALOGV(" bus: %04x\n" @@ -1187,10 +1187,10 @@ status_t EventHub::openDeviceLocked(const char *devicePath) { " product %04x\n" " version %04x\n", identifier.bus, identifier.vendor, identifier.product, identifier.version); - ALOGV(" name: \"%s\"\n", identifier.name.string()); - ALOGV(" location: \"%s\"\n", identifier.location.string()); - ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.string()); - ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.string()); + ALOGV(" name: \"%s\"\n", identifier.name.c_str()); + ALOGV(" location: \"%s\"\n", identifier.location.c_str()); + ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str()); + ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str()); ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff); @@ -1343,7 +1343,7 @@ status_t EventHub::openDeviceLocked(const char *devicePath) { // If the device isn't recognized as something we handle, don't monitor it. if (device->classes == 0) { ALOGV("Dropping device: id=%d, path='%s', name='%s'", - deviceId, devicePath, device->identifier.name.string()); + deviceId, devicePath, device->identifier.name.c_str()); delete device; return -1; } @@ -1374,11 +1374,11 @@ status_t EventHub::openDeviceLocked(const char *devicePath) { ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, " "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ", - deviceId, fd, devicePath, device->identifier.name.string(), + deviceId, fd, devicePath, device->identifier.name.c_str(), device->classes, - device->configurationFile.string(), - device->keyMap.keyLayoutFile.string(), - device->keyMap.keyCharacterMapFile.string(), + device->configurationFile.c_str(), + device->keyMap.keyLayoutFile.c_str(), + device->keyMap.keyCharacterMapFile.c_str(), toString(mBuiltInKeyboardId == deviceId)); addDeviceLocked(device); @@ -1392,11 +1392,11 @@ void EventHub::configureFd(Device* device) { unsigned int repeatRate[] = {0, 0}; if (ioctl(device->fd, EVIOCSREP, repeatRate)) { ALOGW("Unable to disable kernel key repeat for %s: %s", - device->path.string(), strerror(errno)); + device->path.c_str(), strerror(errno)); } } - String8 wakeMechanism("EPOLLWAKEUP"); + std::string wakeMechanism = "EPOLLWAKEUP"; if (!mUsingEpollWakeup) { #ifndef EVIOCSSUSPENDBLOCK // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels @@ -1416,7 +1416,7 @@ void EventHub::configureFd(Device* device) { // clock. int clockId = CLOCK_MONOTONIC; bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId); - ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.string(), + ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(), toString(usingClockIoctl)); } @@ -1473,7 +1473,7 @@ void EventHub::createVirtualKeyboardLocked() { identifier.uniqueId = ""; assignDescriptorLocked(identifier); - Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, String8(""), identifier); + Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, "", identifier); device->classes = INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_ALPHAKEY | INPUT_DEVICE_CLASS_DPAD @@ -1491,26 +1491,26 @@ void EventHub::addDeviceLocked(Device* device) { void EventHub::loadConfigurationLocked(Device* device) { device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier( device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION); - if (device->configurationFile.isEmpty()) { + if (device->configurationFile.empty()) { ALOGD("No input device configuration file found for device '%s'.", - device->identifier.name.string()); + device->identifier.name.c_str()); } else { - status_t status = PropertyMap::load(device->configurationFile, + status_t status = PropertyMap::load(String8(device->configurationFile.c_str()), &device->configuration); if (status) { ALOGE("Error loading input device configuration file for device '%s'. " "Using default configuration.", - device->identifier.name.string()); + device->identifier.name.c_str()); } } } status_t EventHub::loadVirtualKeyMapLocked(Device* device) { // The virtual key map is supplied by the kernel as a system board property file. - String8 path; - path.append("/sys/board_properties/virtualkeys."); - path.append(device->identifier.name); - if (access(path.string(), R_OK)) { + std::string path; + path += "/sys/board_properties/virtualkeys."; + path += device->identifier.name; + if (access(path.c_str(), R_OK)) { return NAME_NOT_FOUND; } return VirtualKeyMap::load(path, &device->virtualKeyMap); @@ -1543,7 +1543,7 @@ bool EventHub::deviceHasMicLocked(Device* device) { int32_t EventHub::getNextControllerNumberLocked(Device* device) { if (mControllerNumbers.isFull()) { ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s", - device->identifier.name.string()); + device->identifier.name.c_str()); return 0; } // Since the controller number 0 is reserved for non-controllers, translate all numbers up by @@ -1617,12 +1617,12 @@ void EventHub::closeAllDevicesLocked() { void EventHub::closeDeviceLocked(Device* device) { ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n", - device->path.string(), device->identifier.name.string(), device->id, + device->path.c_str(), device->identifier.name.c_str(), device->id, device->fd, device->classes); if (device->id == mBuiltInKeyboardId) { ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this", - device->path.string(), mBuiltInKeyboardId); + device->path.c_str(), mBuiltInKeyboardId); mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD; } @@ -1648,7 +1648,7 @@ void EventHub::closeDeviceLocked(Device* device) { // Unlink the device from the opening devices list then delete it. // We don't need to tell the client that the device was closed because // it does not even know it was opened in the first place. - ALOGI("Device %s was immediately closed after opening.", device->path.string()); + ALOGI("Device %s was immediately closed after opening.", device->path.c_str()); if (pred) { pred->next = device->next; } else { @@ -1750,28 +1750,28 @@ void EventHub::dump(std::string& dump) { const Device* device = mDevices.valueAt(i); if (mBuiltInKeyboardId == device->id) { dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n", - device->id, device->identifier.name.string()); + device->id, device->identifier.name.c_str()); } else { dump += StringPrintf(INDENT2 "%d: %s\n", device->id, - device->identifier.name.string()); + device->identifier.name.c_str()); } dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes); - dump += StringPrintf(INDENT3 "Path: %s\n", device->path.string()); + dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str()); dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled)); - dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.string()); - dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.string()); + dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str()); + dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str()); dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber); - dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.string()); + dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str()); dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, " "product=0x%04x, version=0x%04x\n", device->identifier.bus, device->identifier.vendor, device->identifier.product, device->identifier.version); dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n", - device->keyMap.keyLayoutFile.string()); + device->keyMap.keyLayoutFile.c_str()); dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n", - device->keyMap.keyCharacterMapFile.string()); + device->keyMap.keyCharacterMapFile.c_str()); dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n", - device->configurationFile.string()); + device->configurationFile.c_str()); dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n", toString(device->overlayKeyMap != nullptr)); } diff --git a/services/inputflinger/EventHub.h b/services/inputflinger/EventHub.h index dfe3defc73..ea663b7cb6 100644 --- a/services/inputflinger/EventHub.h +++ b/services/inputflinger/EventHub.h @@ -18,6 +18,8 @@ #ifndef _RUNTIME_EVENT_HUB_H #define _RUNTIME_EVENT_HUB_H +#include + #include #include #include @@ -29,7 +31,6 @@ #include #include #include -#include #include #include @@ -207,7 +208,7 @@ public: // Sets devices that are excluded from opening. // This can be used to ignore input devices for sensors. - virtual void setExcludedDevices(const Vector& devices) = 0; + virtual void setExcludedDevices(const std::vector& devices) = 0; /* * Wait for events to become available and returns them. @@ -303,7 +304,7 @@ public: virtual status_t mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const; - virtual void setExcludedDevices(const Vector& devices); + virtual void setExcludedDevices(const std::vector& devices); virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const; virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const; @@ -344,7 +345,7 @@ private: int fd; // may be -1 if device is closed const int32_t id; - const String8 path; + const std::string path; const InputDeviceIdentifier identifier; uint32_t classes; @@ -357,7 +358,7 @@ private: uint8_t ffBitmask[(FF_MAX + 1) / 8]; uint8_t propBitmask[(INPUT_PROP_MAX + 1) / 8]; - String8 configurationFile; + std::string configurationFile; PropertyMap* configuration; VirtualKeyMap* virtualKeyMap; KeyMap keyMap; @@ -373,7 +374,8 @@ private: int32_t timestampOverrideSec; int32_t timestampOverrideUsec; - Device(int fd, int32_t id, const String8& path, const InputDeviceIdentifier& identifier); + Device(int fd, int32_t id, const std::string& path, + const InputDeviceIdentifier& identifier); ~Device(); void close(); @@ -413,7 +415,7 @@ private: void scanDevicesLocked(); status_t readNotifyLocked(); - Device* getDeviceByDescriptorLocked(String8& descriptor) const; + Device* getDeviceByDescriptorLocked(const std::string& descriptor) const; Device* getDeviceLocked(int32_t deviceId) const; Device* getDeviceByPathLocked(const char* devicePath) const; @@ -457,7 +459,7 @@ private: bool mNeedToSendFinishedDeviceScan; bool mNeedToReopenDevices; bool mNeedToScanDevices; - Vector mExcludedDevices; + std::vector mExcludedDevices; int mEpollFd; int mINotifyFd; diff --git a/services/inputflinger/InputApplication.h b/services/inputflinger/InputApplication.h index 724fc2c4f4..9b365b9f0d 100644 --- a/services/inputflinger/InputApplication.h +++ b/services/inputflinger/InputApplication.h @@ -17,6 +17,8 @@ #ifndef _UI_INPUT_APPLICATION_H #define _UI_INPUT_APPLICATION_H +#include + #include #include #include diff --git a/services/inputflinger/InputManager.h b/services/inputflinger/InputManager.h index a213b2dfaa..92e0af21c3 100644 --- a/services/inputflinger/InputManager.h +++ b/services/inputflinger/InputManager.h @@ -31,7 +31,6 @@ #include #include #include -#include namespace android { diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index a4f83b7ebb..8f12129455 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -257,11 +257,12 @@ static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, // --- InputReaderConfiguration --- bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType, - const String8* uniqueDisplayId, DisplayViewport* outViewport) const { + const std::string& uniqueDisplayId, DisplayViewport* outViewport) const { const DisplayViewport* viewport = nullptr; - if (viewportType == ViewportType::VIEWPORT_VIRTUAL && uniqueDisplayId != nullptr) { + if (viewportType == ViewportType::VIEWPORT_VIRTUAL && !uniqueDisplayId.empty()) { + for (const DisplayViewport& currentViewport : mVirtualDisplays) { - if (currentViewport.uniqueId == *uniqueDisplayId) { + if (currentViewport.uniqueId == uniqueDisplayId) { viewport = ¤tViewport; break; } @@ -473,10 +474,10 @@ void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) { if (device->isIgnored()) { ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, - identifier.name.string()); + identifier.name.c_str()); } else { ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, - identifier.name.string(), device->getSources()); + identifier.name.c_str(), device->getSources()); } mDevices.add(deviceId, device); @@ -501,10 +502,10 @@ void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) { if (device->isIgnored()) { ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)", - device->getId(), device->getName().string()); + device->getId(), device->getName().c_str()); } else { ALOGI("Device removed: id=%d, name='%s', sources=0x%08x", - device->getId(), device->getName().string(), device->getSources()); + device->getId(), device->getName().c_str(), device->getSources()); } if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) { @@ -687,7 +688,7 @@ bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now, if (now < mDisableVirtualKeysTimeout) { ALOGI("Dropping virtual key from device %s because virtual keys are " "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d", - device->getName().string(), + device->getName().c_str(), (mDisableVirtualKeysTimeout - now) * 0.000001, keyCode, scanCode); return true; @@ -894,7 +895,7 @@ void InputReader::dump(std::string& dump) { if (i != 0) { dump += ", "; } - dump += mConfig.excludedDeviceNames.itemAt(i).string(); + dump += mConfig.excludedDeviceNames[i]; } dump += "]\n"; dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n", @@ -1077,7 +1078,7 @@ void InputDevice::dump(std::string& dump) { getDeviceInfo(& deviceInfo); dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(), - deviceInfo.getDisplayName().string()); + deviceInfo.getDisplayName().c_str()); dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration); dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal)); dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic)); @@ -1135,7 +1136,7 @@ void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) { if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) { - String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier); + std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier); if (mAlias != alias) { mAlias = alias; bumpGeneration(); @@ -1196,7 +1197,7 @@ void InputDevice::process(const RawEvent* rawEvents, size_t count) { #endif } } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) { - ALOGI("Detected input event buffer overrun for device %s.", getName().string()); + ALOGI("Detected input event buffer overrun for device %s.", getName().c_str()); mDropUntilNextSync = true; reset(rawEvent->when); } else { @@ -2294,7 +2295,7 @@ void KeyboardInputMapper::configure(nsecs_t when, if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { if (mParameters.orientationAware) { DisplayViewport dvp; - config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, nullptr, &dvp); + config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "", &dvp); mViewport = dvp; } } @@ -2464,7 +2465,7 @@ void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode, // key was not actually down ALOGI("Dropping key up from device %s because the key was not down. " "keyCode=%d, scanCode=%d", - getDeviceName().string(), keyCode, scanCode); + getDeviceName().c_str(), keyCode, scanCode); return; } } @@ -2705,7 +2706,7 @@ void CursorInputMapper::configure(nsecs_t when, mOrientation = DISPLAY_ORIENTATION_0; if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { DisplayViewport v; - if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, nullptr, &v)) { + if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "", &v)) { mOrientation = v.orientation; } } @@ -3020,7 +3021,7 @@ void RotaryEncoderInputMapper::configure(nsecs_t when, } if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { DisplayViewport v; - if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, nullptr, &v)) { + if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "", &v)) { mOrientation = v.orientation; } else { mOrientation = DISPLAY_ORIENTATION_0; @@ -3394,8 +3395,10 @@ void TouchInputMapper::configureParameters() { mParameters.hasAssociatedDisplay = true; if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) { mParameters.associatedDisplayIsExternal = getDevice()->isExternal(); + String8 uniqueDisplayId; getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"), - mParameters.uniqueDisplayId); + uniqueDisplayId); + mParameters.uniqueDisplayId = uniqueDisplayId.c_str(); } } @@ -3506,7 +3509,7 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { // Ensure we have valid X and Y axes. if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) { ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! " - "The device will be inoperable.", getDeviceName().string()); + "The device will be inoperable.", getDeviceName().c_str()); mDeviceMode = DEVICE_MODE_DISABLED; return; } @@ -3518,15 +3521,15 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { // Get associated display dimensions. DisplayViewport newViewport; if (mParameters.hasAssociatedDisplay) { - const String8* uniqueDisplayId = nullptr; + std::string uniqueDisplayId; ViewportType viewportTypeToUse; if (mParameters.associatedDisplayIsExternal) { viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL; - } else if (!mParameters.uniqueDisplayId.isEmpty()) { + } else if (!mParameters.uniqueDisplayId.empty()) { // If the IDC file specified a unique display Id, then it expects to be linked to a // virtual display with the same unique ID. - uniqueDisplayId = &mParameters.uniqueDisplayId; + uniqueDisplayId = mParameters.uniqueDisplayId; viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL; } else { viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL; @@ -3536,7 +3539,7 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { ALOGI(INDENT "Touch device '%s' could not query the properties of its associated " "display. The device will be inoperable until the display size " "becomes available.", - getDeviceName().string()); + getDeviceName().c_str()); mDeviceMode = DEVICE_MODE_DISABLED; return; } @@ -3642,7 +3645,7 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { if (viewportChanged || deviceModeChanged) { ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, " "display id %d", - getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight, + getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight, mSurfaceOrientation, mDeviceMode, mViewport.displayId); // Configure X and Y factors. @@ -6925,7 +6928,7 @@ void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) { #if DEBUG_POINTERS ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; " "ignoring the rest.", - getDeviceName().string(), MAX_POINTERS); + getDeviceName().c_str(), MAX_POINTERS); #endif break; // too many fingers! } @@ -7016,7 +7019,7 @@ void MultiTouchInputMapper::configureRawPointerAxes() { if (slotCount > MAX_SLOTS) { ALOGW("MultiTouch Device %s reported %zu slots but the framework " "only supports a maximum of %zu slots at this time.", - getDeviceName().string(), slotCount, MAX_SLOTS); + getDeviceName().c_str(), slotCount, MAX_SLOTS); slotCount = MAX_SLOTS; } mMultiTouchMotionAccumulator.configure(getDevice(), @@ -7259,7 +7262,7 @@ void JoystickInputMapper::configure(nsecs_t when, // Prefer to keep explicitly mapped axes. if (mAxes.size() > PointerCoords::MAX_AXES) { ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.", - getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES); + getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES); pruneAxes(true); pruneAxes(false); } @@ -7281,7 +7284,7 @@ void JoystickInputMapper::configure(nsecs_t when, } else { ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids " "have already been assigned to other axes.", - getDeviceName().string(), mAxes.keyAt(i)); + getDeviceName().c_str(), mAxes.keyAt(i)); mAxes.removeItemsAt(i--); numAxes -= 1; } @@ -7310,7 +7313,7 @@ void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) { continue; } ALOGI("Discarding joystick '%s' axis %d because there are too many axes.", - getDeviceName().string(), mAxes.keyAt(i)); + getDeviceName().c_str(), mAxes.keyAt(i)); mAxes.removeItemsAt(i); } } diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h index af26b4f27b..c06168d5a2 100644 --- a/services/inputflinger/InputReader.h +++ b/services/inputflinger/InputReader.h @@ -101,7 +101,7 @@ struct InputReaderConfiguration { // The excluded device names for the platform. // Devices with these names will be ignored. - Vector excludedDeviceNames; + std::vector excludedDeviceNames; // Velocity control parameters for mouse pointer movements. VelocityControlParameters pointerVelocityControlParameters; @@ -201,7 +201,7 @@ struct InputReaderConfiguration { pointerGestureZoomSpeedRatio(0.3f), showTouches(false) { } - bool getDisplayViewport(ViewportType viewportType, const String8* displayId, + bool getDisplayViewport(ViewportType viewportType, const std::string& uniqueDisplayId, DisplayViewport* outViewport) const; void setPhysicalDisplayViewport(ViewportType viewportType, const DisplayViewport& viewport); void setVirtualDisplayViewports(const Vector& viewports); @@ -274,11 +274,11 @@ public: const InputDeviceIdentifier& identifier) = 0; /* Gets a user-supplied alias for a particular input device, or an empty string if none. */ - virtual String8 getDeviceAlias(const InputDeviceIdentifier& identifier) = 0; + virtual std::string getDeviceAlias(const InputDeviceIdentifier& identifier) = 0; /* Gets the affine calibration associated with the specified device. */ virtual TouchAffineTransformation getTouchAffineTransformation( - const String8& inputDeviceDescriptor, int32_t surfaceRotation) = 0; + const std::string& inputDeviceDescriptor, int32_t surfaceRotation) = 0; }; @@ -553,8 +553,8 @@ public: inline int32_t getId() const { return mId; } inline int32_t getControllerNumber() const { return mControllerNumber; } inline int32_t getGeneration() const { return mGeneration; } - inline const String8& getName() const { return mIdentifier.name; } - inline const String8& getDescriptor() { return mIdentifier.descriptor; } + inline const std::string getName() const { return mIdentifier.name; } + inline const std::string getDescriptor() { return mIdentifier.descriptor; } inline uint32_t getClasses() const { return mClasses; } inline uint32_t getSources() const { return mSources; } @@ -625,7 +625,7 @@ private: int32_t mGeneration; int32_t mControllerNumber; InputDeviceIdentifier mIdentifier; - String8 mAlias; + std::string mAlias; uint32_t mClasses; Vector mMappers; @@ -981,7 +981,7 @@ public: inline InputDevice* getDevice() { return mDevice; } inline int32_t getDeviceId() { return mDevice->getId(); } - inline const String8 getDeviceName() { return mDevice->getName(); } + inline const std::string getDeviceName() { return mDevice->getName(); } inline InputReaderContext* getContext() { return mContext; } inline InputReaderPolicyInterface* getPolicy() { return mContext->getPolicy(); } inline InputListenerInterface* getListener() { return mContext->getListener(); } @@ -1309,7 +1309,7 @@ protected: bool associatedDisplayIsExternal; bool orientationAware; bool hasButtonUnderPad; - String8 uniqueDisplayId; + std::string uniqueDisplayId; enum GestureMode { GESTURE_MODE_SINGLE_TOUCH, diff --git a/services/inputflinger/host/InputDriver.cpp b/services/inputflinger/host/InputDriver.cpp index bd11d5620b..2f046c3527 100644 --- a/services/inputflinger/host/InputDriver.cpp +++ b/services/inputflinger/host/InputDriver.cpp @@ -217,18 +217,18 @@ input_property_map_t* InputDriver::inputGetDevicePropertyMap(input_device_identi idi.product = id->productId; idi.version = id->version; - String8 configFile = getInputDeviceConfigurationFilePathByDeviceIdentifier( + std::string configFile = getInputDeviceConfigurationFilePathByDeviceIdentifier( idi, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION); - if (configFile.isEmpty()) { + if (configFile.empty()) { ALOGD("No input device configuration file found for device '%s'.", - idi.name.string()); + idi.name.c_str()); } else { auto propMap = new input_property_map_t(); - status_t status = PropertyMap::load(configFile, &propMap->propertyMap); + status_t status = PropertyMap::load(String8(configFile.c_str()), &propMap->propertyMap); if (status) { ALOGE("Error loading input device configuration file for device '%s'. " "Using default configuration.", - idi.name.string()); + idi.name.c_str()); delete propMap; return nullptr; } diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index 286cf880f1..9b985dc23d 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -142,7 +142,7 @@ public: } void setDisplayViewport(int32_t displayId, int32_t width, int32_t height, int32_t orientation, - const String8& uniqueId) { + const std::string& uniqueId) { DisplayViewport v = createDisplayViewport(displayId, width, height, orientation, uniqueId); // Set the size of both the internal and external display at the same time. mConfig.setPhysicalDisplayViewport(ViewportType::VIEWPORT_INTERNAL, v); @@ -150,14 +150,14 @@ public: } void setVirtualDisplayViewport(int32_t displayId, int32_t width, int32_t height, int32_t orientation, - const String8& uniqueId) { + const std::string& uniqueId) { Vector viewports; viewports.push_back(createDisplayViewport(displayId, width, height, orientation, uniqueId)); mConfig.setVirtualDisplayViewports(viewports); } - void addExcludedDeviceName(const String8& deviceName) { - mConfig.excludedDeviceNames.push(deviceName); + void addExcludedDeviceName(const std::string& deviceName) { + mConfig.excludedDeviceNames.push_back(deviceName); } void addDisabledDevice(int32_t deviceId) { @@ -188,7 +188,7 @@ public: return mInputDevices; } - TouchAffineTransformation getTouchAffineTransformation(const String8& inputDeviceDescriptor, + TouchAffineTransformation getTouchAffineTransformation(const std::string& inputDeviceDescriptor, int32_t surfaceRotation) { return transform; } @@ -203,7 +203,7 @@ public: private: DisplayViewport createDisplayViewport(int32_t displayId, int32_t width, int32_t height, - int32_t orientation, const String8& uniqueId) { + int32_t orientation, const std::string& uniqueId) { bool isRotated = (orientation == DISPLAY_ORIENTATION_90 || orientation == DISPLAY_ORIENTATION_270); DisplayViewport v; @@ -239,8 +239,8 @@ private: return nullptr; } - virtual String8 getDeviceAlias(const InputDeviceIdentifier&) { - return String8::empty(); + virtual std::string getDeviceAlias(const InputDeviceIdentifier&) { + return ""; } }; @@ -392,7 +392,7 @@ class FakeEventHub : public EventHubInterface { }; KeyedVector mDevices; - Vector mExcludedDevices; + std::vector mExcludedDevices; List mEvents; protected: @@ -405,7 +405,7 @@ protected: public: FakeEventHub() { } - void addDevice(int32_t deviceId, const String8& name, uint32_t classes) { + void addDevice(int32_t deviceId, const std::string& name, uint32_t classes) { Device* device = new Device(classes); device->identifier.name = name; mDevices.add(deviceId, device); @@ -534,7 +534,7 @@ public: return device->leds.valueFor(led); } - Vector& getExcludedDevices() { + std::vector& getExcludedDevices() { return mExcludedDevices; } @@ -566,7 +566,7 @@ public: private: Device* getDevice(int32_t deviceId) const { ssize_t index = mDevices.indexOfKey(deviceId); - return index >= 0 ? mDevices.valueAt(index) : NULL; + return index >= 0 ? mDevices.valueAt(index) : nullptr; } virtual uint32_t getDeviceClasses(int32_t deviceId) const { @@ -658,7 +658,7 @@ private: return NAME_NOT_FOUND; } - virtual void setExcludedDevices(const Vector& devices) { + virtual void setExcludedDevices(const std::vector& devices) { mExcludedDevices = devices; } @@ -1052,7 +1052,7 @@ public: mNextDevice = device; } - InputDevice* newDevice(int32_t deviceId, int32_t controllerNumber, const String8& name, + InputDevice* newDevice(int32_t deviceId, int32_t controllerNumber, const std::string& name, uint32_t classes) { InputDeviceIdentifier identifier; identifier.name = name; @@ -1101,7 +1101,7 @@ protected: mFakeEventHub.clear(); } - void addDevice(int32_t deviceId, const String8& name, uint32_t classes, + void addDevice(int32_t deviceId, const std::string& name, uint32_t classes, const PropertyMap* configuration) { mFakeEventHub->addDevice(deviceId, name, classes); @@ -1129,7 +1129,7 @@ protected: } FakeInputMapper* addDeviceWithFakeInputMapper(int32_t deviceId, int32_t controllerNumber, - const String8& name, uint32_t classes, uint32_t sources, + const std::string& name, uint32_t classes, uint32_t sources, const PropertyMap* configuration) { InputDevice* device = mReader->newDevice(deviceId, controllerNumber, name, classes); FakeInputMapper* mapper = new FakeInputMapper(device, sources); @@ -1141,17 +1141,18 @@ protected: }; TEST_F(InputReaderTest, GetInputDevices) { - ASSERT_NO_FATAL_FAILURE(addDevice(1, String8("keyboard"), + ASSERT_NO_FATAL_FAILURE(addDevice(1, "keyboard", INPUT_DEVICE_CLASS_KEYBOARD, nullptr)); - ASSERT_NO_FATAL_FAILURE(addDevice(2, String8("ignored"), + ASSERT_NO_FATAL_FAILURE(addDevice(2, "ignored", 0, nullptr)); // no classes so device will be ignored + Vector inputDevices; mReader->getInputDevices(inputDevices); ASSERT_EQ(1U, inputDevices.size()); ASSERT_EQ(1, inputDevices[0].getId()); - ASSERT_STREQ("keyboard", inputDevices[0].getIdentifier().name.string()); + ASSERT_STREQ("keyboard", inputDevices[0].getIdentifier().name.c_str()); ASSERT_EQ(AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC, inputDevices[0].getKeyboardType()); ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, inputDevices[0].getSources()); ASSERT_EQ(size_t(0), inputDevices[0].getMotionRanges().size()); @@ -1160,7 +1161,7 @@ TEST_F(InputReaderTest, GetInputDevices) { inputDevices = mFakePolicy->getInputDevices(); ASSERT_EQ(1U, inputDevices.size()); ASSERT_EQ(1, inputDevices[0].getId()); - ASSERT_STREQ("keyboard", inputDevices[0].getIdentifier().name.string()); + ASSERT_STREQ("keyboard", inputDevices[0].getIdentifier().name.c_str()); ASSERT_EQ(AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC, inputDevices[0].getKeyboardType()); ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, inputDevices[0].getSources()); ASSERT_EQ(size_t(0), inputDevices[0].getMotionRanges().size()); @@ -1169,12 +1170,12 @@ TEST_F(InputReaderTest, GetInputDevices) { TEST_F(InputReaderTest, WhenEnabledChanges_SendsDeviceResetNotification) { constexpr int32_t deviceId = 1; constexpr uint32_t deviceClass = INPUT_DEVICE_CLASS_KEYBOARD; - InputDevice* device = mReader->newDevice(deviceId, 0, String8("fake"), deviceClass); + InputDevice* device = mReader->newDevice(deviceId, 0, "fake", deviceClass); // Must add at least one mapper or the device will be ignored! FakeInputMapper* mapper = new FakeInputMapper(device, AINPUT_SOURCE_KEYBOARD); device->addMapper(mapper); mReader->setNextDevice(device); - addDevice(deviceId, String8("fake"), deviceClass, nullptr); + addDevice(deviceId, "fake", deviceClass, nullptr); ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyConfigurationChangedWasCalled(nullptr)); @@ -1208,7 +1209,7 @@ TEST_F(InputReaderTest, WhenEnabledChanges_SendsDeviceResetNotification) { TEST_F(InputReaderTest, GetKeyCodeState_ForwardsRequestsToMappers) { FakeInputMapper* mapper = nullptr; - ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, String8("fake"), + ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, "fake", INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, nullptr)); mapper->setKeyCodeState(AKEYCODE_A, AKEY_STATE_DOWN); @@ -1235,7 +1236,7 @@ TEST_F(InputReaderTest, GetKeyCodeState_ForwardsRequestsToMappers) { TEST_F(InputReaderTest, GetScanCodeState_ForwardsRequestsToMappers) { FakeInputMapper* mapper = nullptr; - ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, String8("fake"), + ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, "fake", INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, nullptr)); mapper->setScanCodeState(KEY_A, AKEY_STATE_DOWN); @@ -1262,7 +1263,7 @@ TEST_F(InputReaderTest, GetScanCodeState_ForwardsRequestsToMappers) { TEST_F(InputReaderTest, GetSwitchState_ForwardsRequestsToMappers) { FakeInputMapper* mapper = nullptr; - ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, String8("fake"), + ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, "fake", INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, nullptr)); mapper->setSwitchState(SW_LID, AKEY_STATE_DOWN); @@ -1289,8 +1290,9 @@ TEST_F(InputReaderTest, GetSwitchState_ForwardsRequestsToMappers) { TEST_F(InputReaderTest, MarkSupportedKeyCodes_ForwardsRequestsToMappers) { FakeInputMapper* mapper = nullptr; - ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, String8("fake"), + ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, "fake", INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, nullptr)); + mapper->addSupportedKeyCode(AKEYCODE_A); mapper->addSupportedKeyCode(AKEYCODE_B); @@ -1323,7 +1325,7 @@ TEST_F(InputReaderTest, MarkSupportedKeyCodes_ForwardsRequestsToMappers) { } TEST_F(InputReaderTest, LoopOnce_WhenDeviceScanFinished_SendsConfigurationChanged) { - addDevice(1, String8("ignored"), INPUT_DEVICE_CLASS_KEYBOARD, nullptr); + addDevice(1, "ignored", INPUT_DEVICE_CLASS_KEYBOARD, nullptr); NotifyConfigurationChangedArgs args; @@ -1333,7 +1335,7 @@ TEST_F(InputReaderTest, LoopOnce_WhenDeviceScanFinished_SendsConfigurationChange TEST_F(InputReaderTest, LoopOnce_ForwardsRawEventsToMappers) { FakeInputMapper* mapper = nullptr; - ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, String8("fake"), + ASSERT_NO_FATAL_FAILURE(mapper = addDeviceWithFakeInputMapper(1, 0, "fake", INPUT_DEVICE_CLASS_KEYBOARD, AINPUT_SOURCE_KEYBOARD, nullptr)); mFakeEventHub->enqueueEvent(0, 1, EV_KEY, KEY_A, 1); @@ -1373,7 +1375,7 @@ protected: mFakeListener = new FakeInputListener(); mFakeContext = new FakeInputReaderContext(mFakeEventHub, mFakePolicy, mFakeListener); - mFakeEventHub->addDevice(DEVICE_ID, String8(DEVICE_NAME), 0); + mFakeEventHub->addDevice(DEVICE_ID, DEVICE_NAME, 0); InputDeviceIdentifier identifier; identifier.name = DEVICE_NAME; mDevice = new InputDevice(mFakeContext, DEVICE_ID, DEVICE_GENERATION, @@ -1399,7 +1401,7 @@ const uint32_t InputDeviceTest::DEVICE_CLASSES = INPUT_DEVICE_CLASS_KEYBOARD TEST_F(InputDeviceTest, ImmutableProperties) { ASSERT_EQ(DEVICE_ID, mDevice->getId()); - ASSERT_STREQ(DEVICE_NAME, mDevice->getName()); + ASSERT_STREQ(DEVICE_NAME, mDevice->getName().c_str()); ASSERT_EQ(DEVICE_CLASSES, mDevice->getClasses()); } @@ -1427,7 +1429,7 @@ TEST_F(InputDeviceTest, WhenNoMappersAreRegistered_DeviceIsIgnored) { InputDeviceInfo info; mDevice->getDeviceInfo(&info); ASSERT_EQ(DEVICE_ID, info.getId()); - ASSERT_STREQ(DEVICE_NAME, info.getIdentifier().name.string()); + ASSERT_STREQ(DEVICE_NAME, info.getIdentifier().name.c_str()); ASSERT_EQ(AINPUT_KEYBOARD_TYPE_NONE, info.getKeyboardType()); ASSERT_EQ(AINPUT_SOURCE_UNKNOWN, info.getSources()); @@ -1497,7 +1499,7 @@ TEST_F(InputDeviceTest, WhenMappersAreRegistered_DeviceIsNotIgnoredAndForwardsRe InputDeviceInfo info; mDevice->getDeviceInfo(&info); ASSERT_EQ(DEVICE_ID, info.getId()); - ASSERT_STREQ(DEVICE_NAME, info.getIdentifier().name.string()); + ASSERT_STREQ(DEVICE_NAME, info.getIdentifier().name.c_str()); ASSERT_EQ(AINPUT_KEYBOARD_TYPE_ALPHABETIC, info.getKeyboardType()); ASSERT_EQ(uint32_t(AINPUT_SOURCE_KEYBOARD | AINPUT_SOURCE_TOUCHSCREEN), info.getSources()); @@ -1570,7 +1572,7 @@ protected: mDevice = new InputDevice(mFakeContext, DEVICE_ID, DEVICE_GENERATION, DEVICE_CONTROLLER_NUMBER, identifier, DEVICE_CLASSES); - mFakeEventHub->addDevice(DEVICE_ID, String8(DEVICE_NAME), 0); + mFakeEventHub->addDevice(DEVICE_ID, DEVICE_NAME, 0); } virtual void TearDown() { @@ -1597,12 +1599,12 @@ protected: void setDisplayInfoAndReconfigure(int32_t displayId, int32_t width, int32_t height, int32_t orientation) { - mFakePolicy->setDisplayViewport(displayId, width, height, orientation, String8::empty()); + mFakePolicy->setDisplayViewport(displayId, width, height, orientation, ""); configureDevice(InputReaderConfiguration::CHANGE_DISPLAY_INFO); } void setVirtualDisplayInfoAndReconfigure(int32_t displayId, int32_t width, int32_t height, - int32_t orientation, const String8& uniqueId) { + int32_t orientation, const std::string& uniqueId) { mFakePolicy->setVirtualDisplayViewport(displayId, width, height, orientation, uniqueId); configureDevice(InputReaderConfiguration::CHANGE_DISPLAY_INFO); } @@ -3048,7 +3050,7 @@ void TouchInputMapperTest::prepareDisplay(int32_t orientation) { void TouchInputMapperTest::prepareVirtualDisplay(int32_t orientation) { setVirtualDisplayInfoAndReconfigure(VIRTUAL_DISPLAY_ID, VIRTUAL_DISPLAY_WIDTH, - VIRTUAL_DISPLAY_HEIGHT, orientation, String8(VIRTUAL_DISPLAY_UNIQUE_ID)); + VIRTUAL_DISPLAY_HEIGHT, orientation, VIRTUAL_DISPLAY_UNIQUE_ID); } void TouchInputMapperTest::prepareVirtualKeys() { -- cgit v1.2.3-59-g8ed1b From d634392abcc0522bd9b470aa2ff57397206bb336 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Fri, 6 Jul 2018 23:33:37 +0100 Subject: Add type to DisplayViewport Add type to DisplayViewport. Store a single array of viewports, but only allow 1 internal and 1 external viewport for now. DisplayManagerService now totally in charge of the viewports. Bug: 111108021 Test: atest -a libinput_tests inputflinger_tests Change-Id: Iac3dbc2e4a61b9609344db475d29bcdc7c167b1c --- include/input/DisplayViewport.h | 55 ++++++++++++---- services/inputflinger/InputReader.cpp | 80 +++++++----------------- services/inputflinger/InputReader.h | 8 +-- services/inputflinger/tests/InputReader_test.cpp | 19 +++--- 4 files changed, 83 insertions(+), 79 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/include/input/DisplayViewport.h b/include/input/DisplayViewport.h index 0f336dd2b8..0de3bb7a08 100644 --- a/include/input/DisplayViewport.h +++ b/include/input/DisplayViewport.h @@ -17,11 +17,37 @@ #ifndef _LIBINPUT_DISPLAY_VIEWPORT_H #define _LIBINPUT_DISPLAY_VIEWPORT_H +#include #include #include +using android::base::StringPrintf; + namespace android { +/** + * Describes the different type of viewports supported by input flinger. + * Keep in sync with values in InputManagerService.java. + */ +enum class ViewportType : int32_t { + VIEWPORT_INTERNAL = 1, + VIEWPORT_EXTERNAL = 2, + VIEWPORT_VIRTUAL = 3, +}; + +static const char* viewportTypeToString(ViewportType type) { + switch(type) { + case ViewportType::VIEWPORT_INTERNAL: + return "INTERNAL"; + case ViewportType::VIEWPORT_EXTERNAL: + return "EXTERNAL"; + case ViewportType::VIEWPORT_VIRTUAL: + return "VIRTUAL"; + default: + return "UNKNOWN"; + } +} + /* * Describes how coordinates are mapped on a physical display. * See com.android.server.display.DisplayViewport. @@ -40,12 +66,13 @@ struct DisplayViewport { int32_t deviceWidth; int32_t deviceHeight; std::string uniqueId; + ViewportType type; DisplayViewport() : displayId(ADISPLAY_ID_NONE), orientation(DISPLAY_ORIENTATION_0), logicalLeft(0), logicalTop(0), logicalRight(0), logicalBottom(0), physicalLeft(0), physicalTop(0), physicalRight(0), physicalBottom(0), - deviceWidth(0), deviceHeight(0), uniqueId() { + deviceWidth(0), deviceHeight(0), uniqueId(), type(ViewportType::VIEWPORT_INTERNAL) { } bool operator==(const DisplayViewport& other) const { @@ -61,7 +88,8 @@ struct DisplayViewport { && physicalBottom == other.physicalBottom && deviceWidth == other.deviceWidth && deviceHeight == other.deviceHeight - && uniqueId == other.uniqueId; + && uniqueId == other.uniqueId + && type == other.type; } bool operator!=(const DisplayViewport& other) const { @@ -86,17 +114,22 @@ struct DisplayViewport { deviceWidth = width; deviceHeight = height; uniqueId.clear(); + type = ViewportType::VIEWPORT_INTERNAL; } -}; -/** - * Describes the different type of viewports supported by input flinger. - * Keep in sync with values in InputManagerService.java. - */ -enum class ViewportType : int32_t { - VIEWPORT_INTERNAL = 1, - VIEWPORT_EXTERNAL = 2, - VIEWPORT_VIRTUAL = 3, + std::string toString() const { + return StringPrintf("Viewport %s: displayId=%d, orientation=%d, " + "logicalFrame=[%d, %d, %d, %d], " + "physicalFrame=[%d, %d, %d, %d], " + "deviceSize=[%d, %d]", + viewportTypeToString(type), + displayId, orientation, + logicalLeft, logicalTop, + logicalRight, logicalBottom, + physicalLeft, physicalTop, + physicalRight, physicalBottom, + deviceWidth, deviceHeight); + } }; } // namespace android diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 8f12129455..528e937712 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -258,64 +258,36 @@ static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType, const std::string& uniqueDisplayId, DisplayViewport* outViewport) const { - const DisplayViewport* viewport = nullptr; - if (viewportType == ViewportType::VIEWPORT_VIRTUAL && !uniqueDisplayId.empty()) { - - for (const DisplayViewport& currentViewport : mVirtualDisplays) { - if (currentViewport.uniqueId == uniqueDisplayId) { - viewport = ¤tViewport; - break; + for (const DisplayViewport& currentViewport : mDisplays) { + // for virtual displays, uniqueId must match + if (viewportType == ViewportType::VIEWPORT_VIRTUAL) { + if (currentViewport.type == ViewportType::VIEWPORT_VIRTUAL + && currentViewport.uniqueId == uniqueDisplayId) { + *outViewport = currentViewport; + return true; } + } else if (viewportType == currentViewport.type) { + // there can only be 1 internal or external viewport, for now + *outViewport = currentViewport; + return true; } - } else if (viewportType == ViewportType::VIEWPORT_EXTERNAL) { - viewport = &mExternalDisplay; - } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) { - viewport = &mInternalDisplay; - } - - if (viewport != nullptr && viewport->displayId >= 0) { - *outViewport = *viewport; - return true; } return false; } -void InputReaderConfiguration::setPhysicalDisplayViewport(ViewportType viewportType, - const DisplayViewport& viewport) { - if (viewportType == ViewportType::VIEWPORT_EXTERNAL) { - mExternalDisplay = viewport; - } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) { - mInternalDisplay = viewport; - } -} - -void InputReaderConfiguration::setVirtualDisplayViewports( - const Vector& viewports) { - mVirtualDisplays = viewports; +void InputReaderConfiguration::setDisplayViewports(const std::vector& viewports) { + mDisplays = viewports; } void InputReaderConfiguration::dump(std::string& dump) const { - dump += INDENT4 "ViewportInternal:\n"; - dumpViewport(dump, mInternalDisplay); - dump += INDENT4 "ViewportExternal:\n"; - dumpViewport(dump, mExternalDisplay); - dump += INDENT4 "ViewportVirtual:\n"; - for (const DisplayViewport& viewport : mVirtualDisplays) { + for (const DisplayViewport& viewport : mDisplays) { dumpViewport(dump, viewport); } } -void InputReaderConfiguration::dumpViewport(std::string& dump, const DisplayViewport& viewport) const { - dump += StringPrintf(INDENT5 "Viewport: displayId=%d, orientation=%d, uniqueId='%s', " - "logicalFrame=[%d, %d, %d, %d], " - "physicalFrame=[%d, %d, %d, %d], " - "deviceSize=[%d, %d]\n", - viewport.displayId, viewport.orientation, viewport.uniqueId.c_str(), - viewport.logicalLeft, viewport.logicalTop, - viewport.logicalRight, viewport.logicalBottom, - viewport.physicalLeft, viewport.physicalTop, - viewport.physicalRight, viewport.physicalBottom, - viewport.deviceWidth, viewport.deviceHeight); +void InputReaderConfiguration::dumpViewport(std::string& dump, const DisplayViewport& viewport) + const { + dump += StringPrintf(INDENT4 "%s\n", viewport.toString().c_str()); } @@ -3600,6 +3572,12 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { break; } + if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) { + ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str()); + naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight; + naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth; + } + mPhysicalWidth = naturalPhysicalWidth; mPhysicalHeight = naturalPhysicalHeight; mPhysicalLeft = naturalPhysicalLeft; @@ -3913,17 +3891,7 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { } void TouchInputMapper::dumpSurface(std::string& dump) { - dump += StringPrintf(INDENT3 "Viewport: displayId=%d, orientation=%d, " - "logicalFrame=[%d, %d, %d, %d], " - "physicalFrame=[%d, %d, %d, %d], " - "deviceSize=[%d, %d]\n", - mViewport.displayId, mViewport.orientation, - mViewport.logicalLeft, mViewport.logicalTop, - mViewport.logicalRight, mViewport.logicalBottom, - mViewport.physicalLeft, mViewport.physicalTop, - mViewport.physicalRight, mViewport.physicalBottom, - mViewport.deviceWidth, mViewport.deviceHeight); - + dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str()); dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth); dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight); dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft); diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h index c06168d5a2..74668b7de0 100644 --- a/services/inputflinger/InputReader.h +++ b/services/inputflinger/InputReader.h @@ -38,6 +38,7 @@ #include #include #include +#include // Maximum supported size of a vibration pattern. // Must be at least 2. @@ -203,17 +204,14 @@ struct InputReaderConfiguration { bool getDisplayViewport(ViewportType viewportType, const std::string& uniqueDisplayId, DisplayViewport* outViewport) const; - void setPhysicalDisplayViewport(ViewportType viewportType, const DisplayViewport& viewport); - void setVirtualDisplayViewports(const Vector& viewports); + void setDisplayViewports(const std::vector& viewports); void dump(std::string& dump) const; void dumpViewport(std::string& dump, const DisplayViewport& viewport) const; private: - DisplayViewport mInternalDisplay; - DisplayViewport mExternalDisplay; - Vector mVirtualDisplays; + std::vector mDisplays; }; diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index 9b985dc23d..b70ee09035 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -132,6 +132,7 @@ class FakeInputReaderPolicy : public InputReaderPolicyInterface { InputReaderConfiguration mConfig; KeyedVector > mPointerControllers; Vector mInputDevices; + std::vector mViewports; TouchAffineTransformation transform; protected: @@ -143,17 +144,20 @@ public: void setDisplayViewport(int32_t displayId, int32_t width, int32_t height, int32_t orientation, const std::string& uniqueId) { - DisplayViewport v = createDisplayViewport(displayId, width, height, orientation, uniqueId); + mViewports.clear(); // Set the size of both the internal and external display at the same time. - mConfig.setPhysicalDisplayViewport(ViewportType::VIEWPORT_INTERNAL, v); - mConfig.setPhysicalDisplayViewport(ViewportType::VIEWPORT_EXTERNAL, v); + mViewports.push_back(createDisplayViewport(displayId, width, height, orientation, uniqueId, + ViewportType::VIEWPORT_INTERNAL)); + mViewports.push_back(createDisplayViewport(displayId, width, height, orientation, uniqueId, + ViewportType::VIEWPORT_EXTERNAL)); + mConfig.setDisplayViewports(mViewports); } void setVirtualDisplayViewport(int32_t displayId, int32_t width, int32_t height, int32_t orientation, const std::string& uniqueId) { - Vector viewports; - viewports.push_back(createDisplayViewport(displayId, width, height, orientation, uniqueId)); - mConfig.setVirtualDisplayViewports(viewports); + mViewports.push_back(createDisplayViewport(displayId, width, height, orientation, uniqueId, + ViewportType::VIEWPORT_VIRTUAL)); + mConfig.setDisplayViewports(mViewports); } void addExcludedDeviceName(const std::string& deviceName) { @@ -203,7 +207,7 @@ public: private: DisplayViewport createDisplayViewport(int32_t displayId, int32_t width, int32_t height, - int32_t orientation, const std::string& uniqueId) { + int32_t orientation, const std::string& uniqueId, ViewportType type) { bool isRotated = (orientation == DISPLAY_ORIENTATION_90 || orientation == DISPLAY_ORIENTATION_270); DisplayViewport v; @@ -220,6 +224,7 @@ private: v.deviceWidth = isRotated ? height : width; v.deviceHeight = isRotated ? width : height; v.uniqueId = uniqueId; + v.type = type; return v; } -- cgit v1.2.3-59-g8ed1b From 2d0867fd7f943af6d6c33413370f71200f3c035d Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Wed, 8 Aug 2018 17:57:57 -0700 Subject: Changed getViewport strategy If a uniqueId is specified, then it must match. If it is not specified, then return the first display view port that has the requested type. This means that if an internal or external viewport does not have any uniqueId specified, there should only be 1 of each of these. Otherwise, there will be confusion, and the viewports are not kept in any specific order. Test: atest -a libinput_tests inputflinger_tests Bug: 111108021 Change-Id: I2437104ad98fa24334f2a8e19f1ca330bd873c93 --- services/inputflinger/InputReader.cpp | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 528e937712..57fc17fb50 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -259,17 +259,12 @@ static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType, const std::string& uniqueDisplayId, DisplayViewport* outViewport) const { for (const DisplayViewport& currentViewport : mDisplays) { - // for virtual displays, uniqueId must match - if (viewportType == ViewportType::VIEWPORT_VIRTUAL) { - if (currentViewport.type == ViewportType::VIEWPORT_VIRTUAL - && currentViewport.uniqueId == uniqueDisplayId) { + if (currentViewport.type == viewportType) { + if (uniqueDisplayId.empty() || + (!uniqueDisplayId.empty() && uniqueDisplayId == currentViewport.uniqueId)) { *outViewport = currentViewport; return true; } - } else if (viewportType == currentViewport.type) { - // there can only be 1 internal or external viewport, for now - *outViewport = currentViewport; - return true; } } return false; -- cgit v1.2.3-59-g8ed1b From 05a8fe28dbda15c38881462bf273fd258c674fd8 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Wed, 3 Oct 2018 16:38:28 -0700 Subject: Add DisplayViewport native tests The strategy for finding DisplayViewport has changed in ag/4723479. Add native tests for the new lookup logic here. The matching is done by uniqueId if it is specified, and by type only if it is not. Some additional refactors: - Return std::optional from getDisplayViewport - Make internal viewport optional. Expect normal operation if internal viewport is not present at all. Bug: 111108021 Test: atest -a inputflinger_tests Change-Id: I7d7d698438d0d691f5f07fef2da80e792a504978 --- services/inputflinger/InputReader.cpp | 33 +-- services/inputflinger/InputReader.h | 4 +- services/inputflinger/tests/Android.bp | 1 + services/inputflinger/tests/InputReader_test.cpp | 263 ++++++++++++++++++----- 4 files changed, 229 insertions(+), 72 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 57fc17fb50..0b73be0a98 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -256,18 +256,17 @@ static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, // --- InputReaderConfiguration --- -bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType, - const std::string& uniqueDisplayId, DisplayViewport* outViewport) const { +std::optional InputReaderConfiguration::getDisplayViewport( + ViewportType viewportType, const std::string& uniqueDisplayId) const { for (const DisplayViewport& currentViewport : mDisplays) { if (currentViewport.type == viewportType) { if (uniqueDisplayId.empty() || (!uniqueDisplayId.empty() && uniqueDisplayId == currentViewport.uniqueId)) { - *outViewport = currentViewport; - return true; + return std::make_optional(currentViewport); } } } - return false; + return std::nullopt; } void InputReaderConfiguration::setDisplayViewports(const std::vector& viewports) { @@ -2249,7 +2248,6 @@ void KeyboardInputMapper::dump(std::string& dump) { dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime); } - void KeyboardInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { InputMapper::configure(when, config, changes); @@ -2261,9 +2259,7 @@ void KeyboardInputMapper::configure(nsecs_t when, if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { if (mParameters.orientationAware) { - DisplayViewport dvp; - config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "", &dvp); - mViewport = dvp; + mViewport = config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, ""); } } } @@ -2672,9 +2668,10 @@ void CursorInputMapper::configure(nsecs_t when, if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { mOrientation = DISPLAY_ORIENTATION_0; if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { - DisplayViewport v; - if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "", &v)) { - mOrientation = v.orientation; + std::optional internalViewport = + config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, ""); + if (internalViewport) { + mOrientation = internalViewport->orientation; } } bumpGeneration(); @@ -2987,9 +2984,10 @@ void RotaryEncoderInputMapper::configure(nsecs_t when, mRotaryEncoderScrollAccumulator.configure(getDevice()); } if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { - DisplayViewport v; - if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "", &v)) { - mOrientation = v.orientation; + std::optional internalViewport = + config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, ""); + if (internalViewport) { + mOrientation = internalViewport->orientation; } else { mOrientation = DISPLAY_ORIENTATION_0; } @@ -3502,7 +3500,9 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL; } - if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) { + std::optional viewportToUse = + mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId); + if (!viewportToUse) { ALOGI(INDENT "Touch device '%s' could not query the properties of its associated " "display. The device will be inoperable until the display size " "becomes available.", @@ -3510,6 +3510,7 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { mDeviceMode = DEVICE_MODE_DISABLED; return; } + newViewport = *viewportToUse; } else { newViewport.setNonDisplayViewport(rawWidth, rawHeight); } diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h index 74668b7de0..3410bc9c5f 100644 --- a/services/inputflinger/InputReader.h +++ b/services/inputflinger/InputReader.h @@ -202,8 +202,8 @@ struct InputReaderConfiguration { pointerGestureZoomSpeedRatio(0.3f), showTouches(false) { } - bool getDisplayViewport(ViewportType viewportType, const std::string& uniqueDisplayId, - DisplayViewport* outViewport) const; + std::optional getDisplayViewport(ViewportType viewportType, + const std::string& uniqueDisplayId) const; void setDisplayViewports(const std::vector& viewports); diff --git a/services/inputflinger/tests/Android.bp b/services/inputflinger/tests/Android.bp index 517e63945d..a1cd71ca9d 100644 --- a/services/inputflinger/tests/Android.bp +++ b/services/inputflinger/tests/Android.bp @@ -10,6 +10,7 @@ cc_test { cflags: [ "-Wall", "-Werror", + "-Wextra", "-Wno-unused-parameter", ], shared_libs: [ diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index b70ee09035..707f3c5040 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -33,7 +33,7 @@ static const int32_t DISPLAY_HEIGHT = 800; static const int32_t VIRTUAL_DISPLAY_ID = 1; static const int32_t VIRTUAL_DISPLAY_WIDTH = 400; static const int32_t VIRTUAL_DISPLAY_HEIGHT = 500; -static const char* VIRTUAL_DISPLAY_UNIQUE_ID = "Vr-display-unique-ID"; +static const char* VIRTUAL_DISPLAY_UNIQUE_ID = "virtual:1"; // Error tolerance for floating point assertions. static const float EPSILON = 0.001f; @@ -142,21 +142,21 @@ public: FakeInputReaderPolicy() { } - void setDisplayViewport(int32_t displayId, int32_t width, int32_t height, int32_t orientation, - const std::string& uniqueId) { + virtual void clearViewports() { mViewports.clear(); - // Set the size of both the internal and external display at the same time. - mViewports.push_back(createDisplayViewport(displayId, width, height, orientation, uniqueId, - ViewportType::VIEWPORT_INTERNAL)); - mViewports.push_back(createDisplayViewport(displayId, width, height, orientation, uniqueId, - ViewportType::VIEWPORT_EXTERNAL)); mConfig.setDisplayViewports(mViewports); } - void setVirtualDisplayViewport(int32_t displayId, int32_t width, int32_t height, int32_t orientation, + std::optional getDisplayViewport(ViewportType viewportType, const std::string& uniqueId) { - mViewports.push_back(createDisplayViewport(displayId, width, height, orientation, uniqueId, - ViewportType::VIEWPORT_VIRTUAL)); + return mConfig.getDisplayViewport(viewportType, uniqueId); + } + + void addDisplayViewport(int32_t displayId, int32_t width, int32_t height, int32_t orientation, + const std::string& uniqueId, ViewportType viewportType) { + const DisplayViewport viewport = createDisplayViewport(displayId, width, height, + orientation, uniqueId, viewportType); + mViewports.push_back(viewport); mConfig.setDisplayViewports(mViewports); } @@ -1080,6 +1080,146 @@ protected: friend class InputReaderTest; }; +// --- InputReaderPolicyTest --- +class InputReaderPolicyTest : public testing::Test { + protected: + sp mFakePolicy; + + virtual void SetUp() { + mFakePolicy = new FakeInputReaderPolicy(); + } + virtual void TearDown() { + mFakePolicy.clear(); + } +}; + +/** + * Check that empty set of viewports is an acceptable configuration. + * Also try to get internal viewport two different ways - by type and by uniqueId. + * + * There will be confusion if two viewports with empty uniqueId and identical type are present. + * Such configuration is not currently allowed. + */ +TEST_F(InputReaderPolicyTest, Viewports_GetCleared) { + const std::string uniqueId = "local:0"; + + // We didn't add any viewports yet, so there shouldn't be any. + std::optional internalViewport = + mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, uniqueId); + ASSERT_FALSE(internalViewport); + + // Add an internal viewport, then clear it + mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, + DISPLAY_ORIENTATION_0, uniqueId, ViewportType::VIEWPORT_INTERNAL); + + // Check matching by uniqueId + internalViewport = mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, uniqueId); + ASSERT_TRUE(internalViewport); + + // Check matching by viewport type + internalViewport = mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, ""); + ASSERT_TRUE(internalViewport); + + mFakePolicy->clearViewports(); + // Make sure nothing is found after clear + internalViewport = mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, uniqueId); + ASSERT_FALSE(internalViewport); + internalViewport = mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, ""); + ASSERT_FALSE(internalViewport); +} + +TEST_F(InputReaderPolicyTest, Viewports_GetByType) { + const std::string internalUniqueId = "local:0"; + const std::string externalUniqueId = "local:1"; + const std::string virtualUniqueId1 = "virtual:2"; + const std::string virtualUniqueId2 = "virtual:3"; + constexpr int32_t virtualDisplayId1 = 2; + constexpr int32_t virtualDisplayId2 = 3; + + // Add an internal viewport + mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, + DISPLAY_ORIENTATION_0, internalUniqueId, ViewportType::VIEWPORT_INTERNAL); + // Add an external viewport + mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, + DISPLAY_ORIENTATION_0, externalUniqueId, ViewportType::VIEWPORT_EXTERNAL); + // Add an virtual viewport + mFakePolicy->addDisplayViewport(virtualDisplayId1, DISPLAY_WIDTH, DISPLAY_HEIGHT, + DISPLAY_ORIENTATION_0, virtualUniqueId1, ViewportType::VIEWPORT_VIRTUAL); + // Add another virtual viewport + mFakePolicy->addDisplayViewport(virtualDisplayId2, DISPLAY_WIDTH, DISPLAY_HEIGHT, + DISPLAY_ORIENTATION_0, virtualUniqueId2, ViewportType::VIEWPORT_VIRTUAL); + + // Check matching by type for internal + std::optional internalViewport = + mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, ""); + ASSERT_TRUE(internalViewport); + ASSERT_EQ(internalUniqueId, internalViewport->uniqueId); + + // Check matching by type for external + std::optional externalViewport = + mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_EXTERNAL, ""); + ASSERT_TRUE(externalViewport); + ASSERT_EQ(externalUniqueId, externalViewport->uniqueId); + + // Check matching by uniqueId for virtual viewport #1 + std::optional virtualViewport1 = + mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_VIRTUAL, virtualUniqueId1); + ASSERT_TRUE(virtualViewport1); + ASSERT_EQ(virtualUniqueId1, virtualViewport1->uniqueId); + ASSERT_EQ(virtualDisplayId1, virtualViewport1->displayId); + + // Check matching by uniqueId for virtual viewport #2 + std::optional virtualViewport2 = + mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_VIRTUAL, virtualUniqueId2); + ASSERT_TRUE(virtualViewport2); + ASSERT_EQ(virtualUniqueId2, virtualViewport2->uniqueId); + ASSERT_EQ(virtualDisplayId2, virtualViewport2->displayId); +} + + +/** + * We can have 2 viewports of the same kind. We can distinguish them by uniqueId, and confirm + * that lookup works by checking display id. + * Check that 2 viewports of each kind is possible, for all existing viewport types. + */ +TEST_F(InputReaderPolicyTest, Viewports_TwoOfSameType) { + const std::string uniqueId1 = "uniqueId1"; + const std::string uniqueId2 = "uniqueId2"; + constexpr int32_t displayId1 = 2; + constexpr int32_t displayId2 = 3; + + std::vector types = {ViewportType::VIEWPORT_INTERNAL, + ViewportType::VIEWPORT_EXTERNAL, ViewportType::VIEWPORT_VIRTUAL}; + for (const ViewportType& type : types) { + mFakePolicy->clearViewports(); + // Add a viewport + mFakePolicy->addDisplayViewport(displayId1, DISPLAY_WIDTH, DISPLAY_HEIGHT, + DISPLAY_ORIENTATION_0, uniqueId1, type); + // Add another viewport + mFakePolicy->addDisplayViewport(displayId2, DISPLAY_WIDTH, DISPLAY_HEIGHT, + DISPLAY_ORIENTATION_0, uniqueId2, type); + + // Check that correct display viewport was returned by comparing the display IDs. + std::optional viewport1 = mFakePolicy->getDisplayViewport(type, uniqueId1); + ASSERT_TRUE(viewport1); + ASSERT_EQ(displayId1, viewport1->displayId); + ASSERT_EQ(type, viewport1->type); + + std::optional viewport2 = mFakePolicy->getDisplayViewport(type, uniqueId2); + ASSERT_TRUE(viewport2); + ASSERT_EQ(displayId2, viewport2->displayId); + ASSERT_EQ(type, viewport2->type); + + // When there are multiple viewports of the same kind, and uniqueId is not specified + // in the call to getDisplayViewport, then that situation is not supported. + // The viewports can be stored in any order, so we cannot rely on the order, since that + // is just implementation detail. + // However, we can check that it still returns *a* viewport, we just cannot assert + // which one specifically is returned. + std::optional someViewport = mFakePolicy->getDisplayViewport(type, ""); + ASSERT_TRUE(someViewport); + } +} // --- InputReaderTest --- @@ -1603,15 +1743,14 @@ protected: } void setDisplayInfoAndReconfigure(int32_t displayId, int32_t width, int32_t height, - int32_t orientation) { - mFakePolicy->setDisplayViewport(displayId, width, height, orientation, ""); + int32_t orientation, const std::string& uniqueId, ViewportType viewportType) { + mFakePolicy->addDisplayViewport( + displayId, width, height, orientation, uniqueId, viewportType); configureDevice(InputReaderConfiguration::CHANGE_DISPLAY_INFO); } - void setVirtualDisplayInfoAndReconfigure(int32_t displayId, int32_t width, int32_t height, - int32_t orientation, const std::string& uniqueId) { - mFakePolicy->setVirtualDisplayViewport(displayId, width, height, orientation, uniqueId); - configureDevice(InputReaderConfiguration::CHANGE_DISPLAY_INFO); + void clearViewports() { + mFakePolicy->clearViewports(); } static void process(InputMapper* mapper, nsecs_t when, int32_t deviceId, int32_t type, @@ -1715,12 +1854,24 @@ TEST_F(SwitchInputMapperTest, Process) { class KeyboardInputMapperTest : public InputMapperTest { protected: + const std::string UNIQUE_ID = "local:0"; + + void prepareDisplay(int32_t orientation); + void testDPadKeyRotation(KeyboardInputMapper* mapper, int32_t originalScanCode, int32_t originalKeyCode, int32_t rotatedKeyCode); }; +/* Similar to setDisplayInfoAndReconfigure, but pre-populates all parameters except for the + * orientation. + */ +void KeyboardInputMapperTest::prepareDisplay(int32_t orientation) { + setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, + orientation, UNIQUE_ID, ViewportType::VIEWPORT_INTERNAL); +} + void KeyboardInputMapperTest::testDPadKeyRotation(KeyboardInputMapper* mapper, - int32_t originalScanCode, int32_t, int32_t rotatedKeyCode) { + int32_t originalScanCode, int32_t originalKeyCode, int32_t rotatedKeyCode) { NotifyKeyArgs args; process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, originalScanCode, 1); @@ -1908,9 +2059,7 @@ TEST_F(KeyboardInputMapperTest, Process_WhenNotOrientationAware_ShouldNotRotateD AINPUT_SOURCE_KEYBOARD, AINPUT_KEYBOARD_TYPE_ALPHABETIC); addMapperAndConfigure(mapper); - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_90); + prepareDisplay(DISPLAY_ORIENTATION_90); ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_UP)); ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, @@ -1932,9 +2081,7 @@ TEST_F(KeyboardInputMapperTest, Process_WhenOrientationAware_ShouldRotateDPad) { addConfigurationProperty("keyboard.orientationAware", "1"); addMapperAndConfigure(mapper); - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_0); + prepareDisplay(DISPLAY_ORIENTATION_0); ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_UP)); ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, @@ -1944,9 +2091,8 @@ TEST_F(KeyboardInputMapperTest, Process_WhenOrientationAware_ShouldRotateDPad) { ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_LEFT)); - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_90); + clearViewports(); + prepareDisplay(DISPLAY_ORIENTATION_90); ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT)); ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, @@ -1956,9 +2102,8 @@ TEST_F(KeyboardInputMapperTest, Process_WhenOrientationAware_ShouldRotateDPad) { ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN)); - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_180); + clearViewports(); + prepareDisplay(DISPLAY_ORIENTATION_180); ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_DOWN)); ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, @@ -1968,9 +2113,8 @@ TEST_F(KeyboardInputMapperTest, Process_WhenOrientationAware_ShouldRotateDPad) { ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_LEFT, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_RIGHT)); - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_270); + clearViewports(); + prepareDisplay(DISPLAY_ORIENTATION_270); ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, KEY_UP, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_RIGHT)); ASSERT_NO_FATAL_FAILURE(testDPadKeyRotation(mapper, @@ -1983,19 +2127,16 @@ TEST_F(KeyboardInputMapperTest, Process_WhenOrientationAware_ShouldRotateDPad) { // Special case: if orientation changes while key is down, we still emit the same keycode // in the key up as we did in the key down. NotifyKeyArgs args; - - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_270); + clearViewports(); + prepareDisplay(DISPLAY_ORIENTATION_270); process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 1); ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action); ASSERT_EQ(KEY_UP, args.scanCode); ASSERT_EQ(AKEYCODE_DPAD_RIGHT, args.keyCode); - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_180); + clearViewports(); + prepareDisplay(DISPLAY_ORIENTATION_180); process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 0); ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action); @@ -2020,8 +2161,7 @@ TEST_F(KeyboardInputMapperTest, DisplayIdConfigurationChange_NotOrientationAware ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); ASSERT_EQ(ADISPLAY_ID_NONE, args.displayId); - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0); + prepareDisplay(DISPLAY_ORIENTATION_0); process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 1); ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 0); @@ -2043,8 +2183,8 @@ TEST_F(KeyboardInputMapperTest, DisplayIdConfigurationChange_OrientationAware) { // Display id should be ADISPLAY_ID_NONE without any display configuration. // ^--- already checked by the previous test - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0); + setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0, + UNIQUE_ID, ViewportType::VIEWPORT_INTERNAL); process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 1); ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 0); @@ -2052,8 +2192,9 @@ TEST_F(KeyboardInputMapperTest, DisplayIdConfigurationChange_OrientationAware) { ASSERT_EQ(DISPLAY_ID, args.displayId); constexpr int32_t newDisplayId = 2; - setDisplayInfoAndReconfigure(newDisplayId, - DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0); + clearViewports(); + setDisplayInfoAndReconfigure(newDisplayId, DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0, + UNIQUE_ID, ViewportType::VIEWPORT_INTERNAL); process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 1); ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); process(mapper, ARBITRARY_TIME, DEVICE_ID, EV_KEY, KEY_UP, 0); @@ -2484,9 +2625,12 @@ TEST_F(CursorInputMapperTest, Process_WhenNotOrientationAware_ShouldNotRotateMot addConfigurationProperty("cursor.mode", "navigation"); addMapperAndConfigure(mapper); + const std::string uniqueId = "local:0"; + const ViewportType viewportType = ViewportType::VIEWPORT_INTERNAL; + setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_90); + DISPLAY_ORIENTATION_90, uniqueId, viewportType); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, 0, 1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, 1, 1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 0, 1, 0)); @@ -2503,8 +2647,11 @@ TEST_F(CursorInputMapperTest, Process_WhenOrientationAware_ShouldRotateMotions) addConfigurationProperty("cursor.orientationAware", "1"); addMapperAndConfigure(mapper); + const std::string uniqueId = "local:0"; + const ViewportType viewportType = ViewportType::VIEWPORT_INTERNAL; + setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0); + DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0, uniqueId, viewportType); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, 0, 1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, 1, 1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 0, 1, 0)); @@ -2515,7 +2662,7 @@ TEST_F(CursorInputMapperTest, Process_WhenOrientationAware_ShouldRotateMotions) ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 1, -1, 1)); setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_90); + DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_90, uniqueId, viewportType); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, 1, 0)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, 1, -1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 0, 0, -1)); @@ -2526,7 +2673,7 @@ TEST_F(CursorInputMapperTest, Process_WhenOrientationAware_ShouldRotateMotions) ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 1, 1, 1)); setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_180); + DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_180, uniqueId, viewportType); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, 0, -1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, -1, -1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 0, -1, 0)); @@ -2537,7 +2684,7 @@ TEST_F(CursorInputMapperTest, Process_WhenOrientationAware_ShouldRotateMotions) ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 1, 1, -1)); setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_270); + DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_270, uniqueId, viewportType); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, -1, 0)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, -1, 1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 0, 0, 1)); @@ -2982,6 +3129,8 @@ protected: static const VirtualKeyDefinition VIRTUAL_KEYS[2]; + const std::string UNIQUE_ID = "local:0"; + enum Axes { POSITION = 1 << 0, TOUCH = 1 << 1, @@ -3050,12 +3199,14 @@ const VirtualKeyDefinition TouchInputMapperTest::VIRTUAL_KEYS[2] = { }; void TouchInputMapperTest::prepareDisplay(int32_t orientation) { - setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, orientation); + setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, orientation, + UNIQUE_ID, ViewportType::VIEWPORT_INTERNAL); } void TouchInputMapperTest::prepareVirtualDisplay(int32_t orientation) { - setVirtualDisplayInfoAndReconfigure(VIRTUAL_DISPLAY_ID, VIRTUAL_DISPLAY_WIDTH, - VIRTUAL_DISPLAY_HEIGHT, orientation, VIRTUAL_DISPLAY_UNIQUE_ID); + setDisplayInfoAndReconfigure(VIRTUAL_DISPLAY_ID, VIRTUAL_DISPLAY_WIDTH, + VIRTUAL_DISPLAY_HEIGHT, orientation, + VIRTUAL_DISPLAY_UNIQUE_ID, ViewportType::VIEWPORT_VIRTUAL); } void TouchInputMapperTest::prepareVirtualKeys() { @@ -3784,6 +3935,7 @@ TEST_F(SingleTouchInputMapperTest, Process_WhenOrientationAware_RotatesMotions) NotifyMotionArgs args; // Rotation 0. + clearViewports(); prepareDisplay(DISPLAY_ORIENTATION_0); processDown(mapper, toRawX(50), toRawY(75)); processSync(mapper); @@ -3797,6 +3949,7 @@ TEST_F(SingleTouchInputMapperTest, Process_WhenOrientationAware_RotatesMotions) ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled()); // Rotation 90. + clearViewports(); prepareDisplay(DISPLAY_ORIENTATION_90); processDown(mapper, RAW_X_MAX - toRawX(75) + RAW_X_MIN, toRawY(50)); processSync(mapper); @@ -3810,6 +3963,7 @@ TEST_F(SingleTouchInputMapperTest, Process_WhenOrientationAware_RotatesMotions) ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled()); // Rotation 180. + clearViewports(); prepareDisplay(DISPLAY_ORIENTATION_180); processDown(mapper, RAW_X_MAX - toRawX(50) + RAW_X_MIN, RAW_Y_MAX - toRawY(75) + RAW_Y_MIN); processSync(mapper); @@ -3823,6 +3977,7 @@ TEST_F(SingleTouchInputMapperTest, Process_WhenOrientationAware_RotatesMotions) ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled()); // Rotation 270. + clearViewports(); prepareDisplay(DISPLAY_ORIENTATION_270); processDown(mapper, toRawX(75), RAW_Y_MAX - toRawY(50) + RAW_Y_MIN); processSync(mapper); -- cgit v1.2.3-59-g8ed1b From cd7ac1ecad7c53767484d13ca3425873a3eae126 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Mon, 15 Oct 2018 13:39:50 -0700 Subject: Remove implicit fallthrough exception Implicit fallthrough has already been fixed, but we also need to clean up Android.bp file. Bug: none Test: build only Change-Id: Ibcf274fb1cfacfb7bba6c6f66d6bf3b2320c85b1 --- services/inputflinger/Android.bp | 2 -- services/inputflinger/InputReader.cpp | 2 +- services/inputflinger/tests/InputReader_test.cpp | 4 ++-- 3 files changed, 3 insertions(+), 5 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/Android.bp b/services/inputflinger/Android.bp index 622a623644..9a65452f60 100644 --- a/services/inputflinger/Android.bp +++ b/services/inputflinger/Android.bp @@ -41,8 +41,6 @@ cc_library_shared { "-Wall", "-Wextra", "-Werror", - // Allow implicit fallthroughs in InputReader.cpp until they are fixed. - "-Wno-error=implicit-fallthrough", "-Wno-unused-parameter", // TODO: Move inputflinger to its own process and mark it hidden //-fvisibility=hidden diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 869a2fc170..869bd71487 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -1041,7 +1041,7 @@ void InputDevice::setEnabled(bool enabled, nsecs_t when) { void InputDevice::dump(std::string& dump) { InputDeviceInfo deviceInfo; - getDeviceInfo(& deviceInfo); + getDeviceInfo(&deviceInfo); dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(), deviceInfo.getDisplayName().c_str()); diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index 707f3c5040..6114f51c46 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -1082,7 +1082,7 @@ protected: // --- InputReaderPolicyTest --- class InputReaderPolicyTest : public testing::Test { - protected: +protected: sp mFakePolicy; virtual void SetUp() { @@ -1101,7 +1101,7 @@ class InputReaderPolicyTest : public testing::Test { * Such configuration is not currently allowed. */ TEST_F(InputReaderPolicyTest, Viewports_GetCleared) { - const std::string uniqueId = "local:0"; + static const std::string uniqueId = "local:0"; // We didn't add any viewports yet, so there shouldn't be any. std::optional internalViewport = -- cgit v1.2.3-59-g8ed1b From 26e34d9d6bb4990891a50af65f573f82deea1f45 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Mon, 12 Nov 2018 13:51:26 -0800 Subject: Add getRawWidth() and getRawHeight() Minor refactor to move the computation of raw width and raw height into RawPointerAxes. This is needed because a future CL will use these functions again. Bug: 116239493 Test: atest inputflinger_tests Change-Id: I25086f9ba370f9891851e87a2b2375af867409f3 --- services/inputflinger/InputReader.cpp | 8 ++++---- services/inputflinger/InputReader.h | 2 ++ 2 files changed, 6 insertions(+), 4 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 869bd71487..e85e6efe5d 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -3480,8 +3480,8 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { } // Raw width and height in the natural orientation. - int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1; - int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1; + int32_t rawWidth = mRawPointerAxes.getRawWidth(); + int32_t rawHeight = mRawPointerAxes.getRawHeight(); // Get associated display dimensions. DisplayViewport newViewport; @@ -3913,8 +3913,8 @@ void TouchInputMapper::configureVirtualKeys() { int32_t touchScreenLeft = mRawPointerAxes.x.minValue; int32_t touchScreenTop = mRawPointerAxes.y.minValue; - int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1; - int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1; + int32_t touchScreenWidth = mRawPointerAxes.getRawWidth(); + int32_t touchScreenHeight = mRawPointerAxes.getRawHeight(); for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) { const VirtualKeyDefinition& virtualKeyDefinition = diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h index 3410bc9c5f..9b0007a2b8 100644 --- a/services/inputflinger/InputReader.h +++ b/services/inputflinger/InputReader.h @@ -772,6 +772,8 @@ struct RawPointerAxes { RawAbsoluteAxisInfo slot; RawPointerAxes(); + inline int32_t getRawWidth() const { return x.maxValue - x.minValue + 1; } + inline int32_t getRawHeight() const { return y.maxValue - y.minValue + 1; } void clear(); }; -- cgit v1.2.3-59-g8ed1b From 29c95334ebb5346c92cff9a9c928af175644ad8f Mon Sep 17 00:00:00 2001 From: Prabir Pradhan Date: Wed, 14 Nov 2018 20:14:11 -0800 Subject: Split InputFlinger into multiple libraries This is the InputFlinger FE/BE split as detailed in go/arc++inputflinger-split. We split libinputflinger into the following dynamic libraries: - libinputflinger: Acts as the frontend for inputflinger and implements InputDispatcher and InputManager. - libinputreader: Acts as the backend for inputflinger and impliements InputReader and EventHub, and adds a InputReaderFactory to create the InputReader. - libinputflinger_base: Contains the common logic that is shared throughout InputFlinger, and contains the definitions for InputReaderInterface (in InputReaderBase.h) and InputListenerInterface (in InputListener.h). Bug: 119264687 Test: manual: Build, run, and test input (touch, mouse) Change-Id: I8567635f48de58ee8e5bdb0f8a17a73ea6fa37ef --- services/inputflinger/Android.bp | 92 +++- services/inputflinger/EventHub.h | 470 --------------------- services/inputflinger/InputListener.h | 207 --------- services/inputflinger/InputManager.cpp | 12 +- services/inputflinger/InputManager.h | 8 +- services/inputflinger/InputReader.cpp | 56 --- services/inputflinger/InputReader.h | 308 +------------- services/inputflinger/InputReaderBase.cpp | 91 ++++ services/inputflinger/InputReaderFactory.cpp | 28 ++ services/inputflinger/PointerControllerInterface.h | 105 ----- services/inputflinger/include/EventHub.h | 470 +++++++++++++++++++++ services/inputflinger/include/InputListener.h | 207 +++++++++ services/inputflinger/include/InputReaderBase.h | 342 +++++++++++++++ services/inputflinger/include/InputReaderFactory.h | 29 ++ .../include/PointerControllerInterface.h | 105 +++++ services/inputflinger/tests/Android.bp | 2 + 16 files changed, 1364 insertions(+), 1168 deletions(-) delete mode 100644 services/inputflinger/EventHub.h delete mode 100644 services/inputflinger/InputListener.h create mode 100644 services/inputflinger/InputReaderBase.cpp create mode 100644 services/inputflinger/InputReaderFactory.cpp delete mode 100644 services/inputflinger/PointerControllerInterface.h create mode 100644 services/inputflinger/include/EventHub.h create mode 100644 services/inputflinger/include/InputListener.h create mode 100644 services/inputflinger/include/InputReaderBase.h create mode 100644 services/inputflinger/include/InputReaderFactory.h create mode 100644 services/inputflinger/include/PointerControllerInterface.h (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/Android.bp b/services/inputflinger/Android.bp index 7812cb2a61..4a8b6139ee 100644 --- a/services/inputflinger/Android.bp +++ b/services/inputflinger/Android.bp @@ -18,16 +18,59 @@ cc_library_shared { cpp_std: "c++17", srcs: [ - "EventHub.cpp", "InputDispatcher.cpp", - "InputListener.cpp", "InputManager.cpp", - "InputReader.cpp", ], shared_libs: [ + "libinputflinger_base", + "libinputreader", "libbase", "libbinder", + "libcutils", + "libinput", + "liblog", + "libutils", + "libui", + ], + + cflags: [ + "-Wall", + "-Wextra", + "-Werror", + "-Wno-unused-parameter", + // TODO: Move inputflinger to its own process and mark it hidden + //-fvisibility=hidden + ], + + export_include_dirs: [ + ".", + "include", + ], + +} + + +cc_library_headers { + name: "libinputflinger_headers", + + export_include_dirs: ["include"], +} + +cc_library_shared { + name: "libinputreader", + + cpp_std: "c++17", + + srcs: [ + "EventHub.cpp", + "InputReader.cpp", + "InputReaderFactory.cpp", + ], + + shared_libs: [ + "libinputflinger_base", + "libbase", "libcrypto", "libcutils", "libinput", @@ -38,16 +81,53 @@ cc_library_shared { "libutils" ], + header_libs: [ + "libinputflinger_headers", + ], + + export_header_lib_headers: [ + "libinputflinger_headers", + ], + cflags: [ "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", - // TODO: Move inputflinger to its own process and mark it hidden - //-fvisibility=hidden + ], +} + +cc_library_shared { + name: "libinputflinger_base", + + cpp_std: "c++17", + + srcs: [ + "InputListener.cpp", + "InputReaderBase.cpp", ], - export_include_dirs: ["."], + shared_libs: [ + "libbase", + "libinput", + "liblog", + "libutils", + ], + + header_libs: [ + "libinputflinger_headers", + ], + + export_header_lib_headers: [ + "libinputflinger_headers", + ], + + cflags: [ + "-Wall", + "-Wextra", + "-Werror", + "-Wno-unused-parameter", + ], } subdirs = [ diff --git a/services/inputflinger/EventHub.h b/services/inputflinger/EventHub.h deleted file mode 100644 index e2c7e82f9f..0000000000 --- a/services/inputflinger/EventHub.h +++ /dev/null @@ -1,470 +0,0 @@ -/* - * Copyright (C) 2005 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -#ifndef _RUNTIME_EVENT_HUB_H -#define _RUNTIME_EVENT_HUB_H - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -/* Convenience constants. */ - -#define BTN_FIRST 0x100 // first button code -#define BTN_LAST 0x15f // last button code - -namespace android { - -enum { - // Device id of a special "virtual" keyboard that is always present. - VIRTUAL_KEYBOARD_ID = -1, - // Device id of the "built-in" keyboard if there is one. - BUILT_IN_KEYBOARD_ID = 0, -}; - -/* - * A raw event as retrieved from the EventHub. - */ -struct RawEvent { - nsecs_t when; - int32_t deviceId; - int32_t type; - int32_t code; - int32_t value; -}; - -/* Describes an absolute axis. */ -struct RawAbsoluteAxisInfo { - bool valid; // true if the information is valid, false otherwise - - int32_t minValue; // minimum value - int32_t maxValue; // maximum value - int32_t flat; // center flat position, eg. flat == 8 means center is between -8 and 8 - int32_t fuzz; // error tolerance, eg. fuzz == 4 means value is +/- 4 due to noise - int32_t resolution; // resolution in units per mm or radians per mm - - inline void clear() { - valid = false; - minValue = 0; - maxValue = 0; - flat = 0; - fuzz = 0; - resolution = 0; - } -}; - -/* - * Input device classes. - */ -enum { - /* The input device is a keyboard or has buttons. */ - INPUT_DEVICE_CLASS_KEYBOARD = 0x00000001, - - /* The input device is an alpha-numeric keyboard (not just a dial pad). */ - INPUT_DEVICE_CLASS_ALPHAKEY = 0x00000002, - - /* The input device is a touchscreen or a touchpad (either single-touch or multi-touch). */ - INPUT_DEVICE_CLASS_TOUCH = 0x00000004, - - /* The input device is a cursor device such as a trackball or mouse. */ - INPUT_DEVICE_CLASS_CURSOR = 0x00000008, - - /* The input device is a multi-touch touchscreen. */ - INPUT_DEVICE_CLASS_TOUCH_MT = 0x00000010, - - /* The input device is a directional pad (implies keyboard, has DPAD keys). */ - INPUT_DEVICE_CLASS_DPAD = 0x00000020, - - /* The input device is a gamepad (implies keyboard, has BUTTON keys). */ - INPUT_DEVICE_CLASS_GAMEPAD = 0x00000040, - - /* The input device has switches. */ - INPUT_DEVICE_CLASS_SWITCH = 0x00000080, - - /* The input device is a joystick (implies gamepad, has joystick absolute axes). */ - INPUT_DEVICE_CLASS_JOYSTICK = 0x00000100, - - /* The input device has a vibrator (supports FF_RUMBLE). */ - INPUT_DEVICE_CLASS_VIBRATOR = 0x00000200, - - /* The input device has a microphone. */ - INPUT_DEVICE_CLASS_MIC = 0x00000400, - - /* The input device is an external stylus (has data we want to fuse with touch data). */ - INPUT_DEVICE_CLASS_EXTERNAL_STYLUS = 0x00000800, - - /* The input device has a rotary encoder */ - INPUT_DEVICE_CLASS_ROTARY_ENCODER = 0x00001000, - - /* The input device is virtual (not a real device, not part of UI configuration). */ - INPUT_DEVICE_CLASS_VIRTUAL = 0x40000000, - - /* The input device is external (not built-in). */ - INPUT_DEVICE_CLASS_EXTERNAL = 0x80000000, -}; - -/* - * Gets the class that owns an axis, in cases where multiple classes might claim - * the same axis for different purposes. - */ -extern uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses); - -/* - * Grand Central Station for events. - * - * The event hub aggregates input events received across all known input - * devices on the system, including devices that may be emulated by the simulator - * environment. In addition, the event hub generates fake input events to indicate - * when devices are added or removed. - * - * The event hub provides a stream of input events (via the getEvent function). - * It also supports querying the current actual state of input devices such as identifying - * which keys are currently down. Finally, the event hub keeps track of the capabilities of - * individual input devices, such as their class and the set of key codes that they support. - */ -class EventHubInterface : public virtual RefBase { -protected: - EventHubInterface() { } - virtual ~EventHubInterface() { } - -public: - // Synthetic raw event type codes produced when devices are added or removed. - enum { - // Sent when a device is added. - DEVICE_ADDED = 0x10000000, - // Sent when a device is removed. - DEVICE_REMOVED = 0x20000000, - // Sent when all added/removed devices from the most recent scan have been reported. - // This event is always sent at least once. - FINISHED_DEVICE_SCAN = 0x30000000, - - FIRST_SYNTHETIC_EVENT = DEVICE_ADDED, - }; - - virtual uint32_t getDeviceClasses(int32_t deviceId) const = 0; - - virtual InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const = 0; - - virtual int32_t getDeviceControllerNumber(int32_t deviceId) const = 0; - - virtual void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const = 0; - - virtual status_t getAbsoluteAxisInfo(int32_t deviceId, int axis, - RawAbsoluteAxisInfo* outAxisInfo) const = 0; - - virtual bool hasRelativeAxis(int32_t deviceId, int axis) const = 0; - - virtual bool hasInputProperty(int32_t deviceId, int property) const = 0; - - virtual status_t mapKey(int32_t deviceId, - int32_t scanCode, int32_t usageCode, int32_t metaState, - int32_t* outKeycode, int32_t *outMetaState, uint32_t* outFlags) const = 0; - - virtual status_t mapAxis(int32_t deviceId, int32_t scanCode, - AxisInfo* outAxisInfo) const = 0; - - // Sets devices that are excluded from opening. - // This can be used to ignore input devices for sensors. - virtual void setExcludedDevices(const std::vector& devices) = 0; - - /* - * Wait for events to become available and returns them. - * After returning, the EventHub holds onto a wake lock until the next call to getEvent. - * This ensures that the device will not go to sleep while the event is being processed. - * If the device needs to remain awake longer than that, then the caller is responsible - * for taking care of it (say, by poking the power manager user activity timer). - * - * The timeout is advisory only. If the device is asleep, it will not wake just to - * service the timeout. - * - * Returns the number of events obtained, or 0 if the timeout expired. - */ - virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) = 0; - - /* - * Query current input state. - */ - virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const = 0; - virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const = 0; - virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const = 0; - virtual status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis, - int32_t* outValue) const = 0; - - /* - * Examine key input devices for specific framework keycode support - */ - virtual bool markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes, - uint8_t* outFlags) const = 0; - - virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const = 0; - - /* LED related functions expect Android LED constants, not scan codes or HID usages */ - virtual bool hasLed(int32_t deviceId, int32_t led) const = 0; - virtual void setLedState(int32_t deviceId, int32_t led, bool on) = 0; - - virtual void getVirtualKeyDefinitions(int32_t deviceId, - Vector& outVirtualKeys) const = 0; - - virtual sp getKeyCharacterMap(int32_t deviceId) const = 0; - virtual bool setKeyboardLayoutOverlay(int32_t deviceId, const sp& map) = 0; - - /* Control the vibrator. */ - virtual void vibrate(int32_t deviceId, nsecs_t duration) = 0; - virtual void cancelVibrate(int32_t deviceId) = 0; - - /* Requests the EventHub to reopen all input devices on the next call to getEvents(). */ - virtual void requestReopenDevices() = 0; - - /* Wakes up getEvents() if it is blocked on a read. */ - virtual void wake() = 0; - - /* Dump EventHub state to a string. */ - virtual void dump(std::string& dump) = 0; - - /* Called by the heatbeat to ensures that the reader has not deadlocked. */ - virtual void monitor() = 0; - - /* Return true if the device is enabled. */ - virtual bool isDeviceEnabled(int32_t deviceId) = 0; - - /* Enable an input device */ - virtual status_t enableDevice(int32_t deviceId) = 0; - - /* Disable an input device. Closes file descriptor to that device. */ - virtual status_t disableDevice(int32_t deviceId) = 0; -}; - -class EventHub : public EventHubInterface -{ -public: - EventHub(); - - virtual uint32_t getDeviceClasses(int32_t deviceId) const; - - virtual InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const; - - virtual int32_t getDeviceControllerNumber(int32_t deviceId) const; - - virtual void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const; - - virtual status_t getAbsoluteAxisInfo(int32_t deviceId, int axis, - RawAbsoluteAxisInfo* outAxisInfo) const; - - virtual bool hasRelativeAxis(int32_t deviceId, int axis) const; - - virtual bool hasInputProperty(int32_t deviceId, int property) const; - - virtual status_t mapKey(int32_t deviceId, - int32_t scanCode, int32_t usageCode, int32_t metaState, - int32_t* outKeycode, int32_t *outMetaState, uint32_t* outFlags) const; - - virtual status_t mapAxis(int32_t deviceId, int32_t scanCode, - AxisInfo* outAxisInfo) const; - - virtual void setExcludedDevices(const std::vector& devices); - - virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const; - virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const; - virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const; - virtual status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const; - - virtual bool markSupportedKeyCodes(int32_t deviceId, size_t numCodes, - const int32_t* keyCodes, uint8_t* outFlags) const; - - virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize); - - virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const; - virtual bool hasLed(int32_t deviceId, int32_t led) const; - virtual void setLedState(int32_t deviceId, int32_t led, bool on); - - virtual void getVirtualKeyDefinitions(int32_t deviceId, - Vector& outVirtualKeys) const; - - virtual sp getKeyCharacterMap(int32_t deviceId) const; - virtual bool setKeyboardLayoutOverlay(int32_t deviceId, const sp& map); - - virtual void vibrate(int32_t deviceId, nsecs_t duration); - virtual void cancelVibrate(int32_t deviceId); - - virtual void requestReopenDevices(); - - virtual void wake(); - - virtual void dump(std::string& dump); - virtual void monitor(); - -protected: - virtual ~EventHub(); - -private: - struct Device { - Device* next; - - int fd; // may be -1 if device is closed - const int32_t id; - const std::string path; - const InputDeviceIdentifier identifier; - - uint32_t classes; - - uint8_t keyBitmask[(KEY_MAX + 1) / 8]; - uint8_t absBitmask[(ABS_MAX + 1) / 8]; - uint8_t relBitmask[(REL_MAX + 1) / 8]; - uint8_t swBitmask[(SW_MAX + 1) / 8]; - uint8_t ledBitmask[(LED_MAX + 1) / 8]; - uint8_t ffBitmask[(FF_MAX + 1) / 8]; - uint8_t propBitmask[(INPUT_PROP_MAX + 1) / 8]; - - std::string configurationFile; - PropertyMap* configuration; - VirtualKeyMap* virtualKeyMap; - KeyMap keyMap; - - sp overlayKeyMap; - sp combinedKeyMap; - - bool ffEffectPlaying; - int16_t ffEffectId; // initially -1 - - int32_t controllerNumber; - - Device(int fd, int32_t id, const std::string& path, - const InputDeviceIdentifier& identifier); - ~Device(); - - void close(); - - bool enabled; // initially true - status_t enable(); - status_t disable(); - bool hasValidFd(); - const bool isVirtual; // set if fd < 0 is passed to constructor - - const sp& getKeyCharacterMap() const { - if (combinedKeyMap != nullptr) { - return combinedKeyMap; - } - return keyMap.keyCharacterMap; - } - }; - - status_t openDeviceLocked(const char *devicePath); - void createVirtualKeyboardLocked(); - void addDeviceLocked(Device* device); - void assignDescriptorLocked(InputDeviceIdentifier& identifier); - - status_t closeDeviceByPathLocked(const char *devicePath); - void closeDeviceLocked(Device* device); - void closeAllDevicesLocked(); - - void configureFd(Device* device); - - bool isDeviceEnabled(int32_t deviceId); - status_t enableDevice(int32_t deviceId); - status_t disableDevice(int32_t deviceId); - status_t registerDeviceForEpollLocked(Device* device); - status_t unregisterDeviceFromEpollLocked(Device* device); - - status_t scanDirLocked(const char *dirname); - void scanDevicesLocked(); - status_t readNotifyLocked(); - - Device* getDeviceByDescriptorLocked(const std::string& descriptor) const; - Device* getDeviceLocked(int32_t deviceId) const; - Device* getDeviceByPathLocked(const char* devicePath) const; - Device* getDeviceByFdLocked(int fd) const; - - bool hasKeycodeLocked(Device* device, int keycode) const; - - void loadConfigurationLocked(Device* device); - status_t loadVirtualKeyMapLocked(Device* device); - status_t loadKeyMapLocked(Device* device); - - bool isExternalDeviceLocked(Device* device); - bool deviceHasMicLocked(Device* device); - - int32_t getNextControllerNumberLocked(Device* device); - void releaseControllerNumberLocked(Device* device); - void setLedForControllerLocked(Device* device); - - status_t mapLed(Device* device, int32_t led, int32_t* outScanCode) const; - void setLedStateLocked(Device* device, int32_t led, bool on); - - // Protect all internal state. - mutable Mutex mLock; - - // The actual id of the built-in keyboard, or NO_BUILT_IN_KEYBOARD if none. - // EventHub remaps the built-in keyboard to id 0 externally as required by the API. - enum { - // Must not conflict with any other assigned device ids, including - // the virtual keyboard id (-1). - NO_BUILT_IN_KEYBOARD = -2, - }; - int32_t mBuiltInKeyboardId; - - int32_t mNextDeviceId; - - BitSet32 mControllerNumbers; - - KeyedVector mDevices; - - Device *mOpeningDevices; - Device *mClosingDevices; - - bool mNeedToSendFinishedDeviceScan; - bool mNeedToReopenDevices; - bool mNeedToScanDevices; - std::vector mExcludedDevices; - - int mEpollFd; - int mINotifyFd; - int mWakeReadPipeFd; - int mWakeWritePipeFd; - - // Epoll FD list size hint. - static const int EPOLL_SIZE_HINT = 8; - - // Maximum number of signalled FDs to handle at a time. - static const int EPOLL_MAX_EVENTS = 16; - - // The array of pending epoll events and the index of the next event to be handled. - struct epoll_event mPendingEventItems[EPOLL_MAX_EVENTS]; - size_t mPendingEventCount; - size_t mPendingEventIndex; - bool mPendingINotify; - - bool mUsingEpollWakeup; -}; - -}; // namespace android - -#endif // _RUNTIME_EVENT_HUB_H diff --git a/services/inputflinger/InputListener.h b/services/inputflinger/InputListener.h deleted file mode 100644 index a3d919bf5a..0000000000 --- a/services/inputflinger/InputListener.h +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _UI_INPUT_LISTENER_H -#define _UI_INPUT_LISTENER_H - -#include -#include -#include - -namespace android { - -class InputListenerInterface; - - -/* Superclass of all input event argument objects */ -struct NotifyArgs { - virtual ~NotifyArgs() { } - - virtual void notify(const sp& listener) const = 0; -}; - - -/* Describes a configuration change event. */ -struct NotifyConfigurationChangedArgs : public NotifyArgs { - nsecs_t eventTime; - - inline NotifyConfigurationChangedArgs() { } - - explicit NotifyConfigurationChangedArgs(nsecs_t eventTime); - - NotifyConfigurationChangedArgs(const NotifyConfigurationChangedArgs& other); - - virtual ~NotifyConfigurationChangedArgs() { } - - virtual void notify(const sp& listener) const; -}; - - -/* Describes a key event. */ -struct NotifyKeyArgs : public NotifyArgs { - nsecs_t eventTime; - int32_t deviceId; - uint32_t source; - int32_t displayId; - uint32_t policyFlags; - int32_t action; - int32_t flags; - int32_t keyCode; - int32_t scanCode; - int32_t metaState; - nsecs_t downTime; - - inline NotifyKeyArgs() { } - - NotifyKeyArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, - uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, - int32_t metaState, nsecs_t downTime); - - NotifyKeyArgs(const NotifyKeyArgs& other); - - virtual ~NotifyKeyArgs() { } - - virtual void notify(const sp& listener) const; -}; - - -/* Describes a motion event. */ -struct NotifyMotionArgs : public NotifyArgs { - nsecs_t eventTime; - int32_t deviceId; - uint32_t source; - int32_t displayId; - uint32_t policyFlags; - int32_t action; - int32_t actionButton; - int32_t flags; - int32_t metaState; - int32_t buttonState; - int32_t edgeFlags; - /** - * A timestamp in the input device's time base, not the platform's. - * The units are microseconds since the last reset. - * This can only be compared to other device timestamps from the same device. - * This value will overflow after a little over an hour. - */ - uint32_t deviceTimestamp; - uint32_t pointerCount; - PointerProperties pointerProperties[MAX_POINTERS]; - PointerCoords pointerCoords[MAX_POINTERS]; - float xPrecision; - float yPrecision; - nsecs_t downTime; - - inline NotifyMotionArgs() { } - - NotifyMotionArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, - uint32_t policyFlags, - int32_t action, int32_t actionButton, int32_t flags, - int32_t metaState, int32_t buttonState, - int32_t edgeFlags, uint32_t deviceTimestamp, uint32_t pointerCount, - const PointerProperties* pointerProperties, const PointerCoords* pointerCoords, - float xPrecision, float yPrecision, nsecs_t downTime); - - NotifyMotionArgs(const NotifyMotionArgs& other); - - virtual ~NotifyMotionArgs() { } - - virtual void notify(const sp& listener) const; -}; - - -/* Describes a switch event. */ -struct NotifySwitchArgs : public NotifyArgs { - nsecs_t eventTime; - uint32_t policyFlags; - uint32_t switchValues; - uint32_t switchMask; - - inline NotifySwitchArgs() { } - - NotifySwitchArgs(nsecs_t eventTime, uint32_t policyFlags, - uint32_t switchValues, uint32_t switchMask); - - NotifySwitchArgs(const NotifySwitchArgs& other); - - virtual ~NotifySwitchArgs() { } - - virtual void notify(const sp& listener) const; -}; - - -/* Describes a device reset event, such as when a device is added, - * reconfigured, or removed. */ -struct NotifyDeviceResetArgs : public NotifyArgs { - nsecs_t eventTime; - int32_t deviceId; - - inline NotifyDeviceResetArgs() { } - - NotifyDeviceResetArgs(nsecs_t eventTime, int32_t deviceId); - - NotifyDeviceResetArgs(const NotifyDeviceResetArgs& other); - - virtual ~NotifyDeviceResetArgs() { } - - virtual void notify(const sp& listener) const; -}; - - -/* - * The interface used by the InputReader to notify the InputListener about input events. - */ -class InputListenerInterface : public virtual RefBase { -protected: - InputListenerInterface() { } - virtual ~InputListenerInterface() { } - -public: - virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) = 0; - virtual void notifyKey(const NotifyKeyArgs* args) = 0; - virtual void notifyMotion(const NotifyMotionArgs* args) = 0; - virtual void notifySwitch(const NotifySwitchArgs* args) = 0; - virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args) = 0; -}; - - -/* - * An implementation of the listener interface that queues up and defers dispatch - * of decoded events until flushed. - */ -class QueuedInputListener : public InputListenerInterface { -protected: - virtual ~QueuedInputListener(); - -public: - explicit QueuedInputListener(const sp& innerListener); - - virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args); - virtual void notifyKey(const NotifyKeyArgs* args); - virtual void notifyMotion(const NotifyMotionArgs* args); - virtual void notifySwitch(const NotifySwitchArgs* args); - virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args); - - void flush(); - -private: - sp mInnerListener; - Vector mArgsQueue; -}; - -} // namespace android - -#endif // _UI_INPUT_LISTENER_H diff --git a/services/inputflinger/InputManager.cpp b/services/inputflinger/InputManager.cpp index 40ca6a7d6d..388423ca20 100644 --- a/services/inputflinger/InputManager.cpp +++ b/services/inputflinger/InputManager.cpp @@ -19,6 +19,7 @@ //#define LOG_NDEBUG 0 #include "InputManager.h" +#include "InputReaderFactory.h" #include #include @@ -26,19 +27,10 @@ namespace android { InputManager::InputManager( - const sp& eventHub, const sp& readerPolicy, const sp& dispatcherPolicy) { mDispatcher = new InputDispatcher(dispatcherPolicy); - mReader = new InputReader(eventHub, readerPolicy, mDispatcher); - initialize(); -} - -InputManager::InputManager( - const sp& reader, - const sp& dispatcher) : - mReader(reader), - mDispatcher(dispatcher) { + mReader = createInputReader(readerPolicy, mDispatcher); initialize(); } diff --git a/services/inputflinger/InputManager.h b/services/inputflinger/InputManager.h index d0e4cb02be..1173fa165f 100644 --- a/services/inputflinger/InputManager.h +++ b/services/inputflinger/InputManager.h @@ -22,7 +22,7 @@ */ #include "EventHub.h" -#include "InputReader.h" +#include "InputReaderBase.h" #include "InputDispatcher.h" #include @@ -80,15 +80,9 @@ protected: public: InputManager( - const sp& eventHub, const sp& readerPolicy, const sp& dispatcherPolicy); - // (used for testing purposes) - InputManager( - const sp& reader, - const sp& dispatcher); - virtual status_t start(); virtual status_t stop(); diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index e85e6efe5d..9dd14dc799 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -254,47 +254,6 @@ static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, } -// --- InputReaderConfiguration --- - -std::optional InputReaderConfiguration::getDisplayViewport( - ViewportType viewportType, const std::string& uniqueDisplayId) const { - for (const DisplayViewport& currentViewport : mDisplays) { - if (currentViewport.type == viewportType) { - if (uniqueDisplayId.empty() || - (!uniqueDisplayId.empty() && uniqueDisplayId == currentViewport.uniqueId)) { - return std::make_optional(currentViewport); - } - } - } - return std::nullopt; -} - -void InputReaderConfiguration::setDisplayViewports(const std::vector& viewports) { - mDisplays = viewports; -} - -void InputReaderConfiguration::dump(std::string& dump) const { - for (const DisplayViewport& viewport : mDisplays) { - dumpViewport(dump, viewport); - } -} - -void InputReaderConfiguration::dumpViewport(std::string& dump, const DisplayViewport& viewport) - const { - dump += StringPrintf(INDENT4 "%s\n", viewport.toString().c_str()); -} - - -// -- TouchAffineTransformation -- -void TouchAffineTransformation::applyTo(float& x, float& y) const { - float newX, newY; - newX = x * x_scale + y * x_ymix + x_offset; - newY = x * y_xmix + y * y_scale + y_offset; - - x = newX; - y = newY; -} - // --- InputReader --- @@ -987,21 +946,6 @@ EventHubInterface* InputReader::ContextImpl::getEventHub() { } -// --- InputReaderThread --- - -InputReaderThread::InputReaderThread(const sp& reader) : - Thread(/*canCallJava*/ true), mReader(reader) { -} - -InputReaderThread::~InputReaderThread() { -} - -bool InputReaderThread::threadLoop() { - mReader->loopOnce(); - return true; -} - - // --- InputDevice --- InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation, diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h index 9b0007a2b8..1786fe8f26 100644 --- a/services/inputflinger/InputReader.h +++ b/services/inputflinger/InputReader.h @@ -20,6 +20,7 @@ #include "EventHub.h" #include "PointerControllerInterface.h" #include "InputListener.h" +#include "InputReaderBase.h" #include #include @@ -28,314 +29,20 @@ #include #include #include -#include #include #include -#include #include -#include #include #include #include #include -// Maximum supported size of a vibration pattern. -// Must be at least 2. -#define MAX_VIBRATE_PATTERN_SIZE 100 - -// Maximum allowable delay value in a vibration pattern before -// which the delay will be truncated. -#define MAX_VIBRATE_PATTERN_DELAY_NSECS (1000000 * 1000000000LL) - namespace android { class InputDevice; class InputMapper; -/* - * Input reader configuration. - * - * Specifies various options that modify the behavior of the input reader. - */ -struct InputReaderConfiguration { - // Describes changes that have occurred. - enum { - // The pointer speed changed. - CHANGE_POINTER_SPEED = 1 << 0, - - // The pointer gesture control changed. - CHANGE_POINTER_GESTURE_ENABLEMENT = 1 << 1, - - // The display size or orientation changed. - CHANGE_DISPLAY_INFO = 1 << 2, - - // The visible touches option changed. - CHANGE_SHOW_TOUCHES = 1 << 3, - - // The keyboard layouts must be reloaded. - CHANGE_KEYBOARD_LAYOUTS = 1 << 4, - - // The device name alias supplied by the may have changed for some devices. - CHANGE_DEVICE_ALIAS = 1 << 5, - - // The location calibration matrix changed. - CHANGE_TOUCH_AFFINE_TRANSFORMATION = 1 << 6, - - // The presence of an external stylus has changed. - CHANGE_EXTERNAL_STYLUS_PRESENCE = 1 << 7, - - // The pointer capture mode has changed. - CHANGE_POINTER_CAPTURE = 1 << 8, - - // The set of disabled input devices (disabledDevices) has changed. - CHANGE_ENABLED_STATE = 1 << 9, - - // All devices must be reopened. - CHANGE_MUST_REOPEN = 1 << 31, - }; - - // Gets the amount of time to disable virtual keys after the screen is touched - // in order to filter out accidental virtual key presses due to swiping gestures - // or taps near the edge of the display. May be 0 to disable the feature. - nsecs_t virtualKeyQuietTime; - - // The excluded device names for the platform. - // Devices with these names will be ignored. - std::vector excludedDeviceNames; - - // Velocity control parameters for mouse pointer movements. - VelocityControlParameters pointerVelocityControlParameters; - - // Velocity control parameters for mouse wheel movements. - VelocityControlParameters wheelVelocityControlParameters; - - // True if pointer gestures are enabled. - bool pointerGesturesEnabled; - - // Quiet time between certain pointer gesture transitions. - // Time to allow for all fingers or buttons to settle into a stable state before - // starting a new gesture. - nsecs_t pointerGestureQuietInterval; - - // The minimum speed that a pointer must travel for us to consider switching the active - // touch pointer to it during a drag. This threshold is set to avoid switching due - // to noise from a finger resting on the touch pad (perhaps just pressing it down). - float pointerGestureDragMinSwitchSpeed; // in pixels per second - - // Tap gesture delay time. - // The time between down and up must be less than this to be considered a tap. - nsecs_t pointerGestureTapInterval; - - // Tap drag gesture delay time. - // The time between the previous tap's up and the next down must be less than - // this to be considered a drag. Otherwise, the previous tap is finished and a - // new tap begins. - // - // Note that the previous tap will be held down for this entire duration so this - // interval must be shorter than the long press timeout. - nsecs_t pointerGestureTapDragInterval; - - // The distance in pixels that the pointer is allowed to move from initial down - // to up and still be called a tap. - float pointerGestureTapSlop; // in pixels - - // Time after the first touch points go down to settle on an initial centroid. - // This is intended to be enough time to handle cases where the user puts down two - // fingers at almost but not quite exactly the same time. - nsecs_t pointerGestureMultitouchSettleInterval; - - // The transition from PRESS to SWIPE or FREEFORM gesture mode is made when - // at least two pointers have moved at least this far from their starting place. - float pointerGestureMultitouchMinDistance; // in pixels - - // The transition from PRESS to SWIPE gesture mode can only occur when the - // cosine of the angle between the two vectors is greater than or equal to than this value - // which indicates that the vectors are oriented in the same direction. - // When the vectors are oriented in the exactly same direction, the cosine is 1.0. - // (In exactly opposite directions, the cosine is -1.0.) - float pointerGestureSwipeTransitionAngleCosine; - - // The transition from PRESS to SWIPE gesture mode can only occur when the - // fingers are no more than this far apart relative to the diagonal size of - // the touch pad. For example, a ratio of 0.5 means that the fingers must be - // no more than half the diagonal size of the touch pad apart. - float pointerGestureSwipeMaxWidthRatio; - - // The gesture movement speed factor relative to the size of the display. - // Movement speed applies when the fingers are moving in the same direction. - // Without acceleration, a full swipe of the touch pad diagonal in movement mode - // will cover this portion of the display diagonal. - float pointerGestureMovementSpeedRatio; - - // The gesture zoom speed factor relative to the size of the display. - // Zoom speed applies when the fingers are mostly moving relative to each other - // to execute a scale gesture or similar. - // Without acceleration, a full swipe of the touch pad diagonal in zoom mode - // will cover this portion of the display diagonal. - float pointerGestureZoomSpeedRatio; - - // True to show the location of touches on the touch screen as spots. - bool showTouches; - - // True if pointer capture is enabled. - bool pointerCapture; - - // The set of currently disabled input devices. - SortedVector disabledDevices; - - InputReaderConfiguration() : - virtualKeyQuietTime(0), - pointerVelocityControlParameters(1.0f, 500.0f, 3000.0f, 3.0f), - wheelVelocityControlParameters(1.0f, 15.0f, 50.0f, 4.0f), - pointerGesturesEnabled(true), - pointerGestureQuietInterval(100 * 1000000LL), // 100 ms - pointerGestureDragMinSwitchSpeed(50), // 50 pixels per second - pointerGestureTapInterval(150 * 1000000LL), // 150 ms - pointerGestureTapDragInterval(150 * 1000000LL), // 150 ms - pointerGestureTapSlop(10.0f), // 10 pixels - pointerGestureMultitouchSettleInterval(100 * 1000000LL), // 100 ms - pointerGestureMultitouchMinDistance(15), // 15 pixels - pointerGestureSwipeTransitionAngleCosine(0.2588f), // cosine of 75 degrees - pointerGestureSwipeMaxWidthRatio(0.25f), - pointerGestureMovementSpeedRatio(0.8f), - pointerGestureZoomSpeedRatio(0.3f), - showTouches(false) { } - - std::optional getDisplayViewport(ViewportType viewportType, - const std::string& uniqueDisplayId) const; - void setDisplayViewports(const std::vector& viewports); - - - void dump(std::string& dump) const; - void dumpViewport(std::string& dump, const DisplayViewport& viewport) const; - -private: - std::vector mDisplays; -}; - - -struct TouchAffineTransformation { - float x_scale; - float x_ymix; - float x_offset; - float y_xmix; - float y_scale; - float y_offset; - - TouchAffineTransformation() : - x_scale(1.0f), x_ymix(0.0f), x_offset(0.0f), - y_xmix(0.0f), y_scale(1.0f), y_offset(0.0f) { - } - - TouchAffineTransformation(float xscale, float xymix, float xoffset, - float yxmix, float yscale, float yoffset) : - x_scale(xscale), x_ymix(xymix), x_offset(xoffset), - y_xmix(yxmix), y_scale(yscale), y_offset(yoffset) { - } - - void applyTo(float& x, float& y) const; -}; - - -/* - * Input reader policy interface. - * - * The input reader policy is used by the input reader to interact with the Window Manager - * and other system components. - * - * The actual implementation is partially supported by callbacks into the DVM - * via JNI. This interface is also mocked in the unit tests. - * - * These methods must NOT re-enter the input reader since they may be called while - * holding the input reader lock. - */ -class InputReaderPolicyInterface : public virtual RefBase { -protected: - InputReaderPolicyInterface() { } - virtual ~InputReaderPolicyInterface() { } - -public: - /* Gets the input reader configuration. */ - virtual void getReaderConfiguration(InputReaderConfiguration* outConfig) = 0; - - /* Gets a pointer controller associated with the specified cursor device (ie. a mouse). */ - virtual sp obtainPointerController(int32_t deviceId) = 0; - - /* Notifies the input reader policy that some input devices have changed - * and provides information about all current input devices. - */ - virtual void notifyInputDevicesChanged(const Vector& inputDevices) = 0; - - /* Gets the keyboard layout for a particular input device. */ - virtual sp getKeyboardLayoutOverlay( - const InputDeviceIdentifier& identifier) = 0; - - /* Gets a user-supplied alias for a particular input device, or an empty string if none. */ - virtual std::string getDeviceAlias(const InputDeviceIdentifier& identifier) = 0; - - /* Gets the affine calibration associated with the specified device. */ - virtual TouchAffineTransformation getTouchAffineTransformation( - const std::string& inputDeviceDescriptor, int32_t surfaceRotation) = 0; -}; - - -/* Processes raw input events and sends cooked event data to an input listener. */ -class InputReaderInterface : public virtual RefBase { -protected: - InputReaderInterface() { } - virtual ~InputReaderInterface() { } - -public: - /* Dumps the state of the input reader. - * - * This method may be called on any thread (usually by the input manager). */ - virtual void dump(std::string& dump) = 0; - - /* Called by the heatbeat to ensures that the reader has not deadlocked. */ - virtual void monitor() = 0; - - /* Returns true if the input device is enabled. */ - virtual bool isInputDeviceEnabled(int32_t deviceId) = 0; - - /* Runs a single iteration of the processing loop. - * Nominally reads and processes one incoming message from the EventHub. - * - * This method should be called on the input reader thread. - */ - virtual void loopOnce() = 0; - - /* Gets information about all input devices. - * - * This method may be called on any thread (usually by the input manager). - */ - virtual void getInputDevices(Vector& outInputDevices) = 0; - - /* Query current input state. */ - virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask, - int32_t scanCode) = 0; - virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask, - int32_t keyCode) = 0; - virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask, - int32_t sw) = 0; - - /* Toggle Caps Lock */ - virtual void toggleCapsLockState(int32_t deviceId) = 0; - - /* Determine whether physical keys exist for the given framework-domain key codes. */ - virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask, - size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) = 0; - - /* Requests that a reconfiguration of all input devices. - * The changes flag is a bitfield that indicates what has changed and whether - * the input devices must all be reopened. */ - virtual void requestRefreshConfiguration(uint32_t changes) = 0; - - /* Controls the vibrator of a particular input device. */ - virtual void vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize, - ssize_t repeat, int32_t token) = 0; - virtual void cancelVibrate(int32_t deviceId, int32_t token) = 0; -}; struct StylusState { /* Time the stylus event was received. */ @@ -527,19 +234,6 @@ private: }; -/* Reads raw events from the event hub and processes them, endlessly. */ -class InputReaderThread : public Thread { -public: - explicit InputReaderThread(const sp& reader); - virtual ~InputReaderThread(); - -private: - sp mReader; - - virtual bool threadLoop(); -}; - - /* Represents the state of a single input device. */ class InputDevice { public: diff --git a/services/inputflinger/InputReaderBase.cpp b/services/inputflinger/InputReaderBase.cpp new file mode 100644 index 0000000000..17a116e822 --- /dev/null +++ b/services/inputflinger/InputReaderBase.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "InputReaderBase" + +//#define LOG_NDEBUG 0 + +#include "InputReaderBase.h" + +#include +#include + +#define INDENT " " +#define INDENT2 " " +#define INDENT3 " " +#define INDENT4 " " +#define INDENT5 " " + +using android::base::StringPrintf; + +namespace android { + +// --- InputReaderThread --- + +InputReaderThread::InputReaderThread(const sp& reader) : + Thread(/*canCallJava*/ true), mReader(reader) { +} + +InputReaderThread::~InputReaderThread() { +} + +bool InputReaderThread::threadLoop() { + mReader->loopOnce(); + return true; +} + +// --- InputReaderConfiguration --- + +std::optional InputReaderConfiguration::getDisplayViewport( + ViewportType viewportType, const std::string& uniqueDisplayId) const { + for (const DisplayViewport& currentViewport : mDisplays) { + if (currentViewport.type == viewportType) { + if (uniqueDisplayId.empty() || + (!uniqueDisplayId.empty() && uniqueDisplayId == currentViewport.uniqueId)) { + return std::make_optional(currentViewport); + } + } + } + return std::nullopt; +} + +void InputReaderConfiguration::setDisplayViewports(const std::vector& viewports) { + mDisplays = viewports; +} + +void InputReaderConfiguration::dump(std::string& dump) const { + for (const DisplayViewport& viewport : mDisplays) { + dumpViewport(dump, viewport); + } +} + +void InputReaderConfiguration::dumpViewport(std::string& dump, const DisplayViewport& viewport) + const { + dump += StringPrintf(INDENT4 "%s\n", viewport.toString().c_str()); +} + + +// -- TouchAffineTransformation -- +void TouchAffineTransformation::applyTo(float& x, float& y) const { + float newX, newY; + newX = x * x_scale + y * x_ymix + x_offset; + newY = x * y_xmix + y * y_scale + y_offset; + + x = newX; + y = newY; +} + +} // namespace android \ No newline at end of file diff --git a/services/inputflinger/InputReaderFactory.cpp b/services/inputflinger/InputReaderFactory.cpp new file mode 100644 index 0000000000..3534f6b760 --- /dev/null +++ b/services/inputflinger/InputReaderFactory.cpp @@ -0,0 +1,28 @@ +/* + * Copyright 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "InputReaderFactory.h" +#include "InputReader.h" + +namespace android { + +sp createInputReader( + const sp& policy, + const sp& listener) { + return new InputReader(new EventHub(), policy, listener); +} + +} // namespace android \ No newline at end of file diff --git a/services/inputflinger/PointerControllerInterface.h b/services/inputflinger/PointerControllerInterface.h deleted file mode 100644 index e94dd94868..0000000000 --- a/services/inputflinger/PointerControllerInterface.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2014 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _INPUTFLINGER_POINTER_CONTROLLER_INTERFACE_H -#define _INPUTFLINGER_POINTER_CONTROLLER_INTERFACE_H - -#include -#include -#include - -namespace android { - -/** - * Interface for tracking a mouse / touch pad pointer and touch pad spots. - * - * The spots are sprites on screen that visually represent the positions of - * fingers - * - * The pointer controller is responsible for providing synchronization and for tracking - * display orientation changes if needed. - */ -class PointerControllerInterface : public virtual RefBase { -protected: - PointerControllerInterface() { } - virtual ~PointerControllerInterface() { } - -public: - /* Gets the bounds of the region that the pointer can traverse. - * Returns true if the bounds are available. */ - virtual bool getBounds(float* outMinX, float* outMinY, - float* outMaxX, float* outMaxY) const = 0; - - /* Move the pointer. */ - virtual void move(float deltaX, float deltaY) = 0; - - /* Sets a mask that indicates which buttons are pressed. */ - virtual void setButtonState(int32_t buttonState) = 0; - - /* Gets a mask that indicates which buttons are pressed. */ - virtual int32_t getButtonState() const = 0; - - /* Sets the absolute location of the pointer. */ - virtual void setPosition(float x, float y) = 0; - - /* Gets the absolute location of the pointer. */ - virtual void getPosition(float* outX, float* outY) const = 0; - - enum Transition { - // Fade/unfade immediately. - TRANSITION_IMMEDIATE, - // Fade/unfade gradually. - TRANSITION_GRADUAL, - }; - - /* Fades the pointer out now. */ - virtual void fade(Transition transition) = 0; - - /* Makes the pointer visible if it has faded out. - * The pointer never unfades itself automatically. This method must be called - * by the client whenever the pointer is moved or a button is pressed and it - * wants to ensure that the pointer becomes visible again. */ - virtual void unfade(Transition transition) = 0; - - enum Presentation { - // Show the mouse pointer. - PRESENTATION_POINTER, - // Show spots and a spot anchor in place of the mouse pointer. - PRESENTATION_SPOT, - }; - - /* Sets the mode of the pointer controller. */ - virtual void setPresentation(Presentation presentation) = 0; - - /* Sets the spots for the current gesture. - * The spots are not subject to the inactivity timeout like the pointer - * itself it since they are expected to remain visible for so long as - * the fingers are on the touch pad. - * - * The values of the AMOTION_EVENT_AXIS_PRESSURE axis is significant. - * For spotCoords, pressure != 0 indicates that the spot's location is being - * pressed (not hovering). - */ - virtual void setSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex, - BitSet32 spotIdBits) = 0; - - /* Removes all spots. */ - virtual void clearSpots() = 0; -}; - -} // namespace android - -#endif // _INPUTFLINGER_POINTER_CONTROLLER_INTERFACE_H diff --git a/services/inputflinger/include/EventHub.h b/services/inputflinger/include/EventHub.h new file mode 100644 index 0000000000..e2c7e82f9f --- /dev/null +++ b/services/inputflinger/include/EventHub.h @@ -0,0 +1,470 @@ +/* + * Copyright (C) 2005 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// +#ifndef _RUNTIME_EVENT_HUB_H +#define _RUNTIME_EVENT_HUB_H + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +/* Convenience constants. */ + +#define BTN_FIRST 0x100 // first button code +#define BTN_LAST 0x15f // last button code + +namespace android { + +enum { + // Device id of a special "virtual" keyboard that is always present. + VIRTUAL_KEYBOARD_ID = -1, + // Device id of the "built-in" keyboard if there is one. + BUILT_IN_KEYBOARD_ID = 0, +}; + +/* + * A raw event as retrieved from the EventHub. + */ +struct RawEvent { + nsecs_t when; + int32_t deviceId; + int32_t type; + int32_t code; + int32_t value; +}; + +/* Describes an absolute axis. */ +struct RawAbsoluteAxisInfo { + bool valid; // true if the information is valid, false otherwise + + int32_t minValue; // minimum value + int32_t maxValue; // maximum value + int32_t flat; // center flat position, eg. flat == 8 means center is between -8 and 8 + int32_t fuzz; // error tolerance, eg. fuzz == 4 means value is +/- 4 due to noise + int32_t resolution; // resolution in units per mm or radians per mm + + inline void clear() { + valid = false; + minValue = 0; + maxValue = 0; + flat = 0; + fuzz = 0; + resolution = 0; + } +}; + +/* + * Input device classes. + */ +enum { + /* The input device is a keyboard or has buttons. */ + INPUT_DEVICE_CLASS_KEYBOARD = 0x00000001, + + /* The input device is an alpha-numeric keyboard (not just a dial pad). */ + INPUT_DEVICE_CLASS_ALPHAKEY = 0x00000002, + + /* The input device is a touchscreen or a touchpad (either single-touch or multi-touch). */ + INPUT_DEVICE_CLASS_TOUCH = 0x00000004, + + /* The input device is a cursor device such as a trackball or mouse. */ + INPUT_DEVICE_CLASS_CURSOR = 0x00000008, + + /* The input device is a multi-touch touchscreen. */ + INPUT_DEVICE_CLASS_TOUCH_MT = 0x00000010, + + /* The input device is a directional pad (implies keyboard, has DPAD keys). */ + INPUT_DEVICE_CLASS_DPAD = 0x00000020, + + /* The input device is a gamepad (implies keyboard, has BUTTON keys). */ + INPUT_DEVICE_CLASS_GAMEPAD = 0x00000040, + + /* The input device has switches. */ + INPUT_DEVICE_CLASS_SWITCH = 0x00000080, + + /* The input device is a joystick (implies gamepad, has joystick absolute axes). */ + INPUT_DEVICE_CLASS_JOYSTICK = 0x00000100, + + /* The input device has a vibrator (supports FF_RUMBLE). */ + INPUT_DEVICE_CLASS_VIBRATOR = 0x00000200, + + /* The input device has a microphone. */ + INPUT_DEVICE_CLASS_MIC = 0x00000400, + + /* The input device is an external stylus (has data we want to fuse with touch data). */ + INPUT_DEVICE_CLASS_EXTERNAL_STYLUS = 0x00000800, + + /* The input device has a rotary encoder */ + INPUT_DEVICE_CLASS_ROTARY_ENCODER = 0x00001000, + + /* The input device is virtual (not a real device, not part of UI configuration). */ + INPUT_DEVICE_CLASS_VIRTUAL = 0x40000000, + + /* The input device is external (not built-in). */ + INPUT_DEVICE_CLASS_EXTERNAL = 0x80000000, +}; + +/* + * Gets the class that owns an axis, in cases where multiple classes might claim + * the same axis for different purposes. + */ +extern uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses); + +/* + * Grand Central Station for events. + * + * The event hub aggregates input events received across all known input + * devices on the system, including devices that may be emulated by the simulator + * environment. In addition, the event hub generates fake input events to indicate + * when devices are added or removed. + * + * The event hub provides a stream of input events (via the getEvent function). + * It also supports querying the current actual state of input devices such as identifying + * which keys are currently down. Finally, the event hub keeps track of the capabilities of + * individual input devices, such as their class and the set of key codes that they support. + */ +class EventHubInterface : public virtual RefBase { +protected: + EventHubInterface() { } + virtual ~EventHubInterface() { } + +public: + // Synthetic raw event type codes produced when devices are added or removed. + enum { + // Sent when a device is added. + DEVICE_ADDED = 0x10000000, + // Sent when a device is removed. + DEVICE_REMOVED = 0x20000000, + // Sent when all added/removed devices from the most recent scan have been reported. + // This event is always sent at least once. + FINISHED_DEVICE_SCAN = 0x30000000, + + FIRST_SYNTHETIC_EVENT = DEVICE_ADDED, + }; + + virtual uint32_t getDeviceClasses(int32_t deviceId) const = 0; + + virtual InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const = 0; + + virtual int32_t getDeviceControllerNumber(int32_t deviceId) const = 0; + + virtual void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const = 0; + + virtual status_t getAbsoluteAxisInfo(int32_t deviceId, int axis, + RawAbsoluteAxisInfo* outAxisInfo) const = 0; + + virtual bool hasRelativeAxis(int32_t deviceId, int axis) const = 0; + + virtual bool hasInputProperty(int32_t deviceId, int property) const = 0; + + virtual status_t mapKey(int32_t deviceId, + int32_t scanCode, int32_t usageCode, int32_t metaState, + int32_t* outKeycode, int32_t *outMetaState, uint32_t* outFlags) const = 0; + + virtual status_t mapAxis(int32_t deviceId, int32_t scanCode, + AxisInfo* outAxisInfo) const = 0; + + // Sets devices that are excluded from opening. + // This can be used to ignore input devices for sensors. + virtual void setExcludedDevices(const std::vector& devices) = 0; + + /* + * Wait for events to become available and returns them. + * After returning, the EventHub holds onto a wake lock until the next call to getEvent. + * This ensures that the device will not go to sleep while the event is being processed. + * If the device needs to remain awake longer than that, then the caller is responsible + * for taking care of it (say, by poking the power manager user activity timer). + * + * The timeout is advisory only. If the device is asleep, it will not wake just to + * service the timeout. + * + * Returns the number of events obtained, or 0 if the timeout expired. + */ + virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) = 0; + + /* + * Query current input state. + */ + virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const = 0; + virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const = 0; + virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const = 0; + virtual status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis, + int32_t* outValue) const = 0; + + /* + * Examine key input devices for specific framework keycode support + */ + virtual bool markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes, + uint8_t* outFlags) const = 0; + + virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const = 0; + + /* LED related functions expect Android LED constants, not scan codes or HID usages */ + virtual bool hasLed(int32_t deviceId, int32_t led) const = 0; + virtual void setLedState(int32_t deviceId, int32_t led, bool on) = 0; + + virtual void getVirtualKeyDefinitions(int32_t deviceId, + Vector& outVirtualKeys) const = 0; + + virtual sp getKeyCharacterMap(int32_t deviceId) const = 0; + virtual bool setKeyboardLayoutOverlay(int32_t deviceId, const sp& map) = 0; + + /* Control the vibrator. */ + virtual void vibrate(int32_t deviceId, nsecs_t duration) = 0; + virtual void cancelVibrate(int32_t deviceId) = 0; + + /* Requests the EventHub to reopen all input devices on the next call to getEvents(). */ + virtual void requestReopenDevices() = 0; + + /* Wakes up getEvents() if it is blocked on a read. */ + virtual void wake() = 0; + + /* Dump EventHub state to a string. */ + virtual void dump(std::string& dump) = 0; + + /* Called by the heatbeat to ensures that the reader has not deadlocked. */ + virtual void monitor() = 0; + + /* Return true if the device is enabled. */ + virtual bool isDeviceEnabled(int32_t deviceId) = 0; + + /* Enable an input device */ + virtual status_t enableDevice(int32_t deviceId) = 0; + + /* Disable an input device. Closes file descriptor to that device. */ + virtual status_t disableDevice(int32_t deviceId) = 0; +}; + +class EventHub : public EventHubInterface +{ +public: + EventHub(); + + virtual uint32_t getDeviceClasses(int32_t deviceId) const; + + virtual InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const; + + virtual int32_t getDeviceControllerNumber(int32_t deviceId) const; + + virtual void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const; + + virtual status_t getAbsoluteAxisInfo(int32_t deviceId, int axis, + RawAbsoluteAxisInfo* outAxisInfo) const; + + virtual bool hasRelativeAxis(int32_t deviceId, int axis) const; + + virtual bool hasInputProperty(int32_t deviceId, int property) const; + + virtual status_t mapKey(int32_t deviceId, + int32_t scanCode, int32_t usageCode, int32_t metaState, + int32_t* outKeycode, int32_t *outMetaState, uint32_t* outFlags) const; + + virtual status_t mapAxis(int32_t deviceId, int32_t scanCode, + AxisInfo* outAxisInfo) const; + + virtual void setExcludedDevices(const std::vector& devices); + + virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const; + virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const; + virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const; + virtual status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const; + + virtual bool markSupportedKeyCodes(int32_t deviceId, size_t numCodes, + const int32_t* keyCodes, uint8_t* outFlags) const; + + virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize); + + virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const; + virtual bool hasLed(int32_t deviceId, int32_t led) const; + virtual void setLedState(int32_t deviceId, int32_t led, bool on); + + virtual void getVirtualKeyDefinitions(int32_t deviceId, + Vector& outVirtualKeys) const; + + virtual sp getKeyCharacterMap(int32_t deviceId) const; + virtual bool setKeyboardLayoutOverlay(int32_t deviceId, const sp& map); + + virtual void vibrate(int32_t deviceId, nsecs_t duration); + virtual void cancelVibrate(int32_t deviceId); + + virtual void requestReopenDevices(); + + virtual void wake(); + + virtual void dump(std::string& dump); + virtual void monitor(); + +protected: + virtual ~EventHub(); + +private: + struct Device { + Device* next; + + int fd; // may be -1 if device is closed + const int32_t id; + const std::string path; + const InputDeviceIdentifier identifier; + + uint32_t classes; + + uint8_t keyBitmask[(KEY_MAX + 1) / 8]; + uint8_t absBitmask[(ABS_MAX + 1) / 8]; + uint8_t relBitmask[(REL_MAX + 1) / 8]; + uint8_t swBitmask[(SW_MAX + 1) / 8]; + uint8_t ledBitmask[(LED_MAX + 1) / 8]; + uint8_t ffBitmask[(FF_MAX + 1) / 8]; + uint8_t propBitmask[(INPUT_PROP_MAX + 1) / 8]; + + std::string configurationFile; + PropertyMap* configuration; + VirtualKeyMap* virtualKeyMap; + KeyMap keyMap; + + sp overlayKeyMap; + sp combinedKeyMap; + + bool ffEffectPlaying; + int16_t ffEffectId; // initially -1 + + int32_t controllerNumber; + + Device(int fd, int32_t id, const std::string& path, + const InputDeviceIdentifier& identifier); + ~Device(); + + void close(); + + bool enabled; // initially true + status_t enable(); + status_t disable(); + bool hasValidFd(); + const bool isVirtual; // set if fd < 0 is passed to constructor + + const sp& getKeyCharacterMap() const { + if (combinedKeyMap != nullptr) { + return combinedKeyMap; + } + return keyMap.keyCharacterMap; + } + }; + + status_t openDeviceLocked(const char *devicePath); + void createVirtualKeyboardLocked(); + void addDeviceLocked(Device* device); + void assignDescriptorLocked(InputDeviceIdentifier& identifier); + + status_t closeDeviceByPathLocked(const char *devicePath); + void closeDeviceLocked(Device* device); + void closeAllDevicesLocked(); + + void configureFd(Device* device); + + bool isDeviceEnabled(int32_t deviceId); + status_t enableDevice(int32_t deviceId); + status_t disableDevice(int32_t deviceId); + status_t registerDeviceForEpollLocked(Device* device); + status_t unregisterDeviceFromEpollLocked(Device* device); + + status_t scanDirLocked(const char *dirname); + void scanDevicesLocked(); + status_t readNotifyLocked(); + + Device* getDeviceByDescriptorLocked(const std::string& descriptor) const; + Device* getDeviceLocked(int32_t deviceId) const; + Device* getDeviceByPathLocked(const char* devicePath) const; + Device* getDeviceByFdLocked(int fd) const; + + bool hasKeycodeLocked(Device* device, int keycode) const; + + void loadConfigurationLocked(Device* device); + status_t loadVirtualKeyMapLocked(Device* device); + status_t loadKeyMapLocked(Device* device); + + bool isExternalDeviceLocked(Device* device); + bool deviceHasMicLocked(Device* device); + + int32_t getNextControllerNumberLocked(Device* device); + void releaseControllerNumberLocked(Device* device); + void setLedForControllerLocked(Device* device); + + status_t mapLed(Device* device, int32_t led, int32_t* outScanCode) const; + void setLedStateLocked(Device* device, int32_t led, bool on); + + // Protect all internal state. + mutable Mutex mLock; + + // The actual id of the built-in keyboard, or NO_BUILT_IN_KEYBOARD if none. + // EventHub remaps the built-in keyboard to id 0 externally as required by the API. + enum { + // Must not conflict with any other assigned device ids, including + // the virtual keyboard id (-1). + NO_BUILT_IN_KEYBOARD = -2, + }; + int32_t mBuiltInKeyboardId; + + int32_t mNextDeviceId; + + BitSet32 mControllerNumbers; + + KeyedVector mDevices; + + Device *mOpeningDevices; + Device *mClosingDevices; + + bool mNeedToSendFinishedDeviceScan; + bool mNeedToReopenDevices; + bool mNeedToScanDevices; + std::vector mExcludedDevices; + + int mEpollFd; + int mINotifyFd; + int mWakeReadPipeFd; + int mWakeWritePipeFd; + + // Epoll FD list size hint. + static const int EPOLL_SIZE_HINT = 8; + + // Maximum number of signalled FDs to handle at a time. + static const int EPOLL_MAX_EVENTS = 16; + + // The array of pending epoll events and the index of the next event to be handled. + struct epoll_event mPendingEventItems[EPOLL_MAX_EVENTS]; + size_t mPendingEventCount; + size_t mPendingEventIndex; + bool mPendingINotify; + + bool mUsingEpollWakeup; +}; + +}; // namespace android + +#endif // _RUNTIME_EVENT_HUB_H diff --git a/services/inputflinger/include/InputListener.h b/services/inputflinger/include/InputListener.h new file mode 100644 index 0000000000..a3d919bf5a --- /dev/null +++ b/services/inputflinger/include/InputListener.h @@ -0,0 +1,207 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _UI_INPUT_LISTENER_H +#define _UI_INPUT_LISTENER_H + +#include +#include +#include + +namespace android { + +class InputListenerInterface; + + +/* Superclass of all input event argument objects */ +struct NotifyArgs { + virtual ~NotifyArgs() { } + + virtual void notify(const sp& listener) const = 0; +}; + + +/* Describes a configuration change event. */ +struct NotifyConfigurationChangedArgs : public NotifyArgs { + nsecs_t eventTime; + + inline NotifyConfigurationChangedArgs() { } + + explicit NotifyConfigurationChangedArgs(nsecs_t eventTime); + + NotifyConfigurationChangedArgs(const NotifyConfigurationChangedArgs& other); + + virtual ~NotifyConfigurationChangedArgs() { } + + virtual void notify(const sp& listener) const; +}; + + +/* Describes a key event. */ +struct NotifyKeyArgs : public NotifyArgs { + nsecs_t eventTime; + int32_t deviceId; + uint32_t source; + int32_t displayId; + uint32_t policyFlags; + int32_t action; + int32_t flags; + int32_t keyCode; + int32_t scanCode; + int32_t metaState; + nsecs_t downTime; + + inline NotifyKeyArgs() { } + + NotifyKeyArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, + uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, + int32_t metaState, nsecs_t downTime); + + NotifyKeyArgs(const NotifyKeyArgs& other); + + virtual ~NotifyKeyArgs() { } + + virtual void notify(const sp& listener) const; +}; + + +/* Describes a motion event. */ +struct NotifyMotionArgs : public NotifyArgs { + nsecs_t eventTime; + int32_t deviceId; + uint32_t source; + int32_t displayId; + uint32_t policyFlags; + int32_t action; + int32_t actionButton; + int32_t flags; + int32_t metaState; + int32_t buttonState; + int32_t edgeFlags; + /** + * A timestamp in the input device's time base, not the platform's. + * The units are microseconds since the last reset. + * This can only be compared to other device timestamps from the same device. + * This value will overflow after a little over an hour. + */ + uint32_t deviceTimestamp; + uint32_t pointerCount; + PointerProperties pointerProperties[MAX_POINTERS]; + PointerCoords pointerCoords[MAX_POINTERS]; + float xPrecision; + float yPrecision; + nsecs_t downTime; + + inline NotifyMotionArgs() { } + + NotifyMotionArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, + uint32_t policyFlags, + int32_t action, int32_t actionButton, int32_t flags, + int32_t metaState, int32_t buttonState, + int32_t edgeFlags, uint32_t deviceTimestamp, uint32_t pointerCount, + const PointerProperties* pointerProperties, const PointerCoords* pointerCoords, + float xPrecision, float yPrecision, nsecs_t downTime); + + NotifyMotionArgs(const NotifyMotionArgs& other); + + virtual ~NotifyMotionArgs() { } + + virtual void notify(const sp& listener) const; +}; + + +/* Describes a switch event. */ +struct NotifySwitchArgs : public NotifyArgs { + nsecs_t eventTime; + uint32_t policyFlags; + uint32_t switchValues; + uint32_t switchMask; + + inline NotifySwitchArgs() { } + + NotifySwitchArgs(nsecs_t eventTime, uint32_t policyFlags, + uint32_t switchValues, uint32_t switchMask); + + NotifySwitchArgs(const NotifySwitchArgs& other); + + virtual ~NotifySwitchArgs() { } + + virtual void notify(const sp& listener) const; +}; + + +/* Describes a device reset event, such as when a device is added, + * reconfigured, or removed. */ +struct NotifyDeviceResetArgs : public NotifyArgs { + nsecs_t eventTime; + int32_t deviceId; + + inline NotifyDeviceResetArgs() { } + + NotifyDeviceResetArgs(nsecs_t eventTime, int32_t deviceId); + + NotifyDeviceResetArgs(const NotifyDeviceResetArgs& other); + + virtual ~NotifyDeviceResetArgs() { } + + virtual void notify(const sp& listener) const; +}; + + +/* + * The interface used by the InputReader to notify the InputListener about input events. + */ +class InputListenerInterface : public virtual RefBase { +protected: + InputListenerInterface() { } + virtual ~InputListenerInterface() { } + +public: + virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) = 0; + virtual void notifyKey(const NotifyKeyArgs* args) = 0; + virtual void notifyMotion(const NotifyMotionArgs* args) = 0; + virtual void notifySwitch(const NotifySwitchArgs* args) = 0; + virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args) = 0; +}; + + +/* + * An implementation of the listener interface that queues up and defers dispatch + * of decoded events until flushed. + */ +class QueuedInputListener : public InputListenerInterface { +protected: + virtual ~QueuedInputListener(); + +public: + explicit QueuedInputListener(const sp& innerListener); + + virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args); + virtual void notifyKey(const NotifyKeyArgs* args); + virtual void notifyMotion(const NotifyMotionArgs* args); + virtual void notifySwitch(const NotifySwitchArgs* args); + virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args); + + void flush(); + +private: + sp mInnerListener; + Vector mArgsQueue; +}; + +} // namespace android + +#endif // _UI_INPUT_LISTENER_H diff --git a/services/inputflinger/include/InputReaderBase.h b/services/inputflinger/include/InputReaderBase.h new file mode 100644 index 0000000000..fff8480f57 --- /dev/null +++ b/services/inputflinger/include/InputReaderBase.h @@ -0,0 +1,342 @@ +/* + * Copyright (C) 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _UI_INPUT_READER_BASE_H +#define _UI_INPUT_READER_BASE_H + +#include "PointerControllerInterface.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +// Maximum supported size of a vibration pattern. +// Must be at least 2. +#define MAX_VIBRATE_PATTERN_SIZE 100 + +// Maximum allowable delay value in a vibration pattern before +// which the delay will be truncated. +#define MAX_VIBRATE_PATTERN_DELAY_NSECS (1000000 * 1000000000LL) + +namespace android { + +/* Processes raw input events and sends cooked event data to an input listener. */ +class InputReaderInterface : public virtual RefBase { +protected: + InputReaderInterface() { } + virtual ~InputReaderInterface() { } + +public: + /* Dumps the state of the input reader. + * + * This method may be called on any thread (usually by the input manager). */ + virtual void dump(std::string& dump) = 0; + + /* Called by the heatbeat to ensures that the reader has not deadlocked. */ + virtual void monitor() = 0; + + /* Returns true if the input device is enabled. */ + virtual bool isInputDeviceEnabled(int32_t deviceId) = 0; + + /* Runs a single iteration of the processing loop. + * Nominally reads and processes one incoming message from the EventHub. + * + * This method should be called on the input reader thread. + */ + virtual void loopOnce() = 0; + + /* Gets information about all input devices. + * + * This method may be called on any thread (usually by the input manager). + */ + virtual void getInputDevices(Vector& outInputDevices) = 0; + + /* Query current input state. */ + virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask, + int32_t scanCode) = 0; + virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask, + int32_t keyCode) = 0; + virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask, + int32_t sw) = 0; + + /* Toggle Caps Lock */ + virtual void toggleCapsLockState(int32_t deviceId) = 0; + + /* Determine whether physical keys exist for the given framework-domain key codes. */ + virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask, + size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) = 0; + + /* Requests that a reconfiguration of all input devices. + * The changes flag is a bitfield that indicates what has changed and whether + * the input devices must all be reopened. */ + virtual void requestRefreshConfiguration(uint32_t changes) = 0; + + /* Controls the vibrator of a particular input device. */ + virtual void vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize, + ssize_t repeat, int32_t token) = 0; + virtual void cancelVibrate(int32_t deviceId, int32_t token) = 0; +}; + +/* Reads raw events from the event hub and processes them, endlessly. */ +class InputReaderThread : public Thread { +public: + explicit InputReaderThread(const sp& reader); + virtual ~InputReaderThread(); + +private: + sp mReader; + + virtual bool threadLoop(); +}; + +/* + * Input reader configuration. + * + * Specifies various options that modify the behavior of the input reader. + */ +struct InputReaderConfiguration { + // Describes changes that have occurred. + enum { + // The pointer speed changed. + CHANGE_POINTER_SPEED = 1 << 0, + + // The pointer gesture control changed. + CHANGE_POINTER_GESTURE_ENABLEMENT = 1 << 1, + + // The display size or orientation changed. + CHANGE_DISPLAY_INFO = 1 << 2, + + // The visible touches option changed. + CHANGE_SHOW_TOUCHES = 1 << 3, + + // The keyboard layouts must be reloaded. + CHANGE_KEYBOARD_LAYOUTS = 1 << 4, + + // The device name alias supplied by the may have changed for some devices. + CHANGE_DEVICE_ALIAS = 1 << 5, + + // The location calibration matrix changed. + CHANGE_TOUCH_AFFINE_TRANSFORMATION = 1 << 6, + + // The presence of an external stylus has changed. + CHANGE_EXTERNAL_STYLUS_PRESENCE = 1 << 7, + + // The pointer capture mode has changed. + CHANGE_POINTER_CAPTURE = 1 << 8, + + // The set of disabled input devices (disabledDevices) has changed. + CHANGE_ENABLED_STATE = 1 << 9, + + // All devices must be reopened. + CHANGE_MUST_REOPEN = 1 << 31, + }; + + // Gets the amount of time to disable virtual keys after the screen is touched + // in order to filter out accidental virtual key presses due to swiping gestures + // or taps near the edge of the display. May be 0 to disable the feature. + nsecs_t virtualKeyQuietTime; + + // The excluded device names for the platform. + // Devices with these names will be ignored. + std::vector excludedDeviceNames; + + // Velocity control parameters for mouse pointer movements. + VelocityControlParameters pointerVelocityControlParameters; + + // Velocity control parameters for mouse wheel movements. + VelocityControlParameters wheelVelocityControlParameters; + + // True if pointer gestures are enabled. + bool pointerGesturesEnabled; + + // Quiet time between certain pointer gesture transitions. + // Time to allow for all fingers or buttons to settle into a stable state before + // starting a new gesture. + nsecs_t pointerGestureQuietInterval; + + // The minimum speed that a pointer must travel for us to consider switching the active + // touch pointer to it during a drag. This threshold is set to avoid switching due + // to noise from a finger resting on the touch pad (perhaps just pressing it down). + float pointerGestureDragMinSwitchSpeed; // in pixels per second + + // Tap gesture delay time. + // The time between down and up must be less than this to be considered a tap. + nsecs_t pointerGestureTapInterval; + + // Tap drag gesture delay time. + // The time between the previous tap's up and the next down must be less than + // this to be considered a drag. Otherwise, the previous tap is finished and a + // new tap begins. + // + // Note that the previous tap will be held down for this entire duration so this + // interval must be shorter than the long press timeout. + nsecs_t pointerGestureTapDragInterval; + + // The distance in pixels that the pointer is allowed to move from initial down + // to up and still be called a tap. + float pointerGestureTapSlop; // in pixels + + // Time after the first touch points go down to settle on an initial centroid. + // This is intended to be enough time to handle cases where the user puts down two + // fingers at almost but not quite exactly the same time. + nsecs_t pointerGestureMultitouchSettleInterval; + + // The transition from PRESS to SWIPE or FREEFORM gesture mode is made when + // at least two pointers have moved at least this far from their starting place. + float pointerGestureMultitouchMinDistance; // in pixels + + // The transition from PRESS to SWIPE gesture mode can only occur when the + // cosine of the angle between the two vectors is greater than or equal to than this value + // which indicates that the vectors are oriented in the same direction. + // When the vectors are oriented in the exactly same direction, the cosine is 1.0. + // (In exactly opposite directions, the cosine is -1.0.) + float pointerGestureSwipeTransitionAngleCosine; + + // The transition from PRESS to SWIPE gesture mode can only occur when the + // fingers are no more than this far apart relative to the diagonal size of + // the touch pad. For example, a ratio of 0.5 means that the fingers must be + // no more than half the diagonal size of the touch pad apart. + float pointerGestureSwipeMaxWidthRatio; + + // The gesture movement speed factor relative to the size of the display. + // Movement speed applies when the fingers are moving in the same direction. + // Without acceleration, a full swipe of the touch pad diagonal in movement mode + // will cover this portion of the display diagonal. + float pointerGestureMovementSpeedRatio; + + // The gesture zoom speed factor relative to the size of the display. + // Zoom speed applies when the fingers are mostly moving relative to each other + // to execute a scale gesture or similar. + // Without acceleration, a full swipe of the touch pad diagonal in zoom mode + // will cover this portion of the display diagonal. + float pointerGestureZoomSpeedRatio; + + // True to show the location of touches on the touch screen as spots. + bool showTouches; + + // True if pointer capture is enabled. + bool pointerCapture; + + // The set of currently disabled input devices. + SortedVector disabledDevices; + + InputReaderConfiguration() : + virtualKeyQuietTime(0), + pointerVelocityControlParameters(1.0f, 500.0f, 3000.0f, 3.0f), + wheelVelocityControlParameters(1.0f, 15.0f, 50.0f, 4.0f), + pointerGesturesEnabled(true), + pointerGestureQuietInterval(100 * 1000000LL), // 100 ms + pointerGestureDragMinSwitchSpeed(50), // 50 pixels per second + pointerGestureTapInterval(150 * 1000000LL), // 150 ms + pointerGestureTapDragInterval(150 * 1000000LL), // 150 ms + pointerGestureTapSlop(10.0f), // 10 pixels + pointerGestureMultitouchSettleInterval(100 * 1000000LL), // 100 ms + pointerGestureMultitouchMinDistance(15), // 15 pixels + pointerGestureSwipeTransitionAngleCosine(0.2588f), // cosine of 75 degrees + pointerGestureSwipeMaxWidthRatio(0.25f), + pointerGestureMovementSpeedRatio(0.8f), + pointerGestureZoomSpeedRatio(0.3f), + showTouches(false) { } + + std::optional getDisplayViewport(ViewportType viewportType, + const std::string& uniqueDisplayId) const; + void setDisplayViewports(const std::vector& viewports); + + + void dump(std::string& dump) const; + void dumpViewport(std::string& dump, const DisplayViewport& viewport) const; + +private: + std::vector mDisplays; +}; + +struct TouchAffineTransformation { + float x_scale; + float x_ymix; + float x_offset; + float y_xmix; + float y_scale; + float y_offset; + + TouchAffineTransformation() : + x_scale(1.0f), x_ymix(0.0f), x_offset(0.0f), + y_xmix(0.0f), y_scale(1.0f), y_offset(0.0f) { + } + + TouchAffineTransformation(float xscale, float xymix, float xoffset, + float yxmix, float yscale, float yoffset) : + x_scale(xscale), x_ymix(xymix), x_offset(xoffset), + y_xmix(yxmix), y_scale(yscale), y_offset(yoffset) { + } + + void applyTo(float& x, float& y) const; +}; + +/* + * Input reader policy interface. + * + * The input reader policy is used by the input reader to interact with the Window Manager + * and other system components. + * + * The actual implementation is partially supported by callbacks into the DVM + * via JNI. This interface is also mocked in the unit tests. + * + * These methods must NOT re-enter the input reader since they may be called while + * holding the input reader lock. + */ +class InputReaderPolicyInterface : public virtual RefBase { +protected: + InputReaderPolicyInterface() { } + virtual ~InputReaderPolicyInterface() { } + +public: + /* Gets the input reader configuration. */ + virtual void getReaderConfiguration(InputReaderConfiguration* outConfig) = 0; + + /* Gets a pointer controller associated with the specified cursor device (ie. a mouse). */ + virtual sp obtainPointerController(int32_t deviceId) = 0; + + /* Notifies the input reader policy that some input devices have changed + * and provides information about all current input devices. + */ + virtual void notifyInputDevicesChanged(const Vector& inputDevices) = 0; + + /* Gets the keyboard layout for a particular input device. */ + virtual sp getKeyboardLayoutOverlay( + const InputDeviceIdentifier& identifier) = 0; + + /* Gets a user-supplied alias for a particular input device, or an empty string if none. */ + virtual std::string getDeviceAlias(const InputDeviceIdentifier& identifier) = 0; + + /* Gets the affine calibration associated with the specified device. */ + virtual TouchAffineTransformation getTouchAffineTransformation( + const std::string& inputDeviceDescriptor, int32_t surfaceRotation) = 0; +}; + +} // namespace android + +#endif // _UI_INPUT_READER_COMMON_H \ No newline at end of file diff --git a/services/inputflinger/include/InputReaderFactory.h b/services/inputflinger/include/InputReaderFactory.h new file mode 100644 index 0000000000..9db6233d28 --- /dev/null +++ b/services/inputflinger/include/InputReaderFactory.h @@ -0,0 +1,29 @@ +/* + * Copyright 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +namespace android { + +class InputReaderInterface; +class InputReaderPolicyInterface; +class InputListenerInterface; + +sp createInputReader( + const sp& policy, + const sp& listener); + +} // namespace android diff --git a/services/inputflinger/include/PointerControllerInterface.h b/services/inputflinger/include/PointerControllerInterface.h new file mode 100644 index 0000000000..e94dd94868 --- /dev/null +++ b/services/inputflinger/include/PointerControllerInterface.h @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _INPUTFLINGER_POINTER_CONTROLLER_INTERFACE_H +#define _INPUTFLINGER_POINTER_CONTROLLER_INTERFACE_H + +#include +#include +#include + +namespace android { + +/** + * Interface for tracking a mouse / touch pad pointer and touch pad spots. + * + * The spots are sprites on screen that visually represent the positions of + * fingers + * + * The pointer controller is responsible for providing synchronization and for tracking + * display orientation changes if needed. + */ +class PointerControllerInterface : public virtual RefBase { +protected: + PointerControllerInterface() { } + virtual ~PointerControllerInterface() { } + +public: + /* Gets the bounds of the region that the pointer can traverse. + * Returns true if the bounds are available. */ + virtual bool getBounds(float* outMinX, float* outMinY, + float* outMaxX, float* outMaxY) const = 0; + + /* Move the pointer. */ + virtual void move(float deltaX, float deltaY) = 0; + + /* Sets a mask that indicates which buttons are pressed. */ + virtual void setButtonState(int32_t buttonState) = 0; + + /* Gets a mask that indicates which buttons are pressed. */ + virtual int32_t getButtonState() const = 0; + + /* Sets the absolute location of the pointer. */ + virtual void setPosition(float x, float y) = 0; + + /* Gets the absolute location of the pointer. */ + virtual void getPosition(float* outX, float* outY) const = 0; + + enum Transition { + // Fade/unfade immediately. + TRANSITION_IMMEDIATE, + // Fade/unfade gradually. + TRANSITION_GRADUAL, + }; + + /* Fades the pointer out now. */ + virtual void fade(Transition transition) = 0; + + /* Makes the pointer visible if it has faded out. + * The pointer never unfades itself automatically. This method must be called + * by the client whenever the pointer is moved or a button is pressed and it + * wants to ensure that the pointer becomes visible again. */ + virtual void unfade(Transition transition) = 0; + + enum Presentation { + // Show the mouse pointer. + PRESENTATION_POINTER, + // Show spots and a spot anchor in place of the mouse pointer. + PRESENTATION_SPOT, + }; + + /* Sets the mode of the pointer controller. */ + virtual void setPresentation(Presentation presentation) = 0; + + /* Sets the spots for the current gesture. + * The spots are not subject to the inactivity timeout like the pointer + * itself it since they are expected to remain visible for so long as + * the fingers are on the touch pad. + * + * The values of the AMOTION_EVENT_AXIS_PRESSURE axis is significant. + * For spotCoords, pressure != 0 indicates that the spot's location is being + * pressed (not hovering). + */ + virtual void setSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex, + BitSet32 spotIdBits) = 0; + + /* Removes all spots. */ + virtual void clearSpots() = 0; +}; + +} // namespace android + +#endif // _INPUTFLINGER_POINTER_CONTROLLER_INTERFACE_H diff --git a/services/inputflinger/tests/Android.bp b/services/inputflinger/tests/Android.bp index ea42855437..389a57c7f3 100644 --- a/services/inputflinger/tests/Android.bp +++ b/services/inputflinger/tests/Android.bp @@ -24,6 +24,8 @@ cc_test { "libui", "libinput", "libinputflinger", + "libinputreader", + "libinputflinger_base", "libinputservice", ], } -- cgit v1.2.3-59-g8ed1b From 8158e7e33a95732b9963909b9fb471678ff8b7d4 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Mon, 15 Oct 2018 14:28:20 -0700 Subject: Add physical port to display viewport DisplayViewport now also stores the physical port information of the associated display. The physical port of the display can be used to match an input device to the corresponding viewport, therefore ensuring that a specific input device generates events that go to a particular display. The associations are provided to InputReaderConfiguration by the JNI callback. Change getViewport strategy once more. Now, uniqueId match by itself is sufficient (viewport type does not need to match if the viewport with the matching uniqueId is found). Added a check for assumptions about the number of viewports that can have the same type. These should be relaxed once (and if) support for multiple internal viewports is added. Bug: 116239493 Test: atest -a libinput_tests inputflinger_tests Change-Id: I1c84f281e8c255f12aea0d15939c70685fe94c41 --- include/input/DisplayViewport.h | 18 +- services/inputflinger/InputReader.cpp | 120 +++++++++---- services/inputflinger/InputReader.h | 6 + services/inputflinger/InputReaderBase.cpp | 51 +++++- services/inputflinger/include/InputReaderBase.h | 11 +- services/inputflinger/tests/InputReader_test.cpp | 215 +++++++++++++++++------ 6 files changed, 317 insertions(+), 104 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/include/input/DisplayViewport.h b/include/input/DisplayViewport.h index 0de3bb7a08..fa456bb213 100644 --- a/include/input/DisplayViewport.h +++ b/include/input/DisplayViewport.h @@ -20,6 +20,8 @@ #include #include #include +#include +#include using android::base::StringPrintf; @@ -66,13 +68,17 @@ struct DisplayViewport { int32_t deviceWidth; int32_t deviceHeight; std::string uniqueId; + // The actual (hardware) port that the associated display is connected to. + // Not all viewports will have this specified. + std::optional physicalPort; ViewportType type; DisplayViewport() : displayId(ADISPLAY_ID_NONE), orientation(DISPLAY_ORIENTATION_0), logicalLeft(0), logicalTop(0), logicalRight(0), logicalBottom(0), physicalLeft(0), physicalTop(0), physicalRight(0), physicalBottom(0), - deviceWidth(0), deviceHeight(0), uniqueId(), type(ViewportType::VIEWPORT_INTERNAL) { + deviceWidth(0), deviceHeight(0), uniqueId(), physicalPort(std::nullopt), + type(ViewportType::VIEWPORT_INTERNAL) { } bool operator==(const DisplayViewport& other) const { @@ -89,6 +95,7 @@ struct DisplayViewport { && deviceWidth == other.deviceWidth && deviceHeight == other.deviceHeight && uniqueId == other.uniqueId + && physicalPort == other.physicalPort && type == other.type; } @@ -114,16 +121,19 @@ struct DisplayViewport { deviceWidth = width; deviceHeight = height; uniqueId.clear(); + physicalPort = std::nullopt; type = ViewportType::VIEWPORT_INTERNAL; } std::string toString() const { - return StringPrintf("Viewport %s: displayId=%d, orientation=%d, " + return StringPrintf("Viewport %s: displayId=%d, uniqueId=%s, port=%s, orientation=%d, " "logicalFrame=[%d, %d, %d, %d], " "physicalFrame=[%d, %d, %d, %d], " "deviceSize=[%d, %d]", - viewportTypeToString(type), - displayId, orientation, + viewportTypeToString(type), displayId, + uniqueId.c_str(), + physicalPort ? StringPrintf("%" PRIu8, *physicalPort).c_str() : "", + orientation, logicalLeft, logicalTop, logicalRight, logicalBottom, physicalLeft, physicalTop, diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 9dd14dc799..9e748d8975 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -991,6 +991,12 @@ void InputDevice::dump(std::string& dump) { deviceInfo.getDisplayName().c_str()); dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration); dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal)); + dump += StringPrintf(INDENT2 "AssociatedDisplayPort: "); + if (mAssociatedDisplayPort) { + dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort); + } else { + dump += "\n"; + } dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic)); dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources()); dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType()); @@ -1060,6 +1066,20 @@ void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config setEnabled(enabled, when); } + if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { + // In most situations, no port will be specified. + mAssociatedDisplayPort = std::nullopt; + // Find the display port that corresponds to the current input port. + const std::string& inputPort = mIdentifier.location; + if (!inputPort.empty()) { + const std::unordered_map& ports = config->portAssociations; + const auto& displayPort = ports.find(inputPort); + if (displayPort != ports.end()) { + mAssociatedDisplayPort = std::make_optional(displayPort->second); + } + } + } + size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; @@ -2203,7 +2223,7 @@ void KeyboardInputMapper::configure(nsecs_t when, if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { if (mParameters.orientationAware) { - mViewport = config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, ""); + mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL); } } } @@ -2613,7 +2633,7 @@ void CursorInputMapper::configure(nsecs_t when, mOrientation = DISPLAY_ORIENTATION_0; if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { std::optional internalViewport = - config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, ""); + config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL); if (internalViewport) { mOrientation = internalViewport->orientation; } @@ -2929,7 +2949,7 @@ void RotaryEncoderInputMapper::configure(nsecs_t when, } if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { std::optional internalViewport = - config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, ""); + config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL); if (internalViewport) { mOrientation = internalViewport->orientation; } else { @@ -3310,6 +3330,9 @@ void TouchInputMapper::configureParameters() { mParameters.uniqueDisplayId = uniqueDisplayId.c_str(); } } + if (getDevice()->getAssociatedDisplayPort()) { + mParameters.hasAssociatedDisplay = true; + } // Initial downs on external touch devices should wake the device. // Normally we don't do this for internal touch screens to prevent them from waking @@ -3384,6 +3407,49 @@ bool TouchInputMapper::hasExternalStylus() const { return mExternalStylusConnected; } +/** + * Determine which DisplayViewport to use. + * 1. If display port is specified, return the matching viewport. If matching viewport not + * found, then return. + * 2. If a device has associated display, get the matching viewport by either unique id or by + * the display type (internal or external). + * 3. Otherwise, use a non-display viewport. + */ +std::optional TouchInputMapper::findViewport() { + if (mParameters.hasAssociatedDisplay) { + const std::optional displayPort = mDevice->getAssociatedDisplayPort(); + if (displayPort) { + // Find the viewport that contains the same port + std::optional v = mConfig.getDisplayViewportByPort(*displayPort); + if (!v) { + ALOGW("Input device %s should be associated with display on port %" PRIu8 ", " + "but the corresponding viewport is not found.", + getDeviceName().c_str(), *displayPort); + } + return v; + } + + if (!mParameters.uniqueDisplayId.empty()) { + return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId); + } + + ViewportType viewportTypeToUse; + if (mParameters.associatedDisplayIsExternal) { + viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL; + } else { + viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL; + } + return mConfig.getDisplayViewportByType(viewportTypeToUse); + } + + DisplayViewport newViewport; + // Raw width and height in the natural orientation. + int32_t rawWidth = mRawPointerAxes.getRawWidth(); + int32_t rawHeight = mRawPointerAxes.getRawHeight(); + newViewport.setNonDisplayViewport(rawWidth, rawHeight); + return std::make_optional(newViewport); +} + void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { int32_t oldDeviceMode = mDeviceMode; @@ -3417,50 +3483,30 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { // Ensure we have valid X and Y axes. if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) { - ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! " + ALOGW("Touch device '%s' did not report support for X or Y axis! " "The device will be inoperable.", getDeviceName().c_str()); mDeviceMode = DEVICE_MODE_DISABLED; return; } + // Get associated display dimensions. + std::optional newViewport = findViewport(); + if (!newViewport) { + ALOGI("Touch device '%s' could not query the properties of its associated " + "display. The device will be inoperable until the display size " + "becomes available.", + getDeviceName().c_str()); + mDeviceMode = DEVICE_MODE_DISABLED; + return; + } + // Raw width and height in the natural orientation. int32_t rawWidth = mRawPointerAxes.getRawWidth(); int32_t rawHeight = mRawPointerAxes.getRawHeight(); - // Get associated display dimensions. - DisplayViewport newViewport; - if (mParameters.hasAssociatedDisplay) { - std::string uniqueDisplayId; - ViewportType viewportTypeToUse; - - if (mParameters.associatedDisplayIsExternal) { - viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL; - } else if (!mParameters.uniqueDisplayId.empty()) { - // If the IDC file specified a unique display Id, then it expects to be linked to a - // virtual display with the same unique ID. - uniqueDisplayId = mParameters.uniqueDisplayId; - viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL; - } else { - viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL; - } - - std::optional viewportToUse = - mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId); - if (!viewportToUse) { - ALOGI(INDENT "Touch device '%s' could not query the properties of its associated " - "display. The device will be inoperable until the display size " - "becomes available.", - getDeviceName().c_str()); - mDeviceMode = DEVICE_MODE_DISABLED; - return; - } - newViewport = *viewportToUse; - } else { - newViewport.setNonDisplayViewport(rawWidth, rawHeight); - } - bool viewportChanged = mViewport != newViewport; + bool viewportChanged = mViewport != *newViewport; if (viewportChanged) { - mViewport = newViewport; + mViewport = *newViewport; if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) { // Convert rotated viewport to natural surface coordinates. diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h index 1786fe8f26..13f1bedb65 100644 --- a/services/inputflinger/InputReader.h +++ b/services/inputflinger/InputReader.h @@ -252,6 +252,9 @@ public: inline bool isExternal() { return mIsExternal; } inline void setExternal(bool external) { mIsExternal = external; } + inline std::optional getAssociatedDisplayPort() const { + return mAssociatedDisplayPort; + } inline void setMic(bool hasMic) { mHasMic = hasMic; } inline bool hasMic() const { return mHasMic; } @@ -324,6 +327,7 @@ private: uint32_t mSources; bool mIsExternal; + std::optional mAssociatedDisplayPort; bool mHasMic; bool mDropUntilNextSync; @@ -1501,6 +1505,8 @@ private: VelocityControl mWheelXVelocityControl; VelocityControl mWheelYVelocityControl; + std::optional findViewport(); + void resetExternalStylus(); void clearStylusDataPendingFlags(); diff --git a/services/inputflinger/InputReaderBase.cpp b/services/inputflinger/InputReaderBase.cpp index 17a116e822..f48a64551e 100644 --- a/services/inputflinger/InputReaderBase.cpp +++ b/services/inputflinger/InputReaderBase.cpp @@ -49,14 +49,51 @@ bool InputReaderThread::threadLoop() { // --- InputReaderConfiguration --- -std::optional InputReaderConfiguration::getDisplayViewport( - ViewportType viewportType, const std::string& uniqueDisplayId) const { +std::optional InputReaderConfiguration::getDisplayViewportByUniqueId( + const std::string& uniqueDisplayId) const { + if (uniqueDisplayId.empty()) { + ALOGE("Empty string provided to %s", __func__); + return std::nullopt; + } + size_t count = 0; + std::optional result = std::nullopt; + for (const DisplayViewport& currentViewport : mDisplays) { + if (uniqueDisplayId == currentViewport.uniqueId) { + result = std::make_optional(currentViewport); + count++; + } + } + if (count > 1) { + ALOGE("Found %zu viewports with uniqueId %s, but expected 1 at most", + count, uniqueDisplayId.c_str()); + } + return result; +} + +std::optional InputReaderConfiguration::getDisplayViewportByType(ViewportType type) + const { + size_t count = 0; + std::optional result = std::nullopt; + for (const DisplayViewport& currentViewport : mDisplays) { + // Return the first match + if (currentViewport.type == type && !result) { + result = std::make_optional(currentViewport); + count++; + } + } + if (count > 1) { + ALOGE("Found %zu viewports with type %s, but expected 1 at most", + count, viewportTypeToString(type)); + } + return result; +} + +std::optional InputReaderConfiguration::getDisplayViewportByPort( + uint8_t displayPort) const { for (const DisplayViewport& currentViewport : mDisplays) { - if (currentViewport.type == viewportType) { - if (uniqueDisplayId.empty() || - (!uniqueDisplayId.empty() && uniqueDisplayId == currentViewport.uniqueId)) { - return std::make_optional(currentViewport); - } + const std::optional& physicalPort = currentViewport.physicalPort; + if (physicalPort && (*physicalPort == displayPort)) { + return std::make_optional(currentViewport); } } return std::nullopt; diff --git a/services/inputflinger/include/InputReaderBase.h b/services/inputflinger/include/InputReaderBase.h index fff8480f57..fe1c50bc75 100644 --- a/services/inputflinger/include/InputReaderBase.h +++ b/services/inputflinger/include/InputReaderBase.h @@ -32,6 +32,7 @@ #include #include #include +#include #include // Maximum supported size of a vibration pattern. @@ -164,6 +165,10 @@ struct InputReaderConfiguration { // Devices with these names will be ignored. std::vector excludedDeviceNames; + // The associations between input ports and display ports. + // Used to determine which DisplayViewport should be tied to which InputDevice. + std::unordered_map portAssociations; + // Velocity control parameters for mouse pointer movements. VelocityControlParameters pointerVelocityControlParameters; @@ -262,8 +267,10 @@ struct InputReaderConfiguration { pointerGestureZoomSpeedRatio(0.3f), showTouches(false) { } - std::optional getDisplayViewport(ViewportType viewportType, - const std::string& uniqueDisplayId) const; + std::optional getDisplayViewportByType(ViewportType type) const; + std::optional getDisplayViewportByUniqueId(const std::string& uniqueDisplayId) + const; + std::optional getDisplayViewportByPort(uint8_t physicalPort) const; void setDisplayViewports(const std::vector& viewports); diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index 929424b8b9..04b87d5a33 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -28,12 +28,14 @@ static const nsecs_t ARBITRARY_TIME = 1234; // Arbitrary display properties. static const int32_t DISPLAY_ID = 0; +static const int32_t SECONDARY_DISPLAY_ID = DISPLAY_ID + 1; static const int32_t DISPLAY_WIDTH = 480; static const int32_t DISPLAY_HEIGHT = 800; static const int32_t VIRTUAL_DISPLAY_ID = 1; static const int32_t VIRTUAL_DISPLAY_WIDTH = 400; static const int32_t VIRTUAL_DISPLAY_HEIGHT = 500; static const char* VIRTUAL_DISPLAY_UNIQUE_ID = "virtual:1"; +static constexpr std::optional NO_PORT = std::nullopt; // no physical port is specified // Error tolerance for floating point assertions. static const float EPSILON = 0.001f; @@ -147,15 +149,22 @@ public: mConfig.setDisplayViewports(mViewports); } - std::optional getDisplayViewport(ViewportType viewportType, - const std::string& uniqueId) { - return mConfig.getDisplayViewport(viewportType, uniqueId); + std::optional getDisplayViewportByUniqueId(const std::string& uniqueId) const { + return mConfig.getDisplayViewportByUniqueId(uniqueId); + } + std::optional getDisplayViewportByType(ViewportType type) const { + return mConfig.getDisplayViewportByType(type); + } + + std::optional getDisplayViewportByPort(uint8_t displayPort) const { + return mConfig.getDisplayViewportByPort(displayPort); } void addDisplayViewport(int32_t displayId, int32_t width, int32_t height, int32_t orientation, - const std::string& uniqueId, ViewportType viewportType) { + const std::string& uniqueId, std::optional physicalPort, + ViewportType viewportType) { const DisplayViewport viewport = createDisplayViewport(displayId, width, height, - orientation, uniqueId, viewportType); + orientation, uniqueId, physicalPort, viewportType); mViewports.push_back(viewport); mConfig.setDisplayViewports(mViewports); } @@ -164,6 +173,10 @@ public: mConfig.excludedDeviceNames.push_back(deviceName); } + void addInputPortAssociation(const std::string& inputPort, uint8_t displayPort) { + mConfig.portAssociations.insert({inputPort, displayPort}); + } + void addDisabledDevice(int32_t deviceId) { ssize_t index = mConfig.disabledDevices.indexOf(deviceId); bool currentlyEnabled = index < 0; @@ -207,7 +220,8 @@ public: private: DisplayViewport createDisplayViewport(int32_t displayId, int32_t width, int32_t height, - int32_t orientation, const std::string& uniqueId, ViewportType type) { + int32_t orientation, const std::string& uniqueId, std::optional physicalPort, + ViewportType type) { bool isRotated = (orientation == DISPLAY_ORIENTATION_90 || orientation == DISPLAY_ORIENTATION_270); DisplayViewport v; @@ -224,6 +238,7 @@ private: v.deviceWidth = isRotated ? height : width; v.deviceHeight = isRotated ? width : height; v.uniqueId = uniqueId; + v.physicalPort = physicalPort; v.type = type; return v; } @@ -1105,26 +1120,28 @@ TEST_F(InputReaderPolicyTest, Viewports_GetCleared) { // We didn't add any viewports yet, so there shouldn't be any. std::optional internalViewport = - mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, uniqueId); + mFakePolicy->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL); ASSERT_FALSE(internalViewport); // Add an internal viewport, then clear it mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_0, uniqueId, ViewportType::VIEWPORT_INTERNAL); + DISPLAY_ORIENTATION_0, uniqueId, NO_PORT, ViewportType::VIEWPORT_INTERNAL); // Check matching by uniqueId - internalViewport = mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, uniqueId); + internalViewport = mFakePolicy->getDisplayViewportByUniqueId(uniqueId); ASSERT_TRUE(internalViewport); + ASSERT_EQ(ViewportType::VIEWPORT_INTERNAL, internalViewport->type); // Check matching by viewport type - internalViewport = mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, ""); + internalViewport = mFakePolicy->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL); ASSERT_TRUE(internalViewport); + ASSERT_EQ(uniqueId, internalViewport->uniqueId); mFakePolicy->clearViewports(); // Make sure nothing is found after clear - internalViewport = mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, uniqueId); + internalViewport = mFakePolicy->getDisplayViewportByUniqueId(uniqueId); ASSERT_FALSE(internalViewport); - internalViewport = mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, ""); + internalViewport = mFakePolicy->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL); ASSERT_FALSE(internalViewport); } @@ -1138,40 +1155,42 @@ TEST_F(InputReaderPolicyTest, Viewports_GetByType) { // Add an internal viewport mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_0, internalUniqueId, ViewportType::VIEWPORT_INTERNAL); + DISPLAY_ORIENTATION_0, internalUniqueId, NO_PORT, ViewportType::VIEWPORT_INTERNAL); // Add an external viewport mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_0, externalUniqueId, ViewportType::VIEWPORT_EXTERNAL); + DISPLAY_ORIENTATION_0, externalUniqueId, NO_PORT, ViewportType::VIEWPORT_EXTERNAL); // Add an virtual viewport mFakePolicy->addDisplayViewport(virtualDisplayId1, DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_0, virtualUniqueId1, ViewportType::VIEWPORT_VIRTUAL); + DISPLAY_ORIENTATION_0, virtualUniqueId1, NO_PORT, ViewportType::VIEWPORT_VIRTUAL); // Add another virtual viewport mFakePolicy->addDisplayViewport(virtualDisplayId2, DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_0, virtualUniqueId2, ViewportType::VIEWPORT_VIRTUAL); + DISPLAY_ORIENTATION_0, virtualUniqueId2, NO_PORT, ViewportType::VIEWPORT_VIRTUAL); // Check matching by type for internal std::optional internalViewport = - mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, ""); + mFakePolicy->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL); ASSERT_TRUE(internalViewport); ASSERT_EQ(internalUniqueId, internalViewport->uniqueId); // Check matching by type for external std::optional externalViewport = - mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_EXTERNAL, ""); + mFakePolicy->getDisplayViewportByType(ViewportType::VIEWPORT_EXTERNAL); ASSERT_TRUE(externalViewport); ASSERT_EQ(externalUniqueId, externalViewport->uniqueId); // Check matching by uniqueId for virtual viewport #1 std::optional virtualViewport1 = - mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_VIRTUAL, virtualUniqueId1); + mFakePolicy->getDisplayViewportByUniqueId(virtualUniqueId1); ASSERT_TRUE(virtualViewport1); + ASSERT_EQ(ViewportType::VIEWPORT_VIRTUAL, virtualViewport1->type); ASSERT_EQ(virtualUniqueId1, virtualViewport1->uniqueId); ASSERT_EQ(virtualDisplayId1, virtualViewport1->displayId); // Check matching by uniqueId for virtual viewport #2 std::optional virtualViewport2 = - mFakePolicy->getDisplayViewport(ViewportType::VIEWPORT_VIRTUAL, virtualUniqueId2); + mFakePolicy->getDisplayViewportByUniqueId(virtualUniqueId2); ASSERT_TRUE(virtualViewport2); + ASSERT_EQ(ViewportType::VIEWPORT_VIRTUAL, virtualViewport2->type); ASSERT_EQ(virtualUniqueId2, virtualViewport2->uniqueId); ASSERT_EQ(virtualDisplayId2, virtualViewport2->displayId); } @@ -1194,18 +1213,20 @@ TEST_F(InputReaderPolicyTest, Viewports_TwoOfSameType) { mFakePolicy->clearViewports(); // Add a viewport mFakePolicy->addDisplayViewport(displayId1, DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_0, uniqueId1, type); + DISPLAY_ORIENTATION_0, uniqueId1, NO_PORT, type); // Add another viewport mFakePolicy->addDisplayViewport(displayId2, DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_0, uniqueId2, type); + DISPLAY_ORIENTATION_0, uniqueId2, NO_PORT, type); // Check that correct display viewport was returned by comparing the display IDs. - std::optional viewport1 = mFakePolicy->getDisplayViewport(type, uniqueId1); + std::optional viewport1 = + mFakePolicy->getDisplayViewportByUniqueId(uniqueId1); ASSERT_TRUE(viewport1); ASSERT_EQ(displayId1, viewport1->displayId); ASSERT_EQ(type, viewport1->type); - std::optional viewport2 = mFakePolicy->getDisplayViewport(type, uniqueId2); + std::optional viewport2 = + mFakePolicy->getDisplayViewportByUniqueId(uniqueId2); ASSERT_TRUE(viewport2); ASSERT_EQ(displayId2, viewport2->displayId); ASSERT_EQ(type, viewport2->type); @@ -1216,11 +1237,50 @@ TEST_F(InputReaderPolicyTest, Viewports_TwoOfSameType) { // is just implementation detail. // However, we can check that it still returns *a* viewport, we just cannot assert // which one specifically is returned. - std::optional someViewport = mFakePolicy->getDisplayViewport(type, ""); + std::optional someViewport = mFakePolicy->getDisplayViewportByType(type); ASSERT_TRUE(someViewport); } } +/** + * Check getDisplayViewportByPort + */ +TEST_F(InputReaderPolicyTest, Viewports_GetByPort) { + constexpr ViewportType type = ViewportType::VIEWPORT_EXTERNAL; + const std::string uniqueId1 = "uniqueId1"; + const std::string uniqueId2 = "uniqueId2"; + constexpr int32_t displayId1 = 1; + constexpr int32_t displayId2 = 2; + const uint8_t hdmi1 = 0; + const uint8_t hdmi2 = 1; + const uint8_t hdmi3 = 2; + + mFakePolicy->clearViewports(); + // Add a viewport that's associated with some display port that's not of interest. + mFakePolicy->addDisplayViewport(displayId1, DISPLAY_WIDTH, DISPLAY_HEIGHT, + DISPLAY_ORIENTATION_0, uniqueId1, hdmi3, type); + // Add another viewport, connected to HDMI1 port + mFakePolicy->addDisplayViewport(displayId2, DISPLAY_WIDTH, DISPLAY_HEIGHT, + DISPLAY_ORIENTATION_0, uniqueId2, hdmi1, type); + + // Check that correct display viewport was returned by comparing the display ports. + std::optional hdmi1Viewport = mFakePolicy->getDisplayViewportByPort(hdmi1); + ASSERT_TRUE(hdmi1Viewport); + ASSERT_EQ(displayId2, hdmi1Viewport->displayId); + ASSERT_EQ(uniqueId2, hdmi1Viewport->uniqueId); + + // Check that we can still get the same viewport using the uniqueId + hdmi1Viewport = mFakePolicy->getDisplayViewportByUniqueId(uniqueId2); + ASSERT_TRUE(hdmi1Viewport); + ASSERT_EQ(displayId2, hdmi1Viewport->displayId); + ASSERT_EQ(uniqueId2, hdmi1Viewport->uniqueId); + ASSERT_EQ(type, hdmi1Viewport->type); + + // Check that we cannot find a port with "HDMI2", because we never added one + std::optional hdmi2Viewport = mFakePolicy->getDisplayViewportByPort(hdmi2); + ASSERT_FALSE(hdmi2Viewport); +} + // --- InputReaderTest --- class InputReaderTest : public testing::Test { @@ -1696,6 +1756,7 @@ TEST_F(InputDeviceTest, WhenMappersAreRegistered_DeviceIsNotIgnoredAndForwardsRe class InputMapperTest : public testing::Test { protected: static const char* DEVICE_NAME; + static const char* DEVICE_LOCATION; static const int32_t DEVICE_ID; static const int32_t DEVICE_GENERATION; static const int32_t DEVICE_CONTROLLER_NUMBER; @@ -1714,10 +1775,11 @@ protected: mFakeContext = new FakeInputReaderContext(mFakeEventHub, mFakePolicy, mFakeListener); InputDeviceIdentifier identifier; identifier.name = DEVICE_NAME; + identifier.location = DEVICE_LOCATION; mDevice = new InputDevice(mFakeContext, DEVICE_ID, DEVICE_GENERATION, DEVICE_CONTROLLER_NUMBER, identifier, DEVICE_CLASSES); - mFakeEventHub->addDevice(DEVICE_ID, DEVICE_NAME, 0); + mFakeEventHub->addDevice(mDevice->getId(), DEVICE_NAME, 0); } virtual void TearDown() { @@ -1729,7 +1791,7 @@ protected: } void addConfigurationProperty(const char* key, const char* value) { - mFakeEventHub->addConfigurationProperty(DEVICE_ID, String8(key), String8(value)); + mFakeEventHub->addConfigurationProperty(mDevice->getId(), String8(key), String8(value)); } void configureDevice(uint32_t changes) { @@ -1743,9 +1805,10 @@ protected: } void setDisplayInfoAndReconfigure(int32_t displayId, int32_t width, int32_t height, - int32_t orientation, const std::string& uniqueId, ViewportType viewportType) { + int32_t orientation, const std::string& uniqueId, + std::optional physicalPort, ViewportType viewportType) { mFakePolicy->addDisplayViewport( - displayId, width, height, orientation, uniqueId, viewportType); + displayId, width, height, orientation, uniqueId, physicalPort, viewportType); configureDevice(InputReaderConfiguration::CHANGE_DISPLAY_INFO); } @@ -1801,6 +1864,7 @@ protected: }; const char* InputMapperTest::DEVICE_NAME = "device"; +const char* InputMapperTest::DEVICE_LOCATION = "USB1"; const int32_t InputMapperTest::DEVICE_ID = 1; const int32_t InputMapperTest::DEVICE_GENERATION = 2; const int32_t InputMapperTest::DEVICE_CONTROLLER_NUMBER = 0; @@ -1867,7 +1931,7 @@ protected: */ void KeyboardInputMapperTest::prepareDisplay(int32_t orientation) { setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, - orientation, UNIQUE_ID, ViewportType::VIEWPORT_INTERNAL); + orientation, UNIQUE_ID, NO_PORT, ViewportType::VIEWPORT_INTERNAL); } void KeyboardInputMapperTest::testDPadKeyRotation(KeyboardInputMapper* mapper, @@ -2170,7 +2234,7 @@ TEST_F(KeyboardInputMapperTest, DisplayIdConfigurationChange_OrientationAware) { // ^--- already checked by the previous test setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0, - UNIQUE_ID, ViewportType::VIEWPORT_INTERNAL); + UNIQUE_ID, NO_PORT, ViewportType::VIEWPORT_INTERNAL); process(mapper, ARBITRARY_TIME, EV_KEY, KEY_UP, 1); ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); process(mapper, ARBITRARY_TIME, EV_KEY, KEY_UP, 0); @@ -2180,7 +2244,7 @@ TEST_F(KeyboardInputMapperTest, DisplayIdConfigurationChange_OrientationAware) { constexpr int32_t newDisplayId = 2; clearViewports(); setDisplayInfoAndReconfigure(newDisplayId, DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0, - UNIQUE_ID, ViewportType::VIEWPORT_INTERNAL); + UNIQUE_ID, NO_PORT, ViewportType::VIEWPORT_INTERNAL); process(mapper, ARBITRARY_TIME, EV_KEY, KEY_UP, 1); ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args)); process(mapper, ARBITRARY_TIME, EV_KEY, KEY_UP, 0); @@ -2305,11 +2369,18 @@ protected: InputMapperTest::SetUp(); mFakePointerController = new FakePointerController(); - mFakePolicy->setPointerController(DEVICE_ID, mFakePointerController); + mFakePolicy->setPointerController(mDevice->getId(), mFakePointerController); } void testMotionRotation(CursorInputMapper* mapper, int32_t originalX, int32_t originalY, int32_t rotatedX, int32_t rotatedY); + + void prepareDisplay(int32_t orientation) { + const std::string uniqueId = "local:0"; + const ViewportType viewportType = ViewportType::VIEWPORT_INTERNAL; + setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, + orientation, uniqueId, NO_PORT, viewportType); + } }; const int32_t CursorInputMapperTest::TRACKBALL_MOVEMENT_THRESHOLD = 6; @@ -2599,12 +2670,7 @@ TEST_F(CursorInputMapperTest, Process_WhenNotOrientationAware_ShouldNotRotateMot addConfigurationProperty("cursor.mode", "navigation"); addMapperAndConfigure(mapper); - const std::string uniqueId = "local:0"; - const ViewportType viewportType = ViewportType::VIEWPORT_INTERNAL; - - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, - DISPLAY_ORIENTATION_90, uniqueId, viewportType); + prepareDisplay(DISPLAY_ORIENTATION_90); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, 0, 1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, 1, 1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 0, 1, 0)); @@ -2621,11 +2687,7 @@ TEST_F(CursorInputMapperTest, Process_WhenOrientationAware_ShouldRotateMotions) addConfigurationProperty("cursor.orientationAware", "1"); addMapperAndConfigure(mapper); - const std::string uniqueId = "local:0"; - const ViewportType viewportType = ViewportType::VIEWPORT_INTERNAL; - - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_0, uniqueId, viewportType); + prepareDisplay(DISPLAY_ORIENTATION_0); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, 0, 1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, 1, 1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 0, 1, 0)); @@ -2635,8 +2697,7 @@ TEST_F(CursorInputMapperTest, Process_WhenOrientationAware_ShouldRotateMotions) ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 0, -1, 0)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 1, -1, 1)); - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_90, uniqueId, viewportType); + prepareDisplay(DISPLAY_ORIENTATION_90); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, 1, 0)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, 1, -1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 0, 0, -1)); @@ -2646,8 +2707,7 @@ TEST_F(CursorInputMapperTest, Process_WhenOrientationAware_ShouldRotateMotions) ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 0, 0, 1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 1, 1, 1)); - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_180, uniqueId, viewportType); + prepareDisplay(DISPLAY_ORIENTATION_180); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, 0, -1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, -1, -1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 0, -1, 0)); @@ -2657,8 +2717,7 @@ TEST_F(CursorInputMapperTest, Process_WhenOrientationAware_ShouldRotateMotions) ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 0, 1, 0)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 1, 1, -1)); - setDisplayInfoAndReconfigure(DISPLAY_ID, - DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_ORIENTATION_270, uniqueId, viewportType); + prepareDisplay(DISPLAY_ORIENTATION_270); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, -1, 0)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, -1, 1)); ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 0, 0, 1)); @@ -3104,6 +3163,7 @@ protected: static const VirtualKeyDefinition VIRTUAL_KEYS[2]; const std::string UNIQUE_ID = "local:0"; + const std::string SECONDARY_UNIQUE_ID = "local:1"; enum Axes { POSITION = 1 << 0, @@ -3119,7 +3179,8 @@ protected: TOOL_TYPE = 1 << 10, }; - void prepareDisplay(int32_t orientation); + void prepareDisplay(int32_t orientation, std::optional port = NO_PORT); + void prepareSecondaryDisplay(ViewportType type, std::optional port = NO_PORT); void prepareVirtualDisplay(int32_t orientation); void prepareVirtualKeys(); void prepareLocationCalibration(); @@ -3172,15 +3233,20 @@ const VirtualKeyDefinition TouchInputMapperTest::VIRTUAL_KEYS[2] = { { KEY_MENU, DISPLAY_HEIGHT - 60, DISPLAY_WIDTH + 15, 20, 20 }, }; -void TouchInputMapperTest::prepareDisplay(int32_t orientation) { +void TouchInputMapperTest::prepareDisplay(int32_t orientation, std::optional port) { setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, orientation, - UNIQUE_ID, ViewportType::VIEWPORT_INTERNAL); + UNIQUE_ID, port, ViewportType::VIEWPORT_INTERNAL); +} + +void TouchInputMapperTest::prepareSecondaryDisplay(ViewportType type, std::optional port) { + setDisplayInfoAndReconfigure(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, + DISPLAY_ORIENTATION_0, SECONDARY_UNIQUE_ID, port, type); } void TouchInputMapperTest::prepareVirtualDisplay(int32_t orientation) { setDisplayInfoAndReconfigure(VIRTUAL_DISPLAY_ID, VIRTUAL_DISPLAY_WIDTH, VIRTUAL_DISPLAY_HEIGHT, orientation, - VIRTUAL_DISPLAY_UNIQUE_ID, ViewportType::VIEWPORT_VIRTUAL); + VIRTUAL_DISPLAY_UNIQUE_ID, NO_PORT, ViewportType::VIEWPORT_VIRTUAL); } void TouchInputMapperTest::prepareVirtualKeys() { @@ -6138,5 +6204,46 @@ TEST_F(MultiTouchInputMapperTest, WhenMapperIsReset_TimestampIsCleared) { ASSERT_EQ(0U, args.deviceTimestamp); } +/** + * Set the input device port <--> display port associations, and check that the + * events are routed to the display that matches the display port. + * This can be checked by looking at the displayId of the resulting NotifyMotionArgs. + */ +TEST_F(MultiTouchInputMapperTest, Configure_AssignsDisplayPort) { + MultiTouchInputMapper* mapper = new MultiTouchInputMapper(mDevice); + const std::string usb2 = "USB2"; + const uint8_t hdmi1 = 0; + const uint8_t hdmi2 = 1; + const std::string secondaryUniqueId = "uniqueId2"; + constexpr ViewportType type = ViewportType::VIEWPORT_EXTERNAL; + + addConfigurationProperty("touch.deviceType", "touchScreen"); + prepareAxes(POSITION); + addMapperAndConfigure(mapper); + + mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi1); + mFakePolicy->addInputPortAssociation(usb2, hdmi2); + + // We are intentionally not adding the viewport for display 1 yet. Since the port association + // for this input device is specified, and the matching viewport is not present, + // the input device should be disabled (at the mapper level). + + // Add viewport for display 2 on hdmi2 + prepareSecondaryDisplay(type, hdmi2); + // Send a touch event + processPosition(mapper, 100, 100); + processSync(mapper); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled()); + + // Add viewport for display 1 on hdmi1 + prepareDisplay(DISPLAY_ORIENTATION_0, hdmi1); + // Send a touch event again + processPosition(mapper, 100, 100); + processSync(mapper); + + NotifyMotionArgs args; + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args)); + ASSERT_EQ(DISPLAY_ID, args.displayId); +} } // namespace android -- cgit v1.2.3-59-g8ed1b From 620f6d984101959376f7594a1450e9c70bac4019 Mon Sep 17 00:00:00 2001 From: Andrii Kulian Date: Fri, 14 Sep 2018 16:51:59 -0700 Subject: Support mouse pointer on external displays (1/3) If input source is mouse, InputTouchMapper and CursorInputMapper will assign a PointerController which associated with some display. When dispatch a motion event, it should be assigned the displayId from PointerController. - Add getDisplayId for PointerControllerInterface to get the current associated display id. - Add updatePointerDisplay for InputReaderPolicyInterface to find and associate the specified display viewport. - Add test cases for TouchInputMapper and CursorInputMapper. Bug: 113559891 Test: ActivityView test app Test: atest inputflinger_tests Change-Id: Ifc69374a55f39fbc1572d9ea3f979fcbb83b45c0 --- services/inputflinger/InputReader.cpp | 30 ++++++---- services/inputflinger/include/InputReaderBase.h | 3 + .../include/PointerControllerInterface.h | 3 + services/inputflinger/tests/InputReader_test.cpp | 65 +++++++++++++++++++++- 4 files changed, 88 insertions(+), 13 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 9e748d8975..9ba4140312 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -2638,6 +2638,7 @@ void CursorInputMapper::configure(nsecs_t when, mOrientation = internalViewport->orientation; } } + getPolicy()->updatePointerDisplay(); bumpGeneration(); } } @@ -2783,7 +2784,7 @@ void CursorInputMapper::sync(nsecs_t when) { pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY); - displayId = ADISPLAY_ID_DEFAULT; + displayId = mPointerController->getDisplayId(); } else { pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY); @@ -3601,6 +3602,9 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) { if (mPointerController == nullptr) { mPointerController = getPolicy()->obtainPointerController(getDeviceId()); + getPolicy()->updatePointerDisplay(); + } else if (viewportChanged) { + getPolicy()->updatePointerDisplay(); } } else { mPointerController.clear(); @@ -5387,7 +5391,8 @@ void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlag pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); - NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, + int32_t displayId = mPointerController->getDisplayId(); + NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, @@ -6294,6 +6299,7 @@ void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) { void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down, bool hovering) { int32_t metaState = getContext()->getGlobalMetaState(); + int32_t displayId = mViewport.displayId; if (mPointerController != nullptr) { if (down || hovering) { @@ -6304,13 +6310,14 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } + displayId = mPointerController->getDisplayId(); } if (mPointerSimple.down && !down) { mPointerSimple.down = false; // Send up. - NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, @@ -6323,7 +6330,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.hovering = false; // Send hover exit. - NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, @@ -6338,7 +6345,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.downTime = when; // Send down. - NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, @@ -6348,7 +6355,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } // Send move. - NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, @@ -6362,7 +6369,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.hovering = true; // Send hover enter. - NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, @@ -6373,7 +6380,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } // Send hover move. - NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, @@ -6395,7 +6402,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); - NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &pointerCoords, @@ -6457,8 +6464,9 @@ void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32 ALOG_ASSERT(false); } } - - NotifyMotionArgs args(when, getDeviceId(), source, mViewport.displayId, policyFlags, + int32_t displayId = mPointerController != nullptr ? + mPointerController->getDisplayId() : mViewport.displayId; + NotifyMotionArgs args(when, getDeviceId(), source, displayId, policyFlags, action, actionButton, flags, metaState, buttonState, edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords, xPrecision, yPrecision, downTime); diff --git a/services/inputflinger/include/InputReaderBase.h b/services/inputflinger/include/InputReaderBase.h index fe1c50bc75..5a78df75ff 100644 --- a/services/inputflinger/include/InputReaderBase.h +++ b/services/inputflinger/include/InputReaderBase.h @@ -342,6 +342,9 @@ public: /* Gets the affine calibration associated with the specified device. */ virtual TouchAffineTransformation getTouchAffineTransformation( const std::string& inputDeviceDescriptor, int32_t surfaceRotation) = 0; + + /* Update the pointer controller associated with the specified display. */ + virtual void updatePointerDisplay() = 0; }; } // namespace android diff --git a/services/inputflinger/include/PointerControllerInterface.h b/services/inputflinger/include/PointerControllerInterface.h index e94dd94868..e60b3f48b5 100644 --- a/services/inputflinger/include/PointerControllerInterface.h +++ b/services/inputflinger/include/PointerControllerInterface.h @@ -58,6 +58,9 @@ public: /* Gets the absolute location of the pointer. */ virtual void getPosition(float* outX, float* outY) const = 0; + /* Gets the id of the display where the pointer should be shown. */ + virtual int32_t getDisplayId() const = 0; + enum Transition { // Fade/unfade immediately. TRANSITION_IMMEDIATE, diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index 04b87d5a33..b18cae3e8f 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -57,6 +57,7 @@ class FakePointerController : public PointerControllerInterface { float mMinX, mMinY, mMaxX, mMaxY; float mX, mY; int32_t mButtonState; + int32_t mDisplayId; protected: virtual ~FakePointerController() { } @@ -64,7 +65,7 @@ protected: public: FakePointerController() : mHaveBounds(false), mMinX(0), mMinY(0), mMaxX(0), mMaxY(0), mX(0), mY(0), - mButtonState(0) { + mButtonState(0), mDisplayId(ADISPLAY_ID_DEFAULT) { } void setBounds(float minX, float minY, float maxX, float maxY) { @@ -75,6 +76,10 @@ public: mMaxY = maxY; } + void setDisplayId(int32_t displayId) { + mDisplayId = displayId; + } + virtual void setPosition(float x, float y) { mX = x; mY = y; @@ -93,6 +98,10 @@ public: *outY = mY; } + virtual int32_t getDisplayId() const { + return mDisplayId; + } + private: virtual bool getBounds(float* outMinX, float* outMinY, float* outMaxX, float* outMaxY) const { *outMinX = mMinX; @@ -262,6 +271,9 @@ private: virtual std::string getDeviceAlias(const InputDeviceIdentifier&) { return ""; } + + virtual void updatePointerDisplay() { + } }; @@ -3127,6 +3139,30 @@ TEST_F(CursorInputMapperTest, Process_PointerCapture) { ASSERT_NO_FATAL_FAILURE(assertPosition(mFakePointerController, 110.0f, 220.0f)); } +TEST_F(CursorInputMapperTest, Process_ShouldHandleDisplayId) { + CursorInputMapper* mapper = new CursorInputMapper(mDevice); + addMapperAndConfigure(mapper); + + // Setup PointerController for second display. + constexpr int32_t SECOND_DISPLAY_ID = 1; + mFakePointerController->setBounds(0, 0, 800 - 1, 480 - 1); + mFakePointerController->setPosition(100, 200); + mFakePointerController->setButtonState(0); + mFakePointerController->setDisplayId(SECOND_DISPLAY_ID); + + NotifyMotionArgs args; + process(mapper, ARBITRARY_TIME, EV_REL, REL_X, 10); + process(mapper, ARBITRARY_TIME, EV_REL, REL_Y, 20); + process(mapper, ARBITRARY_TIME, EV_SYN, SYN_REPORT, 0); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args)); + ASSERT_EQ(AINPUT_SOURCE_MOUSE, args.source); + ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, args.action); + ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0], + 110.0f, 220.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f)); + ASSERT_NO_FATAL_FAILURE(assertPosition(mFakePointerController, 110.0f, 220.0f)); + ASSERT_EQ(SECOND_DISPLAY_ID, args.displayId); +} + // --- TouchInputMapperTest --- @@ -4625,7 +4661,6 @@ TEST_F(SingleTouchInputMapperTest, Process_WhenAbsPressureIsPresent_HoversIfItsV toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0)); } - // --- MultiTouchInputMapperTest --- class MultiTouchInputMapperTest : public TouchInputMapperTest { @@ -6246,4 +6281,30 @@ TEST_F(MultiTouchInputMapperTest, Configure_AssignsDisplayPort) { ASSERT_EQ(DISPLAY_ID, args.displayId); } +TEST_F(MultiTouchInputMapperTest, Process_Pointer_ShouldHandleDisplayId) { + // Setup PointerController for second display. + sp fakePointerController = new FakePointerController(); + fakePointerController->setBounds(0, 0, 800 - 1, 480 - 1); + fakePointerController->setPosition(100, 200); + fakePointerController->setButtonState(0); + fakePointerController->setDisplayId(SECONDARY_DISPLAY_ID); + mFakePolicy->setPointerController(mDevice->getId(), fakePointerController); + + MultiTouchInputMapper* mapper = new MultiTouchInputMapper(mDevice); + prepareDisplay(DISPLAY_ORIENTATION_0); + prepareAxes(POSITION); + addMapperAndConfigure(mapper); + + // Check source is mouse that would obtain the PointerController. + ASSERT_EQ(AINPUT_SOURCE_MOUSE, mapper->getSources()); + + NotifyMotionArgs motionArgs; + processPosition(mapper, 100, 100); + processSync(mapper); + + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs)); + ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action); + ASSERT_EQ(SECONDARY_DISPLAY_ID, motionArgs.displayId); +} + } // namespace android -- cgit v1.2.3-59-g8ed1b From 42611e031b19fd6f545bb00622c6ffc98559d802 Mon Sep 17 00:00:00 2001 From: Prabir Pradhan Date: Tue, 27 Nov 2018 14:04:02 -0800 Subject: Add sequence number to events in inputflinger This adds a sequece number field to NotifyArgs and EventEntry in order to uniquely track individual events. The sequence number for the events is added in InputReader, where the next sequence number is an increment of the previous event's sequence number. Synthesized events have a sequence number of 0. Bug: 119312685 Test: inputflinger_tests Change-Id: I1690979a5aa019e99ab89f5f7279a1b42068e658 --- services/inputflinger/InputDispatcher.cpp | 52 +++++++++------- services/inputflinger/InputDispatcher.h | 11 ++-- services/inputflinger/InputListener.cpp | 44 ++++++------- services/inputflinger/InputReader.cpp | 78 ++++++++++++++---------- services/inputflinger/InputReader.h | 6 ++ services/inputflinger/include/InputListener.h | 22 ++++--- services/inputflinger/tests/InputReader_test.cpp | 40 +++++++++++- 7 files changed, 166 insertions(+), 87 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputDispatcher.cpp b/services/inputflinger/InputDispatcher.cpp index ac17dcaa7f..6879a73251 100644 --- a/services/inputflinger/InputDispatcher.cpp +++ b/services/inputflinger/InputDispatcher.cpp @@ -97,6 +97,9 @@ constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms; // Number of recent events to keep for debugging purposes. constexpr size_t RECENT_QUEUE_MAX_SIZE = 10; +// Sequence number for synthesized or injected events. +constexpr uint32_t SYNTHESIZED_EVENT_SEQUENCE_NUM = 0; + static inline nsecs_t now() { return systemTime(SYSTEM_TIME_MONOTONIC); @@ -710,7 +713,7 @@ InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t cu entry->policyFlags = policyFlags; entry->repeatCount += 1; } else { - KeyEntry* newEntry = new KeyEntry(currentTime, + KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId, entry->source, entry->displayId, policyFlags, entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount + 1, entry->downTime); @@ -2474,6 +2477,7 @@ InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet } MotionEntry* splitMotionEntry = new MotionEntry( + originalMotionEntry->sequenceNum, originalMotionEntry->eventTime, originalMotionEntry->deviceId, originalMotionEntry->source, @@ -2507,7 +2511,8 @@ void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChange { // acquire lock AutoMutex _l(mLock); - ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime); + ConfigurationChangedEntry* newEntry = + new ConfigurationChangedEntry(args->sequenceNum, args->eventTime); needWake = enqueueInboundEventLocked(newEntry); } // release lock @@ -2612,7 +2617,7 @@ void InputDispatcher::notifyKey(const NotifyKeyArgs* args) { mLock.lock(); } - KeyEntry* newEntry = new KeyEntry(args->eventTime, + KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source, args->displayId, policyFlags, args->action, flags, keyCode, args->scanCode, metaState, repeatCount, args->downTime); @@ -2696,7 +2701,7 @@ void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) { } // Just enqueue a new motion event. - MotionEntry* newEntry = new MotionEntry(args->eventTime, + MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source, args->displayId, policyFlags, args->action, args->actionButton, args->flags, args->metaState, args->buttonState, @@ -2740,7 +2745,8 @@ void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) { { // acquire lock AutoMutex _l(mLock); - DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId); + DeviceResetEntry* newEntry = + new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId); needWake = enqueueInboundEventLocked(newEntry); } // release lock @@ -2799,7 +2805,7 @@ int32_t InputDispatcher::injectInputEvent(const InputEvent* event, } mLock.lock(); - firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(), + firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(), keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(), policyFlags, action, flags, keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(), @@ -2831,7 +2837,7 @@ int32_t InputDispatcher::injectInputEvent(const InputEvent* event, mLock.lock(); const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes(); const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords(); - firstInjectedEntry = new MotionEntry(*sampleEventTimes, + firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes, motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(), policyFlags, action, actionButton, motionEvent->getFlags(), @@ -2845,7 +2851,8 @@ int32_t InputDispatcher::injectInputEvent(const InputEvent* event, for (size_t i = motionEvent->getHistorySize(); i > 0; i--) { sampleEventTimes += 1; samplePointerCoords += pointerCount; - MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes, + MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, + *sampleEventTimes, motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(), policyFlags, action, actionButton, motionEvent->getFlags(), @@ -4279,9 +4286,10 @@ void InputDispatcher::InjectionState::release() { // --- InputDispatcher::EventEntry --- -InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) : - refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags), - injectionState(nullptr), dispatchInProgress(false) { +InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type, + nsecs_t eventTime, uint32_t policyFlags) : + sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime), + policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) { } InputDispatcher::EventEntry::~EventEntry() { @@ -4307,8 +4315,9 @@ void InputDispatcher::EventEntry::releaseInjectionState() { // --- InputDispatcher::ConfigurationChangedEntry --- -InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) : - EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) { +InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry( + uint32_t sequenceNum, nsecs_t eventTime) : + EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) { } InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() { @@ -4321,8 +4330,9 @@ void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& // --- InputDispatcher::DeviceResetEntry --- -InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) : - EventEntry(TYPE_DEVICE_RESET, eventTime, 0), +InputDispatcher::DeviceResetEntry::DeviceResetEntry( + uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) : + EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0), deviceId(deviceId) { } @@ -4337,11 +4347,11 @@ void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) cons // --- InputDispatcher::KeyEntry --- -InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime, +InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, int32_t repeatCount, nsecs_t downTime) : - EventEntry(TYPE_KEY, eventTime, policyFlags), + EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags), deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags), keyCode(keyCode), scanCode(scanCode), metaState(metaState), repeatCount(repeatCount), downTime(downTime), @@ -4372,7 +4382,7 @@ void InputDispatcher::KeyEntry::recycle() { // --- InputDispatcher::MotionEntry --- -InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId, +InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action, int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags, @@ -4380,7 +4390,7 @@ InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId, uint32_t pointerCount, const PointerProperties* pointerProperties, const PointerCoords* pointerCoords, float xOffset, float yOffset) : - EventEntry(TYPE_MOTION, eventTime, policyFlags), + EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags), eventTime(eventTime), deviceId(deviceId), source(source), displayId(displayId), action(action), actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState), @@ -4694,7 +4704,7 @@ void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTim for (size_t i = 0; i < mKeyMementos.size(); i++) { const KeyMemento& memento = mKeyMementos.itemAt(i); if (shouldCancelKey(memento, options)) { - outEvents.push(new KeyEntry(currentTime, + outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, memento.deviceId, memento.source, memento.displayId, memento.policyFlags, AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED, memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime)); @@ -4704,7 +4714,7 @@ void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTim for (size_t i = 0; i < mMotionMementos.size(); i++) { const MotionMemento& memento = mMotionMementos.itemAt(i); if (shouldCancelMotion(memento, options)) { - outEvents.push(new MotionEntry(currentTime, + outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, memento.deviceId, memento.source, memento.displayId, memento.policyFlags, memento.hovering ? AMOTION_EVENT_ACTION_HOVER_EXIT diff --git a/services/inputflinger/InputDispatcher.h b/services/inputflinger/InputDispatcher.h index 73bcc25848..05b5dadc66 100644 --- a/services/inputflinger/InputDispatcher.h +++ b/services/inputflinger/InputDispatcher.h @@ -454,6 +454,7 @@ private: TYPE_MOTION }; + uint32_t sequenceNum; mutable int32_t refCount; int32_t type; nsecs_t eventTime; @@ -469,13 +470,13 @@ private: virtual void appendDescription(std::string& msg) const = 0; protected: - EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags); + EventEntry(uint32_t sequenceNum, int32_t type, nsecs_t eventTime, uint32_t policyFlags); virtual ~EventEntry(); void releaseInjectionState(); }; struct ConfigurationChangedEntry : EventEntry { - explicit ConfigurationChangedEntry(nsecs_t eventTime); + explicit ConfigurationChangedEntry(uint32_t sequenceNum, nsecs_t eventTime); virtual void appendDescription(std::string& msg) const; protected: @@ -485,7 +486,7 @@ private: struct DeviceResetEntry : EventEntry { int32_t deviceId; - DeviceResetEntry(nsecs_t eventTime, int32_t deviceId); + DeviceResetEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId); virtual void appendDescription(std::string& msg) const; protected: @@ -515,7 +516,7 @@ private: InterceptKeyResult interceptKeyResult; // set based on the interception result nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER - KeyEntry(nsecs_t eventTime, + KeyEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, int32_t repeatCount, nsecs_t downTime); @@ -544,7 +545,7 @@ private: PointerProperties pointerProperties[MAX_POINTERS]; PointerCoords pointerCoords[MAX_POINTERS]; - MotionEntry(nsecs_t eventTime, + MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action, int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags, diff --git a/services/inputflinger/InputListener.cpp b/services/inputflinger/InputListener.cpp index 25a39a8274..23cceb4713 100644 --- a/services/inputflinger/InputListener.cpp +++ b/services/inputflinger/InputListener.cpp @@ -26,13 +26,14 @@ namespace android { // --- NotifyConfigurationChangedArgs --- -NotifyConfigurationChangedArgs::NotifyConfigurationChangedArgs(nsecs_t eventTime) : - eventTime(eventTime) { +NotifyConfigurationChangedArgs::NotifyConfigurationChangedArgs( + uint32_t sequenceNum, nsecs_t eventTime) : + NotifyArgs(sequenceNum), eventTime(eventTime) { } NotifyConfigurationChangedArgs::NotifyConfigurationChangedArgs( const NotifyConfigurationChangedArgs& other) : - eventTime(other.eventTime) { + NotifyArgs(other.sequenceNum), eventTime(other.eventTime) { } void NotifyConfigurationChangedArgs::notify(const sp& listener) const { @@ -42,19 +43,19 @@ void NotifyConfigurationChangedArgs::notify(const sp& li // --- NotifyKeyArgs --- -NotifyKeyArgs::NotifyKeyArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, - int32_t displayId, uint32_t policyFlags, +NotifyKeyArgs::NotifyKeyArgs(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, + uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) : - eventTime(eventTime), deviceId(deviceId), source(source), displayId(displayId), - policyFlags(policyFlags), + NotifyArgs(sequenceNum), eventTime(eventTime), deviceId(deviceId), source(source), + displayId(displayId), policyFlags(policyFlags), action(action), flags(flags), keyCode(keyCode), scanCode(scanCode), metaState(metaState), downTime(downTime) { } NotifyKeyArgs::NotifyKeyArgs(const NotifyKeyArgs& other) : - eventTime(other.eventTime), deviceId(other.deviceId), source(other.source), - displayId(other.displayId), policyFlags(other.policyFlags), + NotifyArgs(other.sequenceNum), eventTime(other.eventTime), deviceId(other.deviceId), + source(other.source), displayId(other.displayId), policyFlags(other.policyFlags), action(other.action), flags(other.flags), keyCode(other.keyCode), scanCode(other.scanCode), metaState(other.metaState), downTime(other.downTime) { @@ -67,15 +68,15 @@ void NotifyKeyArgs::notify(const sp& listener) const { // --- NotifyMotionArgs --- -NotifyMotionArgs::NotifyMotionArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, - int32_t displayId, uint32_t policyFlags, +NotifyMotionArgs::NotifyMotionArgs(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, + uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action, int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp, uint32_t pointerCount, const PointerProperties* pointerProperties, const PointerCoords* pointerCoords, float xPrecision, float yPrecision, nsecs_t downTime) : - eventTime(eventTime), deviceId(deviceId), source(source), displayId(displayId), - policyFlags(policyFlags), + NotifyArgs(sequenceNum), eventTime(eventTime), deviceId(deviceId), source(source), + displayId(displayId), policyFlags(policyFlags), action(action), actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags), deviceTimestamp(deviceTimestamp), @@ -88,8 +89,8 @@ NotifyMotionArgs::NotifyMotionArgs(nsecs_t eventTime, int32_t deviceId, uint32_t } NotifyMotionArgs::NotifyMotionArgs(const NotifyMotionArgs& other) : - eventTime(other.eventTime), deviceId(other.deviceId), source(other.source), - displayId(other.displayId), policyFlags(other.policyFlags), + NotifyArgs(other.sequenceNum), eventTime(other.eventTime), deviceId(other.deviceId), + source(other.source), displayId(other.displayId), policyFlags(other.policyFlags), action(other.action), actionButton(other.actionButton), flags(other.flags), metaState(other.metaState), buttonState(other.buttonState), edgeFlags(other.edgeFlags), @@ -108,14 +109,14 @@ void NotifyMotionArgs::notify(const sp& listener) const // --- NotifySwitchArgs --- -NotifySwitchArgs::NotifySwitchArgs(nsecs_t eventTime, uint32_t policyFlags, +NotifySwitchArgs::NotifySwitchArgs(uint32_t sequenceNum, nsecs_t eventTime, uint32_t policyFlags, uint32_t switchValues, uint32_t switchMask) : - eventTime(eventTime), policyFlags(policyFlags), + NotifyArgs(sequenceNum), eventTime(eventTime), policyFlags(policyFlags), switchValues(switchValues), switchMask(switchMask) { } NotifySwitchArgs::NotifySwitchArgs(const NotifySwitchArgs& other) : - eventTime(other.eventTime), policyFlags(other.policyFlags), + NotifyArgs(other.sequenceNum), eventTime(other.eventTime), policyFlags(other.policyFlags), switchValues(other.switchValues), switchMask(other.switchMask) { } @@ -126,12 +127,13 @@ void NotifySwitchArgs::notify(const sp& listener) const // --- NotifyDeviceResetArgs --- -NotifyDeviceResetArgs::NotifyDeviceResetArgs(nsecs_t eventTime, int32_t deviceId) : - eventTime(eventTime), deviceId(deviceId) { +NotifyDeviceResetArgs::NotifyDeviceResetArgs( + uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) : + NotifyArgs(sequenceNum), eventTime(eventTime), deviceId(deviceId) { } NotifyDeviceResetArgs::NotifyDeviceResetArgs(const NotifyDeviceResetArgs& other) : - eventTime(other.eventTime), deviceId(other.deviceId) { + NotifyArgs(other.sequenceNum), eventTime(other.eventTime), deviceId(other.deviceId) { } void NotifyDeviceResetArgs::notify(const sp& listener) const { diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 9ba4140312..7e00f420cc 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -236,8 +236,8 @@ static void synthesizeButtonKey(InputReaderContext* context, int32_t action, || (action == AKEY_EVENT_ACTION_UP && (lastButtonState & buttonState) && !(currentButtonState & buttonState))) { - NotifyKeyArgs args(when, deviceId, source, displayId, policyFlags, - action, 0, keyCode, 0, context->getGlobalMetaState(), when); + NotifyKeyArgs args(context->getNextSequenceNum(), when, deviceId, source, displayId, + policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when); context->getListener()->notifyKey(&args); } } @@ -261,7 +261,7 @@ InputReader::InputReader(const sp& eventHub, const sp& policy, const sp& listener) : mContext(this), mEventHub(eventHub), mPolicy(policy), - mGlobalMetaState(0), mGeneration(1), + mNextSequenceNum(1), mGlobalMetaState(0), mGeneration(1), mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX), mConfigurationChangesToRefresh(0) { mQueuedListener = new QueuedInputListener(listener); @@ -547,7 +547,7 @@ void InputReader::handleConfigurationChangedLocked(nsecs_t when) { updateGlobalMetaStateLocked(); // Enqueue configuration changed. - NotifyConfigurationChangedArgs args(when); + NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when); mQueuedListener->notifyConfigurationChanged(&args); } @@ -945,6 +945,9 @@ EventHubInterface* InputReader::ContextImpl::getEventHub() { return mReader->mEventHub.get(); } +uint32_t InputReader::ContextImpl::getNextSequenceNum() { + return (mReader->mNextSequenceNum)++; +} // --- InputDevice --- @@ -1265,7 +1268,7 @@ void InputDevice::bumpGeneration() { } void InputDevice::notifyReset(nsecs_t when) { - NotifyDeviceResetArgs args(when, mId); + NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId); mContext->getListener()->notifyDeviceReset(&args); } @@ -2038,7 +2041,8 @@ void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) { void SwitchInputMapper::sync(nsecs_t when) { if (mUpdatedSwitchMask) { uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask; - NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask); + NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues, + mUpdatedSwitchMask); getListener()->notifySwitch(&args); mUpdatedSwitchMask = 0; @@ -2420,8 +2424,8 @@ void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode, policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT; } - NotifyKeyArgs args(when, getDeviceId(), mSource, getDisplayId(), policyFlags, - down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP, + NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, + getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP, AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime); getListener()->notifyKey(&args); } @@ -2824,7 +2828,8 @@ void CursorInputMapper::sync(nsecs_t when) { while (!released.isEmpty()) { int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit()); buttonState &= ~actionButton; - NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, displayId, policyFlags, + NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, @@ -2833,8 +2838,8 @@ void CursorInputMapper::sync(nsecs_t when) { } } - NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, - motionEventAction, 0, 0, metaState, currentButtonState, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, + displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); @@ -2845,9 +2850,9 @@ void CursorInputMapper::sync(nsecs_t when) { while (!pressed.isEmpty()) { int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit()); buttonState |= actionButton; - NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, displayId, policyFlags, - AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, - metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, + NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS, + actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&pressArgs); @@ -2859,8 +2864,8 @@ void CursorInputMapper::sync(nsecs_t when) { // Send hover move after UP to tell the application that the mouse is hovering now. if (motionEventAction == AMOTION_EVENT_ACTION_UP && (mSource == AINPUT_SOURCE_MOUSE)) { - NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, displayId, policyFlags, - AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, + NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); @@ -2872,7 +2877,8 @@ void CursorInputMapper::sync(nsecs_t when) { pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); - NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags, + NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, @@ -3003,7 +3009,8 @@ void RotaryEncoderInputMapper::sync(nsecs_t when) { int32_t metaState = mContext->getGlobalMetaState(); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor); - NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags, + NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, @@ -4698,7 +4705,8 @@ void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags, int32_t metaState = mContext->getGlobalMetaState(); policyFlags |= POLICY_FLAG_VIRTUAL; - NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId, + NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, + mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime); getListener()->notifyKey(&args); } @@ -5392,8 +5400,8 @@ void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlag pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); int32_t displayId = mPointerController->getDisplayId(); - NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, - AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, displayId, mSource, + mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, 0, 0, mPointerGesture.downTime); @@ -6317,7 +6325,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.down = false; // Send up. - NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, @@ -6330,7 +6339,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.hovering = false; // Send hover exit. - NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, @@ -6345,7 +6355,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.downTime = when; // Send down. - NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, @@ -6355,7 +6366,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } // Send move. - NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, @@ -6369,7 +6381,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.hovering = true; // Send hover enter. - NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, @@ -6380,7 +6393,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } // Send hover move. - NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, @@ -6402,7 +6416,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); - NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &pointerCoords, @@ -6466,7 +6481,8 @@ void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32 } int32_t displayId = mPointerController != nullptr ? mPointerController->getDisplayId() : mViewport.displayId; - NotifyMotionArgs args(when, getDeviceId(), source, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + source, displayId, policyFlags, action, actionButton, flags, metaState, buttonState, edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords, xPrecision, yPrecision, downTime); @@ -7390,8 +7406,8 @@ void JoystickInputMapper::sync(nsecs_t when, bool force) { // TODO: Use the input device configuration to control this behavior more finely. uint32_t policyFlags = 0; - NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, - policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, 0, 0, 0); diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h index 13f1bedb65..35f3c232c7 100644 --- a/services/inputflinger/InputReader.h +++ b/services/inputflinger/InputReader.h @@ -96,6 +96,8 @@ public: virtual InputReaderPolicyInterface* getPolicy() = 0; virtual InputListenerInterface* getListener() = 0; virtual EventHubInterface* getEventHub() = 0; + + virtual uint32_t getNextSequenceNum() = 0; }; @@ -168,6 +170,7 @@ protected: virtual InputReaderPolicyInterface* getPolicy(); virtual InputListenerInterface* getListener(); virtual EventHubInterface* getEventHub(); + virtual uint32_t getNextSequenceNum(); } mContext; friend class ContextImpl; @@ -183,6 +186,9 @@ private: InputReaderConfiguration mConfig; + // used by InputReaderContext::getNextSequenceNum() as a counter for event sequence numbers + uint32_t mNextSequenceNum; + // The event queue. static const int EVENT_BUFFER_SIZE = 256; RawEvent mEventBuffer[EVENT_BUFFER_SIZE]; diff --git a/services/inputflinger/include/InputListener.h b/services/inputflinger/include/InputListener.h index a3d919bf5a..f3a30ab684 100644 --- a/services/inputflinger/include/InputListener.h +++ b/services/inputflinger/include/InputListener.h @@ -28,6 +28,12 @@ class InputListenerInterface; /* Superclass of all input event argument objects */ struct NotifyArgs { + uint32_t sequenceNum; + + inline NotifyArgs() : sequenceNum(0) { } + + inline explicit NotifyArgs(uint32_t sequenceNum) : sequenceNum(sequenceNum) { } + virtual ~NotifyArgs() { } virtual void notify(const sp& listener) const = 0; @@ -40,7 +46,7 @@ struct NotifyConfigurationChangedArgs : public NotifyArgs { inline NotifyConfigurationChangedArgs() { } - explicit NotifyConfigurationChangedArgs(nsecs_t eventTime); + NotifyConfigurationChangedArgs(uint32_t sequenceNum, nsecs_t eventTime); NotifyConfigurationChangedArgs(const NotifyConfigurationChangedArgs& other); @@ -66,9 +72,9 @@ struct NotifyKeyArgs : public NotifyArgs { inline NotifyKeyArgs() { } - NotifyKeyArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, - uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, - int32_t metaState, nsecs_t downTime); + NotifyKeyArgs(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, uint32_t source, + int32_t displayId, uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, + int32_t scanCode, int32_t metaState, nsecs_t downTime); NotifyKeyArgs(const NotifyKeyArgs& other); @@ -107,8 +113,8 @@ struct NotifyMotionArgs : public NotifyArgs { inline NotifyMotionArgs() { } - NotifyMotionArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, - uint32_t policyFlags, + NotifyMotionArgs(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, uint32_t source, + int32_t displayId, uint32_t policyFlags, int32_t action, int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp, uint32_t pointerCount, @@ -132,7 +138,7 @@ struct NotifySwitchArgs : public NotifyArgs { inline NotifySwitchArgs() { } - NotifySwitchArgs(nsecs_t eventTime, uint32_t policyFlags, + NotifySwitchArgs(uint32_t sequenceNum, nsecs_t eventTime, uint32_t policyFlags, uint32_t switchValues, uint32_t switchMask); NotifySwitchArgs(const NotifySwitchArgs& other); @@ -151,7 +157,7 @@ struct NotifyDeviceResetArgs : public NotifyArgs { inline NotifyDeviceResetArgs() { } - NotifyDeviceResetArgs(nsecs_t eventTime, int32_t deviceId); + NotifyDeviceResetArgs(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId); NotifyDeviceResetArgs(const NotifyDeviceResetArgs& other); diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index b18cae3e8f..855247f29d 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -853,13 +853,14 @@ class FakeInputReaderContext : public InputReaderContext { int32_t mGlobalMetaState; bool mUpdateGlobalMetaStateWasCalled; int32_t mGeneration; + uint32_t mNextSequenceNum; public: FakeInputReaderContext(const sp& eventHub, const sp& policy, const sp& listener) : mEventHub(eventHub), mPolicy(policy), mListener(listener), - mGlobalMetaState(0) { + mGlobalMetaState(0), mNextSequenceNum(1) { } virtual ~FakeInputReaderContext() { } @@ -923,6 +924,10 @@ private: virtual void dispatchExternalStylusState(const StylusState&) { } + + virtual uint32_t getNextSequenceNum() { + return mNextSequenceNum++; + } }; @@ -1568,6 +1573,39 @@ TEST_F(InputReaderTest, LoopOnce_ForwardsRawEventsToMappers) { ASSERT_EQ(1, event.value); } +TEST_F(InputReaderTest, DeviceReset_IncrementsSequenceNumber) { + constexpr int32_t deviceId = 1; + constexpr uint32_t deviceClass = INPUT_DEVICE_CLASS_KEYBOARD; + InputDevice* device = mReader->newDevice(deviceId, 0, "fake", deviceClass); + // Must add at least one mapper or the device will be ignored! + FakeInputMapper* mapper = new FakeInputMapper(device, AINPUT_SOURCE_KEYBOARD); + device->addMapper(mapper); + mReader->setNextDevice(device); + addDevice(deviceId, "fake", deviceClass, nullptr); + + NotifyDeviceResetArgs resetArgs; + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs)); + uint32_t prevSequenceNum = resetArgs.sequenceNum; + + disableDevice(deviceId, device); + mReader->loopOnce(); + mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs); + ASSERT_TRUE(prevSequenceNum < resetArgs.sequenceNum); + prevSequenceNum = resetArgs.sequenceNum; + + enableDevice(deviceId, device); + mReader->loopOnce(); + mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs); + ASSERT_TRUE(prevSequenceNum < resetArgs.sequenceNum); + prevSequenceNum = resetArgs.sequenceNum; + + disableDevice(deviceId, device); + mReader->loopOnce(); + mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs); + ASSERT_TRUE(prevSequenceNum < resetArgs.sequenceNum); + prevSequenceNum = resetArgs.sequenceNum; +} + // --- InputDeviceTest --- -- cgit v1.2.3-59-g8ed1b From aca28400dce21dc9b840d1986e4e5f0227ceb03a Mon Sep 17 00:00:00 2001 From: Dan Harms Date: Mon, 17 Dec 2018 13:55:20 -0800 Subject: Revert "Support mouse pointer on external displays (1/3)" This reverts commit 620f6d984101959376f7594a1450e9c70bac4019. Test: Manual Bug: b/120864177 Test: Presubmit Change-Id: I27e13ea18a6f94b1d01d6734853f521306a8cee1 --- services/inputflinger/InputReader.cpp | 59 +++++++++----------- services/inputflinger/include/InputReaderBase.h | 3 - .../include/PointerControllerInterface.h | 3 - services/inputflinger/tests/InputReader_test.cpp | 65 +--------------------- 4 files changed, 28 insertions(+), 102 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 7e00f420cc..5d0b894dd0 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -2642,7 +2642,6 @@ void CursorInputMapper::configure(nsecs_t when, mOrientation = internalViewport->orientation; } } - getPolicy()->updatePointerDisplay(); bumpGeneration(); } } @@ -2788,7 +2787,7 @@ void CursorInputMapper::sync(nsecs_t when) { pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY); - displayId = mPointerController->getDisplayId(); + displayId = ADISPLAY_ID_DEFAULT; } else { pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY); @@ -3609,9 +3608,6 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) { if (mPointerController == nullptr) { mPointerController = getPolicy()->obtainPointerController(getDeviceId()); - getPolicy()->updatePointerDisplay(); - } else if (viewportChanged) { - getPolicy()->updatePointerDisplay(); } } else { mPointerController.clear(); @@ -5399,9 +5395,9 @@ void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlag pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); - int32_t displayId = mPointerController->getDisplayId(); - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, displayId, mSource, - mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, mViewport.displayId, policyFlags, + AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, 0, 0, mPointerGesture.downTime); @@ -6307,7 +6303,6 @@ void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) { void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down, bool hovering) { int32_t metaState = getContext()->getGlobalMetaState(); - int32_t displayId = mViewport.displayId; if (mPointerController != nullptr) { if (down || hovering) { @@ -6318,20 +6313,19 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } - displayId = mPointerController->getDisplayId(); } if (mPointerSimple.down && !down) { mPointerSimple.down = false; // Send up. - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, displayId, policyFlags, - AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0, - /* deviceTimestamp */ 0, - 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, - mOrientedXPrecision, mOrientedYPrecision, - mPointerSimple.downTime); + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, mViewport.displayId, policyFlags, + AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0, + /* deviceTimestamp */ 0, + 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, + mOrientedXPrecision, mOrientedYPrecision, + mPointerSimple.downTime); getListener()->notifyMotion(&args); } @@ -6339,8 +6333,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.hovering = false; // Send hover exit. - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, @@ -6355,8 +6349,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.downTime = when; // Send down. - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, @@ -6366,8 +6360,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } // Send move. - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, @@ -6381,8 +6375,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.hovering = true; // Send hover enter. - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, @@ -6393,8 +6387,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } // Send hover move. - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, @@ -6416,8 +6410,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &pointerCoords, @@ -6479,10 +6473,9 @@ void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32 ALOG_ASSERT(false); } } - int32_t displayId = mPointerController != nullptr ? - mPointerController->getDisplayId() : mViewport.displayId; - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - source, displayId, policyFlags, + + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + source, mViewport.displayId, policyFlags, action, actionButton, flags, metaState, buttonState, edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords, xPrecision, yPrecision, downTime); diff --git a/services/inputflinger/include/InputReaderBase.h b/services/inputflinger/include/InputReaderBase.h index 5a78df75ff..fe1c50bc75 100644 --- a/services/inputflinger/include/InputReaderBase.h +++ b/services/inputflinger/include/InputReaderBase.h @@ -342,9 +342,6 @@ public: /* Gets the affine calibration associated with the specified device. */ virtual TouchAffineTransformation getTouchAffineTransformation( const std::string& inputDeviceDescriptor, int32_t surfaceRotation) = 0; - - /* Update the pointer controller associated with the specified display. */ - virtual void updatePointerDisplay() = 0; }; } // namespace android diff --git a/services/inputflinger/include/PointerControllerInterface.h b/services/inputflinger/include/PointerControllerInterface.h index e60b3f48b5..e94dd94868 100644 --- a/services/inputflinger/include/PointerControllerInterface.h +++ b/services/inputflinger/include/PointerControllerInterface.h @@ -58,9 +58,6 @@ public: /* Gets the absolute location of the pointer. */ virtual void getPosition(float* outX, float* outY) const = 0; - /* Gets the id of the display where the pointer should be shown. */ - virtual int32_t getDisplayId() const = 0; - enum Transition { // Fade/unfade immediately. TRANSITION_IMMEDIATE, diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index 855247f29d..167a6243dd 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -57,7 +57,6 @@ class FakePointerController : public PointerControllerInterface { float mMinX, mMinY, mMaxX, mMaxY; float mX, mY; int32_t mButtonState; - int32_t mDisplayId; protected: virtual ~FakePointerController() { } @@ -65,7 +64,7 @@ protected: public: FakePointerController() : mHaveBounds(false), mMinX(0), mMinY(0), mMaxX(0), mMaxY(0), mX(0), mY(0), - mButtonState(0), mDisplayId(ADISPLAY_ID_DEFAULT) { + mButtonState(0) { } void setBounds(float minX, float minY, float maxX, float maxY) { @@ -76,10 +75,6 @@ public: mMaxY = maxY; } - void setDisplayId(int32_t displayId) { - mDisplayId = displayId; - } - virtual void setPosition(float x, float y) { mX = x; mY = y; @@ -98,10 +93,6 @@ public: *outY = mY; } - virtual int32_t getDisplayId() const { - return mDisplayId; - } - private: virtual bool getBounds(float* outMinX, float* outMinY, float* outMaxX, float* outMaxY) const { *outMinX = mMinX; @@ -271,9 +262,6 @@ private: virtual std::string getDeviceAlias(const InputDeviceIdentifier&) { return ""; } - - virtual void updatePointerDisplay() { - } }; @@ -3177,30 +3165,6 @@ TEST_F(CursorInputMapperTest, Process_PointerCapture) { ASSERT_NO_FATAL_FAILURE(assertPosition(mFakePointerController, 110.0f, 220.0f)); } -TEST_F(CursorInputMapperTest, Process_ShouldHandleDisplayId) { - CursorInputMapper* mapper = new CursorInputMapper(mDevice); - addMapperAndConfigure(mapper); - - // Setup PointerController for second display. - constexpr int32_t SECOND_DISPLAY_ID = 1; - mFakePointerController->setBounds(0, 0, 800 - 1, 480 - 1); - mFakePointerController->setPosition(100, 200); - mFakePointerController->setButtonState(0); - mFakePointerController->setDisplayId(SECOND_DISPLAY_ID); - - NotifyMotionArgs args; - process(mapper, ARBITRARY_TIME, EV_REL, REL_X, 10); - process(mapper, ARBITRARY_TIME, EV_REL, REL_Y, 20); - process(mapper, ARBITRARY_TIME, EV_SYN, SYN_REPORT, 0); - ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args)); - ASSERT_EQ(AINPUT_SOURCE_MOUSE, args.source); - ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, args.action); - ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0], - 110.0f, 220.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f)); - ASSERT_NO_FATAL_FAILURE(assertPosition(mFakePointerController, 110.0f, 220.0f)); - ASSERT_EQ(SECOND_DISPLAY_ID, args.displayId); -} - // --- TouchInputMapperTest --- @@ -4699,6 +4663,7 @@ TEST_F(SingleTouchInputMapperTest, Process_WhenAbsPressureIsPresent_HoversIfItsV toDisplayX(150), toDisplayY(250), 0, 0, 0, 0, 0, 0, 0, 0)); } + // --- MultiTouchInputMapperTest --- class MultiTouchInputMapperTest : public TouchInputMapperTest { @@ -6319,30 +6284,4 @@ TEST_F(MultiTouchInputMapperTest, Configure_AssignsDisplayPort) { ASSERT_EQ(DISPLAY_ID, args.displayId); } -TEST_F(MultiTouchInputMapperTest, Process_Pointer_ShouldHandleDisplayId) { - // Setup PointerController for second display. - sp fakePointerController = new FakePointerController(); - fakePointerController->setBounds(0, 0, 800 - 1, 480 - 1); - fakePointerController->setPosition(100, 200); - fakePointerController->setButtonState(0); - fakePointerController->setDisplayId(SECONDARY_DISPLAY_ID); - mFakePolicy->setPointerController(mDevice->getId(), fakePointerController); - - MultiTouchInputMapper* mapper = new MultiTouchInputMapper(mDevice); - prepareDisplay(DISPLAY_ORIENTATION_0); - prepareAxes(POSITION); - addMapperAndConfigure(mapper); - - // Check source is mouse that would obtain the PointerController. - ASSERT_EQ(AINPUT_SOURCE_MOUSE, mapper->getSources()); - - NotifyMotionArgs motionArgs; - processPosition(mapper, 100, 100); - processSync(mapper); - - ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs)); - ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action); - ASSERT_EQ(SECONDARY_DISPLAY_ID, motionArgs.displayId); -} - } // namespace android -- cgit v1.2.3-59-g8ed1b From 41a712e2e56aac3da8c929117df79c498f3c254d Mon Sep 17 00:00:00 2001 From: Arthur Hung Date: Thu, 22 Nov 2018 19:41:03 +0800 Subject: DisplayViewport should only have actual viewports (1/2) If input device is external, TouchInputMapper would be associated with external display. But if external viewport is not present, it should fallback to the internal viewport. Bug: 116850516 Test: atest inputflinger_tests Change-Id: I044a5c66fd28ae1d032e56791478c4c46f13ef25 --- services/inputflinger/InputReader.cpp | 13 ++++++++-- services/inputflinger/tests/InputReader_test.cpp | 30 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 5d0b894dd0..75095cb4f7 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -254,7 +254,6 @@ static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, } - // --- InputReader --- InputReader::InputReader(const sp& eventHub, @@ -3446,7 +3445,17 @@ std::optional TouchInputMapper::findViewport() { } else { viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL; } - return mConfig.getDisplayViewportByType(viewportTypeToUse); + + std::optional viewport = + mConfig.getDisplayViewportByType(viewportTypeToUse); + if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) { + ALOGW("Input device %s should be associated with external display, " + "fallback to internal one for the external viewport is not found.", + getDeviceName().c_str()); + viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL); + } + + return viewport; } DisplayViewport newViewport; diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index 167a6243dd..b5d209092a 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -6284,4 +6284,34 @@ TEST_F(MultiTouchInputMapperTest, Configure_AssignsDisplayPort) { ASSERT_EQ(DISPLAY_ID, args.displayId); } +/** + * Expect fallback to internal viewport if device is external and external viewport is not present. + */ +TEST_F(MultiTouchInputMapperTest, Viewports_Fallback) { + MultiTouchInputMapper* mapper = new MultiTouchInputMapper(mDevice); + prepareAxes(POSITION); + addConfigurationProperty("touch.deviceType", "touchScreen"); + prepareDisplay(DISPLAY_ORIENTATION_0); + mDevice->setExternal(true); + addMapperAndConfigure(mapper); + + ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, mapper->getSources()); + + NotifyMotionArgs motionArgs; + + // Expect the event to be sent to the internal viewport, + // because an external viewport is not present. + processPosition(mapper, 100, 100); + processSync(mapper); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs)); + ASSERT_EQ(ADISPLAY_ID_DEFAULT, motionArgs.displayId); + + // Expect the event to be sent to the external viewport if it is present. + prepareSecondaryDisplay(ViewportType::VIEWPORT_EXTERNAL); + processPosition(mapper, 100, 100); + processSync(mapper); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs)); + ASSERT_EQ(SECONDARY_DISPLAY_ID, motionArgs.displayId); +} + } // namespace android -- cgit v1.2.3-59-g8ed1b From 7b7c8f6d867e4ee0e6025899da6c50c531b5e7a5 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Wed, 12 Dec 2018 16:09:20 -0800 Subject: Add vector of TouchVideoFrame to NotifyMotionArgs NotifyMotionArgs is passed to InputListener. We add a vector of TouchVideoFrame here to NotifyMotionArgs in order to provide heatmap information about touch. This heatmap information can later be used to do further processing of touch. For example, it could be used to determine whether a given touch stream represents a user intentionally pressing harder on the screen. Introduce a new class, TouchVideoFrame, that will represent a single scan of the touch heatmap for a given touch event. Test: integration tested by adding a debug log to the case where the finger area is large. That means, the video frames are being passed locally to the InputClassfier HAL. Although HAL is not being submitted together with this change, the current change will make the subsequent CLs simpler to review. Bug: 111480215 Change-Id: I4f16c8b2bd726c6bd4bbd5d2b18d2536a2347bda --- include/input/TouchVideoFrame.h | 67 +++++++++++++++++++++++++++ services/inputflinger/InputListener.cpp | 9 ++-- services/inputflinger/InputReader.cpp | 34 +++++++------- services/inputflinger/include/InputListener.h | 7 ++- 4 files changed, 96 insertions(+), 21 deletions(-) create mode 100644 include/input/TouchVideoFrame.h (limited to 'services/inputflinger/InputReader.cpp') diff --git a/include/input/TouchVideoFrame.h b/include/input/TouchVideoFrame.h new file mode 100644 index 0000000000..d68f27431a --- /dev/null +++ b/include/input/TouchVideoFrame.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _LIBINPUT_TOUCHVIDEOFRAME_H +#define _LIBINPUT_TOUCHVIDEOFRAME_H + +#include +#include +#include + +namespace android { + +/** + * Represents data from a single scan of the touchscreen device. + * Similar in concept to a video frame, but the touch strength is used as + * the values instead. + */ +class TouchVideoFrame { +public: + TouchVideoFrame(uint32_t width, uint32_t height, std::vector data, + const struct timeval& timestamp) : + mWidth(width), mHeight(height), mData(std::move(data)), mTimestamp(timestamp) { + } + + /** + * Width of the frame + */ + uint32_t getWidth() const { return mWidth; } + /** + * Height of the frame + */ + uint32_t getHeight() const { return mHeight; } + /** + * The touch strength data. + * The array is a 2-D row-major matrix, with dimensions (height, width). + * Total size of the array should equal getHeight() * getWidth(). + * Data is allowed to be negative. + */ + const std::vector& getData() const { return mData; } + /** + * Time at which the heatmap was taken. + */ + const struct timeval& getTimestamp() const { return mTimestamp; } + +private: + uint32_t mWidth; + uint32_t mHeight; + std::vector mData; + struct timeval mTimestamp; +}; + +} // namespace android + +#endif // _LIBINPUT_TOUCHVIDEOFRAME_H diff --git a/services/inputflinger/InputListener.cpp b/services/inputflinger/InputListener.cpp index 23cceb4713..b4eb37026b 100644 --- a/services/inputflinger/InputListener.cpp +++ b/services/inputflinger/InputListener.cpp @@ -74,14 +74,16 @@ NotifyMotionArgs::NotifyMotionArgs(uint32_t sequenceNum, nsecs_t eventTime, int3 int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp, uint32_t pointerCount, const PointerProperties* pointerProperties, const PointerCoords* pointerCoords, - float xPrecision, float yPrecision, nsecs_t downTime) : + float xPrecision, float yPrecision, nsecs_t downTime, + const std::vector& videoFrames) : NotifyArgs(sequenceNum), eventTime(eventTime), deviceId(deviceId), source(source), displayId(displayId), policyFlags(policyFlags), action(action), actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags), deviceTimestamp(deviceTimestamp), pointerCount(pointerCount), - xPrecision(xPrecision), yPrecision(yPrecision), downTime(downTime) { + xPrecision(xPrecision), yPrecision(yPrecision), downTime(downTime), + videoFrames(videoFrames) { for (uint32_t i = 0; i < pointerCount; i++) { this->pointerProperties[i].copyFrom(pointerProperties[i]); this->pointerCoords[i].copyFrom(pointerCoords[i]); @@ -95,7 +97,8 @@ NotifyMotionArgs::NotifyMotionArgs(const NotifyMotionArgs& other) : metaState(other.metaState), buttonState(other.buttonState), edgeFlags(other.edgeFlags), deviceTimestamp(other.deviceTimestamp), pointerCount(other.pointerCount), - xPrecision(other.xPrecision), yPrecision(other.yPrecision), downTime(other.downTime) { + xPrecision(other.xPrecision), yPrecision(other.yPrecision), downTime(other.downTime), + videoFrames(other.videoFrames) { for (uint32_t i = 0; i < pointerCount; i++) { pointerProperties[i].copyFrom(other.pointerProperties[i]); pointerCoords[i].copyFrom(other.pointerCoords[i]); diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 5d0b894dd0..2d342bce94 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -2832,7 +2832,7 @@ void CursorInputMapper::sync(nsecs_t when) { AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, - mXPrecision, mYPrecision, downTime); + mXPrecision, mYPrecision, downTime, /* videoFrames */ {}); getListener()->notifyMotion(&releaseArgs); } } @@ -2841,7 +2841,7 @@ void CursorInputMapper::sync(nsecs_t when) { displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, - mXPrecision, mYPrecision, downTime); + mXPrecision, mYPrecision, downTime, /* videoFrames */ {}); getListener()->notifyMotion(&args); if (buttonsPressed) { @@ -2853,7 +2853,7 @@ void CursorInputMapper::sync(nsecs_t when) { mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, - mXPrecision, mYPrecision, downTime); + mXPrecision, mYPrecision, downTime, /* videoFrames */ {}); getListener()->notifyMotion(&pressArgs); } } @@ -2867,7 +2867,7 @@ void CursorInputMapper::sync(nsecs_t when) { mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, - mXPrecision, mYPrecision, downTime); + mXPrecision, mYPrecision, downTime, /* videoFrames */ {}); getListener()->notifyMotion(&hoverArgs); } @@ -2881,7 +2881,7 @@ void CursorInputMapper::sync(nsecs_t when) { AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, - mXPrecision, mYPrecision, downTime); + mXPrecision, mYPrecision, downTime, /* videoFrames */ {}); getListener()->notifyMotion(&scrollArgs); } } @@ -3013,7 +3013,7 @@ void RotaryEncoderInputMapper::sync(nsecs_t when) { AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, - 0, 0, 0); + 0, 0, 0, /* videoFrames */ {}); getListener()->notifyMotion(&scrollArgs); } @@ -5400,7 +5400,7 @@ void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlag AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, - 0, 0, mPointerGesture.downTime); + 0, 0, mPointerGesture.downTime, /* videoFrames */ {}); getListener()->notifyMotion(&args); } @@ -6319,13 +6319,13 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.down = false; // Send up. - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision, - mPointerSimple.downTime); + mPointerSimple.downTime, /* videoFrames */ {}); getListener()->notifyMotion(&args); } @@ -6339,7 +6339,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision, - mPointerSimple.downTime); + mPointerSimple.downTime, /* videoFrames */ {}); getListener()->notifyMotion(&args); } @@ -6355,7 +6355,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, - mPointerSimple.downTime); + mPointerSimple.downTime, /* videoFrames */ {}); getListener()->notifyMotion(&args); } @@ -6366,7 +6366,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, - mPointerSimple.downTime); + mPointerSimple.downTime, /* videoFrames */ {}); getListener()->notifyMotion(&args); } @@ -6382,7 +6382,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, - mPointerSimple.downTime); + mPointerSimple.downTime, /* videoFrames */ {}); getListener()->notifyMotion(&args); } @@ -6394,7 +6394,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, - mPointerSimple.downTime); + mPointerSimple.downTime, /* videoFrames */ {}); getListener()->notifyMotion(&args); } @@ -6416,7 +6416,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &pointerCoords, mOrientedXPrecision, mOrientedYPrecision, - mPointerSimple.downTime); + mPointerSimple.downTime, /* videoFrames */ {}); getListener()->notifyMotion(&args); } @@ -6478,7 +6478,7 @@ void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32 source, mViewport.displayId, policyFlags, action, actionButton, flags, metaState, buttonState, edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords, - xPrecision, yPrecision, downTime); + xPrecision, yPrecision, downTime, /* videoFrames */ {}); getListener()->notifyMotion(&args); } @@ -7403,7 +7403,7 @@ void JoystickInputMapper::sync(nsecs_t when, bool force) { AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, - 0, 0, 0); + 0, 0, 0, /* videoFrames */ {}); getListener()->notifyMotion(&args); } diff --git a/services/inputflinger/include/InputListener.h b/services/inputflinger/include/InputListener.h index f3a30ab684..2442cc052b 100644 --- a/services/inputflinger/include/InputListener.h +++ b/services/inputflinger/include/InputListener.h @@ -17,7 +17,10 @@ #ifndef _UI_INPUT_LISTENER_H #define _UI_INPUT_LISTENER_H +#include + #include +#include #include #include @@ -110,6 +113,7 @@ struct NotifyMotionArgs : public NotifyArgs { float xPrecision; float yPrecision; nsecs_t downTime; + std::vector videoFrames; inline NotifyMotionArgs() { } @@ -119,7 +123,8 @@ struct NotifyMotionArgs : public NotifyArgs { int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp, uint32_t pointerCount, const PointerProperties* pointerProperties, const PointerCoords* pointerCoords, - float xPrecision, float yPrecision, nsecs_t downTime); + float xPrecision, float yPrecision, nsecs_t downTime, + const std::vector& videoFrames); NotifyMotionArgs(const NotifyMotionArgs& other); -- cgit v1.2.3-59-g8ed1b From add8929f1d781fabf5526d90c17a853274655e79 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Thu, 13 Dec 2018 19:23:36 -0800 Subject: Consume video frames An input device currently reads video frames, and stores them into local queue. We limit the queue size to 10 frames. Here, we add the step where an input mapper would consume the video frames from the video device for a given input device, and then pass them onto the input listener. Test: integration tested by checking that frames are processed correctly in input hal. To check if frames are processed correctly, look at the active touch area and print a log message when the total area exceeds a certain threshold. Bug: 111480215 Change-Id: Ifc519389e12b44540e9a54fd273241f9f7cd057d --- services/inputflinger/EventHub.cpp | 10 ++++++++++ services/inputflinger/InputReader.cpp | 6 ++++-- services/inputflinger/include/EventHub.h | 2 ++ services/inputflinger/tests/InputReader_test.cpp | 4 ++++ 4 files changed, 20 insertions(+), 2 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/EventHub.cpp b/services/inputflinger/EventHub.cpp index aa241a00e9..18c3ded880 100644 --- a/services/inputflinger/EventHub.cpp +++ b/services/inputflinger/EventHub.cpp @@ -1028,6 +1028,16 @@ size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSiz return event - buffer; } +std::vector EventHub::getVideoFrames(int32_t deviceId) { + AutoMutex _l(mLock); + + Device* device = getDeviceLocked(deviceId); + if (!device || !device->videoDevice) { + return {}; + } + return device->videoDevice->consumeFrames(); +} + void EventHub::wake() { ALOGV("wake() called"); diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 73fcb1124d..3d5f1d92d5 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -6483,11 +6483,13 @@ void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32 } } - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + const int32_t deviceId = getDeviceId(); + std::vector frames = mDevice->getEventHub()->getVideoFrames(deviceId); + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, source, mViewport.displayId, policyFlags, action, actionButton, flags, metaState, buttonState, edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords, - xPrecision, yPrecision, downTime, /* videoFrames */ {}); + xPrecision, yPrecision, downTime, std::move(frames)); getListener()->notifyMotion(&args); } diff --git a/services/inputflinger/include/EventHub.h b/services/inputflinger/include/EventHub.h index dd64132f3e..295aca8955 100644 --- a/services/inputflinger/include/EventHub.h +++ b/services/inputflinger/include/EventHub.h @@ -211,6 +211,7 @@ public: * Returns the number of events obtained, or 0 if the timeout expired. */ virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) = 0; + virtual std::vector getVideoFrames(int32_t deviceId) = 0; /* * Query current input state. @@ -303,6 +304,7 @@ public: const int32_t* keyCodes, uint8_t* outFlags) const; virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize); + virtual std::vector getVideoFrames(int32_t deviceId); virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const; virtual bool hasLed(int32_t deviceId, int32_t led) const; diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index b5d209092a..d39d8dc852 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -692,6 +692,10 @@ private: return 1; } + virtual std::vector getVideoFrames(int32_t deviceId) { + return {}; + } + virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const { Device* device = getDevice(deviceId); if (device) { -- cgit v1.2.3-59-g8ed1b From c7ad2d0423e9cab841503f3ebf482015322779be Mon Sep 17 00:00:00 2001 From: Arthur Hung Date: Tue, 18 Dec 2018 17:41:29 +0800 Subject: Support mouse pointer on external displays (1/2) If input source is mouse, InputTouchMapper and CursorInputMapper will assign a PointerController which associated with some display. When dispatch a motion event, it should be assigned the displayId from PointerController. - Add getDisplayId for PointerControllerInterface to get the current associated display id. - Add updatePointerDisplay for InputReaderPolicyInterface to find and associate the specified display viewport. - Add test cases for TouchInputMapper and CursorInputMapper. Bug: 113559891 Test: ActivityView test app Test: atest inputflinger_tests Change-Id: I43f848041a7c727f74ad3e00eef546498a7d9314 --- services/inputflinger/InputReader.cpp | 46 +++++++++------- .../include/PointerControllerInterface.h | 3 ++ services/inputflinger/tests/InputReader_test.cpp | 61 +++++++++++++++++++++- 3 files changed, 91 insertions(+), 19 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 3d5f1d92d5..33bf163abb 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -2641,6 +2641,11 @@ void CursorInputMapper::configure(nsecs_t when, mOrientation = internalViewport->orientation; } } + + // Update the PointerController if viewports changed. + if (mParameters.hasAssociatedDisplay) { + getPolicy()->obtainPointerController(getDeviceId()); + } bumpGeneration(); } } @@ -2786,7 +2791,7 @@ void CursorInputMapper::sync(nsecs_t when) { pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY); - displayId = ADISPLAY_ID_DEFAULT; + displayId = mPointerController->getDisplayId(); } else { pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY); @@ -3612,10 +3617,10 @@ void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { mOrientedRanges.clear(); } - // Create pointer controller if needed. + // Create or update pointer controller if needed. if (mDeviceMode == DEVICE_MODE_POINTER || (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) { - if (mPointerController == nullptr) { + if (mPointerController == nullptr || viewportChanged) { mPointerController = getPolicy()->obtainPointerController(getDeviceId()); } } else { @@ -5404,8 +5409,9 @@ void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlag pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); + const int32_t displayId = mPointerController->getDisplayId(); NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, mViewport.displayId, policyFlags, + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, @@ -6312,6 +6318,7 @@ void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) { void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down, bool hovering) { int32_t metaState = getContext()->getGlobalMetaState(); + int32_t displayId = mViewport.displayId; if (mPointerController != nullptr) { if (down || hovering) { @@ -6322,6 +6329,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } + displayId = mPointerController->getDisplayId(); } if (mPointerSimple.down && !down) { @@ -6329,7 +6337,7 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, // Send up. NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, mViewport.displayId, policyFlags, + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, @@ -6342,8 +6350,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.hovering = false; // Send hover exit. - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, @@ -6358,8 +6366,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.downTime = when; // Send down. - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, @@ -6369,8 +6377,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } // Send move. - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, @@ -6384,8 +6392,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, mPointerSimple.hovering = true; // Send hover enter. - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, @@ -6396,8 +6404,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, } // Send hover move. - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, @@ -6419,8 +6427,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); - NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), - mSource, mViewport.displayId, policyFlags, + NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), + mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &pointerCoords, @@ -6482,11 +6490,13 @@ void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32 ALOG_ASSERT(false); } } + const int32_t displayId = mPointerController != nullptr ? + mPointerController->getDisplayId() : mViewport.displayId; const int32_t deviceId = getDeviceId(); std::vector frames = mDevice->getEventHub()->getVideoFrames(deviceId); NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, - source, mViewport.displayId, policyFlags, + source, displayId, policyFlags, action, actionButton, flags, metaState, buttonState, edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords, xPrecision, yPrecision, downTime, std::move(frames)); diff --git a/services/inputflinger/include/PointerControllerInterface.h b/services/inputflinger/include/PointerControllerInterface.h index e94dd94868..bc0f1f919f 100644 --- a/services/inputflinger/include/PointerControllerInterface.h +++ b/services/inputflinger/include/PointerControllerInterface.h @@ -98,6 +98,9 @@ public: /* Removes all spots. */ virtual void clearSpots() = 0; + + /* Gets the id of the display where the pointer should be shown. */ + virtual int32_t getDisplayId() const = 0; }; } // namespace android diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index d39d8dc852..de87e7f6b9 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -57,6 +57,7 @@ class FakePointerController : public PointerControllerInterface { float mMinX, mMinY, mMaxX, mMaxY; float mX, mY; int32_t mButtonState; + int32_t mDisplayId; protected: virtual ~FakePointerController() { } @@ -64,7 +65,7 @@ protected: public: FakePointerController() : mHaveBounds(false), mMinX(0), mMinY(0), mMaxX(0), mMaxY(0), mX(0), mY(0), - mButtonState(0) { + mButtonState(0), mDisplayId(ADISPLAY_ID_DEFAULT) { } void setBounds(float minX, float minY, float maxX, float maxY) { @@ -75,6 +76,10 @@ public: mMaxY = maxY; } + void setDisplayId(int32_t displayId) { + mDisplayId = displayId; + } + virtual void setPosition(float x, float y) { mX = x; mY = y; @@ -93,6 +98,10 @@ public: *outY = mY; } + virtual int32_t getDisplayId() const { + return mDisplayId; + } + private: virtual bool getBounds(float* outMinX, float* outMinY, float* outMaxX, float* outMaxY) const { *outMinX = mMinX; @@ -3169,6 +3178,30 @@ TEST_F(CursorInputMapperTest, Process_PointerCapture) { ASSERT_NO_FATAL_FAILURE(assertPosition(mFakePointerController, 110.0f, 220.0f)); } +TEST_F(CursorInputMapperTest, Process_ShouldHandleDisplayId) { + CursorInputMapper* mapper = new CursorInputMapper(mDevice); + addMapperAndConfigure(mapper); + + // Setup PointerController for second display. + constexpr int32_t SECOND_DISPLAY_ID = 1; + mFakePointerController->setBounds(0, 0, 800 - 1, 480 - 1); + mFakePointerController->setPosition(100, 200); + mFakePointerController->setButtonState(0); + mFakePointerController->setDisplayId(SECOND_DISPLAY_ID); + + NotifyMotionArgs args; + process(mapper, ARBITRARY_TIME, EV_REL, REL_X, 10); + process(mapper, ARBITRARY_TIME, EV_REL, REL_Y, 20); + process(mapper, ARBITRARY_TIME, EV_SYN, SYN_REPORT, 0); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args)); + ASSERT_EQ(AINPUT_SOURCE_MOUSE, args.source); + ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, args.action); + ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0], + 110.0f, 220.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f)); + ASSERT_NO_FATAL_FAILURE(assertPosition(mFakePointerController, 110.0f, 220.0f)); + ASSERT_EQ(SECOND_DISPLAY_ID, args.displayId); +} + // --- TouchInputMapperTest --- @@ -6318,4 +6351,30 @@ TEST_F(MultiTouchInputMapperTest, Viewports_Fallback) { ASSERT_EQ(SECONDARY_DISPLAY_ID, motionArgs.displayId); } +TEST_F(MultiTouchInputMapperTest, Process_Pointer_ShouldHandleDisplayId) { + // Setup PointerController for second display. + sp fakePointerController = new FakePointerController(); + fakePointerController->setBounds(0, 0, 800 - 1, 480 - 1); + fakePointerController->setPosition(100, 200); + fakePointerController->setButtonState(0); + fakePointerController->setDisplayId(SECONDARY_DISPLAY_ID); + mFakePolicy->setPointerController(mDevice->getId(), fakePointerController); + + MultiTouchInputMapper* mapper = new MultiTouchInputMapper(mDevice); + prepareDisplay(DISPLAY_ORIENTATION_0); + prepareAxes(POSITION); + addMapperAndConfigure(mapper); + + // Check source is mouse that would obtain the PointerController. + ASSERT_EQ(AINPUT_SOURCE_MOUSE, mapper->getSources()); + + NotifyMotionArgs motionArgs; + processPosition(mapper, 100, 100); + processSync(mapper); + + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs)); + ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, motionArgs.action); + ASSERT_EQ(SECONDARY_DISPLAY_ID, motionArgs.displayId); +} + } // namespace android -- cgit v1.2.3-59-g8ed1b From ae478d3e78259fc6fb61388611af13abcb94df86 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Thu, 3 Jan 2019 14:45:18 -0800 Subject: Add MotionClassification to NotifyMotionArgs This classification will be set in the InputClassifier stage and will get passed on to MotionEvent. It will be consumed in user-facing API MotionEvent.getClassification() that will provide an IntDef classification. The ultimate user will be GestureDetector, View, and other similar APIs that provide information about long press. The goal is to provide means for accelerating the long-press gesture. Bug: 62940136 Test: Integration tested in upper layers on MotionEvent. Change-Id: I66e062c21c6a860a3abb16e265e37b18ebef1bcb --- services/inputflinger/InputDispatcher.cpp | 2 +- services/inputflinger/InputListener.cpp | 8 ++-- services/inputflinger/InputReader.cpp | 56 ++++++++++++++------------- services/inputflinger/include/InputListener.h | 6 ++- 4 files changed, 40 insertions(+), 32 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputDispatcher.cpp b/services/inputflinger/InputDispatcher.cpp index a6d3b75176..0bde5fda3c 100644 --- a/services/inputflinger/InputDispatcher.cpp +++ b/services/inputflinger/InputDispatcher.cpp @@ -2691,7 +2691,7 @@ void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) { event.initialize(args->deviceId, args->source, args->displayId, args->action, args->actionButton, args->flags, args->edgeFlags, args->metaState, args->buttonState, - MotionClassification::NONE, 0, 0, args->xPrecision, args->yPrecision, + args->classification, 0, 0, args->xPrecision, args->yPrecision, args->downTime, args->eventTime, args->pointerCount, args->pointerProperties, args->pointerCoords); diff --git a/services/inputflinger/InputListener.cpp b/services/inputflinger/InputListener.cpp index b4eb37026b..b349c73d5a 100644 --- a/services/inputflinger/InputListener.cpp +++ b/services/inputflinger/InputListener.cpp @@ -71,8 +71,8 @@ void NotifyKeyArgs::notify(const sp& listener) const { NotifyMotionArgs::NotifyMotionArgs(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action, int32_t actionButton, int32_t flags, int32_t metaState, - int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp, - uint32_t pointerCount, + int32_t buttonState, MotionClassification classification, + int32_t edgeFlags, uint32_t deviceTimestamp, uint32_t pointerCount, const PointerProperties* pointerProperties, const PointerCoords* pointerCoords, float xPrecision, float yPrecision, nsecs_t downTime, const std::vector& videoFrames) : @@ -80,7 +80,7 @@ NotifyMotionArgs::NotifyMotionArgs(uint32_t sequenceNum, nsecs_t eventTime, int3 displayId(displayId), policyFlags(policyFlags), action(action), actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState), - edgeFlags(edgeFlags), deviceTimestamp(deviceTimestamp), + classification(classification), edgeFlags(edgeFlags), deviceTimestamp(deviceTimestamp), pointerCount(pointerCount), xPrecision(xPrecision), yPrecision(yPrecision), downTime(downTime), videoFrames(videoFrames) { @@ -95,7 +95,7 @@ NotifyMotionArgs::NotifyMotionArgs(const NotifyMotionArgs& other) : source(other.source), displayId(other.displayId), policyFlags(other.policyFlags), action(other.action), actionButton(other.actionButton), flags(other.flags), metaState(other.metaState), buttonState(other.buttonState), - edgeFlags(other.edgeFlags), + classification(other.classification), edgeFlags(other.edgeFlags), deviceTimestamp(other.deviceTimestamp), pointerCount(other.pointerCount), xPrecision(other.xPrecision), yPrecision(other.yPrecision), downTime(other.downTime), videoFrames(other.videoFrames) { diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 33bf163abb..2b31f6e0e6 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -2834,7 +2834,8 @@ void CursorInputMapper::sync(nsecs_t when) { NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0, - metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, + metaState, buttonState, + MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime, /* videoFrames */ {}); getListener()->notifyMotion(&releaseArgs); @@ -2843,7 +2844,7 @@ void CursorInputMapper::sync(nsecs_t when) { NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState, - AMOTION_EVENT_EDGE_FLAG_NONE, + MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime, /* videoFrames */ {}); getListener()->notifyMotion(&args); @@ -2855,7 +2856,8 @@ void CursorInputMapper::sync(nsecs_t when) { buttonState |= actionButton; NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS, - actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, + actionButton, 0, metaState, buttonState, + MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime, /* videoFrames */ {}); getListener()->notifyMotion(&pressArgs); @@ -2869,7 +2871,8 @@ void CursorInputMapper::sync(nsecs_t when) { && (mSource == AINPUT_SOURCE_MOUSE)) { NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, - metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, + metaState, currentButtonState, + MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime, /* videoFrames */ {}); getListener()->notifyMotion(&hoverArgs); @@ -2883,7 +2886,7 @@ void CursorInputMapper::sync(nsecs_t when) { NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState, - AMOTION_EVENT_EDGE_FLAG_NONE, + MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime, /* videoFrames */ {}); getListener()->notifyMotion(&scrollArgs); @@ -3014,8 +3017,8 @@ void RotaryEncoderInputMapper::sync(nsecs_t when) { NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, - AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0, - AMOTION_EVENT_EDGE_FLAG_NONE, + AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, /* buttonState */ 0, + MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, 0, 0, 0, /* videoFrames */ {}); getListener()->notifyMotion(&scrollArgs); @@ -5413,7 +5416,7 @@ void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlag NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, - metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, + metaState, buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, 0, 0, mPointerGesture.downTime, /* videoFrames */ {}); getListener()->notifyMotion(&args); @@ -6338,8 +6341,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, // Send up. NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, - AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0, - /* deviceTimestamp */ 0, + AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, + MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime, /* videoFrames */ {}); @@ -6352,8 +6355,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, // Send hover exit. NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, - AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0, - /* deviceTimestamp */ 0, + AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, + MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime, /* videoFrames */ {}); @@ -6368,7 +6371,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, // Send down. NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, - AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0, + AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, + MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, @@ -6379,8 +6383,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, // Send move. NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, - AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, - /* deviceTimestamp */ 0, + AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, + MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime, /* videoFrames */ {}); @@ -6395,8 +6399,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState, - mCurrentRawState.buttonState, 0, - /* deviceTimestamp */ 0, + mCurrentRawState.buttonState, MotionClassification::NONE, + AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime, /* videoFrames */ {}); @@ -6407,8 +6411,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, - mCurrentRawState.buttonState, 0, - /* deviceTimestamp */ 0, + mCurrentRawState.buttonState, MotionClassification::NONE, + AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime, /* videoFrames */ {}); @@ -6429,8 +6433,8 @@ void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, displayId, policyFlags, - AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0, - /* deviceTimestamp */ 0, + AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, + MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties, &pointerCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime, /* videoFrames */ {}); @@ -6497,8 +6501,8 @@ void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32 std::vector frames = mDevice->getEventHub()->getVideoFrames(deviceId); NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, source, displayId, policyFlags, - action, actionButton, flags, metaState, buttonState, edgeFlags, - deviceTimestamp, pointerCount, pointerProperties, pointerCoords, + action, actionButton, flags, metaState, buttonState, MotionClassification::NONE, + edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords, xPrecision, yPrecision, downTime, std::move(frames)); getListener()->notifyMotion(&args); } @@ -7422,9 +7426,9 @@ void JoystickInputMapper::sync(nsecs_t when, bool force) { NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags, - AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, - /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, - 0, 0, 0, /* videoFrames */ {}); + AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, MotionClassification::NONE, + AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1, + &pointerProperties, &pointerCoords, 0, 0, 0, /* videoFrames */ {}); getListener()->notifyMotion(&args); } diff --git a/services/inputflinger/include/InputListener.h b/services/inputflinger/include/InputListener.h index 2442cc052b..53247a059b 100644 --- a/services/inputflinger/include/InputListener.h +++ b/services/inputflinger/include/InputListener.h @@ -99,6 +99,10 @@ struct NotifyMotionArgs : public NotifyArgs { int32_t flags; int32_t metaState; int32_t buttonState; + /** + * Classification of the current touch gesture + */ + MotionClassification classification; int32_t edgeFlags; /** * A timestamp in the input device's time base, not the platform's. @@ -120,7 +124,7 @@ struct NotifyMotionArgs : public NotifyArgs { NotifyMotionArgs(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action, int32_t actionButton, int32_t flags, - int32_t metaState, int32_t buttonState, + int32_t metaState, int32_t buttonState, MotionClassification classification, int32_t edgeFlags, uint32_t deviceTimestamp, uint32_t pointerCount, const PointerProperties* pointerProperties, const PointerCoords* pointerCoords, float xPrecision, float yPrecision, nsecs_t downTime, -- cgit v1.2.3-59-g8ed1b From 9ffab0cc56a4b7e12fe329845c4c60d422129370 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Thu, 8 Nov 2018 19:54:22 -0800 Subject: Metrics for touch latency Add some basic metrics for touch latency here. Currently just measure the time from evdev to eventhub. This will later become "hard interrupt" to eventhub, after we fix b/119840121. Bug: 111431676 Test: set reporting interval to 5 seconds instead of 5 minutes, then run 'statsd_testdrive 34' and touch the screen for a minute. Review the results to ensure that times are reported as expected. Change-Id: I6144aa0feab897a161f1ee058686dd0a790d17f1 --- services/inputflinger/Android.bp | 3 +- services/inputflinger/InputReader.cpp | 25 ++++++++++--- services/inputflinger/InputReader.h | 68 +++++++++++++++++++++++++++++++++++ 3 files changed, 91 insertions(+), 5 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/Android.bp b/services/inputflinger/Android.bp index 843eb379d9..e3a237ef73 100644 --- a/services/inputflinger/Android.bp +++ b/services/inputflinger/Android.bp @@ -76,7 +76,8 @@ cc_library_shared { "libutils", "libui", "libhardware_legacy", - "libutils" + "libstatslog", + "libutils", ], header_libs: [ diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 2b31f6e0e6..64070e3fa3 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -57,6 +57,7 @@ #include #include #include +#include #define INDENT " " #define INDENT2 " " @@ -71,18 +72,21 @@ namespace android { // --- Constants --- // Maximum number of slots supported when using the slot-based Multitouch Protocol B. -static const size_t MAX_SLOTS = 32; +static constexpr size_t MAX_SLOTS = 32; // Maximum amount of latency to add to touch events while waiting for data from an // external stylus. -static const nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72); +static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72); // Maximum amount of time to wait on touch data before pushing out new pressure data. -static const nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20); +static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20); // Artificial latency on synthetic events created from stylus data without corresponding touch // data. -static const nsecs_t STYLUS_DATA_LATENCY = ms2ns(10); +static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10); + +// How often to report input event statistics +static constexpr nsecs_t STATISTICS_REPORT_FREQUENCY = seconds_to_nanoseconds(5 * 60); // --- Static Functions --- @@ -4287,12 +4291,25 @@ void TouchInputMapper::clearStylusDataPendingFlags() { mExternalStylusFusionTimeout = LLONG_MAX; } +void TouchInputMapper::reportEventForStatistics(nsecs_t evdevTime) { + nsecs_t now = systemTime(CLOCK_MONOTONIC); + nsecs_t latency = now - evdevTime; + mStatistics.addValue(nanoseconds_to_microseconds(latency)); + nsecs_t timeSinceLastReport = now - mStatistics.lastReportTime; + if (timeSinceLastReport > STATISTICS_REPORT_FREQUENCY) { + android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, + mStatistics.min, mStatistics.max, mStatistics.mean(), mStatistics.stdev()); + mStatistics.reset(now); + } +} + void TouchInputMapper::process(const RawEvent* rawEvent) { mCursorButtonAccumulator.process(rawEvent); mCursorScrollAccumulator.process(rawEvent); mTouchButtonAccumulator.process(rawEvent); if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) { + reportEventForStatistics(rawEvent->when); sync(rawEvent->when); } } diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h index 35f3c232c7..aaffce294e 100644 --- a/services/inputflinger/InputReader.h +++ b/services/inputflinger/InputReader.h @@ -567,6 +567,69 @@ struct CookedPointerData { } }; +/** + * Basic statistics information. + * Keep track of min, max, average, and standard deviation of the received samples. + * Used to report latency information about input events. + */ +struct LatencyStatistics { + float min; + float max; + // Sum of all samples + float sum; + // Sum of squares of all samples + float sum2; + // The number of samples + size_t count; + // The last time statistics were reported. + nsecs_t lastReportTime; + + LatencyStatistics() { + reset(systemTime(SYSTEM_TIME_MONOTONIC)); + } + + inline void addValue(float x) { + if (x < min) { + min = x; + } + if (x > max) { + max = x; + } + sum += x; + sum2 += x * x; + count++; + } + + // Get the average value. Should not be called if no samples have been added. + inline float mean() { + if (count == 0) { + return 0; + } + return sum / count; + } + + // Get the standard deviation. Should not be called if no samples have been added. + inline float stdev() { + if (count == 0) { + return 0; + } + float average = mean(); + return sqrt(sum2 / count - average * average); + } + + /** + * Reset internal state. The variable 'when' is the time when the data collection started. + * Call this to start a new data collection window. + */ + inline void reset(nsecs_t when) { + max = 0; + min = std::numeric_limits::max(); + sum = 0; + sum2 = 0; + count = 0; + lastReportTime = when; + } +}; /* Keeps track of the state of single-touch protocol. */ class SingleTouchMotionAccumulator { @@ -1511,6 +1574,9 @@ private: VelocityControl mWheelXVelocityControl; VelocityControl mWheelYVelocityControl; + // Latency statistics for touch events + struct LatencyStatistics mStatistics; + std::optional findViewport(); void resetExternalStylus(); @@ -1580,6 +1646,8 @@ private: static void assignPointerIds(const RawState* last, RawState* current); + void reportEventForStatistics(nsecs_t evdevTime); + const char* modeToString(DeviceMode deviceMode); }; -- cgit v1.2.3-59-g8ed1b From 7c64540cb3a25d3009c5c79860afe078a936ef43 Mon Sep 17 00:00:00 2001 From: Arthur Hung Date: Fri, 25 Jan 2019 17:45:42 +0800 Subject: Support showTouches on multi-display (1/2) Pass the displayId to PointerController to show the corresponding touch spots. Test: atest inputflinger_tests Test: Use device support multi-display and touch screen (like mojave). Enable showTaps from develop options and check if show tap spots. Bug: 120815589 Change-Id: I529ad2c9bfd891bc3372143fc663824efa99f53b --- services/inputflinger/InputReader.cpp | 6 +- .../include/PointerControllerInterface.h | 2 +- services/inputflinger/tests/InputReader_test.cpp | 102 ++++++++++++++++++++- 3 files changed, 106 insertions(+), 4 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 64070e3fa3..68983a907c 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -4501,7 +4501,8 @@ void TouchInputMapper::cookAndDispatch(nsecs_t when) { mPointerController->setButtonState(mCurrentRawState.buttonState); mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords, mCurrentCookedState.cookedPointerData.idToIndex, - mCurrentCookedState.cookedPointerData.touchingIdBits); + mCurrentCookedState.cookedPointerData.touchingIdBits, + mViewport.displayId); } if (!mCurrentMotionAborted) { @@ -5265,7 +5266,8 @@ void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlag if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) { mPointerController->setSpots(mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, - mPointerGesture.currentGestureIdBits); + mPointerGesture.currentGestureIdBits, + mPointerController->getDisplayId()); } } else { mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER); diff --git a/services/inputflinger/include/PointerControllerInterface.h b/services/inputflinger/include/PointerControllerInterface.h index bc0f1f919f..0ff28e4174 100644 --- a/services/inputflinger/include/PointerControllerInterface.h +++ b/services/inputflinger/include/PointerControllerInterface.h @@ -94,7 +94,7 @@ public: * pressed (not hovering). */ virtual void setSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex, - BitSet32 spotIdBits) = 0; + BitSet32 spotIdBits, int32_t displayId) = 0; /* Removes all spots. */ virtual void clearSpots() = 0; diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index de87e7f6b9..84f416869a 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -102,6 +102,10 @@ public: return mDisplayId; } + const std::map>& getSpots() { + return mSpotsByDisplay; + } + private: virtual bool getBounds(float* outMinX, float* outMinY, float* outMaxX, float* outMaxY) const { *outMinX = mMinX; @@ -129,11 +133,22 @@ private: virtual void setPresentation(Presentation) { } - virtual void setSpots(const PointerCoords*, const uint32_t*, BitSet32) { + virtual void setSpots(const PointerCoords*, const uint32_t*, BitSet32 spotIdBits, + int32_t displayId) { + std::vector newSpots; + // Add spots for fingers that are down. + for (BitSet32 idBits(spotIdBits); !idBits.isEmpty(); ) { + uint32_t id = idBits.clearFirstMarkedBit(); + newSpots.push_back(id); + } + + mSpotsByDisplay[displayId] = newSpots; } virtual void clearSpots() { } + + std::map> mSpotsByDisplay; }; @@ -227,6 +242,10 @@ public: mConfig.pointerCapture = enabled; } + void setShowTouches(bool enabled) { + mConfig.showTouches = enabled; + } + private: DisplayViewport createDisplayViewport(int32_t displayId, int32_t width, int32_t height, int32_t orientation, const std::string& uniqueId, std::optional physicalPort, @@ -6377,4 +6396,85 @@ TEST_F(MultiTouchInputMapperTest, Process_Pointer_ShouldHandleDisplayId) { ASSERT_EQ(SECONDARY_DISPLAY_ID, motionArgs.displayId); } +TEST_F(MultiTouchInputMapperTest, Process_Pointer_ShowTouches) { + // Setup the first touch screen device. + MultiTouchInputMapper* mapper = new MultiTouchInputMapper(mDevice); + prepareAxes(POSITION | ID | SLOT); + addConfigurationProperty("touch.deviceType", "touchScreen"); + addMapperAndConfigure(mapper); + + // Create the second touch screen device, and enable multi fingers. + const std::string USB2 = "USB2"; + const int32_t SECOND_DEVICE_ID = 2; + InputDeviceIdentifier identifier; + identifier.name = DEVICE_NAME; + identifier.location = USB2; + InputDevice* device2 = new InputDevice(mFakeContext, SECOND_DEVICE_ID, DEVICE_GENERATION, + DEVICE_CONTROLLER_NUMBER, identifier, DEVICE_CLASSES); + mFakeEventHub->addDevice(SECOND_DEVICE_ID, DEVICE_NAME, 0 /*classes*/); + mFakeEventHub->addAbsoluteAxis(SECOND_DEVICE_ID, ABS_MT_POSITION_X, RAW_X_MIN, RAW_X_MAX, + 0 /*flat*/, 0 /*fuzz*/); + mFakeEventHub->addAbsoluteAxis(SECOND_DEVICE_ID, ABS_MT_POSITION_Y, RAW_Y_MIN, RAW_Y_MAX, + 0 /*flat*/, 0 /*fuzz*/); + mFakeEventHub->addAbsoluteAxis(SECOND_DEVICE_ID, ABS_MT_TRACKING_ID, RAW_ID_MIN, RAW_ID_MAX, + 0 /*flat*/, 0 /*fuzz*/); + mFakeEventHub->addAbsoluteAxis(SECOND_DEVICE_ID, ABS_MT_SLOT, RAW_SLOT_MIN, RAW_SLOT_MAX, + 0 /*flat*/, 0 /*fuzz*/); + mFakeEventHub->setAbsoluteAxisValue(SECOND_DEVICE_ID, ABS_MT_SLOT, 0 /*value*/); + mFakeEventHub->addConfigurationProperty(SECOND_DEVICE_ID, String8("touch.deviceType"), + String8("touchScreen")); + + // Setup the second touch screen device. + MultiTouchInputMapper* mapper2 = new MultiTouchInputMapper(device2); + device2->addMapper(mapper2); + device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(), 0 /*changes*/); + device2->reset(ARBITRARY_TIME); + + // Setup PointerController. + sp fakePointerController = new FakePointerController(); + mFakePolicy->setPointerController(mDevice->getId(), fakePointerController); + mFakePolicy->setPointerController(SECOND_DEVICE_ID, fakePointerController); + + // Setup policy for associated displays and show touches. + const uint8_t hdmi1 = 0; + const uint8_t hdmi2 = 1; + mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi1); + mFakePolicy->addInputPortAssociation(USB2, hdmi2); + mFakePolicy->setShowTouches(true); + + // Create displays. + prepareDisplay(DISPLAY_ORIENTATION_0, hdmi1); + prepareSecondaryDisplay(ViewportType::VIEWPORT_EXTERNAL, hdmi2); + + // Default device will reconfigure above, need additional reconfiguration for another device. + device2->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(), + InputReaderConfiguration::CHANGE_DISPLAY_INFO); + + // Two fingers down at default display. + int32_t x1 = 100, y1 = 125, x2 = 300, y2 = 500; + processPosition(mapper, x1, y1); + processId(mapper, 1); + processSlot(mapper, 1); + processPosition(mapper, x2, y2); + processId(mapper, 2); + processSync(mapper); + + std::map>::const_iterator iter = + fakePointerController->getSpots().find(DISPLAY_ID); + ASSERT_TRUE(iter != fakePointerController->getSpots().end()); + ASSERT_EQ(size_t(2), iter->second.size()); + + // Two fingers down at second display. + processPosition(mapper2, x1, y1); + processId(mapper2, 1); + processSlot(mapper2, 1); + processPosition(mapper2, x2, y2); + processId(mapper2, 2); + processSync(mapper2); + + iter = fakePointerController->getSpots().find(SECONDARY_DISPLAY_ID); + ASSERT_TRUE(iter != fakePointerController->getSpots().end()); + ASSERT_EQ(size_t(2), iter->second.size()); +} + } // namespace android -- cgit v1.2.3-59-g8ed1b From c23540e791f4816ae24664118a2227f3929f8a39 Mon Sep 17 00:00:00 2001 From: Arthur Hung Date: Thu, 29 Nov 2018 20:42:11 +0800 Subject: Input devices configure on per-display basis (1/2) A InputDevice may be associated with a specific display. This would provide a function to check if an input device can dispatch input events to the specific display. If the device has no associated, the events can dispatch to any display. Bug: 116767202 Test: atest -a libinput_tests inputflinger_tests Change-Id: I05a1c8db191ef1e6c4182f902a7a3b51e420740d --- services/inputflinger/InputReader.cpp | 65 ++++++++++++++++++++++-- services/inputflinger/InputReader.h | 9 +++- services/inputflinger/include/InputReaderBase.h | 3 ++ services/inputflinger/tests/InputReader_test.cpp | 53 +++++++++++++++++-- 4 files changed, 120 insertions(+), 10 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 64070e3fa3..f84aa34a5c 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -805,6 +805,30 @@ bool InputReader::isInputDeviceEnabled(int32_t deviceId) { return false; } +bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) { + AutoMutex _l(mLock); + + ssize_t deviceIndex = mDevices.indexOfKey(deviceId); + if (deviceIndex < 0) { + ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId); + return false; + } + + InputDevice* device = mDevices.valueAt(deviceIndex); + std::optional associatedDisplayId = device->getAssociatedDisplay(); + // No associated display. By default, can dispatch to all displays. + if (!associatedDisplayId) { + return true; + } + + if (*associatedDisplayId == ADISPLAY_ID_NONE) { + ALOGW("Device has associated, but no associated display id."); + return true; + } + + return *associatedDisplayId == displayId; +} + void InputReader::dump(std::string& dump) { AutoMutex _l(mLock); @@ -1275,6 +1299,18 @@ void InputDevice::notifyReset(nsecs_t when) { mContext->getListener()->notifyDeviceReset(&args); } +std::optional InputDevice::getAssociatedDisplay() { + size_t numMappers = mMappers.size(); + for (size_t i = 0; i < numMappers; i++) { + InputMapper* mapper = mMappers[i]; + std::optional associatedDisplayId = mapper->getAssociatedDisplay(); + if (associatedDisplayId) { + return associatedDisplayId; + } + } + + return std::nullopt; +} // --- CursorButtonAccumulator --- @@ -2647,7 +2683,7 @@ void CursorInputMapper::configure(nsecs_t when, } // Update the PointerController if viewports changed. - if (mParameters.hasAssociatedDisplay) { + if (mParameters.mode == Parameters::MODE_POINTER) { getPolicy()->obtainPointerController(getDeviceId()); } bumpGeneration(); @@ -2919,6 +2955,19 @@ void CursorInputMapper::fadePointer() { } } +std::optional CursorInputMapper::getAssociatedDisplay() { + if (mParameters.hasAssociatedDisplay) { + if (mParameters.mode == Parameters::MODE_POINTER) { + return std::make_optional(mPointerController->getDisplayId()); + } else { + // If the device is orientationAware and not a mouse, + // it expects to dispatch events to any display + return std::make_optional(ADISPLAY_ID_NONE); + } + } + return std::nullopt; +} + // --- RotaryEncoderInputMapper --- RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) : @@ -6511,9 +6560,7 @@ void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32 ALOG_ASSERT(false); } } - const int32_t displayId = mPointerController != nullptr ? - mPointerController->getDisplayId() : mViewport.displayId; - + const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE); const int32_t deviceId = getDeviceId(); std::vector frames = mDevice->getEventHub()->getVideoFrames(deviceId); NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, @@ -6830,6 +6877,16 @@ bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCode return true; } +std::optional TouchInputMapper::getAssociatedDisplay() { + if (mParameters.hasAssociatedDisplay) { + if (mDeviceMode == DEVICE_MODE_POINTER) { + return std::make_optional(mPointerController->getDisplayId()); + } else { + return std::make_optional(mViewport.displayId); + } + } + return std::nullopt; +} // --- SingleTouchInputMapper --- diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h index aaffce294e..fed55ac0e6 100644 --- a/services/inputflinger/InputReader.h +++ b/services/inputflinger/InputReader.h @@ -146,6 +146,7 @@ public: ssize_t repeat, int32_t token); virtual void cancelVibrate(int32_t deviceId, int32_t token); + virtual bool canDispatchToDisplay(int32_t deviceId, int32_t displayId); protected: // These members are protected so they can be instrumented by test cases. virtual InputDevice* createDeviceLocked(int32_t deviceId, int32_t controllerNumber, @@ -320,6 +321,7 @@ public: return value; } + std::optional getAssociatedDisplay(); private: InputReaderContext* mContext; int32_t mId; @@ -778,7 +780,9 @@ public: virtual void updateExternalStylusState(const StylusState& state); virtual void fadePointer(); - + virtual std::optional getAssociatedDisplay() { + return std::nullopt; + } protected: InputDevice* mDevice; InputReaderContext* mContext; @@ -932,6 +936,7 @@ public: virtual void fadePointer(); + virtual std::optional getAssociatedDisplay(); private: // Amount that trackball needs to move in order to generate a key event. static const int32_t TRACKBALL_MOVEMENT_THRESHOLD = 6; @@ -1025,7 +1030,7 @@ public: virtual void cancelTouch(nsecs_t when); virtual void timeoutExpired(nsecs_t when); virtual void updateExternalStylusState(const StylusState& state); - + virtual std::optional getAssociatedDisplay(); protected: CursorButtonAccumulator mCursorButtonAccumulator; CursorScrollAccumulator mCursorScrollAccumulator; diff --git a/services/inputflinger/include/InputReaderBase.h b/services/inputflinger/include/InputReaderBase.h index fe1c50bc75..c411ec00a9 100644 --- a/services/inputflinger/include/InputReaderBase.h +++ b/services/inputflinger/include/InputReaderBase.h @@ -100,6 +100,9 @@ public: virtual void vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token) = 0; virtual void cancelVibrate(int32_t deviceId, int32_t token) = 0; + + /* Return true if the device can send input events to the specified display. */ + virtual bool canDispatchToDisplay(int32_t deviceId, int32_t displayId) = 0; }; /* Reads raw events from the event hub and processes them, endlessly. */ diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index 0b86555fb3..84c5ad6dd9 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -841,6 +841,7 @@ class FakeInputMapper : public InputMapper { bool mResetWasCalled; bool mProcessWasCalled; + std::optional mViewport; public: FakeInputMapper(InputDevice* device, uint32_t sources) : InputMapper(device), @@ -909,8 +910,14 @@ private: } } - virtual void configure(nsecs_t, const InputReaderConfiguration*, uint32_t) { + virtual void configure(nsecs_t, const InputReaderConfiguration* config, uint32_t changes) { mConfigureWasCalled = true; + + // Find the associated viewport if exist. + const std::optional displayPort = mDevice->getAssociatedDisplayPort(); + if (displayPort && (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { + mViewport = config->getDisplayViewportByPort(*displayPort); + } } virtual void reset(nsecs_t) { @@ -957,6 +964,13 @@ private: virtual void fadePointer() { } + + virtual std::optional getAssociatedDisplay() { + if (mViewport) { + return std::make_optional(mViewport->displayId); + } + return std::nullopt; + } }; @@ -984,9 +998,10 @@ public: } InputDevice* newDevice(int32_t deviceId, int32_t controllerNumber, const std::string& name, - uint32_t classes) { + uint32_t classes, const std::string& location = "") { InputDeviceIdentifier identifier; identifier.name = name; + identifier.location = location; int32_t generation = deviceId + 1; return new InputDevice(&mContext, deviceId, generation, controllerNumber, identifier, classes); @@ -1286,7 +1301,7 @@ TEST_F(InputReaderTest, GetInputDevices) { TEST_F(InputReaderTest, WhenEnabledChanges_SendsDeviceResetNotification) { constexpr int32_t deviceId = 1; constexpr uint32_t deviceClass = INPUT_DEVICE_CLASS_KEYBOARD; - InputDevice* device = mReader->newDevice(deviceId, 0, "fake", deviceClass); + InputDevice* device = mReader->newDevice(deviceId, 0 /*controllerNumber*/, "fake", deviceClass); // Must add at least one mapper or the device will be ignored! FakeInputMapper* mapper = new FakeInputMapper(device, AINPUT_SOURCE_KEYBOARD); device->addMapper(mapper); @@ -1470,7 +1485,7 @@ TEST_F(InputReaderTest, LoopOnce_ForwardsRawEventsToMappers) { TEST_F(InputReaderTest, DeviceReset_IncrementsSequenceNumber) { constexpr int32_t deviceId = 1; constexpr uint32_t deviceClass = INPUT_DEVICE_CLASS_KEYBOARD; - InputDevice* device = mReader->newDevice(deviceId, 0, "fake", deviceClass); + InputDevice* device = mReader->newDevice(deviceId, 0 /*controllerNumber*/, "fake", deviceClass); // Must add at least one mapper or the device will be ignored! FakeInputMapper* mapper = new FakeInputMapper(device, AINPUT_SOURCE_KEYBOARD); device->addMapper(mapper); @@ -1500,6 +1515,36 @@ TEST_F(InputReaderTest, DeviceReset_IncrementsSequenceNumber) { prevSequenceNum = resetArgs.sequenceNum; } +TEST_F(InputReaderTest, Device_CanDispatchToDisplay) { + constexpr int32_t deviceId = 1; + constexpr uint32_t deviceClass = INPUT_DEVICE_CLASS_KEYBOARD; + const char* DEVICE_LOCATION = "USB1"; + InputDevice* device = mReader->newDevice(deviceId, 0 /*controllerNumber*/, "fake", deviceClass, + DEVICE_LOCATION); + FakeInputMapper* mapper = new FakeInputMapper(device, AINPUT_SOURCE_TOUCHSCREEN); + device->addMapper(mapper); + mReader->setNextDevice(device); + addDevice(deviceId, "fake", deviceClass, nullptr); + + const uint8_t hdmi1 = 1; + + // Associated touch screen with second display. + mFakePolicy->addInputPortAssociation(DEVICE_LOCATION, hdmi1); + + // Add default and second display. + mFakePolicy->addDisplayViewport(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, + DISPLAY_ORIENTATION_0, "local:0", NO_PORT, ViewportType::VIEWPORT_INTERNAL); + mFakePolicy->addDisplayViewport(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, + DISPLAY_ORIENTATION_0, "local:1", hdmi1, ViewportType::VIEWPORT_EXTERNAL); + mReader->requestRefreshConfiguration(InputReaderConfiguration::CHANGE_DISPLAY_INFO); + mReader->loopOnce(); + + // Check device. + ASSERT_EQ(deviceId, device->getId()); + ASSERT_FALSE(mReader->canDispatchToDisplay(deviceId, DISPLAY_ID)); + ASSERT_TRUE(mReader->canDispatchToDisplay(deviceId, SECONDARY_DISPLAY_ID)); +} + // --- InputDeviceTest --- -- cgit v1.2.3-59-g8ed1b From 8154bbdf6bb2c5de865e9408a1452bbfd3c37a17 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Fri, 15 Feb 2019 17:21:03 -0600 Subject: Rotate TouchVideoFrames When a screen orientation change happens, the touch coordinates are adjusted in InputReader to accomodate this rotation. When the user is holding the device, the origin (0, 0) is always at the top left of the screen. However, currently, the TouchVideoFrames are not being rotated. This presents a problem, because the touch coordinates cannot be directly matched to the heatmap, as received in the HAL. To account for this, we rotate the touch video frame. Test: atest libinput_tests inputflinger_tests Bug: 123241238 Change-Id: Iff45c68b1d2b237d2b1657ed76f50bb23ef8468a --- include/input/TouchVideoFrame.h | 13 +++ libs/input/TouchVideoFrame.cpp | 58 +++++++++++ libs/input/tests/TouchVideoFrame_test.cpp | 125 +++++++++++++++++++++++ services/inputflinger/InputReader.cpp | 2 + services/inputflinger/tests/InputReader_test.cpp | 48 +++++++++ 5 files changed, 246 insertions(+) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/include/input/TouchVideoFrame.h b/include/input/TouchVideoFrame.h index 566c334e57..b49c623204 100644 --- a/include/input/TouchVideoFrame.h +++ b/include/input/TouchVideoFrame.h @@ -19,6 +19,7 @@ #include #include +#include #include namespace android { @@ -55,11 +56,23 @@ public: */ const struct timeval& getTimestamp() const; + /** + * Rotate the video frame. + * The rotation value is an enum from ui/DisplayInfo.h + */ + void rotate(int32_t orientation); + private: uint32_t mHeight; uint32_t mWidth; std::vector mData; struct timeval mTimestamp; + + /** + * Common method for 90 degree and 270 degree rotation + */ + void rotateQuarterTurn(bool clockwise); + void rotate180(); }; } // namespace android diff --git a/libs/input/TouchVideoFrame.cpp b/libs/input/TouchVideoFrame.cpp index 35cb4a73ea..8a4298a36f 100644 --- a/libs/input/TouchVideoFrame.cpp +++ b/libs/input/TouchVideoFrame.cpp @@ -39,4 +39,62 @@ const std::vector& TouchVideoFrame::getData() const { return mData; } const struct timeval& TouchVideoFrame::getTimestamp() const { return mTimestamp; } +void TouchVideoFrame::rotate(int32_t orientation) { + switch (orientation) { + case DISPLAY_ORIENTATION_90: + rotateQuarterTurn(true /*clockwise*/); + break; + case DISPLAY_ORIENTATION_180: + rotate180(); + break; + case DISPLAY_ORIENTATION_270: + rotateQuarterTurn(false /*clockwise*/); + break; + } +} + +/** + * Rotate once clockwise by a quarter turn === rotate 90 degrees + * Rotate once counterclockwise by a quarter turn === rotate 270 degrees + * For a clockwise rotation: + * An element at position (i, j) is rotated to (j, height - i - 1) + * For a counterclockwise rotation: + * An element at position (i, j) is rotated to (width - j - 1, i) + */ +void TouchVideoFrame::rotateQuarterTurn(bool clockwise) { + std::vector rotated(mData.size()); + for (size_t i = 0; i < mHeight; i++) { + for (size_t j = 0; j < mWidth; j++) { + size_t iRotated, jRotated; + if (clockwise) { + iRotated = j; + jRotated = mHeight - i - 1; + } else { + iRotated = mWidth - j - 1; + jRotated = i; + } + size_t indexRotated = iRotated * mHeight + jRotated; + rotated[indexRotated] = mData[i * mWidth + j]; + } + } + mData = std::move(rotated); + std::swap(mHeight, mWidth); +} + +/** + * An element at position (i, j) is rotated to (height - i - 1, width - j - 1) + * This is equivalent to moving element [i] to position [height * width - i - 1] + * Since element at [height * width - i - 1] would move to position [i], + * we can just swap elements [i] and [height * width - i - 1]. + */ +void TouchVideoFrame::rotate180() { + if (mData.size() == 0) { + return; + } + // Just need to swap elements i and (height * width - 1 - i) + for (size_t i = 0; i < mData.size() / 2; i++) { + std::swap(mData[i], mData[mHeight * mWidth - 1 - i]); + } +} + } // namespace android diff --git a/libs/input/tests/TouchVideoFrame_test.cpp b/libs/input/tests/TouchVideoFrame_test.cpp index 3c1c7f3295..815424ee31 100644 --- a/libs/input/tests/TouchVideoFrame_test.cpp +++ b/libs/input/tests/TouchVideoFrame_test.cpp @@ -67,5 +67,130 @@ TEST(TouchVideoFrame, Equality) { ASSERT_FALSE(frame == changedTimestampFrame); } +// --- Rotate 90 degrees --- + +TEST(TouchVideoFrame, Rotate90_0x0) { + TouchVideoFrame frame(0, 0, {}, TIMESTAMP); + TouchVideoFrame frameRotated(0, 0, {}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_90); + ASSERT_EQ(frame, frameRotated); +} + +TEST(TouchVideoFrame, Rotate90_1x1) { + TouchVideoFrame frame(1, 1, {1}, TIMESTAMP); + TouchVideoFrame frameRotated(1, 1, {1}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_90); + ASSERT_EQ(frame, frameRotated); +} + +TEST(TouchVideoFrame, Rotate90_2x2) { + TouchVideoFrame frame(2, 2, {1, 2, 3, 4}, TIMESTAMP); + TouchVideoFrame frameRotated(2, 2, {3, 1, 4, 2}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_90); + ASSERT_EQ(frame, frameRotated); +} + +TEST(TouchVideoFrame, Rotate90_3x2) { + TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, TIMESTAMP); + TouchVideoFrame frameRotated(2, 3, {5, 3, 1, 6, 4, 2}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_90); + ASSERT_EQ(frame, frameRotated); +} + +TEST(TouchVideoFrame, Rotate90_3x2_4times) { + TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, TIMESTAMP); + TouchVideoFrame frameOriginal(3, 2, {1, 2, 3, 4, 5, 6}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_90); + frame.rotate(DISPLAY_ORIENTATION_90); + frame.rotate(DISPLAY_ORIENTATION_90); + frame.rotate(DISPLAY_ORIENTATION_90); + ASSERT_EQ(frame, frameOriginal); +} + +// --- Rotate 180 degrees --- + +TEST(TouchVideoFrame, Rotate180_0x0) { + TouchVideoFrame frame(0, 0, {}, TIMESTAMP); + TouchVideoFrame frameRotated(0, 0, {}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_180); + ASSERT_EQ(frame, frameRotated); +} + +TEST(TouchVideoFrame, Rotate180_1x1) { + TouchVideoFrame frame(1, 1, {1}, TIMESTAMP); + TouchVideoFrame frameRotated(1, 1, {1}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_180); + ASSERT_EQ(frame, frameRotated); +} + +TEST(TouchVideoFrame, Rotate180_2x2) { + TouchVideoFrame frame(2, 2, {1, 2, 3, 4}, TIMESTAMP); + TouchVideoFrame frameRotated(2, 2, {4, 3, 2, 1}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_180); + ASSERT_EQ(frame, frameRotated); +} + +TEST(TouchVideoFrame, Rotate180_3x2) { + TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, TIMESTAMP); + TouchVideoFrame frameRotated(3, 2, {6, 5, 4, 3, 2, 1}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_180); + ASSERT_EQ(frame, frameRotated); +} + +TEST(TouchVideoFrame, Rotate180_3x2_2times) { + TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, TIMESTAMP); + TouchVideoFrame frameOriginal(3, 2, {1, 2, 3, 4, 5, 6}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_180); + frame.rotate(DISPLAY_ORIENTATION_180); + ASSERT_EQ(frame, frameOriginal); +} + +TEST(TouchVideoFrame, Rotate180_3x3) { + TouchVideoFrame frame(3, 3, {1, 2, 3, 4, 5, 6, 7, 8, 9}, TIMESTAMP); + TouchVideoFrame frameRotated(3, 3, {9, 8, 7, 6, 5, 4, 3, 2, 1}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_180); + ASSERT_EQ(frame, frameRotated); +} + +// --- Rotate 270 degrees --- + +TEST(TouchVideoFrame, Rotate270_0x0) { + TouchVideoFrame frame(0, 0, {}, TIMESTAMP); + TouchVideoFrame frameRotated(0, 0, {}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_270); + ASSERT_EQ(frame, frameRotated); +} + +TEST(TouchVideoFrame, Rotate270_1x1) { + TouchVideoFrame frame(1, 1, {1}, TIMESTAMP); + TouchVideoFrame frameRotated(1, 1, {1}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_270); + ASSERT_EQ(frame, frameRotated); +} + +TEST(TouchVideoFrame, Rotate270_2x2) { + TouchVideoFrame frame(2, 2, {1, 2, 3, 4}, TIMESTAMP); + TouchVideoFrame frameRotated(2, 2, {2, 4, 1, 3}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_270); + ASSERT_EQ(frame, frameRotated); +} + +TEST(TouchVideoFrame, Rotate270_3x2) { + TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, TIMESTAMP); + TouchVideoFrame frameRotated(2, 3, {2, 4, 6, 1, 3, 5}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_270); + ASSERT_EQ(frame, frameRotated); +} + +TEST(TouchVideoFrame, Rotate270_3x2_4times) { + TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, TIMESTAMP); + TouchVideoFrame frameOriginal(3, 2, {1, 2, 3, 4, 5, 6}, TIMESTAMP); + frame.rotate(DISPLAY_ORIENTATION_270); + frame.rotate(DISPLAY_ORIENTATION_270); + frame.rotate(DISPLAY_ORIENTATION_270); + frame.rotate(DISPLAY_ORIENTATION_270); + ASSERT_EQ(frame, frameOriginal); +} + } // namespace test } // namespace android diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 1a1ae21123..21ba029854 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -6565,6 +6565,8 @@ void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32 const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE); const int32_t deviceId = getDeviceId(); std::vector frames = mDevice->getEventHub()->getVideoFrames(deviceId); + std::for_each(frames.begin(), frames.end(), + [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); }); NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, source, displayId, policyFlags, action, actionButton, flags, metaState, buttonState, MotionClassification::NONE, diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index a08074491d..80a55f1a65 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -6453,4 +6453,52 @@ TEST_F(MultiTouchInputMapperTest, VideoFrames_ReceivedByListener) { ASSERT_EQ(std::vector(), motionArgs.videoFrames); } +TEST_F(MultiTouchInputMapperTest, VideoFrames_AreRotated) { + MultiTouchInputMapper* mapper = new MultiTouchInputMapper(mDevice); + prepareAxes(POSITION); + addConfigurationProperty("touch.deviceType", "touchScreen"); + addMapperAndConfigure(mapper); + // Unrotated video frame + TouchVideoFrame frame(3, 2, {1, 2, 3, 4, 5, 6}, {1, 2}); + NotifyMotionArgs motionArgs; + + // Test all 4 orientations + for (int32_t orientation : {DISPLAY_ORIENTATION_0, DISPLAY_ORIENTATION_90, + DISPLAY_ORIENTATION_180, DISPLAY_ORIENTATION_270}) { + SCOPED_TRACE("Orientation " + StringPrintf("%i", orientation)); + clearViewports(); + prepareDisplay(orientation); + std::vector frames{frame}; + mFakeEventHub->setVideoFrames({{mDevice->getId(), frames}}); + processPosition(mapper, 100, 200); + processSync(mapper); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs)); + frames[0].rotate(orientation); + ASSERT_EQ(frames, motionArgs.videoFrames); + } +} + +TEST_F(MultiTouchInputMapperTest, VideoFrames_MultipleFramesAreRotated) { + MultiTouchInputMapper* mapper = new MultiTouchInputMapper(mDevice); + prepareAxes(POSITION); + addConfigurationProperty("touch.deviceType", "touchScreen"); + addMapperAndConfigure(mapper); + // Unrotated video frames. There's no rule that they must all have the same dimensions, + // so mix these. + TouchVideoFrame frame1(3, 2, {1, 2, 3, 4, 5, 6}, {1, 2}); + TouchVideoFrame frame2(3, 3, {0, 1, 2, 3, 4, 5, 6, 7, 8}, {1, 3}); + TouchVideoFrame frame3(2, 2, {10, 20, 10, 0}, {1, 4}); + std::vector frames{frame1, frame2, frame3}; + NotifyMotionArgs motionArgs; + + prepareDisplay(DISPLAY_ORIENTATION_90); + mFakeEventHub->setVideoFrames({{mDevice->getId(), frames}}); + processPosition(mapper, 100, 200); + processSync(mapper); + ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs)); + std::for_each(frames.begin(), frames.end(), + [](TouchVideoFrame& frame) { frame.rotate(DISPLAY_ORIENTATION_90); }); + ASSERT_EQ(frames, motionArgs.videoFrames); +} + } // namespace android -- cgit v1.2.3-59-g8ed1b From 7c3ae9c745ec325690cd60d791bde7ec1183da42 Mon Sep 17 00:00:00 2001 From: Arthur Hung Date: Mon, 11 Mar 2019 11:23:03 +0800 Subject: Use std::vector over Vector for InputFlinger (1/3) Replace Vector with std::vector. Bug: 112399697 Test: atest inputflinger_tests Change-Id: I8baec68f7a684d97210077f3e387ca1096586a25 --- include/input/IInputFlinger.h | 3 +- include/input/InputDevice.h | 5 +- include/input/KeyLayoutMap.h | 2 +- include/input/VirtualKeyMap.h | 5 +- libs/input/IInputFlinger.cpp | 7 +- libs/input/InputDevice.cpp | 6 +- libs/input/KeyLayoutMap.cpp | 5 +- libs/input/VirtualKeyMap.cpp | 2 +- services/inputflinger/EventHub.cpp | 16 +- services/inputflinger/EventHub.h | 4 +- services/inputflinger/InputDispatcher.cpp | 242 +++++++++------------ services/inputflinger/InputDispatcher.h | 33 ++- services/inputflinger/InputListener.cpp | 10 +- services/inputflinger/InputManager.cpp | 10 +- services/inputflinger/InputManager.h | 2 +- services/inputflinger/InputReader.cpp | 154 +++++-------- services/inputflinger/InputReader.h | 20 +- services/inputflinger/host/InputFlinger.h | 3 +- services/inputflinger/include/InputListener.h | 2 +- services/inputflinger/include/InputReaderBase.h | 4 +- .../inputflinger/tests/InputDispatcher_test.cpp | 38 ++-- services/inputflinger/tests/InputReader_test.cpp | 26 +-- services/surfaceflinger/SurfaceFlinger.cpp | 4 +- 23 files changed, 268 insertions(+), 335 deletions(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/include/input/IInputFlinger.h b/include/input/IInputFlinger.h index cd12fcd255..4365a3c4e3 100644 --- a/include/input/IInputFlinger.h +++ b/include/input/IInputFlinger.h @@ -22,7 +22,6 @@ #include -#include #include #include @@ -36,7 +35,7 @@ class IInputFlinger : public IInterface { public: DECLARE_META_INTERFACE(InputFlinger) - virtual void setInputWindows(const Vector& inputHandles, + virtual void setInputWindows(const std::vector& inputHandles, const sp& setInputWindowsListener) = 0; virtual void transferTouchFocus(const sp& fromToken, const sp& toToken) = 0; virtual void registerInputChannel(const sp& channel) = 0; diff --git a/include/input/InputDevice.h b/include/input/InputDevice.h index 48ac88d50e..b6efc82fd4 100644 --- a/include/input/InputDevice.h +++ b/include/input/InputDevice.h @@ -19,6 +19,7 @@ #include #include +#include namespace android { @@ -121,7 +122,7 @@ public: inline void setButtonUnderPad(bool hasButton) { mHasButtonUnderPad = hasButton; } inline bool hasButtonUnderPad() const { return mHasButtonUnderPad; } - inline const Vector& getMotionRanges() const { + inline const std::vector& getMotionRanges() const { return mMotionRanges; } @@ -139,7 +140,7 @@ private: bool mHasVibrator; bool mHasButtonUnderPad; - Vector mMotionRanges; + std::vector mMotionRanges; }; /* Types of input device configuration files. */ diff --git a/include/input/KeyLayoutMap.h b/include/input/KeyLayoutMap.h index 73815fe8b4..26f35012e2 100644 --- a/include/input/KeyLayoutMap.h +++ b/include/input/KeyLayoutMap.h @@ -66,7 +66,7 @@ public: status_t mapKey(int32_t scanCode, int32_t usageCode, int32_t* outKeyCode, uint32_t* outFlags) const; - status_t findScanCodesForKey(int32_t keyCode, Vector* outScanCodes) const; + status_t findScanCodesForKey(int32_t keyCode, std::vector* outScanCodes) const; status_t findScanCodeForLed(int32_t ledCode, int32_t* outScanCode) const; status_t findUsageCodeForLed(int32_t ledCode, int32_t* outUsageCode) const; diff --git a/include/input/VirtualKeyMap.h b/include/input/VirtualKeyMap.h index 4f7cfb6b75..6e8e2c9cf4 100644 --- a/include/input/VirtualKeyMap.h +++ b/include/input/VirtualKeyMap.h @@ -24,6 +24,7 @@ #include #include #include +#include namespace android { @@ -51,7 +52,7 @@ public: static std::unique_ptr load(const std::string& filename); - inline const Vector& getVirtualKeys() const { + inline const std::vector& getVirtualKeys() const { return mVirtualKeys; } @@ -70,7 +71,7 @@ private: bool parseNextIntField(int32_t* outValue); }; - Vector mVirtualKeys; + std::vector mVirtualKeys; VirtualKeyMap(); }; diff --git a/libs/input/IInputFlinger.cpp b/libs/input/IInputFlinger.cpp index 4ce5a10e5c..d6a73bfd27 100644 --- a/libs/input/IInputFlinger.cpp +++ b/libs/input/IInputFlinger.cpp @@ -30,7 +30,7 @@ public: explicit BpInputFlinger(const sp& impl) : BpInterface(impl) { } - virtual void setInputWindows(const Vector& inputInfo, + virtual void setInputWindows(const std::vector& inputInfo, const sp& setInputWindowsListener) { Parcel data, reply; data.writeInterfaceToken(IInputFlinger::getInterfaceDescriptor()); @@ -81,10 +81,9 @@ status_t BnInputFlinger::onTransact( if (count > data.dataSize()) { return BAD_VALUE; } - Vector handles; - handles.setCapacity(count); + std::vector handles; for (size_t i = 0; i < count; i++) { - handles.add(InputWindowInfo(data)); + handles.push_back(InputWindowInfo::read(data)); } const sp setInputWindowsListener = ISetInputWindowsListener::asInterface(data.readStrongBinder()); diff --git a/libs/input/InputDevice.cpp b/libs/input/InputDevice.cpp index dab6eac2f4..4db9e06d8d 100644 --- a/libs/input/InputDevice.cpp +++ b/libs/input/InputDevice.cpp @@ -186,7 +186,7 @@ const InputDeviceInfo::MotionRange* InputDeviceInfo::getMotionRange( int32_t axis, uint32_t source) const { size_t numRanges = mMotionRanges.size(); for (size_t i = 0; i < numRanges; i++) { - const MotionRange& range = mMotionRanges.itemAt(i); + const MotionRange& range = mMotionRanges[i]; if (range.axis == axis && range.source == source) { return ⦥ } @@ -201,11 +201,11 @@ void InputDeviceInfo::addSource(uint32_t source) { void InputDeviceInfo::addMotionRange(int32_t axis, uint32_t source, float min, float max, float flat, float fuzz, float resolution) { MotionRange range = { axis, source, min, max, flat, fuzz, resolution }; - mMotionRanges.add(range); + mMotionRanges.push_back(range); } void InputDeviceInfo::addMotionRange(const MotionRange& range) { - mMotionRanges.add(range); + mMotionRanges.push_back(range); } } // namespace android diff --git a/libs/input/KeyLayoutMap.cpp b/libs/input/KeyLayoutMap.cpp index 88cb0dbdb4..efca68d171 100644 --- a/libs/input/KeyLayoutMap.cpp +++ b/libs/input/KeyLayoutMap.cpp @@ -120,11 +120,12 @@ const KeyLayoutMap::Key* KeyLayoutMap::getKey(int32_t scanCode, int32_t usageCod return nullptr; } -status_t KeyLayoutMap::findScanCodesForKey(int32_t keyCode, Vector* outScanCodes) const { +status_t KeyLayoutMap::findScanCodesForKey( + int32_t keyCode, std::vector* outScanCodes) const { const size_t N = mKeysByScanCode.size(); for (size_t i=0; iadd(mKeysByScanCode.keyAt(i)); + outScanCodes->push_back(mKeysByScanCode.keyAt(i)); } } return NO_ERROR; diff --git a/libs/input/VirtualKeyMap.cpp b/libs/input/VirtualKeyMap.cpp index 624f152996..865366bcb2 100644 --- a/libs/input/VirtualKeyMap.cpp +++ b/libs/input/VirtualKeyMap.cpp @@ -112,7 +112,7 @@ status_t VirtualKeyMap::Parser::parse() { "width=%d, height=%d", defn.scanCode, defn.centerX, defn.centerY, defn.width, defn.height); #endif - mMap->mVirtualKeys.push(defn); + mMap->mVirtualKeys.push_back(defn); } while (consumeFieldDelimiterAndSkipWhitespace()); if (!mTokenizer->isEol()) { diff --git a/services/inputflinger/EventHub.cpp b/services/inputflinger/EventHub.cpp index 4da1473904..0544ec16c5 100644 --- a/services/inputflinger/EventHub.cpp +++ b/services/inputflinger/EventHub.cpp @@ -415,14 +415,14 @@ int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const { Device* device = getDeviceLocked(deviceId); if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) { - Vector scanCodes; + std::vector scanCodes; device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes); if (scanCodes.size() != 0) { uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)]; memset(keyState, 0, sizeof(keyState)); if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) { for (size_t i = 0; i < scanCodes.size(); i++) { - int32_t sc = scanCodes.itemAt(i); + int32_t sc = scanCodes[i]; if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) { return AKEY_STATE_DOWN; } @@ -478,7 +478,7 @@ bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, Device* device = getDeviceLocked(deviceId); if (device && device->keyMap.haveKeyLayout()) { - Vector scanCodes; + std::vector scanCodes; for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) { scanCodes.clear(); @@ -609,13 +609,15 @@ void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) { } void EventHub::getVirtualKeyDefinitions(int32_t deviceId, - Vector& outVirtualKeys) const { + std::vector& outVirtualKeys) const { outVirtualKeys.clear(); AutoMutex _l(mLock); Device* device = getDeviceLocked(deviceId); if (device && device->virtualKeyMap) { - outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys()); + const std::vector virtualKeys = + device->virtualKeyMap->getVirtualKeys(); + outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end()); } } @@ -1680,11 +1682,11 @@ bool EventHub::hasKeycodeLocked(Device* device, int keycode) const { return false; } - Vector scanCodes; + std::vector scanCodes; device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes); const size_t N = scanCodes.size(); for (size_t i=0; i= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) { return true; } diff --git a/services/inputflinger/EventHub.h b/services/inputflinger/EventHub.h index 44f7b3715a..63a20ef3e2 100644 --- a/services/inputflinger/EventHub.h +++ b/services/inputflinger/EventHub.h @@ -228,7 +228,7 @@ public: virtual void setLedState(int32_t deviceId, int32_t led, bool on) = 0; virtual void getVirtualKeyDefinitions(int32_t deviceId, - Vector& outVirtualKeys) const = 0; + std::vector& outVirtualKeys) const = 0; virtual sp getKeyCharacterMap(int32_t deviceId) const = 0; virtual bool setKeyboardLayoutOverlay(int32_t deviceId, const sp& map) = 0; @@ -304,7 +304,7 @@ public: virtual void setLedState(int32_t deviceId, int32_t led, bool on); virtual void getVirtualKeyDefinitions(int32_t deviceId, - Vector& outVirtualKeys) const; + std::vector& outVirtualKeys) const; virtual sp getKeyCharacterMap(int32_t deviceId) const; virtual bool setKeyboardLayoutOverlay(int32_t deviceId, const sp& map); diff --git a/services/inputflinger/InputDispatcher.cpp b/services/inputflinger/InputDispatcher.cpp index bcb1ec5fb8..131762060d 100644 --- a/services/inputflinger/InputDispatcher.cpp +++ b/services/inputflinger/InputDispatcher.cpp @@ -524,10 +524,8 @@ void InputDispatcher::addRecentEventLocked(EventEntry* entry) { sp InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y, bool addOutsideTargets, bool addPortalWindows) { // Traverse windows from front to back to find touched window. - const Vector> windowHandles = getWindowHandlesLocked(displayId); - size_t numWindows = windowHandles.size(); - for (size_t i = 0; i < numWindows; i++) { - sp windowHandle = windowHandles.itemAt(i); + const std::vector> windowHandles = getWindowHandlesLocked(displayId); + for (const sp& windowHandle : windowHandles) { const InputWindowInfo* windowInfo = windowHandle->getInfo(); if (windowInfo->displayId == displayId) { int32_t flags = windowInfo->layoutParamsFlags; @@ -859,7 +857,7 @@ bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry, } // Identify targets. - Vector inputTargets; + std::vector inputTargets; int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime); if (injectionResult == INPUT_EVENT_INJECTION_PENDING) { @@ -910,7 +908,7 @@ bool InputDispatcher::dispatchMotionLocked( bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER; // Identify targets. - Vector inputTargets; + std::vector inputTargets; bool conflictingPointerActions = false; int32_t injectionResult; @@ -946,11 +944,11 @@ bool InputDispatcher::dispatchMotionLocked( ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId); if (stateIndex >= 0) { const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex); - if (!state.portalWindows.isEmpty()) { + if (!state.portalWindows.empty()) { // The event has gone through these portal windows, so we add monitoring targets of // the corresponding displays as well. for (size_t i = 0; i < state.portalWindows.size(); i++) { - const InputWindowInfo* windowInfo = state.portalWindows.itemAt(i)->getInfo(); + const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo(); addMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId, -windowInfo->frameLeft, -windowInfo->frameTop); } @@ -1004,7 +1002,7 @@ void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionE } void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, - EventEntry* eventEntry, const Vector& inputTargets) { + EventEntry* eventEntry, const std::vector& inputTargets) { #if DEBUG_DISPATCH_CYCLE ALOGD("dispatchEventToCurrentInputTargets"); #endif @@ -1013,9 +1011,7 @@ void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, pokeUserActivityLocked(eventEntry); - for (size_t i = 0; i < inputTargets.size(); i++) { - const InputTarget& inputTarget = inputTargets.itemAt(i); - + for (const InputTarget& inputTarget : inputTargets) { ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel); if (connectionIndex >= 0) { sp connection = mConnectionsByFd.valueAt(connectionIndex); @@ -1181,7 +1177,7 @@ int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) { } int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime, - const EventEntry* entry, Vector& inputTargets, nsecs_t* nextWakeupTime) { + const EventEntry* entry, std::vector& inputTargets, nsecs_t* nextWakeupTime) { int32_t injectionResult; std::string reason; @@ -1244,7 +1240,7 @@ Unresponsive: } int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, - const MotionEntry* entry, Vector& inputTargets, nsecs_t* nextWakeupTime, + const MotionEntry* entry, std::vector& inputTargets, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) { enum InjectionPermission { INJECTION_PERMISSION_UNKNOWN, @@ -1460,8 +1456,7 @@ int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, // is at least one touched foreground window. { bool haveForegroundWindow = false; - for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { - const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; + for (const TouchedWindow& touchedWindow : mTempTouchState.windows) { if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) { haveForegroundWindow = true; if (! checkInjectionPermission(touchedWindow.windowHandle, @@ -1491,8 +1486,7 @@ int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, sp foregroundWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid; - for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { - const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; + for (const TouchedWindow& touchedWindow : mTempTouchState.windows) { if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) { sp inputWindowHandle = touchedWindow.windowHandle; if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) { @@ -1504,8 +1498,7 @@ int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, } // Ensure all touched foreground windows are ready for new input. - for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { - const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; + for (const TouchedWindow& touchedWindow : mTempTouchState.windows) { if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) { // Check whether the window is ready for more input. std::string reason = checkWindowReadyForMoreInputLocked(currentTime, @@ -1528,10 +1521,9 @@ int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, sp foregroundWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); if (foregroundWindowHandle->getInfo()->hasWallpaper) { - const Vector> windowHandles = getWindowHandlesLocked(displayId); - size_t numWindows = windowHandles.size(); - for (size_t i = 0; i < numWindows; i++) { - sp windowHandle = windowHandles.itemAt(i); + const std::vector> windowHandles = + getWindowHandlesLocked(displayId); + for (const sp& windowHandle : windowHandles) { const InputWindowInfo* info = windowHandle->getInfo(); if (info->displayId == displayId && windowHandle->getInfo()->layoutParamsType @@ -1549,8 +1541,7 @@ int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, // Success! Output targets. injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED; - for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { - const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i); + for (const TouchedWindow& touchedWindow : mTempTouchState.windows) { addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags, touchedWindow.pointerIds, inputTargets); } @@ -1613,11 +1604,11 @@ Failed: uint32_t pointerId = entry->pointerProperties[pointerIndex].id; for (size_t i = 0; i < mTempTouchState.windows.size(); ) { - TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i); + TouchedWindow& touchedWindow = mTempTouchState.windows[i]; if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) { touchedWindow.pointerIds.clearBit(pointerId); if (touchedWindow.pointerIds.isEmpty()) { - mTempTouchState.windows.removeAt(i); + mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i); continue; } } @@ -1664,17 +1655,15 @@ Unresponsive: } void InputDispatcher::addWindowTargetLocked(const sp& windowHandle, - int32_t targetFlags, BitSet32 pointerIds, Vector& inputTargets) { + int32_t targetFlags, BitSet32 pointerIds, std::vector& inputTargets) { sp inputChannel = getInputChannelLocked(windowHandle->getToken()); if (inputChannel == nullptr) { ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str()); return; } - inputTargets.push(); - const InputWindowInfo* windowInfo = windowHandle->getInfo(); - InputTarget& target = inputTargets.editTop(); + InputTarget target; target.inputChannel = inputChannel; target.flags = targetFlags; target.xOffset = - windowInfo->frameLeft; @@ -1683,26 +1672,26 @@ void InputDispatcher::addWindowTargetLocked(const sp& windowH target.windowXScale = windowInfo->windowXScale; target.windowYScale = windowInfo->windowYScale; target.pointerIds = pointerIds; + inputTargets.push_back(target); } -void InputDispatcher::addMonitoringTargetsLocked(Vector& inputTargets, +void InputDispatcher::addMonitoringTargetsLocked(std::vector& inputTargets, int32_t displayId, float xOffset, float yOffset) { - std::unordered_map>>::const_iterator it = + std::unordered_map>>::const_iterator it = mMonitoringChannelsByDisplay.find(displayId); if (it != mMonitoringChannelsByDisplay.end()) { - const Vector>& monitoringChannels = it->second; + const std::vector>& monitoringChannels = it->second; const size_t numChannels = monitoringChannels.size(); for (size_t i = 0; i < numChannels; i++) { - inputTargets.push(); - - InputTarget& target = inputTargets.editTop(); + InputTarget target; target.inputChannel = monitoringChannels[i]; target.flags = InputTarget::FLAG_DISPATCH_AS_IS; target.xOffset = xOffset; target.yOffset = yOffset; target.pointerIds.clear(); target.globalScaleFactor = 1.0f; + inputTargets.push_back(target); } } else { // If there is no monitor channel registered or all monitor channel unregistered, @@ -1735,10 +1724,8 @@ bool InputDispatcher::checkInjectionPermission(const sp& wind bool InputDispatcher::isWindowObscuredAtPointLocked( const sp& windowHandle, int32_t x, int32_t y) const { int32_t displayId = windowHandle->getInfo()->displayId; - const Vector> windowHandles = getWindowHandlesLocked(displayId); - size_t numWindows = windowHandles.size(); - for (size_t i = 0; i < numWindows; i++) { - sp otherHandle = windowHandles.itemAt(i); + const std::vector> windowHandles = getWindowHandlesLocked(displayId); + for (const sp& otherHandle : windowHandles) { if (otherHandle == windowHandle) { break; } @@ -1756,11 +1743,9 @@ bool InputDispatcher::isWindowObscuredAtPointLocked( bool InputDispatcher::isWindowObscuredLocked(const sp& windowHandle) const { int32_t displayId = windowHandle->getInfo()->displayId; - const Vector> windowHandles = getWindowHandlesLocked(displayId); + const std::vector> windowHandles = getWindowHandlesLocked(displayId); const InputWindowInfo* windowInfo = windowHandle->getInfo(); - size_t numWindows = windowHandles.size(); - for (size_t i = 0; i < numWindows; i++) { - sp otherHandle = windowHandles.itemAt(i); + for (const sp& otherHandle : windowHandles) { if (otherHandle == windowHandle) { break; } @@ -2333,7 +2318,7 @@ void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked ( void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked ( const CancelationOptions& options) { for (auto& it : mMonitoringChannelsByDisplay) { - const Vector>& monitoringChannels = it.second; + const std::vector>& monitoringChannels = it.second; const size_t numChannels = monitoringChannels.size(); for (size_t i = 0; i < numChannels; i++) { synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options); @@ -2358,11 +2343,11 @@ void InputDispatcher::synthesizeCancelationEventsForConnectionLocked( nsecs_t currentTime = now(); - Vector cancelationEvents; + std::vector cancelationEvents; connection->inputState.synthesizeCancelationEvents(currentTime, cancelationEvents, options); - if (!cancelationEvents.isEmpty()) { + if (!cancelationEvents.empty()) { #if DEBUG_OUTBOUND_EVENT_DETAILS ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync " "with reality: %s, mode=%d.", @@ -2370,7 +2355,7 @@ void InputDispatcher::synthesizeCancelationEventsForConnectionLocked( options.reason, options.mode); #endif for (size_t i = 0; i < cancelationEvents.size(); i++) { - EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i); + EventEntry* cancelationEventEntry = cancelationEvents[i]; switch (cancelationEventEntry->type) { case EventEntry::TYPE_KEY: logOutboundKeyDetails("cancel - ", @@ -3011,24 +2996,23 @@ void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) { } } -Vector> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const { - std::unordered_map>>::const_iterator it = +std::vector> InputDispatcher::getWindowHandlesLocked( + int32_t displayId) const { + std::unordered_map>>::const_iterator it = mWindowHandlesByDisplay.find(displayId); if(it != mWindowHandlesByDisplay.end()) { return it->second; } // Return an empty one if nothing found. - return Vector>(); + return std::vector>(); } sp InputDispatcher::getWindowHandleLocked( const sp& windowHandleToken) const { for (auto& it : mWindowHandlesByDisplay) { - const Vector> windowHandles = it.second; - size_t numWindows = windowHandles.size(); - for (size_t i = 0; i < numWindows; i++) { - const sp& windowHandle = windowHandles.itemAt(i); + const std::vector> windowHandles = it.second; + for (const sp& windowHandle : windowHandles) { if (windowHandle->getToken() == windowHandleToken) { return windowHandle; } @@ -3039,11 +3023,9 @@ sp InputDispatcher::getWindowHandleLocked( bool InputDispatcher::hasWindowHandleLocked(const sp& windowHandle) const { for (auto& it : mWindowHandlesByDisplay) { - const Vector> windowHandles = it.second; - size_t numWindows = windowHandles.size(); - for (size_t i = 0; i < numWindows; i++) { - if (windowHandles.itemAt(i)->getToken() - == windowHandle->getToken()) { + const std::vector> windowHandles = it.second; + for (const sp& handle : windowHandles) { + if (handle->getToken() == windowHandle->getToken()) { if (windowHandle->getInfo()->displayId != it.first) { ALOGE("Found window %s in display %" PRId32 ", but it should belong to display %" PRId32, @@ -3072,7 +3054,7 @@ sp InputDispatcher::getInputChannelLocked(const sp& token * For focused handle, check if need to change and send a cancel event to previous one. * For removed handle, check if need to send a cancel event if already in touch. */ -void InputDispatcher::setInputWindows(const Vector>& inputWindowHandles, +void InputDispatcher::setInputWindows(const std::vector>& inputWindowHandles, int32_t displayId, const sp& setInputWindowsListener) { #if DEBUG_FOCUS ALOGD("setInputWindows displayId=%" PRId32, displayId); @@ -3081,28 +3063,27 @@ void InputDispatcher::setInputWindows(const Vector>& input std::scoped_lock _l(mLock); // Copy old handles for release if they are no longer present. - const Vector> oldWindowHandles = getWindowHandlesLocked(displayId); + const std::vector> oldWindowHandles = + getWindowHandlesLocked(displayId); sp newFocusedWindowHandle = nullptr; bool foundHoveredWindow = false; - if (inputWindowHandles.isEmpty()) { + if (inputWindowHandles.empty()) { // Remove all handles on a display if there are no windows left. mWindowHandlesByDisplay.erase(displayId); } else { // Since we compare the pointer of input window handles across window updates, we need // to make sure the handle object for the same window stays unchanged across updates. - const Vector>& oldHandles = mWindowHandlesByDisplay[displayId]; + const std::vector>& oldHandles = + mWindowHandlesByDisplay[displayId]; std::unordered_map, sp, IBinderHash> oldHandlesByTokens; - for (size_t i = 0; i < oldHandles.size(); i++) { - const sp& handle = oldHandles.itemAt(i); + for (const sp& handle : oldHandles) { oldHandlesByTokens[handle->getToken()] = handle; } - const size_t numWindows = inputWindowHandles.size(); - Vector> newHandles; - for (size_t i = 0; i < numWindows; i++) { - const sp& handle = inputWindowHandles.itemAt(i); + std::vector> newHandles; + for (const sp& handle : inputWindowHandles) { if (!handle->updateInfo() || (getInputChannelLocked(handle->getToken()) == nullptr && handle->getInfo()->portalToDisplayId == ADISPLAY_ID_NONE)) { ALOGE("Window handle %s has no registered input channel", @@ -3127,8 +3108,7 @@ void InputDispatcher::setInputWindows(const Vector>& input } } - for (size_t i = 0; i < newHandles.size(); i++) { - const sp& windowHandle = newHandles.itemAt(i); + for (const sp& windowHandle : newHandles) { // Set newFocusedWindowHandle to the top most focused window instead of the last one if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus && windowHandle->getInfo()->visible) { @@ -3184,7 +3164,7 @@ void InputDispatcher::setInputWindows(const Vector>& input if (stateIndex >= 0) { TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex); for (size_t i = 0; i < state.windows.size(); ) { - TouchedWindow& touchedWindow = state.windows.editItemAt(i); + TouchedWindow& touchedWindow = state.windows[i]; if (!hasWindowHandleLocked(touchedWindow.windowHandle)) { #if DEBUG_FOCUS ALOGD("Touched window was removed: %s in display %" PRId32, @@ -3198,7 +3178,7 @@ void InputDispatcher::setInputWindows(const Vector>& input synthesizeCancelationEventsForInputChannelLocked( touchedInputChannel, options); } - state.windows.removeAt(i); + state.windows.erase(state.windows.begin() + i); } else { ++i; } @@ -3209,9 +3189,7 @@ void InputDispatcher::setInputWindows(const Vector>& input // This ensures that unused input channels are released promptly. // Otherwise, they might stick around until the window handle is destroyed // which might not happen until the next GC. - size_t numWindows = oldWindowHandles.size(); - for (size_t i = 0; i < numWindows; i++) { - const sp& oldWindowHandle = oldWindowHandles.itemAt(i); + for (const sp& oldWindowHandle : oldWindowHandles) { if (!hasWindowHandleLocked(oldWindowHandle)) { #if DEBUG_FOCUS ALOGD("Window went away: %s", oldWindowHandle->getName().c_str()); @@ -3415,7 +3393,7 @@ bool InputDispatcher::transferTouchFocus(const sp& fromToken, const sp< int32_t oldTargetFlags = touchedWindow.targetFlags; BitSet32 pointerIds = touchedWindow.pointerIds; - state.windows.removeAt(i); + state.windows.erase(state.windows.begin() + i); int32_t newTargetFlags = oldTargetFlags & (InputTarget::FLAG_FOREGROUND @@ -3531,7 +3509,7 @@ void InputDispatcher::dumpDispatchStateLocked(std::string& dump) { dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n", state.displayId, toString(state.down), toString(state.split), state.deviceId, state.source); - if (!state.windows.isEmpty()) { + if (!state.windows.empty()) { dump += INDENT3 "Windows:\n"; for (size_t i = 0; i < state.windows.size(); i++) { const TouchedWindow& touchedWindow = state.windows[i]; @@ -3543,10 +3521,10 @@ void InputDispatcher::dumpDispatchStateLocked(std::string& dump) { } else { dump += INDENT3 "Windows: \n"; } - if (!state.portalWindows.isEmpty()) { + if (!state.portalWindows.empty()) { dump += INDENT3 "Portal windows:\n"; for (size_t i = 0; i < state.portalWindows.size(); i++) { - const sp portalWindowHandle = state.portalWindows.itemAt(i); + const sp portalWindowHandle = state.portalWindows[i]; dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i, portalWindowHandle->getName().c_str()); } @@ -3558,12 +3536,12 @@ void InputDispatcher::dumpDispatchStateLocked(std::string& dump) { if (!mWindowHandlesByDisplay.empty()) { for (auto& it : mWindowHandlesByDisplay) { - const Vector> windowHandles = it.second; + const std::vector> windowHandles = it.second; dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first); - if (!windowHandles.isEmpty()) { + if (!windowHandles.empty()) { dump += INDENT2 "Windows:\n"; for (size_t i = 0; i < windowHandles.size(); i++) { - const sp& windowHandle = windowHandles.itemAt(i); + const sp& windowHandle = windowHandles[i]; const InputWindowInfo* windowInfo = windowHandle->getInfo(); dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, " @@ -3600,7 +3578,7 @@ void InputDispatcher::dumpDispatchStateLocked(std::string& dump) { if (!mMonitoringChannelsByDisplay.empty()) { for (auto& it : mMonitoringChannelsByDisplay) { - const Vector>& monitoringChannels = it.second; + const std::vector>& monitoringChannels = it.second; dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first); const size_t numChannels = monitoringChannels.size(); for (size_t i = 0; i < numChannels; i++) { @@ -3754,9 +3732,9 @@ status_t InputDispatcher::registerInputChannel(const sp& inputChan // Store monitor channel by displayId. if (monitor) { - Vector>& monitoringChannels = + std::vector>& monitoringChannels = mMonitoringChannelsByDisplay[displayId]; - monitoringChannels.push(inputChannel); + monitoringChannels.push_back(inputChannel); } mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this); @@ -3817,11 +3795,11 @@ status_t InputDispatcher::unregisterInputChannelLocked(const sp& i void InputDispatcher::removeMonitorChannelLocked(const sp& inputChannel) { for (auto it = mMonitoringChannelsByDisplay.begin(); it != mMonitoringChannelsByDisplay.end(); ) { - Vector>& monitoringChannels = it->second; + std::vector>& monitoringChannels = it->second; const size_t numChannels = monitoringChannels.size(); for (size_t i = 0; i < numChannels; i++) { if (monitoringChannels[i] == inputChannel) { - monitoringChannels.removeAt(i); + monitoringChannels.erase(monitoringChannels.begin() + i); break; } } @@ -4495,13 +4473,12 @@ InputDispatcher::InputState::~InputState() { } bool InputDispatcher::InputState::isNeutral() const { - return mKeyMementos.isEmpty() && mMotionMementos.isEmpty(); + return mKeyMementos.empty() && mMotionMementos.empty(); } bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const { - for (size_t i = 0; i < mMotionMementos.size(); i++) { - const MotionMemento& memento = mMotionMementos.itemAt(i); + for (const MotionMemento& memento : mMotionMementos) { if (memento.deviceId == deviceId && memento.source == source && memento.displayId == displayId @@ -4527,7 +4504,7 @@ bool InputDispatcher::InputState::trackKey(const KeyEntry* entry, } ssize_t index = findKeyMemento(entry); if (index >= 0) { - mKeyMementos.removeAt(index); + mKeyMementos.erase(mKeyMementos.begin() + index); return true; } /* FIXME: We can't just drop the key up event because that prevents creating @@ -4552,7 +4529,7 @@ bool InputDispatcher::InputState::trackKey(const KeyEntry* entry, case AKEY_EVENT_ACTION_DOWN: { ssize_t index = findKeyMemento(entry); if (index >= 0) { - mKeyMementos.removeAt(index); + mKeyMementos.erase(mKeyMementos.begin() + index); } addKeyMemento(entry, flags); return true; @@ -4571,7 +4548,7 @@ bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry, case AMOTION_EVENT_ACTION_CANCEL: { ssize_t index = findMotionMemento(entry, false /*hovering*/); if (index >= 0) { - mMotionMementos.removeAt(index); + mMotionMementos.erase(mMotionMementos.begin() + index); return true; } #if DEBUG_OUTBOUND_EVENT_DETAILS @@ -4585,7 +4562,7 @@ bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry, case AMOTION_EVENT_ACTION_DOWN: { ssize_t index = findMotionMemento(entry, false /*hovering*/); if (index >= 0) { - mMotionMementos.removeAt(index); + mMotionMementos.erase(mMotionMementos.begin() + index); } addMotionMemento(entry, flags, false /*hovering*/); return true; @@ -4610,9 +4587,9 @@ bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry, // anything generating fallback events (e.g. DPad keys for joystick movements). if (index >= 0) { if (entry->pointerCoords[0].isEmpty()) { - mMotionMementos.removeAt(index); + mMotionMementos.erase(mMotionMementos.begin() + index); } else { - MotionMemento& memento = mMotionMementos.editItemAt(index); + MotionMemento& memento = mMotionMementos[index]; memento.setPointers(entry); } } else if (!entry->pointerCoords[0].isEmpty()) { @@ -4623,7 +4600,7 @@ bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry, return true; } if (index >= 0) { - MotionMemento& memento = mMotionMementos.editItemAt(index); + MotionMemento& memento = mMotionMementos[index]; memento.setPointers(entry); return true; } @@ -4638,7 +4615,7 @@ bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry, case AMOTION_EVENT_ACTION_HOVER_EXIT: { ssize_t index = findMotionMemento(entry, true /*hovering*/); if (index >= 0) { - mMotionMementos.removeAt(index); + mMotionMementos.erase(mMotionMementos.begin() + index); return true; } #if DEBUG_OUTBOUND_EVENT_DETAILS @@ -4653,7 +4630,7 @@ bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry, case AMOTION_EVENT_ACTION_HOVER_MOVE: { ssize_t index = findMotionMemento(entry, true /*hovering*/); if (index >= 0) { - mMotionMementos.removeAt(index); + mMotionMementos.erase(mMotionMementos.begin() + index); } addMotionMemento(entry, flags, true /*hovering*/); return true; @@ -4666,7 +4643,7 @@ bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry, ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const { for (size_t i = 0; i < mKeyMementos.size(); i++) { - const KeyMemento& memento = mKeyMementos.itemAt(i); + const KeyMemento& memento = mKeyMementos[i]; if (memento.deviceId == entry->deviceId && memento.source == entry->source && memento.displayId == entry->displayId @@ -4681,7 +4658,7 @@ ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry, bool hovering) const { for (size_t i = 0; i < mMotionMementos.size(); i++) { - const MotionMemento& memento = mMotionMementos.itemAt(i); + const MotionMemento& memento = mMotionMementos[i]; if (memento.deviceId == entry->deviceId && memento.source == entry->source && memento.displayId == entry->displayId @@ -4693,8 +4670,7 @@ ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry, } void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) { - mKeyMementos.push(); - KeyMemento& memento = mKeyMementos.editTop(); + KeyMemento memento; memento.deviceId = entry->deviceId; memento.source = entry->source; memento.displayId = entry->displayId; @@ -4704,12 +4680,12 @@ void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t f memento.flags = flags; memento.downTime = entry->downTime; memento.policyFlags = entry->policyFlags; + mKeyMementos.push_back(memento); } void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering) { - mMotionMementos.push(); - MotionMemento& memento = mMotionMementos.editTop(); + MotionMemento memento; memento.deviceId = entry->deviceId; memento.source = entry->source; memento.displayId = entry->displayId; @@ -4720,6 +4696,7 @@ void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry, memento.setPointers(entry); memento.hovering = hovering; memento.policyFlags = entry->policyFlags; + mMotionMementos.push_back(memento); } void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) { @@ -4731,23 +4708,21 @@ void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* } void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime, - Vector& outEvents, const CancelationOptions& options) { - for (size_t i = 0; i < mKeyMementos.size(); i++) { - const KeyMemento& memento = mKeyMementos.itemAt(i); + std::vector& outEvents, const CancelationOptions& options) { + for (KeyMemento& memento : mKeyMementos) { if (shouldCancelKey(memento, options)) { - outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, + outEvents.push_back(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, memento.deviceId, memento.source, memento.displayId, memento.policyFlags, AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED, memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime)); } } - for (size_t i = 0; i < mMotionMementos.size(); i++) { - const MotionMemento& memento = mMotionMementos.itemAt(i); + for (const MotionMemento& memento : mMotionMementos) { if (shouldCancelMotion(memento, options)) { const int32_t action = memento.hovering ? AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL; - outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, + outEvents.push_back(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, memento.deviceId, memento.source, memento.displayId, memento.policyFlags, action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, @@ -4766,19 +4741,19 @@ void InputDispatcher::InputState::clear() { void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const { for (size_t i = 0; i < mMotionMementos.size(); i++) { - const MotionMemento& memento = mMotionMementos.itemAt(i); + const MotionMemento& memento = mMotionMementos[i]; if (memento.source & AINPUT_SOURCE_CLASS_POINTER) { for (size_t j = 0; j < other.mMotionMementos.size(); ) { - const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j); + const MotionMemento& otherMemento = other.mMotionMementos[j]; if (memento.deviceId == otherMemento.deviceId && memento.source == otherMemento.source && memento.displayId == otherMemento.displayId) { - other.mMotionMementos.removeAt(j); + other.mMotionMementos.erase(other.mMotionMementos.begin() + j); } else { j += 1; } } - other.mMotionMementos.push(memento); + other.mMotionMementos.push_back(memento); } } } @@ -4940,7 +4915,7 @@ void InputDispatcher::TouchState::addOrUpdateWindow(const sp& } for (size_t i = 0; i < windows.size(); i++) { - TouchedWindow& touchedWindow = windows.editItemAt(i); + TouchedWindow& touchedWindow = windows[i]; if (touchedWindow.windowHandle == windowHandle) { touchedWindow.targetFlags |= targetFlags; if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) { @@ -4951,19 +4926,17 @@ void InputDispatcher::TouchState::addOrUpdateWindow(const sp& } } - windows.push(); - - TouchedWindow& touchedWindow = windows.editTop(); + TouchedWindow touchedWindow; touchedWindow.windowHandle = windowHandle; touchedWindow.targetFlags = targetFlags; touchedWindow.pointerIds = pointerIds; + windows.push_back(touchedWindow); } void InputDispatcher::TouchState::addPortalWindow(const sp& windowHandle) { size_t numWindows = portalWindows.size(); for (size_t i = 0; i < numWindows; i++) { - sp portalWindowHandle = portalWindows.itemAt(i); - if (portalWindowHandle == windowHandle) { + if (portalWindows[i] == windowHandle) { return; } } @@ -4972,8 +4945,8 @@ void InputDispatcher::TouchState::addPortalWindow(const sp& w void InputDispatcher::TouchState::removeWindow(const sp& windowHandle) { for (size_t i = 0; i < windows.size(); i++) { - if (windows.itemAt(i).windowHandle == windowHandle) { - windows.removeAt(i); + if (windows[i].windowHandle == windowHandle) { + windows.erase(windows.begin() + i); return; } } @@ -4981,8 +4954,8 @@ void InputDispatcher::TouchState::removeWindow(const sp& wind void InputDispatcher::TouchState::removeWindowByToken(const sp& token) { for (size_t i = 0; i < windows.size(); i++) { - if (windows.itemAt(i).windowHandle->getToken() == token) { - windows.removeAt(i); + if (windows[i].windowHandle->getToken() == token) { + windows.erase(windows.begin() + i); return; } } @@ -4990,21 +4963,21 @@ void InputDispatcher::TouchState::removeWindowByToken(const sp& token) void InputDispatcher::TouchState::filterNonAsIsTouchWindows() { for (size_t i = 0 ; i < windows.size(); ) { - TouchedWindow& window = windows.editItemAt(i); + TouchedWindow& window = windows[i]; if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) { window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK; window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS; i += 1; } else { - windows.removeAt(i); + windows.erase(windows.begin() + i); } } } sp InputDispatcher::TouchState::getFirstForegroundWindowHandle() const { for (size_t i = 0; i < windows.size(); i++) { - const TouchedWindow& window = windows.itemAt(i); + const TouchedWindow& window = windows[i]; if (window.targetFlags & InputTarget::FLAG_FOREGROUND) { return window.windowHandle; } @@ -5015,8 +4988,7 @@ sp InputDispatcher::TouchState::getFirstForegroundWindowHandl bool InputDispatcher::TouchState::isSlippery() const { // Must have exactly one foreground window. bool haveSlipperyForegroundWindow = false; - for (size_t i = 0; i < windows.size(); i++) { - const TouchedWindow& window = windows.itemAt(i); + for (const TouchedWindow& window : windows) { if (window.targetFlags & InputTarget::FLAG_FOREGROUND) { if (haveSlipperyForegroundWindow || !(window.windowHandle->getInfo()->layoutParamsFlags diff --git a/services/inputflinger/InputDispatcher.h b/services/inputflinger/InputDispatcher.h index 24ae32fcf5..4d2c2167ac 100644 --- a/services/inputflinger/InputDispatcher.h +++ b/services/inputflinger/InputDispatcher.h @@ -23,8 +23,6 @@ #include #include #include -#include -#include #include #include #include @@ -315,7 +313,7 @@ public: * * This method may be called on any thread (usually by the input manager). */ - virtual void setInputWindows(const Vector >& inputWindowHandles, + virtual void setInputWindows(const std::vector >& inputWindowHandles, int32_t displayId, const sp& setInputWindowsListener = nullptr) = 0; @@ -407,7 +405,7 @@ public: int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis, uint32_t policyFlags); - virtual void setInputWindows(const Vector >& inputWindowHandles, + virtual void setInputWindows(const std::vector >& inputWindowHandles, int32_t displayId, const sp& setInputWindowsListener = nullptr); virtual void setFocusedApplication(int32_t displayId, @@ -762,7 +760,7 @@ private: // Synthesizes cancelation events for the current state and resets the tracked state. void synthesizeCancelationEvents(nsecs_t currentTime, - Vector& outEvents, const CancelationOptions& options); + std::vector& outEvents, const CancelationOptions& options); // Clears the current state. void clear(); @@ -815,8 +813,8 @@ private: void setPointers(const MotionEntry* entry); }; - Vector mKeyMementos; - Vector mMotionMementos; + std::vector mKeyMementos; + std::vector mMotionMementos; KeyedVector mFallbackKeys; ssize_t findKeyMemento(const KeyEntry* entry) const; @@ -941,7 +939,7 @@ private: ssize_t getConnectionIndexLocked(const sp& inputChannel) REQUIRES(mLock); // Input channels that will receive a copy of all input events sent to the provided display. - std::unordered_map>> mMonitoringChannelsByDisplay + std::unordered_map>> mMonitoringChannelsByDisplay GUARDED_BY(mLock); // Event injection and synchronization. @@ -998,10 +996,11 @@ private: bool mDispatchFrozen GUARDED_BY(mLock); bool mInputFilterEnabled GUARDED_BY(mLock); - std::unordered_map>> mWindowHandlesByDisplay + std::unordered_map>> mWindowHandlesByDisplay GUARDED_BY(mLock); // Get window handles by display, return an empty vector if not found. - Vector> getWindowHandlesLocked(int32_t displayId) const REQUIRES(mLock); + std::vector> getWindowHandlesLocked(int32_t displayId) const + REQUIRES(mLock); sp getWindowHandleLocked(const sp& windowHandleToken) const REQUIRES(mLock); sp getInputChannelLocked(const sp& windowToken) const REQUIRES(mLock); @@ -1023,12 +1022,12 @@ private: int32_t deviceId; // id of the device that is currently down, others are rejected uint32_t source; // source of the device that is current down, others are rejected int32_t displayId; // id to the display that currently has a touch, others are rejected - Vector windows; + std::vector windows; // This collects the portal windows that the touch has gone through. Each portal window // targets a display (embedded display for most cases). With this info, we can add the // monitoring channels of the displays touched. - Vector> portalWindows; + std::vector> portalWindows; TouchState(); ~TouchState(); @@ -1069,7 +1068,7 @@ private: nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) REQUIRES(mLock); void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry, - const Vector& inputTargets) REQUIRES(mLock); + const std::vector& inputTargets) REQUIRES(mLock); void logOutboundKeyDetails(const char* prefix, const KeyEntry* entry); void logOutboundMotionDetails(const char* prefix, const MotionEntry* entry); @@ -1105,15 +1104,15 @@ private: int32_t getTargetDisplayId(const EventEntry* entry); int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry, - Vector& inputTargets, nsecs_t* nextWakeupTime) REQUIRES(mLock); + std::vector& inputTargets, nsecs_t* nextWakeupTime) REQUIRES(mLock); int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry, - Vector& inputTargets, nsecs_t* nextWakeupTime, + std::vector& inputTargets, nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) REQUIRES(mLock); void addWindowTargetLocked(const sp& windowHandle, - int32_t targetFlags, BitSet32 pointerIds, Vector& inputTargets) + int32_t targetFlags, BitSet32 pointerIds, std::vector& inputTargets) REQUIRES(mLock); - void addMonitoringTargetsLocked(Vector& inputTargets, int32_t displayId, + void addMonitoringTargetsLocked(std::vector& inputTargets, int32_t displayId, float xOffset = 0, float yOffset = 0) REQUIRES(mLock); void pokeUserActivityLocked(const EventEntry* eventEntry) REQUIRES(mLock); diff --git a/services/inputflinger/InputListener.cpp b/services/inputflinger/InputListener.cpp index a403f31493..423b69cff3 100644 --- a/services/inputflinger/InputListener.cpp +++ b/services/inputflinger/InputListener.cpp @@ -229,23 +229,23 @@ QueuedInputListener::~QueuedInputListener() { void QueuedInputListener::notifyConfigurationChanged( const NotifyConfigurationChangedArgs* args) { - mArgsQueue.push(new NotifyConfigurationChangedArgs(*args)); + mArgsQueue.push_back(new NotifyConfigurationChangedArgs(*args)); } void QueuedInputListener::notifyKey(const NotifyKeyArgs* args) { - mArgsQueue.push(new NotifyKeyArgs(*args)); + mArgsQueue.push_back(new NotifyKeyArgs(*args)); } void QueuedInputListener::notifyMotion(const NotifyMotionArgs* args) { - mArgsQueue.push(new NotifyMotionArgs(*args)); + mArgsQueue.push_back(new NotifyMotionArgs(*args)); } void QueuedInputListener::notifySwitch(const NotifySwitchArgs* args) { - mArgsQueue.push(new NotifySwitchArgs(*args)); + mArgsQueue.push_back(new NotifySwitchArgs(*args)); } void QueuedInputListener::notifyDeviceReset(const NotifyDeviceResetArgs* args) { - mArgsQueue.push(new NotifyDeviceResetArgs(*args)); + mArgsQueue.push_back(new NotifyDeviceResetArgs(*args)); } void QueuedInputListener::flush() { diff --git a/services/inputflinger/InputManager.cpp b/services/inputflinger/InputManager.cpp index b0157a166f..3996cca646 100644 --- a/services/inputflinger/InputManager.cpp +++ b/services/inputflinger/InputManager.cpp @@ -103,14 +103,14 @@ public: } }; -void InputManager::setInputWindows(const Vector& infos, +void InputManager::setInputWindows(const std::vector& infos, const sp& setInputWindowsListener) { - std::unordered_map>> handlesPerDisplay; + std::unordered_map>> handlesPerDisplay; - Vector> handles; + std::vector> handles; for (const auto& info : infos) { - handlesPerDisplay.emplace(info.displayId, Vector>()); - handlesPerDisplay[info.displayId].add(new BinderWindowHandle(info)); + handlesPerDisplay.emplace(info.displayId, std::vector>()); + handlesPerDisplay[info.displayId].push_back(new BinderWindowHandle(info)); } for (auto const& i : handlesPerDisplay) { mDispatcher->setInputWindows(i.second, i.first, setInputWindowsListener); diff --git a/services/inputflinger/InputManager.h b/services/inputflinger/InputManager.h index ff9a0800da..e568df54df 100644 --- a/services/inputflinger/InputManager.h +++ b/services/inputflinger/InputManager.h @@ -94,7 +94,7 @@ public: virtual sp getClassifier(); virtual sp getDispatcher(); - virtual void setInputWindows(const Vector& handles, + virtual void setInputWindows(const std::vector& handles, const sp& setInputWindowsListener); virtual void transferTouchFocus(const sp& fromToken, const sp& toToken); diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 21ba029854..0cc37a016b 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -287,7 +287,7 @@ void InputReader::loopOnce() { int32_t oldGeneration; int32_t timeoutMillis; bool inputDevicesChanged = false; - Vector inputDevices; + std::vector inputDevices; { // acquire lock AutoMutex _l(mLock); @@ -590,12 +590,13 @@ void InputReader::notifyExternalStylusPresenceChanged() { refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE); } -void InputReader::getExternalStylusDevicesLocked(Vector& outDevices) { +void InputReader::getExternalStylusDevicesLocked(std::vector& outDevices) { for (size_t i = 0; i < mDevices.size(); i++) { InputDevice* device = mDevices.valueAt(i); if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) { - outDevices.push(); - device->getDeviceInfo(&outDevices.editTop()); + InputDeviceInfo info; + device->getDeviceInfo(&info); + outDevices.push_back(info); } } } @@ -643,20 +644,21 @@ int32_t InputReader::bumpGenerationLocked() { return ++mGeneration; } -void InputReader::getInputDevices(Vector& outInputDevices) { +void InputReader::getInputDevices(std::vector& outInputDevices) { AutoMutex _l(mLock); getInputDevicesLocked(outInputDevices); } -void InputReader::getInputDevicesLocked(Vector& outInputDevices) { +void InputReader::getInputDevicesLocked(std::vector& outInputDevices) { outInputDevices.clear(); size_t numDevices = mDevices.size(); for (size_t i = 0; i < numDevices; i++) { InputDevice* device = mDevices.valueAt(i); if (!device->isIgnored()) { - outInputDevices.push(); - device->getDeviceInfo(&outInputDevices.editTop()); + InputDeviceInfo info; + device->getDeviceInfo(&info); + outInputDevices.push_back(info); } } } @@ -951,7 +953,7 @@ int32_t InputReader::ContextImpl::bumpGeneration() { return mReader->bumpGenerationLocked(); } -void InputReader::ContextImpl::getExternalStylusDevices(Vector& outDevices) { +void InputReader::ContextImpl::getExternalStylusDevices(std::vector& outDevices) { // lock is already held by whatever called refreshConfigurationLocked mReader->getExternalStylusDevicesLocked(outDevices); } @@ -1031,11 +1033,11 @@ void InputDevice::dump(std::string& dump) { dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources()); dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType()); - const Vector& ranges = deviceInfo.getMotionRanges(); - if (!ranges.isEmpty()) { + const std::vector& ranges = deviceInfo.getMotionRanges(); + if (!ranges.empty()) { dump += INDENT2 "Motion Ranges:\n"; for (size_t i = 0; i < ranges.size(); i++) { - const InputDeviceInfo::MotionRange& range = ranges.itemAt(i); + const InputDeviceInfo::MotionRange& range = ranges[i]; const char* label = getAxisLabel(range.axis); char name[32]; if (label) { @@ -1059,7 +1061,7 @@ void InputDevice::dump(std::string& dump) { } void InputDevice::addMapper(InputMapper* mapper) { - mMappers.add(mapper); + mMappers.push_back(mapper); } void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { @@ -1110,9 +1112,7 @@ void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config } } - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { mapper->configure(when, config, changes); mSources |= mapper->getSources(); } @@ -1120,9 +1120,7 @@ void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config } void InputDevice::reset(nsecs_t when) { - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { mapper->reset(when); } @@ -1137,7 +1135,6 @@ void InputDevice::process(const RawEvent* rawEvents, size_t count) { // have side-effects that must be interleaved. For example, joystick movement events and // gamepad button presses are handled by different mappers but they should be dispatched // in the order received. - size_t numMappers = mMappers.size(); for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) { #if DEBUG_RAW_EVENTS ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64, @@ -1161,8 +1158,7 @@ void InputDevice::process(const RawEvent* rawEvents, size_t count) { mDropUntilNextSync = true; reset(rawEvent->when); } else { - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { mapper->process(rawEvent); } } @@ -1171,17 +1167,13 @@ void InputDevice::process(const RawEvent* rawEvents, size_t count) { } void InputDevice::timeoutExpired(nsecs_t when) { - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { mapper->timeoutExpired(when); } } void InputDevice::updateExternalStylusState(const StylusState& state) { - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { mapper->updateExternalStylusState(state); } } @@ -1189,9 +1181,7 @@ void InputDevice::updateExternalStylusState(const StylusState& state) { void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) { outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias, mIsExternal, mHasMic); - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { mapper->populateDeviceInfo(outDeviceInfo); } } @@ -1210,9 +1200,7 @@ int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) { int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) { int32_t result = AKEY_STATE_UNKNOWN; - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { if (sourcesMatchMask(mapper->getSources(), sourceMask)) { // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it. @@ -1230,9 +1218,7 @@ int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc ge bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { bool result = false; - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { if (sourcesMatchMask(mapper->getSources(), sourceMask)) { result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags); } @@ -1242,50 +1228,39 @@ bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token) { - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { mapper->vibrate(pattern, patternSize, repeat, token); } } void InputDevice::cancelVibrate(int32_t token) { - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { mapper->cancelVibrate(token); } } void InputDevice::cancelTouch(nsecs_t when) { - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { mapper->cancelTouch(when); } } int32_t InputDevice::getMetaState() { int32_t result = 0; - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { result |= mapper->getMetaState(); } return result; } void InputDevice::updateMetaState(int32_t keyCode) { - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - mMappers[i]->updateMetaState(keyCode); + for (InputMapper* mapper : mMappers) { + mapper->updateMetaState(keyCode); } } void InputDevice::fadePointer() { - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { mapper->fadePointer(); } } @@ -1300,9 +1275,7 @@ void InputDevice::notifyReset(nsecs_t when) { } std::optional InputDevice::getAssociatedDisplay() { - size_t numMappers = mMappers.size(); - for (size_t i = 0; i < numMappers; i++) { - InputMapper* mapper = mMappers[i]; + for (InputMapper* mapper : mMappers) { std::optional associatedDisplayId = mapper->getAssociatedDisplay(); if (associatedDisplayId) { return associatedDisplayId; @@ -2405,7 +2378,7 @@ void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode, ssize_t keyDownIndex = findKeyDown(scanCode); if (keyDownIndex >= 0) { // key repeat, be sure to use same keycode as before in case of rotation - keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode; + keyCode = mKeyDowns[keyDownIndex].keyCode; } else { // key down if ((policyFlags & POLICY_FLAG_VIRTUAL) @@ -2417,10 +2390,10 @@ void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode, mDevice->cancelTouch(when); } - mKeyDowns.push(); - KeyDown& keyDown = mKeyDowns.editTop(); + KeyDown keyDown; keyDown.keyCode = keyCode; keyDown.scanCode = scanCode; + mKeyDowns.push_back(keyDown); } mDownTime = when; @@ -2429,8 +2402,8 @@ void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode, ssize_t keyDownIndex = findKeyDown(scanCode); if (keyDownIndex >= 0) { // key up, be sure to use same keycode as before in case of rotation - keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode; - mKeyDowns.removeAt(size_t(keyDownIndex)); + keyCode = mKeyDowns[keyDownIndex].keyCode; + mKeyDowns.erase(mKeyDowns.begin() + (size_t)keyDownIndex); } else { // key was not actually down ALOGI("Dropping key up from device %s because the key was not down. " @@ -3316,9 +3289,9 @@ void TouchInputMapper::configure(nsecs_t when, } void TouchInputMapper::resolveExternalStylusPresence() { - Vector devices; + std::vector devices; mContext->getExternalStylusDevices(devices); - mExternalStylusConnected = !devices.isEmpty(); + mExternalStylusConnected = !devices.empty(); if (!mExternalStylusConnected) { resetExternalStylus(); @@ -3967,7 +3940,7 @@ void TouchInputMapper::dumpSurface(std::string& dump) { } void TouchInputMapper::configureVirtualKeys() { - Vector virtualKeyDefinitions; + std::vector virtualKeyDefinitions; getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions); mVirtualKeys.clear(); @@ -3976,19 +3949,13 @@ void TouchInputMapper::configureVirtualKeys() { return; } - mVirtualKeys.setCapacity(virtualKeyDefinitions.size()); - int32_t touchScreenLeft = mRawPointerAxes.x.minValue; int32_t touchScreenTop = mRawPointerAxes.y.minValue; int32_t touchScreenWidth = mRawPointerAxes.getRawWidth(); int32_t touchScreenHeight = mRawPointerAxes.getRawHeight(); - for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) { - const VirtualKeyDefinition& virtualKeyDefinition = - virtualKeyDefinitions[i]; - - mVirtualKeys.add(); - VirtualKey& virtualKey = mVirtualKeys.editTop(); + for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) { + VirtualKey virtualKey; virtualKey.scanCode = virtualKeyDefinition.scanCode; int32_t keyCode; @@ -3998,8 +3965,7 @@ void TouchInputMapper::configureVirtualKeys() { &keyCode, &dummyKeyMetaState, &flags)) { ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode); - mVirtualKeys.pop(); // drop the key - continue; + continue; // drop the key } virtualKey.keyCode = keyCode; @@ -4017,15 +3983,16 @@ void TouchInputMapper::configureVirtualKeys() { * touchScreenHeight / mSurfaceHeight + touchScreenTop; virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mSurfaceHeight + touchScreenTop; + mVirtualKeys.push_back(virtualKey); } } void TouchInputMapper::dumpVirtualKeys(std::string& dump) { - if (!mVirtualKeys.isEmpty()) { + if (!mVirtualKeys.empty()) { dump += INDENT3 "Virtual Keys:\n"; for (size_t i = 0; i < mVirtualKeys.size(); i++) { - const VirtualKey& virtualKey = mVirtualKeys.itemAt(i); + const VirtualKey& virtualKey = mVirtualKeys[i]; dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, " "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n", i, virtualKey.scanCode, virtualKey.keyCode, @@ -4364,12 +4331,13 @@ void TouchInputMapper::process(const RawEvent* rawEvent) { } void TouchInputMapper::sync(nsecs_t when) { - const RawState* last = mRawStatesPending.isEmpty() ? - &mCurrentRawState : &mRawStatesPending.top(); + const RawState* last = mRawStatesPending.empty() ? + &mCurrentRawState : &mRawStatesPending.back(); // Push a new state. - mRawStatesPending.push(); - RawState* next = &mRawStatesPending.editTop(); + mRawStatesPending.emplace_back(); + + RawState* next = &mRawStatesPending.back(); next->clear(); next->when = when; @@ -4436,7 +4404,7 @@ void TouchInputMapper::processRawTouches(bool timeout) { cookAndDispatch(mCurrentRawState.when); } if (count != 0) { - mRawStatesPending.removeItemsAt(0, count); + mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count); } if (mExternalStylusDataPending) { @@ -6623,12 +6591,9 @@ bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) { && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight; } -const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit( - int32_t x, int32_t y) { - size_t numVirtualKeys = mVirtualKeys.size(); - for (size_t i = 0; i < numVirtualKeys; i++) { - const VirtualKey& virtualKey = mVirtualKeys[i]; +const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) { + for (const VirtualKey& virtualKey: mVirtualKeys) { #if DEBUG_VIRTUAL_KEYS ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, " "left=%d, top=%d, right=%d, bottom=%d", @@ -6838,9 +6803,7 @@ int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) return AKEY_STATE_VIRTUAL; } - size_t numVirtualKeys = mVirtualKeys.size(); - for (size_t i = 0; i < numVirtualKeys; i++) { - const VirtualKey& virtualKey = mVirtualKeys[i]; + for (const VirtualKey& virtualKey : mVirtualKeys) { if (virtualKey.keyCode == keyCode) { return AKEY_STATE_UP; } @@ -6854,9 +6817,7 @@ int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode return AKEY_STATE_VIRTUAL; } - size_t numVirtualKeys = mVirtualKeys.size(); - for (size_t i = 0; i < numVirtualKeys; i++) { - const VirtualKey& virtualKey = mVirtualKeys[i]; + for (const VirtualKey& virtualKey : mVirtualKeys) { if (virtualKey.scanCode == scanCode) { return AKEY_STATE_UP; } @@ -6867,10 +6828,7 @@ int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { - size_t numVirtualKeys = mVirtualKeys.size(); - for (size_t i = 0; i < numVirtualKeys; i++) { - const VirtualKey& virtualKey = mVirtualKeys[i]; - + for (const VirtualKey& virtualKey : mVirtualKeys) { for (size_t i = 0; i < numCodes; i++) { if (virtualKey.keyCode == keyCodes[i]) { outFlags[i] = 1; diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h index fed55ac0e6..9777779e7d 100644 --- a/services/inputflinger/InputReader.h +++ b/services/inputflinger/InputReader.h @@ -90,7 +90,7 @@ public: virtual void requestTimeoutAtTime(nsecs_t when) = 0; virtual int32_t bumpGeneration() = 0; - virtual void getExternalStylusDevices(Vector& outDevices) = 0; + virtual void getExternalStylusDevices(std::vector& outDevices) = 0; virtual void dispatchExternalStylusState(const StylusState& outState) = 0; virtual InputReaderPolicyInterface* getPolicy() = 0; @@ -124,7 +124,7 @@ public: virtual void loopOnce(); - virtual void getInputDevices(Vector& outInputDevices); + virtual void getInputDevices(std::vector& outInputDevices); virtual bool isInputDeviceEnabled(int32_t deviceId); @@ -166,7 +166,7 @@ protected: virtual void fadePointer(); virtual void requestTimeoutAtTime(nsecs_t when); virtual int32_t bumpGeneration(); - virtual void getExternalStylusDevices(Vector& outDevices); + virtual void getExternalStylusDevices(std::vector& outDevices); virtual void dispatchExternalStylusState(const StylusState& outState); virtual InputReaderPolicyInterface* getPolicy(); virtual InputListenerInterface* getListener(); @@ -211,7 +211,7 @@ private: int32_t getGlobalMetaStateLocked(); void notifyExternalStylusPresenceChanged(); - void getExternalStylusDevicesLocked(Vector& outDevices); + void getExternalStylusDevicesLocked(std::vector& outDevices); void dispatchExternalStylusState(const StylusState& state); void fadePointerLocked(); @@ -219,7 +219,7 @@ private: int32_t mGeneration; int32_t bumpGenerationLocked(); - void getInputDevicesLocked(Vector& outInputDevices); + void getInputDevicesLocked(std::vector& outInputDevices); nsecs_t mDisableVirtualKeysTimeout; void disableVirtualKeysUntilLocked(nsecs_t time); @@ -266,7 +266,7 @@ public: inline void setMic(bool hasMic) { mHasMic = hasMic; } inline bool hasMic() const { return mHasMic; } - inline bool isIgnored() { return mMappers.isEmpty(); } + inline bool isIgnored() { return mMappers.empty(); } bool isEnabled(); void setEnabled(bool enabled, nsecs_t when); @@ -331,7 +331,7 @@ private: std::string mAlias; uint32_t mClasses; - Vector mMappers; + std::vector mMappers; uint32_t mSources; bool mIsExternal; @@ -877,7 +877,7 @@ private: uint32_t mSource; int32_t mKeyboardType; - Vector mKeyDowns; // keys that are down + std::vector mKeyDowns; // keys that are down int32_t mMetaState; nsecs_t mDownTime; // time of most recent key down @@ -1235,7 +1235,7 @@ protected: } }; - Vector mRawStatesPending; + std::vector mRawStatesPending; RawState mCurrentRawState; CookedState mCurrentCookedState; RawState mLastRawState; @@ -1262,7 +1262,7 @@ protected: // The pointer controller, or null if the device is not a pointer. sp mPointerController; - Vector mVirtualKeys; + std::vector mVirtualKeys; virtual void configureParameters(); virtual void dumpParameters(std::string& dump); diff --git a/services/inputflinger/host/InputFlinger.h b/services/inputflinger/host/InputFlinger.h index a00b5fbc13..d8b352cbc6 100644 --- a/services/inputflinger/host/InputFlinger.h +++ b/services/inputflinger/host/InputFlinger.h @@ -40,7 +40,8 @@ public: InputFlinger() ANDROID_API; virtual status_t dump(int fd, const Vector& args); - void setInputWindows(const Vector&, const sp&) {} + void setInputWindows(const std::vector&, + const sp&) {} void transferTouchFocus(const sp&, const sp&) {} void registerInputChannel(const sp&) {} void unregisterInputChannel(const sp&) {} diff --git a/services/inputflinger/include/InputListener.h b/services/inputflinger/include/InputListener.h index cd8caf7530..b51dcb6cad 100644 --- a/services/inputflinger/include/InputListener.h +++ b/services/inputflinger/include/InputListener.h @@ -221,7 +221,7 @@ public: private: sp mInnerListener; - Vector mArgsQueue; + std::vector mArgsQueue; }; } // namespace android diff --git a/services/inputflinger/include/InputReaderBase.h b/services/inputflinger/include/InputReaderBase.h index fe1d4d0bf7..8ad5dd0785 100644 --- a/services/inputflinger/include/InputReaderBase.h +++ b/services/inputflinger/include/InputReaderBase.h @@ -74,7 +74,7 @@ public: * * This method may be called on any thread (usually by the input manager). */ - virtual void getInputDevices(Vector& outInputDevices) = 0; + virtual void getInputDevices(std::vector& outInputDevices) = 0; /* Query current input state. */ virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask, @@ -333,7 +333,7 @@ public: /* Notifies the input reader policy that some input devices have changed * and provides information about all current input devices. */ - virtual void notifyInputDevicesChanged(const Vector& inputDevices) = 0; + virtual void notifyInputDevicesChanged(const std::vector& inputDevices) = 0; /* Gets the keyboard layout for a particular input device. */ virtual sp getKeyboardLayoutOverlay( diff --git a/services/inputflinger/tests/InputDispatcher_test.cpp b/services/inputflinger/tests/InputDispatcher_test.cpp index 3b6fe52a5a..d63ff8c2d6 100644 --- a/services/inputflinger/tests/InputDispatcher_test.cpp +++ b/services/inputflinger/tests/InputDispatcher_test.cpp @@ -571,8 +571,8 @@ TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) { sp window = new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT); - Vector> inputWindowHandles; - inputWindowHandles.add(window); + std::vector> inputWindowHandles; + inputWindowHandles.push_back(window); mDispatcher->setInputWindows(inputWindowHandles, ADISPLAY_ID_DEFAULT); ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectMotionDown(mDispatcher, @@ -591,9 +591,9 @@ TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) { sp windowSecond = new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT); - Vector> inputWindowHandles; - inputWindowHandles.add(windowTop); - inputWindowHandles.add(windowSecond); + std::vector> inputWindowHandles; + inputWindowHandles.push_back(windowTop); + inputWindowHandles.push_back(windowSecond); mDispatcher->setInputWindows(inputWindowHandles, ADISPLAY_ID_DEFAULT); ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectMotionDown(mDispatcher, @@ -617,9 +617,9 @@ TEST_F(InputDispatcherTest, SetInputWindow_FocusedWindow) { // Expect one focus window exist in display. windowSecond->setFocus(); - Vector> inputWindowHandles; - inputWindowHandles.add(windowTop); - inputWindowHandles.add(windowSecond); + std::vector> inputWindowHandles; + inputWindowHandles.push_back(windowTop); + inputWindowHandles.push_back(windowSecond); mDispatcher->setInputWindows(inputWindowHandles, ADISPLAY_ID_DEFAULT); ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher)) @@ -643,9 +643,9 @@ TEST_F(InputDispatcherTest, SetInputWindow_FocusPriority) { // Display has two focused windows. Add them to inputWindowsHandles in z-order (top most first) windowTop->setFocus(); windowSecond->setFocus(); - Vector> inputWindowHandles; - inputWindowHandles.add(windowTop); - inputWindowHandles.add(windowSecond); + std::vector> inputWindowHandles; + inputWindowHandles.push_back(windowTop); + inputWindowHandles.push_back(windowSecond); mDispatcher->setInputWindows(inputWindowHandles, ADISPLAY_ID_DEFAULT); ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher)) @@ -669,9 +669,9 @@ TEST_F(InputDispatcherTest, SetInputWindow_InputWindowInfo) { windowTop->setFocus(); windowSecond->setFocus(); - Vector> inputWindowHandles; - inputWindowHandles.add(windowTop); - inputWindowHandles.add(windowSecond); + std::vector> inputWindowHandles; + inputWindowHandles.push_back(windowTop); + inputWindowHandles.push_back(windowSecond); // Release channel for window is no longer valid. windowTop->releaseChannel(); mDispatcher->setInputWindows(inputWindowHandles, ADISPLAY_ID_DEFAULT); @@ -695,8 +695,8 @@ public: application1 = new FakeApplicationHandle(); windowInPrimary = new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT); - Vector> inputWindowHandles; - inputWindowHandles.push(windowInPrimary); + std::vector> inputWindowHandles; + inputWindowHandles.push_back(windowInPrimary); // Set focus window for primary display, but focused display would be second one. mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1); windowInPrimary->setFocus(); @@ -706,8 +706,8 @@ public: windowInSecondary = new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID); // Set focus to second display window. - Vector> inputWindowHandles_Second; - inputWindowHandles_Second.push(windowInSecondary); + std::vector> inputWindowHandles_Second; + inputWindowHandles_Second.push_back(windowInSecondary); // Set focus display to second one. mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID); // Set focus window for second display. @@ -762,7 +762,7 @@ TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, ADISPLAY_ID_NONE); // Remove secondary display. - Vector> noWindows; + std::vector> noWindows; mDispatcher->setInputWindows(noWindows, SECOND_DISPLAY_ID); // Expect old focus should receive a cancel event. diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp index 80a55f1a65..d35302885d 100644 --- a/services/inputflinger/tests/InputReader_test.cpp +++ b/services/inputflinger/tests/InputReader_test.cpp @@ -158,7 +158,7 @@ private: class FakeInputReaderPolicy : public InputReaderPolicyInterface { InputReaderConfiguration mConfig; KeyedVector > mPointerControllers; - Vector mInputDevices; + std::vector mInputDevices; std::vector mViewports; TouchAffineTransformation transform; @@ -226,7 +226,7 @@ public: return &mConfig; } - const Vector& getInputDevices() const { + const std::vector& getInputDevices() const { return mInputDevices; } @@ -280,7 +280,7 @@ private: return mPointerControllers.valueFor(deviceId); } - virtual void notifyInputDevicesChanged(const Vector& inputDevices) { + virtual void notifyInputDevicesChanged(const std::vector& inputDevices) { mInputDevices = inputDevices; } @@ -314,7 +314,7 @@ class FakeEventHub : public EventHubInterface { KeyedVector keysByScanCode; KeyedVector keysByUsageCode; KeyedVector leds; - Vector virtualKeys; + std::vector virtualKeys; bool enabled; status_t enable() { @@ -482,7 +482,7 @@ public: void addVirtualKeyDefinition(int32_t deviceId, const VirtualKeyDefinition& definition) { Device* device = getDevice(deviceId); - device->virtualKeys.push(definition); + device->virtualKeys.push_back(definition); } void enqueueEvent(nsecs_t when, int32_t deviceId, int32_t type, @@ -728,12 +728,12 @@ private: } virtual void getVirtualKeyDefinitions(int32_t deviceId, - Vector& outVirtualKeys) const { + std::vector& outVirtualKeys) const { outVirtualKeys.clear(); Device* device = getDevice(deviceId); if (device) { - outVirtualKeys.appendVector(device->virtualKeys); + outVirtualKeys = device->virtualKeys; } } @@ -842,7 +842,7 @@ private: return ++mGeneration; } - virtual void getExternalStylusDevices(Vector& outDevices) { + virtual void getExternalStylusDevices(std::vector& outDevices) { } @@ -865,7 +865,7 @@ class FakeInputMapper : public InputMapper { KeyedVector mKeyCodeStates; KeyedVector mScanCodeStates; KeyedVector mSwitchStates; - Vector mSupportedKeyCodes; + std::vector mSupportedKeyCodes; RawEvent mLastEvent; bool mConfigureWasCalled; @@ -925,7 +925,7 @@ public: } void addSupportedKeyCode(int32_t keyCode) { - mSupportedKeyCodes.add(keyCode); + mSupportedKeyCodes.push_back(keyCode); } private: @@ -1309,7 +1309,7 @@ TEST_F(InputReaderTest, GetInputDevices) { 0, nullptr)); // no classes so device will be ignored - Vector inputDevices; + std::vector inputDevices; mReader->getInputDevices(inputDevices); ASSERT_EQ(1U, inputDevices.size()); @@ -4436,7 +4436,7 @@ TEST_F(SingleTouchInputMapperTest, Process_ShouldHandleAllToolTypes) { ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action); ASSERT_EQ(AMOTION_EVENT_TOOL_TYPE_STYLUS, motionArgs.pointerProperties[0].toolType); - // airbrush + // air-brush processKey(mapper, BTN_TOOL_PENCIL, 0); processKey(mapper, BTN_TOOL_AIRBRUSH, 1); processSync(mapper); @@ -5943,7 +5943,7 @@ TEST_F(MultiTouchInputMapperTest, Process_ShouldHandleAllToolTypes) { ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, motionArgs.action); ASSERT_EQ(AMOTION_EVENT_TOOL_TYPE_STYLUS, motionArgs.pointerProperties[0].toolType); - // airbrush + // air-brush processKey(mapper, BTN_TOOL_PENCIL, 0); processKey(mapper, BTN_TOOL_AIRBRUSH, 1); processSync(mapper); diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 4c4a29b544..77c8d109f9 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -2906,13 +2906,13 @@ void SurfaceFlinger::updateInputFlinger() { } void SurfaceFlinger::updateInputWindowInfo() { - Vector inputHandles; + std::vector inputHandles; mDrawingState.traverseInReverseZOrder([&](Layer* layer) { if (layer->hasInput()) { // When calculating the screen bounds we ignore the transparent region since it may // result in an unwanted offset. - inputHandles.add(layer->fillInputInfo()); + inputHandles.push_back(layer->fillInputInfo()); } }); -- cgit v1.2.3-59-g8ed1b From 05247bb70fd301411d7450767ebaa65057ad95c8 Mon Sep 17 00:00:00 2001 From: Siarhei Vishniakou Date: Fri, 22 Mar 2019 17:11:21 -0700 Subject: Report mStatistics.count in InputReader We just added a new field to TouchEventReported, count. The new field specifies the number of events in a particular report. The reports are currently in 5-minute chunks. Report count in InputReader. Bug: 111431676 Test: out/host/linux-x86/bin/statsd_testdrive 34 Change-Id: I9aa6ac8e81a7764a5268e2cde6c7b4b86e28fbe2 --- services/inputflinger/InputReader.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'services/inputflinger/InputReader.cpp') diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp index 0cc37a016b..a45b8a56ce 100644 --- a/services/inputflinger/InputReader.cpp +++ b/services/inputflinger/InputReader.cpp @@ -4314,7 +4314,8 @@ void TouchInputMapper::reportEventForStatistics(nsecs_t evdevTime) { nsecs_t timeSinceLastReport = now - mStatistics.lastReportTime; if (timeSinceLastReport > STATISTICS_REPORT_FREQUENCY) { android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, - mStatistics.min, mStatistics.max, mStatistics.mean(), mStatistics.stdev()); + mStatistics.min, mStatistics.max, + mStatistics.mean(), mStatistics.stdev(), mStatistics.count); mStatistics.reset(now); } } -- cgit v1.2.3-59-g8ed1b