blob: 9119d605ea62fa89b0439a7edea3fca18482272a [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
Prabir Pradhan8d9ba912022-11-11 22:26:33 +000024#include <input/PrintTools.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080025
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070026#include "CursorButtonAccumulator.h"
27#include "CursorScrollAccumulator.h"
28#include "TouchButtonAccumulator.h"
29#include "TouchCursorInputMapperCommon.h"
Michael Wrighta9cf4192022-12-01 23:46:39 +000030#include "ui/Rotation.h"
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070031
32namespace android {
33
34// --- Constants ---
35
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070036// Artificial latency on synthetic events created from stylus data without corresponding touch
37// data.
38static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
39
HQ Liue6983c72022-04-19 22:14:56 +000040// Minimum width between two pointers to determine a gesture as freeform gesture in mm
41static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070042// --- Static Definitions ---
43
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000044static const DisplayViewport kUninitializedViewport;
45
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000046static std::string toString(const Rect& rect) {
47 return base::StringPrintf("Rect{%d, %d, %d, %d}", rect.left, rect.top, rect.right, rect.bottom);
48}
49
50static std::string toString(const ui::Size& size) {
51 return base::StringPrintf("%dx%d", size.width, size.height);
52}
53
Prabir Pradhan675f25a2022-11-10 22:04:07 +000054static bool isPointInRect(const Rect& rect, vec2 p) {
55 return p.x >= rect.left && p.x < rect.right && p.y >= rect.top && p.y < rect.bottom;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000056}
57
Prabir Pradhane04ffaa2022-12-13 23:04:04 +000058static std::string toString(const InputDeviceUsiVersion& v) {
59 return base::StringPrintf("%d.%d", v.majorVersion, v.minorVersion);
60}
61
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070062template <typename T>
63inline static void swap(T& a, T& b) {
64 T temp = a;
65 a = b;
66 b = temp;
67}
68
69static float calculateCommonVector(float a, float b) {
70 if (a > 0 && b > 0) {
71 return a < b ? a : b;
72 } else if (a < 0 && b < 0) {
73 return a > b ? a : b;
74 } else {
75 return 0;
76 }
77}
78
79inline static float distance(float x1, float y1, float x2, float y2) {
80 return hypotf(x1 - x2, y1 - y2);
81}
82
83inline static int32_t signExtendNybble(int32_t value) {
84 return value >= 8 ? value - 16 : value;
85}
86
Prabir Pradhan675f25a2022-11-10 22:04:07 +000087static ui::Size getNaturalDisplaySize(const DisplayViewport& viewport) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000088 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +000089 if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000090 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
91 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +000092 return rotatedDisplaySize;
Prabir Pradhan2d613f42022-11-10 20:22:06 +000093}
94
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +000095static int32_t filterButtonState(InputReaderConfiguration& config, int32_t buttonState) {
96 if (!config.stylusButtonMotionEventsEnabled) {
97 buttonState &=
98 ~(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY | AMOTION_EVENT_BUTTON_STYLUS_SECONDARY);
99 }
100 return buttonState;
101}
102
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700103// --- RawPointerData ---
104
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700105void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
106 float x = 0, y = 0;
107 uint32_t count = touchingIdBits.count();
108 if (count) {
109 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
110 uint32_t id = idBits.clearFirstMarkedBit();
111 const Pointer& pointer = pointerForId(id);
112 x += pointer.x;
113 y += pointer.y;
114 }
115 x /= count;
116 y /= count;
117 }
118 *outX = x;
119 *outY = y;
120}
121
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700122// --- TouchInputMapper ---
123
Arpit Singh8e6fb252023-04-06 11:49:17 +0000124TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext,
125 const InputReaderConfiguration& readerConfig)
126 : InputMapper(deviceContext, readerConfig),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000127 mTouchButtonAccumulator(deviceContext),
Arpit Singha8c236b2023-04-25 13:56:05 +0000128 mConfig(readerConfig) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700129
130TouchInputMapper::~TouchInputMapper() {}
131
Philip Junker4af3b3d2021-12-14 10:36:55 +0100132uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanb08a0e82023-09-14 22:28:32 +0000133 // The SOURCE_BLUETOOTH_STYLUS is added to events dynamically if the current stream is modified
134 // by the external stylus state. That's why we don't add it directly to mSource during
135 // configuration.
136 return mSource | (hasExternalStylus() ? AINPUT_SOURCE_BLUETOOTH_STYLUS : 0);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700137}
138
Harry Cuttsd02ea102023-03-17 18:21:30 +0000139void TouchInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700140 InputMapper::populateDeviceInfo(info);
141
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000142 if (mDeviceMode == DeviceMode::DISABLED) {
143 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700144 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000145
Harry Cuttsd02ea102023-03-17 18:21:30 +0000146 info.addMotionRange(mOrientedRanges.x);
147 info.addMotionRange(mOrientedRanges.y);
148 info.addMotionRange(mOrientedRanges.pressure);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000149
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000150 if (mOrientedRanges.size) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000151 info.addMotionRange(*mOrientedRanges.size);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000152 }
153
154 if (mOrientedRanges.touchMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000155 info.addMotionRange(*mOrientedRanges.touchMajor);
156 info.addMotionRange(*mOrientedRanges.touchMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000157 }
158
159 if (mOrientedRanges.toolMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000160 info.addMotionRange(*mOrientedRanges.toolMajor);
161 info.addMotionRange(*mOrientedRanges.toolMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000162 }
163
164 if (mOrientedRanges.orientation) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000165 info.addMotionRange(*mOrientedRanges.orientation);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000166 }
167
168 if (mOrientedRanges.distance) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000169 info.addMotionRange(*mOrientedRanges.distance);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000170 }
171
172 if (mOrientedRanges.tilt) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000173 info.addMotionRange(*mOrientedRanges.tilt);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000174 }
175
176 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000177 info.addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000178 }
179 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000180 info.addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000181 }
Harry Cuttsd02ea102023-03-17 18:21:30 +0000182 info.setButtonUnderPad(mParameters.hasButtonUnderPad);
183 info.setUsiVersion(mParameters.usiVersion);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700184}
185
186void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700187 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800188 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700189 dumpParameters(dump);
190 dumpVirtualKeys(dump);
191 dumpRawPointerAxes(dump);
192 dumpCalibration(dump);
193 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700194 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700195
196 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000197 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000198 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
199 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
200 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700201 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
202 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
203 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
204 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
205 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
206 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
207 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
208 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
209 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
210 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
211
212 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
213 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
214 mLastRawState.rawPointerData.pointerCount);
215 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
216 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
217 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
218 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
219 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700220 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700221 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
222 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
223 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700224 pointer.distance, ftl::enum_string(pointer.toolType).c_str(),
225 toString(pointer.isHovering));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700226 }
227
228 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
229 mLastCookedState.buttonState);
230 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
231 mLastCookedState.cookedPointerData.pointerCount);
232 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
233 const PointerProperties& pointerProperties =
234 mLastCookedState.cookedPointerData.pointerProperties[i];
235 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000236 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
237 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
238 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700239 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700240 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700241 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000242 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
243 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700244 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
245 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
246 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
247 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
248 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
249 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
250 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
251 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700252 ftl::enum_string(pointerProperties.toolType).c_str(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700253 toString(mLastCookedState.cookedPointerData.isHovering(i)));
254 }
255
256 dump += INDENT3 "Stylus Fusion:\n";
257 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
258 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000259 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
260 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700261 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
262 mExternalStylusFusionTimeout);
Harry Cutts1ee05b62023-06-19 13:49:06 +0000263 dump += StringPrintf(INDENT4 "External Stylus Buttons Applied: 0x%08x\n",
Prabir Pradhan124ea442022-10-28 20:27:44 +0000264 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700265 dump += INDENT3 "External Stylus State:\n";
266 dumpStylusState(dump, mExternalStylusState);
267
Michael Wright227c5542020-07-02 18:30:52 +0100268 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700269 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
270 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
271 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
272 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
273 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
274 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
275 }
276}
277
Arpit Singh4be4eef2023-03-28 14:26:01 +0000278std::list<NotifyArgs> TouchInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000279 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000280 ConfigurationChanges changes) {
Arpit Singh4be4eef2023-03-28 14:26:01 +0000281 std::list<NotifyArgs> out = InputMapper::reconfigure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700282
Arpit Singhed6c3de2023-04-05 19:24:37 +0000283 mConfig = config;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700284
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000285 // Full configuration should happen the first time configure is called and
286 // when the device type is changed. Changing a device type can affect
287 // various other parameters so should result in a reconfiguration.
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000288 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700289 // Configure basic parameters.
Arpit Singh403e53c2023-04-18 11:46:56 +0000290 mParameters = computeParameters(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700291
292 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800293 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000294 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700295
296 // Configure absolute axis information.
297 configureRawPointerAxes();
298
299 // Prepare input device calibration.
300 parseCalibration();
301 resolveCalibration();
302 }
303
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000304 if (!changes.any() ||
305 changes.test(InputReaderConfiguration::Change::TOUCH_AFFINE_TRANSFORMATION)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700306 // Update location calibration to reflect current settings
307 updateAffineTransformation();
308 }
309
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000310 if (!changes.any() || changes.test(InputReaderConfiguration::Change::POINTER_SPEED)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700311 // Update pointer speed.
312 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
313 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
314 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
315 }
316
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000317 using namespace ftl::flag_operators;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700318 bool resetNeeded = false;
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000319 if (!changes.any() ||
320 changes.any(InputReaderConfiguration::Change::DISPLAY_INFO |
321 InputReaderConfiguration::Change::POINTER_CAPTURE |
322 InputReaderConfiguration::Change::POINTER_GESTURE_ENABLEMENT |
323 InputReaderConfiguration::Change::SHOW_TOUCHES |
324 InputReaderConfiguration::Change::EXTERNAL_STYLUS_PRESENCE |
325 InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700326 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700327 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700328 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700329 }
330
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000331 if (changes.any() && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700332 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000333
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700334 // Send reset, unless this is the first time the device has been configured,
335 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000336 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700338 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700339}
340
341void TouchInputMapper::resolveExternalStylusPresence() {
342 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800343 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700344 mExternalStylusConnected = !devices.empty();
345
346 if (!mExternalStylusConnected) {
347 resetExternalStylus();
348 }
349}
350
Arpit Singh403e53c2023-04-18 11:46:56 +0000351TouchInputMapper::Parameters TouchInputMapper::computeParameters(
352 const InputDeviceContext& deviceContext) {
353 Parameters parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700354 // Use the pointer presentation mode for devices that do not support distinct
355 // multitouch. The spot-based presentation relies on being able to accurately
356 // locate two or more fingers on the touch pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000357 parameters.gestureMode = deviceContext.hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100358 ? Parameters::GestureMode::SINGLE_TOUCH
359 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700360
Arpit Singh403e53c2023-04-18 11:46:56 +0000361 const PropertyMap& config = deviceContext.getConfiguration();
Harry Cuttsf13161a2023-03-08 14:15:49 +0000362 std::optional<std::string> gestureModeString = config.getString("touch.gestureMode");
363 if (gestureModeString.has_value()) {
364 if (*gestureModeString == "single-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000365 parameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000366 } else if (*gestureModeString == "multi-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000367 parameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000368 } else if (*gestureModeString != "default") {
369 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700370 }
371 }
372
Arpit Singh403e53c2023-04-18 11:46:56 +0000373 parameters.deviceType = computeDeviceType(deviceContext);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374
Arpit Singh403e53c2023-04-18 11:46:56 +0000375 parameters.hasButtonUnderPad = deviceContext.hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700376
Arpit Singh403e53c2023-04-18 11:46:56 +0000377 parameters.orientationAware =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000378 config.getBool("touch.orientationAware")
Arpit Singh403e53c2023-04-18 11:46:56 +0000379 .value_or(parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700380
Arpit Singh403e53c2023-04-18 11:46:56 +0000381 parameters.orientation = ui::ROTATION_0;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000382 std::optional<std::string> orientationString = config.getString("touch.orientation");
383 if (orientationString.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000384 if (parameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700385 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
Harry Cuttsf13161a2023-03-08 14:15:49 +0000386 } else if (*orientationString == "ORIENTATION_90") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000387 parameters.orientation = ui::ROTATION_90;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000388 } else if (*orientationString == "ORIENTATION_180") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000389 parameters.orientation = ui::ROTATION_180;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000390 } else if (*orientationString == "ORIENTATION_270") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000391 parameters.orientation = ui::ROTATION_270;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000392 } else if (*orientationString != "ORIENTATION_0") {
393 ALOGW("Invalid value for touch.orientation: '%s'", orientationString->c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700394 }
395 }
396
Arpit Singh403e53c2023-04-18 11:46:56 +0000397 parameters.hasAssociatedDisplay = false;
398 parameters.associatedDisplayIsExternal = false;
399 if (parameters.orientationAware ||
400 parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
401 parameters.deviceType == Parameters::DeviceType::POINTER ||
402 (parameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
403 deviceContext.getAssociatedViewport())) {
404 parameters.hasAssociatedDisplay = true;
405 if (parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
406 parameters.associatedDisplayIsExternal = deviceContext.isExternal();
407 parameters.uniqueDisplayId = config.getString("touch.displayId").value_or("").c_str();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700408 }
409 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000410 if (deviceContext.getAssociatedDisplayPort()) {
411 parameters.hasAssociatedDisplay = true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700412 }
413
414 // Initial downs on external touch devices should wake the device.
415 // Normally we don't do this for internal touch screens to prevent them from waking
416 // up in your pocket but you can enable it using the input device configuration.
Arpit Singh403e53c2023-04-18 11:46:56 +0000417 parameters.wake = config.getBool("touch.wake").value_or(deviceContext.isExternal());
Prabir Pradhan167c2702022-09-14 00:37:24 +0000418
Harry Cuttsf13161a2023-03-08 14:15:49 +0000419 std::optional<int32_t> usiVersionMajor = config.getInt("touch.usiVersionMajor");
420 std::optional<int32_t> usiVersionMinor = config.getInt("touch.usiVersionMinor");
421 if (usiVersionMajor.has_value() && usiVersionMinor.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000422 parameters.usiVersion = {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000423 .majorVersion = *usiVersionMajor,
424 .minorVersion = *usiVersionMinor,
425 };
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000426 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700427
Arpit Singh403e53c2023-04-18 11:46:56 +0000428 parameters.enableForInactiveViewport =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000429 config.getBool("touch.enableForInactiveViewport").value_or(false);
Arpit Singh403e53c2023-04-18 11:46:56 +0000430
431 return parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700432}
433
Arpit Singh403e53c2023-04-18 11:46:56 +0000434TouchInputMapper::Parameters::DeviceType TouchInputMapper::computeDeviceType(
435 const InputDeviceContext& deviceContext) {
436 Parameters::DeviceType deviceType;
437 if (deviceContext.hasInputProperty(INPUT_PROP_DIRECT)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000438 // The device is a touch screen.
Arpit Singh403e53c2023-04-18 11:46:56 +0000439 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
440 } else if (deviceContext.hasInputProperty(INPUT_PROP_POINTER)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000441 // The device is a pointing device like a track pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000442 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000443 } else {
444 // The device is a touch pad of unknown purpose.
Arpit Singh403e53c2023-04-18 11:46:56 +0000445 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000446 }
447
448 // Type association takes precedence over the device type found in the idc file.
Arpit Singh403e53c2023-04-18 11:46:56 +0000449 std::string deviceTypeString = deviceContext.getDeviceTypeAssociation().value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000450 if (deviceTypeString.empty()) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000451 deviceTypeString =
Arpit Singh403e53c2023-04-18 11:46:56 +0000452 deviceContext.getConfiguration().getString("touch.deviceType").value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000453 }
454 if (deviceTypeString == "touchScreen") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000455 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000456 } else if (deviceTypeString == "touchNavigation") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000457 deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000458 } else if (deviceTypeString == "pointer") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000459 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000460 } else if (deviceTypeString != "default" && deviceTypeString != "") {
461 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
462 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000463 return deviceType;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000464}
465
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700466void TouchInputMapper::dumpParameters(std::string& dump) {
467 dump += INDENT3 "Parameters:\n";
468
Dominik Laskowski75788452021-02-09 18:51:25 -0800469 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700470
Dominik Laskowski75788452021-02-09 18:51:25 -0800471 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472
473 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
474 "displayId='%s'\n",
475 toString(mParameters.hasAssociatedDisplay),
476 toString(mParameters.associatedDisplayIsExternal),
477 mParameters.uniqueDisplayId.c_str());
478 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800479 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000480 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
481 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700482 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
483 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484}
485
486void TouchInputMapper::configureRawPointerAxes() {
487 mRawPointerAxes.clear();
488}
489
490void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
491 dump += INDENT3 "Raw Touch Axes:\n";
492 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
493 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
494 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
495 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
496 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
497 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
498 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
499 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
500 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
501 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
502 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
503 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
504 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
505}
506
507bool TouchInputMapper::hasExternalStylus() const {
508 return mExternalStylusConnected;
509}
510
511/**
512 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000513 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800514 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000515 * 3. Get the matching viewport by either unique id in idc file or by the display type
516 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800517 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700518 */
519std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Harry Cutts8722be92024-04-05 14:46:05 +0000520 if (mParameters.hasAssociatedDisplay) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000521 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800522 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700523 }
524
Christine Franks2a2293c2022-01-18 11:51:16 -0800525 const std::optional<std::string> associatedDisplayUniqueId =
526 getDeviceContext().getAssociatedDisplayUniqueId();
527 if (associatedDisplayUniqueId) {
528 return getDeviceContext().getAssociatedViewport();
529 }
530
Michael Wright227c5542020-07-02 18:30:52 +0100531 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800532 std::optional<DisplayViewport> viewport =
533 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
534 if (viewport) {
535 return viewport;
536 } else {
537 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
538 mConfig.defaultPointerDisplayId);
539 }
540 }
541
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700542 // Check if uniqueDisplayId is specified in idc file.
543 if (!mParameters.uniqueDisplayId.empty()) {
544 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
545 }
546
547 ViewportType viewportTypeToUse;
548 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100549 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700550 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100551 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700552 }
553
554 std::optional<DisplayViewport> viewport =
555 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100556 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700557 ALOGW("Input device %s should be associated with external display, "
558 "fallback to internal one for the external viewport is not found.",
559 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100560 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700561 }
562
563 return viewport;
564 }
565
566 // No associated display, return a non-display viewport.
567 DisplayViewport newViewport;
568 // Raw width and height in the natural orientation.
569 int32_t rawWidth = mRawPointerAxes.getRawWidth();
570 int32_t rawHeight = mRawPointerAxes.getRawHeight();
571 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
572 return std::make_optional(newViewport);
573}
574
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800575int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
576 if (resolution < 0) {
577 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
578 getDeviceName().c_str());
579 return 0;
580 }
581 return resolution;
582}
583
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800584void TouchInputMapper::initializeSizeRanges() {
585 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
586 mSizeScale = 0.0f;
587 return;
588 }
589
590 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000591 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800592
593 // Size factors.
594 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
595 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
596 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
597 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
598 } else {
599 mSizeScale = 0.0f;
600 }
601
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700602 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
603 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
604 .source = mSource,
605 .min = 0,
606 .max = diagonalSize,
607 .flat = 0,
608 .fuzz = 0,
609 .resolution = 0,
610 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800611
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800612 if (mRawPointerAxes.touchMajor.valid) {
613 mRawPointerAxes.touchMajor.resolution =
614 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700615 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800616 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800617
618 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700619 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800620 if (mRawPointerAxes.touchMinor.valid) {
621 mRawPointerAxes.touchMinor.resolution =
622 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700623 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800624 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800625
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700626 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
627 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
628 .source = mSource,
629 .min = 0,
630 .max = diagonalSize,
631 .flat = 0,
632 .fuzz = 0,
633 .resolution = 0,
634 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800635 if (mRawPointerAxes.toolMajor.valid) {
636 mRawPointerAxes.toolMajor.resolution =
637 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700638 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800639 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800640
641 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700642 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800643 if (mRawPointerAxes.toolMinor.valid) {
644 mRawPointerAxes.toolMinor.resolution =
645 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700646 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800647 }
648
649 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700650 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
651 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
652 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
653 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800654 } else {
655 // Support for other calibrations can be added here.
656 ALOGW("%s calibration is not supported for size ranges at the moment. "
657 "Using raw resolution instead",
658 ftl::enum_string(mCalibration.sizeCalibration).c_str());
659 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800660
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700661 mOrientedRanges.size = InputDeviceInfo::MotionRange{
662 .axis = AMOTION_EVENT_AXIS_SIZE,
663 .source = mSource,
664 .min = 0,
665 .max = 1.0,
666 .flat = 0,
667 .fuzz = 0,
668 .resolution = 0,
669 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800670}
671
672void TouchInputMapper::initializeOrientedRanges() {
673 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000674 const float orientedScaleX = mRawToDisplay.getScaleX();
675 const float orientedScaleY = mRawToDisplay.getScaleY();
676 mOrientedXPrecision = 1.0f / orientedScaleX;
677 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800678
679 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
680 mOrientedRanges.x.source = mSource;
681 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
682 mOrientedRanges.y.source = mSource;
683
684 // Scale factor for terms that are not oriented in a particular axis.
685 // If the pixels are square then xScale == yScale otherwise we fake it
686 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000687 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800688
689 initializeSizeRanges();
690
691 // Pressure factors.
692 mPressureScale = 0;
693 float pressureMax = 1.0;
694 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
695 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700696 if (mCalibration.pressureScale) {
697 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800698 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
699 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
700 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
701 }
702 }
703
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700704 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
705 .axis = AMOTION_EVENT_AXIS_PRESSURE,
706 .source = mSource,
707 .min = 0,
708 .max = pressureMax,
709 .flat = 0,
710 .fuzz = 0,
711 .resolution = 0,
712 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800713
714 // Tilt
715 mTiltXCenter = 0;
716 mTiltXScale = 0;
717 mTiltYCenter = 0;
718 mTiltYScale = 0;
719 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
720 if (mHaveTilt) {
721 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
722 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
723 mTiltXScale = M_PI / 180;
724 mTiltYScale = M_PI / 180;
725
726 if (mRawPointerAxes.tiltX.resolution) {
727 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
728 }
729 if (mRawPointerAxes.tiltY.resolution) {
730 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
731 }
732
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700733 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
734 .axis = AMOTION_EVENT_AXIS_TILT,
735 .source = mSource,
736 .min = 0,
737 .max = M_PI_2,
738 .flat = 0,
739 .fuzz = 0,
740 .resolution = 0,
741 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800742 }
743
744 // Orientation
745 mOrientationScale = 0;
746 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700747 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
748 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
749 .source = mSource,
750 .min = -M_PI,
751 .max = M_PI,
752 .flat = 0,
753 .fuzz = 0,
754 .resolution = 0,
755 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800756
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800757 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
758 if (mCalibration.orientationCalibration ==
759 Calibration::OrientationCalibration::INTERPOLATED) {
760 if (mRawPointerAxes.orientation.valid) {
761 if (mRawPointerAxes.orientation.maxValue > 0) {
762 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
763 } else if (mRawPointerAxes.orientation.minValue < 0) {
764 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
765 } else {
766 mOrientationScale = 0;
767 }
768 }
769 }
770
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700771 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
772 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
773 .source = mSource,
774 .min = -M_PI_2,
775 .max = M_PI_2,
776 .flat = 0,
777 .fuzz = 0,
778 .resolution = 0,
779 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800780 }
781
782 // Distance
783 mDistanceScale = 0;
784 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
785 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700786 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800787 }
788
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700789 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800790
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700791 .axis = AMOTION_EVENT_AXIS_DISTANCE,
792 .source = mSource,
793 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
794 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
795 .flat = 0,
796 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
797 .resolution = 0,
798 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800799 }
800
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000801 // Oriented X/Y range (in the rotated display's orientation)
802 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
803 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
804 .toFloatRect();
805 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
806 mOrientedRanges.x.min = orientedRangeRect.left;
807 mOrientedRanges.y.min = orientedRangeRect.top;
808 mOrientedRanges.x.max = orientedRangeRect.right;
809 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800810
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000811 // Oriented flat (in the rotated display's orientation)
812 const auto orientedFlat =
813 transformWithoutTranslation(mRawToRotatedDisplay,
814 {static_cast<float>(mRawPointerAxes.x.flat),
815 static_cast<float>(mRawPointerAxes.y.flat)});
816 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
817 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800818
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000819 // Oriented fuzz (in the rotated display's orientation)
820 const auto orientedFuzz =
821 transformWithoutTranslation(mRawToRotatedDisplay,
822 {static_cast<float>(mRawPointerAxes.x.fuzz),
823 static_cast<float>(mRawPointerAxes.y.fuzz)});
824 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
825 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800826
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000827 // Oriented resolution (in the rotated display's orientation)
828 const auto orientedRes =
829 transformWithoutTranslation(mRawToRotatedDisplay,
830 {static_cast<float>(mRawPointerAxes.x.resolution),
831 static_cast<float>(mRawPointerAxes.y.resolution)});
832 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
833 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800834}
835
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000836void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000837 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
838 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
839 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000840
Prabir Pradhan3e798762022-12-02 21:02:11 +0000841 // See notes about input coordinates in the inputflinger docs:
842 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000843
844 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000845 ui::Transform undoOffsetInRaw;
846 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000847
Prabir Pradhan3e798762022-12-02 21:02:11 +0000848 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
849 // will now be in the same orientation as the display in ROTATION_0.
850 // Note: Negating an ui::Rotation value will give its inverse rotation.
851 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
852 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
853 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
854 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
855 // When rotating raw values, account for the extra unit added when calculating the raw range.
856 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
857 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000858
Prabir Pradhan3e798762022-12-02 21:02:11 +0000859 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
860 // now be in the same orientation as the rotated display. There is no need to rotate the
861 // coordinates to the display rotation if the device is not orientation-aware.
862 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
863 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
864 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
865 : orientedRawSize;
866 // When rotating raw values, account for the extra unit added when calculating the raw range.
867 const auto rotateInRaw = mParameters.orientationAware
868 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
869 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000870
Prabir Pradhan3e798762022-12-02 21:02:11 +0000871 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000872 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
873 // the surface of the display panel. This is usually true for touchscreens.
874 // - In POINTER mode, we cannot assume that the display and the touch device have the same
875 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
876 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
877 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
878 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000879 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
880 // are in the continuous space of the logical display.
881 ui::Transform scaleRawToDisplay;
882 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
883 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000884 if (mDeviceMode == DeviceMode::DIRECT) {
885 scaleRawToDisplay.set(xScale, 0, 0, yScale);
886 } else if (mDeviceMode == DeviceMode::POINTER) {
887 const float fixedScale = std::max(xScale, yScale);
888 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
889 } else {
890 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
891 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000892
Prabir Pradhan3e798762022-12-02 21:02:11 +0000893 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
894 // that InputReader uses.
895 const auto undoRotateInDisplay =
896 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
897 .inverse();
898
899 // Now put it all together!
900 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
901 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
902 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000903}
904
Prabir Pradhan1728b212021-10-19 16:00:03 -0700905void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000906 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700907
908 resolveExternalStylusPresence();
909
910 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100911 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +0900912 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700913 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100914 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700915 if (hasStylus()) {
916 mSource |= AINPUT_SOURCE_STYLUS;
917 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800918 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700919 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100920 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700921 if (hasStylus()) {
922 mSource |= AINPUT_SOURCE_STYLUS;
923 }
Michael Wright227c5542020-07-02 18:30:52 +0100924 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700925 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100926 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700927 } else {
Harry Cutts8722be92024-04-05 14:46:05 +0000928 ALOGW("Touch device '%s' has invalid parameters or configuration. The device will be "
929 "inoperable.",
930 getDeviceName().c_str());
931 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700932 }
933
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000934 const std::optional<DisplayViewport> newViewportOpt = findViewport();
935
936 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700937 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
938 ALOGW("Touch device '%s' did not report support for X or Y axis! "
939 "The device will be inoperable.",
940 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100941 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000942 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700943 ALOGI("Touch device '%s' could not query the properties of its associated "
944 "display. The device will be inoperable until the display size "
945 "becomes available.",
946 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100947 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700948 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000949 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
950 getDeviceName().c_str(), getDeviceId());
951 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000952 }
953
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700954 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000955 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000956 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
957 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
958 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
959 const float rawMeanResolution =
960 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700961
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000962 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
Josh Thielene986aed2023-06-01 14:17:30 +0000963 bool viewportChanged;
964 if (mParameters.enableForInactiveViewport) {
965 // When touch is enabled for an inactive viewport, ignore the
966 // viewport active status when checking whether the viewport has
967 // changed.
968 DisplayViewport tempViewport = mViewport;
969 tempViewport.isActive = newViewport.isActive;
970 viewportChanged = tempViewport != newViewport;
971 } else {
972 viewportChanged = mViewport != newViewport;
973 }
974
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700975 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700976 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000977 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
978 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
979 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700980
Michael Wright227c5542020-07-02 18:30:52 +0100981 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000982 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700983
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000984 mDisplayBounds = getNaturalDisplaySize(mViewport);
985 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
986 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700987
Prabir Pradhan3e798762022-12-02 21:02:11 +0000988 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
989 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
990 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000991 // InputReader works in the un-rotated display coordinate space, so we don't need to do
992 // anything if the device is already orientation-aware. If the device is not
993 // orientation-aware, then we need to apply the inverse rotation of the display so that
994 // when the display rotation is applied later as a part of the per-window transform, we
995 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700996 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000997 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000998 : getInverseRotation(mViewport.orientation);
999 // For orientation-aware devices that work in the un-rotated coordinate space, the
1000 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001001 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001002 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001003
1004 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001005 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001006 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001007 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001008 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001009 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001010 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001011 mRawToDisplay.reset();
1012 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001013 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001014 }
1015 }
1016
1017 // If moving between pointer modes, need to reset some state.
1018 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1019 if (deviceModeChanged) {
1020 mOrientedRanges.clear();
1021 }
1022
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001023 // Create and preserve the pointer controller in the following cases:
1024 const bool isPointerControllerNeeded =
1025 // - when the device is in pointer mode, to show the mouse cursor;
1026 (mDeviceMode == DeviceMode::POINTER) ||
1027 // - when pointer capture is enabled, to preserve the mouse cursor position;
1028 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +09001029 mConfig.pointerCaptureRequest.isEnable()) ||
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001030 // - when we should be showing touches;
1031 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1032 // - when we should be showing a pointer icon for direct styluses.
1033 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1034 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001035 if (mPointerController == nullptr) {
1036 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001037 }
Hiroki Sato25040232024-02-22 17:21:22 +09001038 if (mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001039 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1040 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001041 } else {
lilinnandef700b2022-06-17 19:32:01 +08001042 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1043 !mConfig.showTouches) {
1044 mPointerController->clearSpots();
1045 }
Michael Wright17db18e2020-06-26 20:51:44 +01001046 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001047 }
1048
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001049 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001050 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001051 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001052 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001053 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001054
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001055 configureVirtualKeys();
1056
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001057 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001058
1059 // Location
1060 updateAffineTransformation();
1061
Michael Wright227c5542020-07-02 18:30:52 +01001062 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001063 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001064 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1065 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001066
1067 // Scale movements such that one whole swipe of the touch pad covers a
1068 // given area relative to the diagonal size of the display when no acceleration
1069 // is applied.
1070 // Assume that the touch pad has a square aspect ratio such that movements in
1071 // X and Y of the same number of raw units cover the same physical distance.
1072 mPointerXMovementScale =
1073 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1074 mPointerYMovementScale = mPointerXMovementScale;
1075
1076 // Scale zooms to cover a smaller range of the display than movements do.
1077 // This value determines the area around the pointer that is affected by freeform
1078 // pointer gestures.
1079 mPointerXZoomScale =
1080 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1081 mPointerYZoomScale = mPointerXZoomScale;
1082
HQ Liue6983c72022-04-19 22:14:56 +00001083 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1084 // axis is non positive value.
1085 const float minFreeformGestureWidth =
1086 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1087
1088 mPointerGestureMaxSwipeWidth =
1089 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1090 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001091 }
1092
1093 // Inform the dispatcher about the changes.
1094 *outResetNeeded = true;
1095 bumpGeneration();
1096 }
1097}
1098
Prabir Pradhan1728b212021-10-19 16:00:03 -07001099void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001100 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001101 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001102 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1103 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001104 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001105}
1106
1107void TouchInputMapper::configureVirtualKeys() {
1108 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001109 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001110
1111 mVirtualKeys.clear();
1112
1113 if (virtualKeyDefinitions.size() == 0) {
1114 return;
1115 }
1116
1117 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1118 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1119 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1120 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1121
1122 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1123 VirtualKey virtualKey;
1124
1125 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1126 int32_t keyCode;
1127 int32_t dummyKeyMetaState;
1128 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001129 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1130 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001131 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1132 continue; // drop the key
1133 }
1134
1135 virtualKey.keyCode = keyCode;
1136 virtualKey.flags = flags;
1137
1138 // convert the key definition's display coordinates into touch coordinates for a hit box
1139 int32_t halfWidth = virtualKeyDefinition.width / 2;
1140 int32_t halfHeight = virtualKeyDefinition.height / 2;
1141
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001142 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1143 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001145 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1146 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001148 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1149 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001151 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1152 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001153 touchScreenTop;
1154 mVirtualKeys.push_back(virtualKey);
1155 }
1156}
1157
1158void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1159 if (!mVirtualKeys.empty()) {
1160 dump += INDENT3 "Virtual Keys:\n";
1161
1162 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1163 const VirtualKey& virtualKey = mVirtualKeys[i];
1164 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1165 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1166 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1167 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1168 }
1169 }
1170}
1171
1172void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001173 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 Calibration& out = mCalibration;
1175
1176 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001177 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001178 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1179 if (sizeCalibrationString.has_value()) {
1180 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001182 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001184 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001186 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001188 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001190 } else if (*sizeCalibrationString != "default") {
1191 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 }
1193 }
1194
Harry Cuttsf13161a2023-03-08 14:15:49 +00001195 out.sizeScale = in.getFloat("touch.size.scale");
1196 out.sizeBias = in.getFloat("touch.size.bias");
1197 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198
1199 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001201 std::optional<std::string> pressureCalibrationString =
1202 in.getString("touch.pressure.calibration");
1203 if (pressureCalibrationString.has_value()) {
1204 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001205 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001206 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001207 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001208 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001209 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001210 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001212 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 }
1214 }
1215
Harry Cuttsf13161a2023-03-08 14:15:49 +00001216 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217
1218 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001219 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001220 std::optional<std::string> orientationCalibrationString =
1221 in.getString("touch.orientation.calibration");
1222 if (orientationCalibrationString.has_value()) {
1223 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001224 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001225 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001226 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001227 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001228 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001229 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001230 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001231 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 }
1233 }
1234
1235 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001236 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001237 std::optional<std::string> distanceCalibrationString =
1238 in.getString("touch.distance.calibration");
1239 if (distanceCalibrationString.has_value()) {
1240 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001241 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001242 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001243 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001244 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001246 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001247 }
1248 }
1249
Harry Cuttsf13161a2023-03-08 14:15:49 +00001250 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001251}
1252
1253void TouchInputMapper::resolveCalibration() {
1254 // Size
1255 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001256 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1257 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 }
1259 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001260 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 }
1262
1263 // Pressure
1264 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001265 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1266 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 }
1268 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001269 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270 }
1271
1272 // Orientation
1273 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001274 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1275 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 }
1277 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001278 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 }
1280
1281 // Distance
1282 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001283 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1284 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 }
1286 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001287 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289}
1290
1291void TouchInputMapper::dumpCalibration(std::string& dump) {
1292 dump += INDENT3 "Calibration:\n";
1293
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001294 dump += INDENT4 "touch.size.calibration: ";
1295 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001296
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001297 if (mCalibration.sizeScale) {
1298 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001299 }
1300
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001301 if (mCalibration.sizeBias) {
1302 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 }
1304
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001305 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001307 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 }
1309
1310 // Pressure
1311 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001312 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.pressure.calibration: none\n";
1314 break;
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.pressure.calibration: physical\n";
1317 break;
Michael Wright227c5542020-07-02 18:30:52 +01001318 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1320 break;
1321 default:
1322 ALOG_ASSERT(false);
1323 }
1324
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001325 if (mCalibration.pressureScale) {
1326 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001327 }
1328
1329 // Orientation
1330 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001331 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 dump += INDENT4 "touch.orientation.calibration: none\n";
1333 break;
Michael Wright227c5542020-07-02 18:30:52 +01001334 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001335 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1336 break;
Michael Wright227c5542020-07-02 18:30:52 +01001337 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001338 dump += INDENT4 "touch.orientation.calibration: vector\n";
1339 break;
1340 default:
1341 ALOG_ASSERT(false);
1342 }
1343
1344 // Distance
1345 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001346 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001347 dump += INDENT4 "touch.distance.calibration: none\n";
1348 break;
Michael Wright227c5542020-07-02 18:30:52 +01001349 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350 dump += INDENT4 "touch.distance.calibration: scaled\n";
1351 break;
1352 default:
1353 ALOG_ASSERT(false);
1354 }
1355
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001356 if (mCalibration.distanceScale) {
1357 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001358 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001359}
1360
1361void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1362 dump += INDENT3 "Affine Transformation:\n";
1363
1364 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1365 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1366 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1367 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1368 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1369 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1370}
1371
1372void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001373 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001374 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001375}
1376
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001377std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001378 std::list<NotifyArgs> out = cancelTouch(when, when);
1379 updateTouchSpots();
1380
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001381 mCursorButtonAccumulator.reset(getDeviceContext());
1382 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001383 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001384
1385 mPointerVelocityControl.reset();
1386 mWheelXVelocityControl.reset();
1387 mWheelYVelocityControl.reset();
1388
1389 mRawStatesPending.clear();
1390 mCurrentRawState.clear();
1391 mCurrentCookedState.clear();
1392 mLastRawState.clear();
1393 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001394 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001395 mSentHoverEnter = false;
1396 mHavePointerIds = false;
1397 mCurrentMotionAborted = false;
1398 mDownTime = 0;
1399
1400 mCurrentVirtualKey.down = false;
1401
1402 mPointerGesture.reset();
1403 mPointerSimple.reset();
1404 resetExternalStylus();
1405
1406 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001407 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001408 mPointerController->clearSpots();
1409 }
1410
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001411 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001412}
1413
1414void TouchInputMapper::resetExternalStylus() {
1415 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001416 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001417 mExternalStylusFusionTimeout = LLONG_MAX;
1418 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001419 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001420}
1421
1422void TouchInputMapper::clearStylusDataPendingFlags() {
1423 mExternalStylusDataPending = false;
1424 mExternalStylusFusionTimeout = LLONG_MAX;
1425}
1426
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001427std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001428 mCursorButtonAccumulator.process(rawEvent);
1429 mCursorScrollAccumulator.process(rawEvent);
1430 mTouchButtonAccumulator.process(rawEvent);
1431
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001432 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001433 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001434 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001435 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001436 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001437}
1438
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001439std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1440 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001441 if (mDeviceMode == DeviceMode::DISABLED) {
1442 // Only save the last pending state when the device is disabled.
1443 mRawStatesPending.clear();
1444 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001445 // Push a new state.
1446 mRawStatesPending.emplace_back();
1447
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001448 RawState& next = mRawStatesPending.back();
1449 next.clear();
1450 next.when = when;
1451 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001452
1453 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001454 next.buttonState = filterButtonState(mConfig,
1455 mTouchButtonAccumulator.getButtonState() |
1456 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001457
1458 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001459 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1460 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001461 mCursorScrollAccumulator.finishSync();
1462
1463 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001464 syncTouch(when, &next);
1465
1466 // The last RawState is the actually second to last, since we just added a new state
1467 const RawState& last =
1468 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001469
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001470 std::tie(next.when, next.readTime) =
1471 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1472 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001473
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001474 // Assign pointer ids.
1475 if (!mHavePointerIds) {
1476 assignPointerIds(last, next);
1477 }
1478
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001479 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001480 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1481 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1482 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1483 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1484 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1485 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001486
Arthur Hung9ad18942021-06-19 02:04:46 +00001487 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1488 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1489 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1490 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1491 next.rawPointerData.hoveringIdBits.value);
1492 }
1493
Harry Cutts33476232023-01-30 19:57:29 +00001494 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001495 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001496}
1497
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001498std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1499 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001500 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001501 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001502 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001503 }
1504
1505 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1506 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1507 // touching the current state will only observe the events that have been dispatched to the
1508 // rest of the pipeline.
1509 const size_t N = mRawStatesPending.size();
1510 size_t count;
1511 for (count = 0; count < N; count++) {
1512 const RawState& next = mRawStatesPending[count];
1513
1514 // A failure to assign the stylus id means that we're waiting on stylus data
1515 // and so should defer the rest of the pipeline.
1516 if (assignExternalStylusId(next, timeout)) {
1517 break;
1518 }
1519
1520 // All ready to go.
1521 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001522 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001523 if (mCurrentRawState.when < mLastRawState.when) {
1524 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001525 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001526 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001527 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001528 }
1529 if (count != 0) {
1530 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1531 }
1532
1533 if (mExternalStylusDataPending) {
1534 if (timeout) {
1535 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1536 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001537 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001538 ALOGD_IF(DEBUG_STYLUS_FUSION,
1539 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001540 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001541 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001542 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1543 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1544 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1545 }
1546 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001547 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001548}
1549
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001550std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1551 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001552 // Always start with a clean state.
1553 mCurrentCookedState.clear();
1554
1555 // Apply stylus buttons to current raw state.
1556 applyExternalStylusButtonState(when);
1557
1558 // Handle policy on initial down or hover events.
1559 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1560 mCurrentRawState.rawPointerData.pointerCount != 0;
1561
1562 uint32_t policyFlags = 0;
1563 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1564 if (initialDown || buttonsPressed) {
1565 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001566 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001567 getContext()->fadePointer();
1568 }
1569
1570 if (mParameters.wake) {
1571 policyFlags |= POLICY_FLAG_WAKE;
1572 }
1573 }
1574
1575 // Consume raw off-screen touches before cooking pointer data.
1576 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001577 bool consumed;
1578 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1579 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001580 mCurrentRawState.rawPointerData.clear();
1581 }
1582
1583 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1584 // with cooked pointer data that has the same ids and indices as the raw data.
1585 // The following code can use either the raw or cooked data, as needed.
1586 cookPointerData();
1587
1588 // Apply stylus pressure to current cooked state.
1589 applyExternalStylusTouchState(when);
1590
1591 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001592 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1593 mSource, mViewport.displayId, policyFlags,
1594 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001595
1596 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001597 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001598 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1599 uint32_t id = idBits.clearFirstMarkedBit();
1600 const RawPointerData::Pointer& pointer =
1601 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001602 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001603 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001604 } else if (pointer.toolType == ToolType::FINGER ||
1605 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001606 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001607 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001608 mCurrentCookedState.mouseIdBits.markBit(id);
1609 }
1610 }
1611 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1612 uint32_t id = idBits.clearFirstMarkedBit();
1613 const RawPointerData::Pointer& pointer =
1614 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001615 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001616 mCurrentCookedState.stylusIdBits.markBit(id);
1617 }
1618 }
1619
1620 // Stylus takes precedence over all tools, then mouse, then finger.
1621 PointerUsage pointerUsage = mPointerUsage;
1622 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1623 mCurrentCookedState.mouseIdBits.clear();
1624 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001625 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001626 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1627 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001628 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001629 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1630 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001631 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632 }
1633
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001634 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001635 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001636 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001637 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001638 out += dispatchButtonRelease(when, readTime, policyFlags);
1639 out += dispatchHoverExit(when, readTime, policyFlags);
1640 out += dispatchTouches(when, readTime, policyFlags);
1641 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1642 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001643 }
1644
1645 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1646 mCurrentMotionAborted = false;
1647 }
1648 }
1649
1650 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001651 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1652 mSource, mViewport.displayId, policyFlags,
1653 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001654
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001655 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1656 mCurrentStreamModifiedByExternalStylus = false;
1657 }
1658
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001659 // Clear some transient state.
1660 mCurrentRawState.rawVScroll = 0;
1661 mCurrentRawState.rawHScroll = 0;
1662
1663 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001664 mLastRawState = mCurrentRawState;
1665 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001666 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001667}
1668
Garfield Tanc734e4f2021-01-15 20:01:39 -08001669void TouchInputMapper::updateTouchSpots() {
1670 if (!mConfig.showTouches || mPointerController == nullptr) {
1671 return;
1672 }
1673
1674 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1675 // clear touch spots.
1676 if (mDeviceMode != DeviceMode::DIRECT &&
1677 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1678 return;
1679 }
1680
1681 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1682 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1683
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001684 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1685 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001686 mCurrentCookedState.cookedPointerData.touchingIdBits |
1687 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001688 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001689}
1690
1691bool TouchInputMapper::isTouchScreen() {
1692 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1693 mParameters.hasAssociatedDisplay;
1694}
1695
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001696void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001697 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1698 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001699 const int32_t pressedButtons =
1700 filterButtonState(mConfig,
1701 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001702 const int32_t releasedButtons =
1703 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1704
1705 mCurrentRawState.buttonState |= pressedButtons;
1706 mCurrentRawState.buttonState &= ~releasedButtons;
1707
1708 mExternalStylusButtonsApplied |= pressedButtons;
1709 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001710
1711 if (mExternalStylusButtonsApplied != 0 || releasedButtons != 0) {
1712 mCurrentStreamModifiedByExternalStylus = true;
1713 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001714 }
1715}
1716
1717void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1718 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1719 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001720 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1721 return;
1722 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001723
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001724 mCurrentStreamModifiedByExternalStylus = true;
1725
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001726 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1727 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1728 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1729 : 0.f;
1730 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1731 pressure = *mExternalStylusState.pressure;
1732 }
1733 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1734 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001735
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001736 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001737 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001738 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001739 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001740 }
1741}
1742
1743bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001744 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001745 return false;
1746 }
1747
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001748 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001749 if (mFusedStylusPointerId &&
1750 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001751 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001752 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001753 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001754 }
1755
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001756 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1757 state.rawPointerData.pointerCount != 0;
1758 if (!initialDown) {
1759 return false;
1760 }
1761
1762 if (!mExternalStylusState.pressure) {
1763 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1764 return false;
1765 }
1766
1767 if (*mExternalStylusState.pressure != 0.0f) {
1768 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1769 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1770 return false;
1771 }
1772
1773 if (timeout) {
1774 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1775 mFusedStylusPointerId.reset();
1776 mExternalStylusFusionTimeout = LLONG_MAX;
1777 return false;
1778 }
1779
1780 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1781 // being processed until we either get pressure data or timeout.
1782 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1783 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1784 }
1785 ALOGD_IF(DEBUG_STYLUS_FUSION,
1786 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1787 mExternalStylusFusionTimeout);
1788 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1789 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001790}
1791
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001792std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1793 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001794 if (mDeviceMode == DeviceMode::POINTER) {
1795 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001796 // Since this is a synthetic event, we can consider its latency to be zero
1797 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001798 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001799 }
Michael Wright227c5542020-07-02 18:30:52 +01001800 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001801 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001802 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001803 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1804 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1805 }
1806 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001807 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001808}
1809
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001810std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1811 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001812 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001813 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001814 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001815 // The following three cases are handled here:
1816 // - We're in the middle of a fused stream of data;
1817 // - We're waiting on external stylus data before dispatching the initial down; or
1818 // - Only the button state, which is not reported through a specific pointer, has changed.
1819 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001820 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001821 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001822 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001823 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001824}
1825
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001826std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1827 uint32_t policyFlags, bool& outConsumed) {
1828 outConsumed = false;
1829 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001830 // Check for release of a virtual key.
1831 if (mCurrentVirtualKey.down) {
1832 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1833 // Pointer went up while virtual key was down.
1834 mCurrentVirtualKey.down = false;
1835 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001836 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1837 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1838 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001839 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1840 AKEY_EVENT_FLAG_FROM_SYSTEM |
1841 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001842 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001843 outConsumed = true;
1844 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001845 }
1846
1847 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1848 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1849 const RawPointerData::Pointer& pointer =
1850 mCurrentRawState.rawPointerData.pointerForId(id);
1851 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1852 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1853 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001854 outConsumed = true;
1855 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001856 }
1857 }
1858
1859 // Pointer left virtual key area or another pointer also went down.
1860 // Send key cancellation but do not consume the touch yet.
1861 // This is useful when the user swipes through from the virtual key area
1862 // into the main display surface.
1863 mCurrentVirtualKey.down = false;
1864 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001865 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1866 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001867 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1868 AKEY_EVENT_FLAG_FROM_SYSTEM |
1869 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1870 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001871 }
1872 }
1873
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001874 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
Harry Cutts8722be92024-04-05 14:46:05 +00001875 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001876 // We have hovering pointers, and there are no touching pointers.
1877 bool hoveringPointersInFrame = false;
1878 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1879 while (!hoveringIds.isEmpty()) {
1880 uint32_t id = hoveringIds.clearFirstMarkedBit();
1881 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1882 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1883 hoveringPointersInFrame = true;
1884 break;
1885 }
1886 }
1887 if (!hoveringPointersInFrame) {
1888 // All hovering pointers are outside the physical frame.
1889 outConsumed = true;
1890 return out;
1891 }
1892 }
1893
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001894 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1895 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1896 // Pointer just went down. Check for virtual key press or off-screen touches.
1897 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1898 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001899 // Skip checking whether the pointer is inside the physical frame if the device is in
Harry Cutts1db43992023-06-19 17:05:07 +00001900 // unscaled or pointer mode.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001901 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
Harry Cutts8722be92024-04-05 14:46:05 +00001902 mDeviceMode != DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001903 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001904 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001905 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1906 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1907 if (virtualKey) {
1908 mCurrentVirtualKey.down = true;
1909 mCurrentVirtualKey.downTime = when;
1910 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1911 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1912 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001913 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1914 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001915
1916 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001917 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1918 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1919 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001920 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1921 AKEY_EVENT_ACTION_DOWN,
1922 AKEY_EVENT_FLAG_FROM_SYSTEM |
1923 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001924 }
1925 }
1926 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001927 outConsumed = true;
1928 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001929 }
1930 }
1931
1932 // Disable all virtual key touches that happen within a short time interval of the
1933 // most recent touch within the screen area. The idea is to filter out stray
1934 // virtual key presses when interacting with the touch screen.
1935 //
1936 // Problems we're trying to solve:
1937 //
1938 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1939 // virtual key area that is implemented by a separate touch panel and accidentally
1940 // triggers a virtual key.
1941 //
1942 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1943 // area and accidentally triggers a virtual key. This often happens when virtual keys
1944 // are layed out below the screen near to where the on screen keyboard's space bar
1945 // is displayed.
1946 if (mConfig.virtualKeyQuietTime > 0 &&
1947 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001948 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001949 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001950 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001951}
1952
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001953NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1954 uint32_t policyFlags, int32_t keyEventAction,
1955 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001956 int32_t keyCode = mCurrentVirtualKey.keyCode;
1957 int32_t scanCode = mCurrentVirtualKey.scanCode;
1958 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001959 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001960 policyFlags |= POLICY_FLAG_VIRTUAL;
1961
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001962 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1963 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1964 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001965}
1966
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001967std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1968 uint32_t policyFlags) {
1969 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001970 if (mCurrentMotionAborted) {
1971 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001972 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001973 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001974 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1975 if (!currentIdBits.isEmpty()) {
1976 int32_t metaState = getContext()->getGlobalMetaState();
1977 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001978 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001979 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1980 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001981 mCurrentCookedState.cookedPointerData.pointerProperties,
1982 mCurrentCookedState.cookedPointerData.pointerCoords,
1983 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1984 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1985 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001986 mCurrentMotionAborted = true;
1987 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001988 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001989}
1990
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001991// Updates pointer coords and properties for pointers with specified ids that have moved.
1992// Returns true if any of them changed.
1993static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1994 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1995 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1996 BitSet32 idBits) {
1997 bool changed = false;
1998 while (!idBits.isEmpty()) {
1999 uint32_t id = idBits.clearFirstMarkedBit();
2000 uint32_t inIndex = inIdToIndex[id];
2001 uint32_t outIndex = outIdToIndex[id];
2002
2003 const PointerProperties& curInProperties = inProperties[inIndex];
2004 const PointerCoords& curInCoords = inCoords[inIndex];
2005 PointerProperties& curOutProperties = outProperties[outIndex];
2006 PointerCoords& curOutCoords = outCoords[outIndex];
2007
2008 if (curInProperties != curOutProperties) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002009 curOutProperties = curInProperties;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002010 changed = true;
2011 }
2012
2013 if (curInCoords != curOutCoords) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002014 curOutCoords = curInCoords;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002015 changed = true;
2016 }
2017 }
2018 return changed;
2019}
2020
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002021std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
2022 uint32_t policyFlags) {
2023 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002024 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2025 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2026 int32_t metaState = getContext()->getGlobalMetaState();
2027 int32_t buttonState = mCurrentCookedState.buttonState;
2028
2029 if (currentIdBits == lastIdBits) {
2030 if (!currentIdBits.isEmpty()) {
2031 // No pointer id changes so this is a move event.
2032 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002033 out.push_back(
2034 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2035 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2036 mCurrentCookedState.cookedPointerData.pointerProperties,
2037 mCurrentCookedState.cookedPointerData.pointerCoords,
2038 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2039 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2040 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002041 }
2042 } else {
2043 // There may be pointers going up and pointers going down and pointers moving
2044 // all at the same time.
2045 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2046 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2047 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2048 BitSet32 dispatchedIdBits(lastIdBits.value);
2049
2050 // Update last coordinates of pointers that have moved so that we observe the new
2051 // pointer positions at the same time as other pointers that have just gone up.
2052 bool moveNeeded =
2053 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2054 mCurrentCookedState.cookedPointerData.pointerCoords,
2055 mCurrentCookedState.cookedPointerData.idToIndex,
2056 mLastCookedState.cookedPointerData.pointerProperties,
2057 mLastCookedState.cookedPointerData.pointerCoords,
2058 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2059 if (buttonState != mLastCookedState.buttonState) {
2060 moveNeeded = true;
2061 }
2062
2063 // Dispatch pointer up events.
2064 while (!upIdBits.isEmpty()) {
2065 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002066 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002067 if (isCanceled) {
2068 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2069 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002070 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2071 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2072 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2073 buttonState, 0,
2074 mLastCookedState.cookedPointerData.pointerProperties,
2075 mLastCookedState.cookedPointerData.pointerCoords,
2076 mLastCookedState.cookedPointerData.idToIndex,
2077 dispatchedIdBits, upId, mOrientedXPrecision,
2078 mOrientedYPrecision, mDownTime,
2079 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002080 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002081 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002082 }
2083
2084 // Dispatch move events if any of the remaining pointers moved from their old locations.
2085 // Although applications receive new locations as part of individual pointer up
2086 // events, they do not generally handle them except when presented in a move event.
2087 if (moveNeeded && !moveIdBits.isEmpty()) {
2088 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002089 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2090 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2091 mCurrentCookedState.cookedPointerData.pointerProperties,
2092 mCurrentCookedState.cookedPointerData.pointerCoords,
2093 mCurrentCookedState.cookedPointerData.idToIndex,
2094 dispatchedIdBits, -1, mOrientedXPrecision,
2095 mOrientedYPrecision, mDownTime,
2096 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002097 }
2098
2099 // Dispatch pointer down events using the new pointer locations.
2100 while (!downIdBits.isEmpty()) {
2101 uint32_t downId = downIdBits.clearFirstMarkedBit();
2102 dispatchedIdBits.markBit(downId);
2103
2104 if (dispatchedIdBits.count() == 1) {
2105 // First pointer is going down. Set down time.
2106 mDownTime = when;
2107 }
2108
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002109 out.push_back(
2110 dispatchMotion(when, readTime, policyFlags, mSource,
2111 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2112 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2113 mCurrentCookedState.cookedPointerData.pointerCoords,
2114 mCurrentCookedState.cookedPointerData.idToIndex,
2115 dispatchedIdBits, downId, mOrientedXPrecision,
2116 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002117 }
2118 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002119 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002120}
2121
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002122std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2123 uint32_t policyFlags) {
2124 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002125 if (mSentHoverEnter &&
2126 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2127 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2128 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002129 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2130 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2131 mLastCookedState.buttonState, 0,
2132 mLastCookedState.cookedPointerData.pointerProperties,
2133 mLastCookedState.cookedPointerData.pointerCoords,
2134 mLastCookedState.cookedPointerData.idToIndex,
2135 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2136 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2137 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002138 mSentHoverEnter = false;
2139 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002140 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002141}
2142
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002143std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2144 uint32_t policyFlags) {
2145 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002146 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2147 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2148 int32_t metaState = getContext()->getGlobalMetaState();
2149 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002150 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2151 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2152 mCurrentRawState.buttonState, 0,
2153 mCurrentCookedState.cookedPointerData.pointerProperties,
2154 mCurrentCookedState.cookedPointerData.pointerCoords,
2155 mCurrentCookedState.cookedPointerData.idToIndex,
2156 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2157 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2158 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002159 mSentHoverEnter = true;
2160 }
2161
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002162 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2163 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2164 mCurrentRawState.buttonState, 0,
2165 mCurrentCookedState.cookedPointerData.pointerProperties,
2166 mCurrentCookedState.cookedPointerData.pointerCoords,
2167 mCurrentCookedState.cookedPointerData.idToIndex,
2168 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2169 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2170 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002171 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002172 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002173}
2174
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002175std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2176 uint32_t policyFlags) {
2177 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002178 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2179 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2180 const int32_t metaState = getContext()->getGlobalMetaState();
2181 int32_t buttonState = mLastCookedState.buttonState;
2182 while (!releasedButtons.isEmpty()) {
2183 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2184 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002185 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2186 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2187 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002188 mLastCookedState.cookedPointerData.pointerProperties,
2189 mLastCookedState.cookedPointerData.pointerCoords,
2190 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002191 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2192 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002193 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002194 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002195}
2196
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002197std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2198 uint32_t policyFlags) {
2199 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002200 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2201 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2202 const int32_t metaState = getContext()->getGlobalMetaState();
2203 int32_t buttonState = mLastCookedState.buttonState;
2204 while (!pressedButtons.isEmpty()) {
2205 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2206 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002207 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2208 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2209 buttonState, 0,
2210 mCurrentCookedState.cookedPointerData.pointerProperties,
2211 mCurrentCookedState.cookedPointerData.pointerCoords,
2212 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2213 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2214 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002215 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002216 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002217}
2218
LiZhihong758eb562022-11-03 15:28:29 +08002219std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2220 uint32_t policyFlags,
2221 BitSet32 idBits,
2222 nsecs_t readTime) {
2223 std::list<NotifyArgs> out;
2224 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2225 const int32_t metaState = getContext()->getGlobalMetaState();
2226 int32_t buttonState = mLastCookedState.buttonState;
2227
2228 while (!releasedButtons.isEmpty()) {
2229 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2230 buttonState &= ~actionButton;
2231 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2232 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2233 metaState, buttonState, 0,
2234 mPointerGesture.lastGestureProperties,
2235 mPointerGesture.lastGestureCoords,
2236 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2237 mOrientedXPrecision, mOrientedYPrecision,
2238 mPointerGesture.downTime, MotionClassification::NONE));
2239 }
2240 return out;
2241}
2242
2243std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2244 uint32_t policyFlags,
2245 BitSet32 idBits,
2246 nsecs_t readTime) {
2247 std::list<NotifyArgs> out;
2248 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2249 const int32_t metaState = getContext()->getGlobalMetaState();
2250 int32_t buttonState = mLastCookedState.buttonState;
2251
2252 while (!pressedButtons.isEmpty()) {
2253 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2254 buttonState |= actionButton;
2255 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2256 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2257 buttonState, 0, mPointerGesture.currentGestureProperties,
2258 mPointerGesture.currentGestureCoords,
2259 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2260 mOrientedXPrecision, mOrientedYPrecision,
2261 mPointerGesture.downTime, MotionClassification::NONE));
2262 }
2263 return out;
2264}
2265
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002266const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2267 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2268 return cookedPointerData.touchingIdBits;
2269 }
2270 return cookedPointerData.hoveringIdBits;
2271}
2272
2273void TouchInputMapper::cookPointerData() {
2274 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2275
2276 mCurrentCookedState.cookedPointerData.clear();
2277 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2278 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2279 mCurrentRawState.rawPointerData.hoveringIdBits;
2280 mCurrentCookedState.cookedPointerData.touchingIdBits =
2281 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002282 mCurrentCookedState.cookedPointerData.canceledIdBits =
2283 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002284
2285 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2286 mCurrentCookedState.buttonState = 0;
2287 } else {
2288 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2289 }
2290
2291 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002292 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002293 for (uint32_t i = 0; i < currentPointerCount; i++) {
2294 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2295
2296 // Size
2297 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2298 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002299 case Calibration::SizeCalibration::GEOMETRIC:
2300 case Calibration::SizeCalibration::DIAMETER:
2301 case Calibration::SizeCalibration::BOX:
2302 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002303 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2304 touchMajor = in.touchMajor;
2305 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2306 toolMajor = in.toolMajor;
2307 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2308 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2309 : in.touchMajor;
2310 } else if (mRawPointerAxes.touchMajor.valid) {
2311 toolMajor = touchMajor = in.touchMajor;
2312 toolMinor = touchMinor =
2313 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2314 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2315 : in.touchMajor;
2316 } else if (mRawPointerAxes.toolMajor.valid) {
2317 touchMajor = toolMajor = in.toolMajor;
2318 touchMinor = toolMinor =
2319 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2320 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2321 : in.toolMajor;
2322 } else {
2323 ALOG_ASSERT(false,
2324 "No touch or tool axes. "
2325 "Size calibration should have been resolved to NONE.");
2326 touchMajor = 0;
2327 touchMinor = 0;
2328 toolMajor = 0;
2329 toolMinor = 0;
2330 size = 0;
2331 }
2332
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002333 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002334 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2335 if (touchingCount > 1) {
2336 touchMajor /= touchingCount;
2337 touchMinor /= touchingCount;
2338 toolMajor /= touchingCount;
2339 toolMinor /= touchingCount;
2340 size /= touchingCount;
2341 }
2342 }
2343
Michael Wright227c5542020-07-02 18:30:52 +01002344 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002345 touchMajor *= mGeometricScale;
2346 touchMinor *= mGeometricScale;
2347 toolMajor *= mGeometricScale;
2348 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002349 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002350 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2351 touchMinor = touchMajor;
2352 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2353 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002354 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 touchMinor = touchMajor;
2356 toolMinor = toolMajor;
2357 }
2358
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002359 mCalibration.applySizeScaleAndBias(touchMajor);
2360 mCalibration.applySizeScaleAndBias(touchMinor);
2361 mCalibration.applySizeScaleAndBias(toolMajor);
2362 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002363 size *= mSizeScale;
2364 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002365 case Calibration::SizeCalibration::DEFAULT:
2366 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2367 break;
2368 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 touchMajor = 0;
2370 touchMinor = 0;
2371 toolMajor = 0;
2372 toolMinor = 0;
2373 size = 0;
2374 break;
2375 }
2376
2377 // Pressure
2378 float pressure;
2379 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002380 case Calibration::PressureCalibration::PHYSICAL:
2381 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 pressure = in.pressure * mPressureScale;
2383 break;
2384 default:
2385 pressure = in.isHovering ? 0 : 1;
2386 break;
2387 }
2388
2389 // Tilt and Orientation
2390 float tilt;
2391 float orientation;
2392 if (mHaveTilt) {
2393 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2394 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002395 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2397 } else {
2398 tilt = 0;
2399
2400 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002401 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002402 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002403 break;
Michael Wright227c5542020-07-02 18:30:52 +01002404 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2406 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2407 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002408 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409 float confidence = hypotf(c1, c2);
2410 float scale = 1.0f + confidence / 16.0f;
2411 touchMajor *= scale;
2412 touchMinor /= scale;
2413 toolMajor *= scale;
2414 toolMinor /= scale;
2415 } else {
2416 orientation = 0;
2417 }
2418 break;
2419 }
2420 default:
2421 orientation = 0;
2422 }
2423 }
2424
2425 // Distance
2426 float distance;
2427 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002428 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002429 distance = in.distance * mDistanceScale;
2430 break;
2431 default:
2432 distance = 0;
2433 }
2434
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002435 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2436 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002437 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2438 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002439
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 // Write output coords.
2441 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2442 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002443 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2444 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2446 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2447 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2448 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2449 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2450 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2451 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002452 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2453 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002454
Chris Ye364fdb52020-08-05 15:07:56 -07002455 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002456 uint32_t id = in.id;
2457 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2458 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2459 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002460 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2461 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002462 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2463 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2464 }
2465
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 // Write output properties.
2467 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 properties.clear();
2469 properties.id = id;
2470 properties.toolType = in.toolType;
2471
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002472 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002473 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002474 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002475 }
2476}
2477
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002478std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2479 uint32_t policyFlags,
2480 PointerUsage pointerUsage) {
2481 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002482 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002483 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002484 mPointerUsage = pointerUsage;
2485 }
2486
2487 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002488 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002489 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002490 break;
Michael Wright227c5542020-07-02 18:30:52 +01002491 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002492 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002493 break;
Michael Wright227c5542020-07-02 18:30:52 +01002494 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002495 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002496 break;
Michael Wright227c5542020-07-02 18:30:52 +01002497 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002498 break;
2499 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002500 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002501}
2502
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002503std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2504 uint32_t policyFlags) {
2505 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002506 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002507 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002508 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 break;
Michael Wright227c5542020-07-02 18:30:52 +01002510 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002511 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512 break;
Michael Wright227c5542020-07-02 18:30:52 +01002513 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002514 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002515 break;
Michael Wright227c5542020-07-02 18:30:52 +01002516 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002517 break;
2518 }
2519
Michael Wright227c5542020-07-02 18:30:52 +01002520 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002521 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522}
2523
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002524std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2525 uint32_t policyFlags,
2526 bool isTimeout) {
2527 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002528 // Update current gesture coordinates.
2529 bool cancelPreviousGesture, finishPreviousGesture;
2530 bool sendEvents =
2531 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2532 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002533 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 }
2535 if (finishPreviousGesture) {
2536 cancelPreviousGesture = false;
2537 }
2538
2539 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002540 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002541 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002542 if (finishPreviousGesture || cancelPreviousGesture) {
2543 mPointerController->clearSpots();
2544 }
2545
Michael Wright227c5542020-07-02 18:30:52 +01002546 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002547 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2548 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002549 mPointerGesture.currentGestureIdBits,
2550 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002551 }
2552 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002553 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002554 }
2555
2556 // Show or hide the pointer if needed.
2557 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002558 case PointerGesture::Mode::NEUTRAL:
2559 case PointerGesture::Mode::QUIET:
2560 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2561 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002562 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002563 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002564 }
2565 break;
Michael Wright227c5542020-07-02 18:30:52 +01002566 case PointerGesture::Mode::TAP:
2567 case PointerGesture::Mode::TAP_DRAG:
2568 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2569 case PointerGesture::Mode::HOVER:
2570 case PointerGesture::Mode::PRESS:
2571 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002572 // Unfade the pointer when the current gesture manipulates the
2573 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002574 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002575 break;
Michael Wright227c5542020-07-02 18:30:52 +01002576 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002577 // Fade the pointer when the current gesture manipulates a different
2578 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002579 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002580 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002581 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002582 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002583 }
2584 break;
2585 }
2586
2587 // Send events!
2588 int32_t metaState = getContext()->getGlobalMetaState();
2589 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002590 const MotionClassification classification =
2591 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2592 ? MotionClassification::TWO_FINGER_SWIPE
2593 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002594
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002595 uint32_t flags = 0;
2596
2597 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2598 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2599 }
2600
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002601 // Update last coordinates of pointers that have moved so that we observe the new
2602 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002603 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2604 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2605 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2606 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2607 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2608 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002609 bool moveNeeded = false;
2610 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2611 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2612 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2613 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2614 mPointerGesture.lastGestureIdBits.value);
2615 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2616 mPointerGesture.currentGestureCoords,
2617 mPointerGesture.currentGestureIdToIndex,
2618 mPointerGesture.lastGestureProperties,
2619 mPointerGesture.lastGestureCoords,
2620 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2621 if (buttonState != mLastCookedState.buttonState) {
2622 moveNeeded = true;
2623 }
2624 }
2625
2626 // Send motion events for all pointers that went up or were canceled.
2627 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2628 if (!dispatchedGestureIdBits.isEmpty()) {
2629 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002630 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002631 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002632 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002633 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2634 mPointerGesture.lastGestureProperties,
2635 mPointerGesture.lastGestureCoords,
2636 mPointerGesture.lastGestureIdToIndex,
2637 dispatchedGestureIdBits, -1, 0, 0,
2638 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002639
2640 dispatchedGestureIdBits.clear();
2641 } else {
2642 BitSet32 upGestureIdBits;
2643 if (finishPreviousGesture) {
2644 upGestureIdBits = dispatchedGestureIdBits;
2645 } else {
2646 upGestureIdBits.value =
2647 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2648 }
2649 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002650 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2651 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2652 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2653 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2654 readTime);
2655 }
2656 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002657 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2658 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2659 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2660 mPointerGesture.lastGestureProperties,
2661 mPointerGesture.lastGestureCoords,
2662 mPointerGesture.lastGestureIdToIndex,
2663 dispatchedGestureIdBits, id, 0, 0,
2664 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002665
2666 dispatchedGestureIdBits.clearBit(id);
2667 }
2668 }
2669 }
2670
2671 // Send motion events for all pointers that moved.
2672 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002673 out.push_back(
2674 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2675 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2676 mPointerGesture.currentGestureProperties,
2677 mPointerGesture.currentGestureCoords,
2678 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2679 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002680 }
2681
2682 // Send motion events for all pointers that went down.
2683 if (down) {
2684 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2685 ~dispatchedGestureIdBits.value);
2686 while (!downGestureIdBits.isEmpty()) {
2687 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2688 dispatchedGestureIdBits.markBit(id);
2689
2690 if (dispatchedGestureIdBits.count() == 1) {
2691 mPointerGesture.downTime = when;
2692 }
2693
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002694 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2695 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2696 buttonState, 0, mPointerGesture.currentGestureProperties,
2697 mPointerGesture.currentGestureCoords,
2698 mPointerGesture.currentGestureIdToIndex,
2699 dispatchedGestureIdBits, id, 0, 0,
2700 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002701 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2702 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2703 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2704 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2705 readTime);
2706 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002707 }
2708 }
2709
2710 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002711 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002712 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2713 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2714 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2715 mPointerGesture.currentGestureProperties,
2716 mPointerGesture.currentGestureCoords,
2717 mPointerGesture.currentGestureIdToIndex,
2718 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2719 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002720 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2721 // Synthesize a hover move event after all pointers go up to indicate that
2722 // the pointer is hovering again even if the user is not currently touching
2723 // the touch pad. This ensures that a view will receive a fresh hover enter
2724 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002725 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002726
2727 PointerProperties pointerProperties;
2728 pointerProperties.clear();
2729 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002730 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002731
2732 PointerCoords pointerCoords;
2733 pointerCoords.clear();
2734 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2735 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2736
2737 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002738 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2739 mSource, displayId, policyFlags,
2740 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2741 buttonState, MotionClassification::NONE,
2742 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2743 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00002744 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002745 }
2746
2747 // Update state.
2748 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2749 if (!down) {
2750 mPointerGesture.lastGestureIdBits.clear();
2751 } else {
2752 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2753 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2754 uint32_t id = idBits.clearFirstMarkedBit();
2755 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002756 mPointerGesture.lastGestureProperties[index] =
2757 mPointerGesture.currentGestureProperties[index];
2758 mPointerGesture.lastGestureCoords[index] = mPointerGesture.currentGestureCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002759 mPointerGesture.lastGestureIdToIndex[id] = index;
2760 }
2761 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002762 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002763}
2764
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002765std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2766 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002767 const MotionClassification classification =
2768 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2769 ? MotionClassification::TWO_FINGER_SWIPE
2770 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002771 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002772 // Cancel previously dispatches pointers.
2773 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2774 int32_t metaState = getContext()->getGlobalMetaState();
2775 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002776 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002777 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2778 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002779 mPointerGesture.lastGestureProperties,
2780 mPointerGesture.lastGestureCoords,
2781 mPointerGesture.lastGestureIdToIndex,
2782 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2783 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002784 }
2785
2786 // Reset the current pointer gesture.
2787 mPointerGesture.reset();
2788 mPointerVelocityControl.reset();
2789
2790 // Remove any current spots.
2791 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002792 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002793 mPointerController->clearSpots();
2794 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002795 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002796}
2797
2798bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2799 bool* outFinishPreviousGesture, bool isTimeout) {
2800 *outCancelPreviousGesture = false;
2801 *outFinishPreviousGesture = false;
2802
2803 // Handle TAP timeout.
2804 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002805 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806
Michael Wright227c5542020-07-02 18:30:52 +01002807 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002808 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2809 // The tap/drag timeout has not yet expired.
2810 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2811 mConfig.pointerGestureTapDragInterval);
2812 } else {
2813 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002814 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002815 *outFinishPreviousGesture = true;
2816
2817 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002818 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002819 mPointerGesture.currentGestureIdBits.clear();
2820
2821 mPointerVelocityControl.reset();
2822 return true;
2823 }
2824 }
2825
2826 // We did not handle this timeout.
2827 return false;
2828 }
2829
2830 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2831 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2832
2833 // Update the velocity tracker.
2834 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002835 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002836 uint32_t id = idBits.clearFirstMarkedBit();
2837 const RawPointerData::Pointer& pointer =
2838 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002839 const float x = pointer.x * mPointerXMovementScale;
2840 const float y = pointer.y * mPointerYMovementScale;
2841 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2842 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002843 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002844 }
2845
2846 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2847 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002848 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2849 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2850 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002851 mPointerGesture.resetTap();
2852 }
2853
2854 // Pick a new active touch id if needed.
2855 // Choose an arbitrary pointer that just went down, if there is one.
2856 // Otherwise choose an arbitrary remaining pointer.
2857 // This guarantees we always have an active touch id when there is at least one pointer.
2858 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002859 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002860 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002861 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002862 mPointerGesture.firstTouchTime = when;
2863 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002864 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2865 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2866 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2867 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002868 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002869 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002870
2871 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002872 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002873 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002874 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2875 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2876 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002877 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002878 *outFinishPreviousGesture = true;
2879 }
2880
2881 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002882 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002883 mPointerGesture.currentGestureIdBits.clear();
2884
2885 mPointerVelocityControl.reset();
2886 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2887 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2888 // The pointer follows the active touch point.
2889 // Emit DOWN, MOVE, UP events at the pointer location.
2890 //
2891 // Only the active touch matters; other fingers are ignored. This policy helps
2892 // to handle the case where the user places a second finger on the touch pad
2893 // to apply the necessary force to depress an integrated button below the surface.
2894 // We don't want the second finger to be delivered to applications.
2895 //
2896 // For this to work well, we need to make sure to track the pointer that is really
2897 // active. If the user first puts one finger down to click then adds another
2898 // finger to drag then the active pointer should switch to the finger that is
2899 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002900 ALOGD_IF(DEBUG_GESTURES,
2901 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2902 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002903 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002904 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002905 *outFinishPreviousGesture = true;
2906 mPointerGesture.activeGestureId = 0;
2907 }
2908
2909 // Switch pointers if needed.
2910 // Find the fastest pointer and follow it.
2911 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002912 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002913 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002914 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002915 ALOGD_IF(DEBUG_GESTURES,
2916 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2917 "bestSpeed=%0.3f",
2918 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 }
2920 }
2921
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002923 // When using spots, the click will occur at the position of the anchor
2924 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002925 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002926 } else {
2927 mPointerVelocityControl.reset();
2928 }
2929
Prabir Pradhan2719e822023-02-28 17:39:36 +00002930 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002931
Michael Wright227c5542020-07-02 18:30:52 +01002932 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002933 mPointerGesture.currentGestureIdBits.clear();
2934 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2935 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2936 mPointerGesture.currentGestureProperties[0].clear();
2937 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002938 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002939 mPointerGesture.currentGestureCoords[0].clear();
2940 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2941 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2942 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2943 } else if (currentFingerCount == 0) {
2944 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002945 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002946 *outFinishPreviousGesture = true;
2947 }
2948
2949 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2950 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2951 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002952 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2953 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002954 lastFingerCount == 1) {
2955 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002956 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002957 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2958 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002959 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002960
2961 mPointerGesture.tapUpTime = when;
2962 getContext()->requestTimeoutAtTime(when +
2963 mConfig.pointerGestureTapDragInterval);
2964
2965 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002966 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002967 mPointerGesture.currentGestureIdBits.clear();
2968 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2969 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2970 mPointerGesture.currentGestureProperties[0].clear();
2971 mPointerGesture.currentGestureProperties[0].id =
2972 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002973 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002974 mPointerGesture.currentGestureCoords[0].clear();
2975 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2976 mPointerGesture.tapX);
2977 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2978 mPointerGesture.tapY);
2979 mPointerGesture.currentGestureCoords[0]
2980 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2981
2982 tapped = true;
2983 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002984 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2985 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002986 }
2987 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002988 if (DEBUG_GESTURES) {
2989 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2990 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2991 (when - mPointerGesture.tapDownTime) * 0.000001f);
2992 } else {
2993 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2994 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002995 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002996 }
2997 }
2998
2999 mPointerVelocityControl.reset();
3000
3001 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00003002 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01003004 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003005 mPointerGesture.currentGestureIdBits.clear();
3006 }
3007 } else if (currentFingerCount == 1) {
3008 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3009 // The pointer follows the active touch point.
3010 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3011 // When in TAP_DRAG, emit MOVE events at the pointer location.
3012 ALOG_ASSERT(activeTouchId >= 0);
3013
Michael Wright227c5542020-07-02 18:30:52 +01003014 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3015 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003016 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003017 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003018 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3019 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003020 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003021 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003022 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3023 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003024 }
3025 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003026 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3027 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003028 }
Michael Wright227c5542020-07-02 18:30:52 +01003029 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3030 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003031 }
3032
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003033 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003034 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003035 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003036 } else {
3037 mPointerVelocityControl.reset();
3038 }
3039
3040 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003041 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003042 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003043 down = true;
3044 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003045 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003046 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003047 *outFinishPreviousGesture = true;
3048 }
3049 mPointerGesture.activeGestureId = 0;
3050 down = false;
3051 }
3052
Prabir Pradhan2719e822023-02-28 17:39:36 +00003053 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003054
3055 mPointerGesture.currentGestureIdBits.clear();
3056 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3057 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3058 mPointerGesture.currentGestureProperties[0].clear();
3059 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003060 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003061 mPointerGesture.currentGestureCoords[0].clear();
3062 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3063 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3064 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3065 down ? 1.0f : 0.0f);
3066
3067 if (lastFingerCount == 0 && currentFingerCount != 0) {
3068 mPointerGesture.resetTap();
3069 mPointerGesture.tapDownTime = when;
3070 mPointerGesture.tapX = x;
3071 mPointerGesture.tapY = y;
3072 }
3073 } else {
3074 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003075 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003076 }
3077
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003078 if (DEBUG_GESTURES) {
3079 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3080 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3081 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3082 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3083 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3084 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3085 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3086 uint32_t id = idBits.clearFirstMarkedBit();
3087 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3088 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3089 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003090 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003091 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003092 id, index, ftl::enum_string(properties.toolType).c_str(),
3093 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003094 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3095 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3096 }
3097 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3098 uint32_t id = idBits.clearFirstMarkedBit();
3099 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3100 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3101 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003102 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003103 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003104 id, index, ftl::enum_string(properties.toolType).c_str(),
3105 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003106 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3107 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3108 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003109 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003110 return true;
3111}
3112
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003113bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3114 if (mPointerGesture.activeTouchId < 0) {
3115 mPointerGesture.resetQuietTime();
3116 return false;
3117 }
3118
3119 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3120 return true;
3121 }
3122
3123 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3124 bool isQuietTime = false;
3125 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3126 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3127 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3128 currentFingerCount < 2) {
3129 // Enter quiet time when exiting swipe or freeform state.
3130 // This is to prevent accidentally entering the hover state and flinging the
3131 // pointer when finishing a swipe and there is still one pointer left onscreen.
3132 isQuietTime = true;
3133 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3134 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3135 // Enter quiet time when releasing the button and there are still two or more
3136 // fingers down. This may indicate that one finger was used to press the button
3137 // but it has not gone up yet.
3138 isQuietTime = true;
3139 }
3140 if (isQuietTime) {
3141 mPointerGesture.quietTime = when;
3142 }
3143 return isQuietTime;
3144}
3145
3146std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3147 int32_t bestId = -1;
3148 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3149 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3150 uint32_t id = idBits.clearFirstMarkedBit();
3151 std::optional<float> vx =
3152 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3153 std::optional<float> vy =
3154 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3155 if (vx && vy) {
3156 float speed = hypotf(*vx, *vy);
3157 if (speed > bestSpeed) {
3158 bestId = id;
3159 bestSpeed = speed;
3160 }
3161 }
3162 }
3163 return std::make_pair(bestId, bestSpeed);
3164}
3165
3166void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3167 bool* finishPreviousGesture) {
3168 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3169 // to move before deciding what to do.
3170 //
3171 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3172 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3173 // just a press or long-press at the pointer location.
3174 //
3175 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3176 // pointer location.
3177 //
3178 // When the two fingers move enough or when additional fingers are added, we make a decision to
3179 // transition into SWIPE or FREEFORM mode accordingly.
3180 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3181 ALOG_ASSERT(activeTouchId >= 0);
3182
3183 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3184 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3185 bool settled =
3186 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3187 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3188 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3189 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3190 *finishPreviousGesture = true;
3191 } else if (!settled && currentFingerCount > lastFingerCount) {
3192 // Additional pointers have gone down but not yet settled.
3193 // Reset the gesture.
3194 ALOGD_IF(DEBUG_GESTURES,
3195 "Gestures: Resetting gesture since additional pointers went down for "
3196 "MULTITOUCH, settle time remaining %0.3fms",
3197 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3198 when) * 0.000001f);
3199 *cancelPreviousGesture = true;
3200 } else {
3201 // Continue previous gesture.
3202 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3203 }
3204
3205 if (*finishPreviousGesture || *cancelPreviousGesture) {
3206 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3207 mPointerGesture.activeGestureId = 0;
3208 mPointerGesture.referenceIdBits.clear();
3209 mPointerVelocityControl.reset();
3210
3211 // Use the centroid and pointer location as the reference points for the gesture.
3212 ALOGD_IF(DEBUG_GESTURES,
3213 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3214 "%0.3fms",
3215 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3216 when) * 0.000001f);
3217 mCurrentRawState.rawPointerData
3218 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3219 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003220 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3221 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003222 }
3223
3224 // Clear the reference deltas for fingers not yet included in the reference calculation.
3225 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3226 ~mPointerGesture.referenceIdBits.value);
3227 !idBits.isEmpty();) {
3228 uint32_t id = idBits.clearFirstMarkedBit();
3229 mPointerGesture.referenceDeltas[id].dx = 0;
3230 mPointerGesture.referenceDeltas[id].dy = 0;
3231 }
3232 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3233
3234 // Add delta for all fingers and calculate a common movement delta.
3235 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3236 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3237 mCurrentCookedState.fingerIdBits.value);
3238 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3239 bool first = (idBits == commonIdBits);
3240 uint32_t id = idBits.clearFirstMarkedBit();
3241 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3242 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3243 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3244 delta.dx += cpd.x - lpd.x;
3245 delta.dy += cpd.y - lpd.y;
3246
3247 if (first) {
3248 commonDeltaRawX = delta.dx;
3249 commonDeltaRawY = delta.dy;
3250 } else {
3251 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3252 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3253 }
3254 }
3255
3256 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3257 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3258 float dist[MAX_POINTER_ID + 1];
3259 int32_t distOverThreshold = 0;
3260 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3261 uint32_t id = idBits.clearFirstMarkedBit();
3262 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3263 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3264 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3265 distOverThreshold += 1;
3266 }
3267 }
3268
3269 // Only transition when at least two pointers have moved further than
3270 // the minimum distance threshold.
3271 if (distOverThreshold >= 2) {
3272 if (currentFingerCount > 2) {
3273 // There are more than two pointers, switch to FREEFORM.
3274 ALOGD_IF(DEBUG_GESTURES,
3275 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3276 currentFingerCount);
3277 *cancelPreviousGesture = true;
3278 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3279 } else {
3280 // There are exactly two pointers.
3281 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3282 uint32_t id1 = idBits.clearFirstMarkedBit();
3283 uint32_t id2 = idBits.firstMarkedBit();
3284 const RawPointerData::Pointer& p1 =
3285 mCurrentRawState.rawPointerData.pointerForId(id1);
3286 const RawPointerData::Pointer& p2 =
3287 mCurrentRawState.rawPointerData.pointerForId(id2);
3288 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3289 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3290 // There are two pointers but they are too far apart for a SWIPE,
3291 // switch to FREEFORM.
3292 ALOGD_IF(DEBUG_GESTURES,
3293 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3294 mutualDistance, mPointerGestureMaxSwipeWidth);
3295 *cancelPreviousGesture = true;
3296 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3297 } else {
3298 // There are two pointers. Wait for both pointers to start moving
3299 // before deciding whether this is a SWIPE or FREEFORM gesture.
3300 float dist1 = dist[id1];
3301 float dist2 = dist[id2];
3302 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3303 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3304 // Calculate the dot product of the displacement vectors.
3305 // When the vectors are oriented in approximately the same direction,
3306 // the angle betweeen them is near zero and the cosine of the angle
3307 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3308 // mag(v2).
3309 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3310 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3311 float dx1 = delta1.dx * mPointerXZoomScale;
3312 float dy1 = delta1.dy * mPointerYZoomScale;
3313 float dx2 = delta2.dx * mPointerXZoomScale;
3314 float dy2 = delta2.dy * mPointerYZoomScale;
3315 float dot = dx1 * dx2 + dy1 * dy2;
3316 float cosine = dot / (dist1 * dist2); // denominator always > 0
3317 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3318 // Pointers are moving in the same direction. Switch to SWIPE.
3319 ALOGD_IF(DEBUG_GESTURES,
3320 "Gestures: PRESS transitioned to SWIPE, "
3321 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3322 "cosine %0.3f >= %0.3f",
3323 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3324 mConfig.pointerGestureMultitouchMinDistance, cosine,
3325 mConfig.pointerGestureSwipeTransitionAngleCosine);
3326 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3327 } else {
3328 // Pointers are moving in different directions. Switch to FREEFORM.
3329 ALOGD_IF(DEBUG_GESTURES,
3330 "Gestures: PRESS transitioned to FREEFORM, "
3331 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3332 "cosine %0.3f < %0.3f",
3333 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3334 mConfig.pointerGestureMultitouchMinDistance, cosine,
3335 mConfig.pointerGestureSwipeTransitionAngleCosine);
3336 *cancelPreviousGesture = true;
3337 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3338 }
3339 }
3340 }
3341 }
3342 }
3343 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3344 // Switch from SWIPE to FREEFORM if additional pointers go down.
3345 // Cancel previous gesture.
3346 if (currentFingerCount > 2) {
3347 ALOGD_IF(DEBUG_GESTURES,
3348 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3349 currentFingerCount);
3350 *cancelPreviousGesture = true;
3351 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3352 }
3353 }
3354
3355 // Move the reference points based on the overall group motion of the fingers
3356 // except in PRESS mode while waiting for a transition to occur.
3357 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3358 (commonDeltaRawX || commonDeltaRawY)) {
3359 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3360 uint32_t id = idBits.clearFirstMarkedBit();
3361 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3362 delta.dx = 0;
3363 delta.dy = 0;
3364 }
3365
3366 mPointerGesture.referenceTouchX += commonDeltaRawX;
3367 mPointerGesture.referenceTouchY += commonDeltaRawY;
3368
3369 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3370 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3371
3372 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3373 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3374
3375 mPointerGesture.referenceGestureX += commonDeltaX;
3376 mPointerGesture.referenceGestureY += commonDeltaY;
3377 }
3378
3379 // Report gestures.
3380 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3381 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3382 // PRESS or SWIPE mode.
3383 ALOGD_IF(DEBUG_GESTURES,
3384 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3385 "currentTouchPointerCount=%d",
3386 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3387 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3388
3389 mPointerGesture.currentGestureIdBits.clear();
3390 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3391 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3392 mPointerGesture.currentGestureProperties[0].clear();
3393 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003394 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003395 mPointerGesture.currentGestureCoords[0].clear();
3396 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3397 mPointerGesture.referenceGestureX);
3398 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3399 mPointerGesture.referenceGestureY);
3400 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3401 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3402 float xOffset = static_cast<float>(commonDeltaRawX) /
3403 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3404 float yOffset = static_cast<float>(commonDeltaRawY) /
3405 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3406 mPointerGesture.currentGestureCoords[0]
3407 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3408 mPointerGesture.currentGestureCoords[0]
3409 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3410 }
3411 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3412 // FREEFORM mode.
3413 ALOGD_IF(DEBUG_GESTURES,
3414 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3415 "currentTouchPointerCount=%d",
3416 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3417 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3418
3419 mPointerGesture.currentGestureIdBits.clear();
3420
3421 BitSet32 mappedTouchIdBits;
3422 BitSet32 usedGestureIdBits;
3423 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3424 // Initially, assign the active gesture id to the active touch point
3425 // if there is one. No other touch id bits are mapped yet.
3426 if (!*cancelPreviousGesture) {
3427 mappedTouchIdBits.markBit(activeTouchId);
3428 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3429 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3430 mPointerGesture.activeGestureId;
3431 } else {
3432 mPointerGesture.activeGestureId = -1;
3433 }
3434 } else {
3435 // Otherwise, assume we mapped all touches from the previous frame.
3436 // Reuse all mappings that are still applicable.
3437 mappedTouchIdBits.value =
3438 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3439 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3440
3441 // Check whether we need to choose a new active gesture id because the
3442 // current went went up.
3443 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3444 ~mCurrentCookedState.fingerIdBits.value);
3445 !upTouchIdBits.isEmpty();) {
3446 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3447 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3448 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3449 mPointerGesture.activeGestureId = -1;
3450 break;
3451 }
3452 }
3453 }
3454
3455 ALOGD_IF(DEBUG_GESTURES,
3456 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3457 "activeGestureId=%d",
3458 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3459
3460 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3461 for (uint32_t i = 0; i < currentFingerCount; i++) {
3462 uint32_t touchId = idBits.clearFirstMarkedBit();
3463 uint32_t gestureId;
3464 if (!mappedTouchIdBits.hasBit(touchId)) {
3465 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3466 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3467 ALOGD_IF(DEBUG_GESTURES,
3468 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3469 gestureId);
3470 } else {
3471 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3472 ALOGD_IF(DEBUG_GESTURES,
3473 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3474 touchId, gestureId);
3475 }
3476 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3477 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3478
3479 const RawPointerData::Pointer& pointer =
3480 mCurrentRawState.rawPointerData.pointerForId(touchId);
3481 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3482 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3483 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3484
3485 mPointerGesture.currentGestureProperties[i].clear();
3486 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003487 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003488 mPointerGesture.currentGestureCoords[i].clear();
3489 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3490 mPointerGesture.referenceGestureX +
3491 deltaX);
3492 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3493 mPointerGesture.referenceGestureY +
3494 deltaY);
3495 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3496 }
3497
3498 if (mPointerGesture.activeGestureId < 0) {
3499 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3500 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3501 mPointerGesture.activeGestureId);
3502 }
3503 }
3504}
3505
Harry Cutts714d1ad2022-08-24 16:36:43 +00003506void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3507 const RawPointerData::Pointer& currentPointer =
3508 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3509 const RawPointerData::Pointer& lastPointer =
3510 mLastRawState.rawPointerData.pointerForId(pointerId);
3511 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3512 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3513
3514 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3515 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3516
3517 mPointerController->move(deltaX, deltaY);
3518}
3519
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003520std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3521 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003522 mPointerSimple.currentCoords.clear();
3523 mPointerSimple.currentProperties.clear();
3524
3525 bool down, hovering;
3526 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3527 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3528 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003529 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3530 down = !hovering;
3531
Prabir Pradhane71e5702023-03-29 14:51:38 +00003532 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3533 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3534 // Styluses are configured specifically for one display. We only update the
3535 // PointerController for this stylus if the PointerController is configured for
3536 // the same display as this stylus,
3537 if (getAssociatedDisplayId() == mViewport.displayId) {
3538 mPointerController->setPosition(x, y);
3539 std::tie(x, y) = mPointerController->getPosition();
3540 }
3541
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003542 mPointerSimple.currentCoords = mCurrentCookedState.cookedPointerData.pointerCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003543 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3544 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3545 mPointerSimple.currentProperties.id = 0;
3546 mPointerSimple.currentProperties.toolType =
3547 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3548 } else {
3549 down = false;
3550 hovering = false;
3551 }
3552
Prabir Pradhane71e5702023-03-29 14:51:38 +00003553 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003554}
3555
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003556std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3557 uint32_t policyFlags) {
3558 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003559}
3560
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003561std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3562 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003563 mPointerSimple.currentCoords.clear();
3564 mPointerSimple.currentProperties.clear();
3565
3566 bool down, hovering;
3567 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3568 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003569 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003570 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003571 } else {
3572 mPointerVelocityControl.reset();
3573 }
3574
3575 down = isPointerDown(mCurrentRawState.buttonState);
3576 hovering = !down;
3577
Prabir Pradhan2719e822023-02-28 17:39:36 +00003578 const auto [x, y] = mPointerController->getPosition();
3579 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003580 mPointerSimple.currentCoords =
3581 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003582 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3583 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3584 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3585 hovering ? 0.0f : 1.0f);
3586 mPointerSimple.currentProperties.id = 0;
3587 mPointerSimple.currentProperties.toolType =
3588 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3589 } else {
3590 mPointerVelocityControl.reset();
3591
3592 down = false;
3593 hovering = false;
3594 }
3595
Prabir Pradhane71e5702023-03-29 14:51:38 +00003596 const int32_t displayId = mPointerController->getDisplayId();
3597 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598}
3599
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003600std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3601 uint32_t policyFlags) {
3602 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003603
3604 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003605
3606 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003607}
3608
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003609std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3610 uint32_t policyFlags, bool down,
Prabir Pradhane71e5702023-03-29 14:51:38 +00003611 bool hovering, int32_t displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003612 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3613 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003614 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003615 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003616 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003617
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003618 if (displayId == mPointerController->getDisplayId()) {
3619 std::tie(cursorPosition.x, cursorPosition.y) = mPointerController->getPosition();
3620 if (down || hovering) {
3621 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
3622 mPointerController->clearSpots();
3623 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3624 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
3625 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3626 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003627 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003628
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003629 if (mPointerSimple.down && !down) {
3630 mPointerSimple.down = false;
3631
3632 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003633 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3634 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3635 0, metaState, mLastRawState.buttonState,
3636 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3637 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003638 mOrientedXPrecision, mOrientedYPrecision,
3639 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3640 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003641 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003642 }
3643
3644 if (mPointerSimple.hovering && !hovering) {
3645 mPointerSimple.hovering = false;
3646
3647 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003648 out.push_back(
3649 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3650 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3651 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3652 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3653 &mPointerSimple.lastCoords, mOrientedXPrecision,
3654 mOrientedYPrecision, mPointerSimple.lastCursorX,
3655 mPointerSimple.lastCursorY, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003656 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003657 }
3658
3659 if (down) {
3660 if (!mPointerSimple.down) {
3661 mPointerSimple.down = true;
3662 mPointerSimple.downTime = when;
3663
3664 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003665 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3666 mSource, displayId, policyFlags,
3667 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3668 mCurrentRawState.buttonState, MotionClassification::NONE,
3669 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3670 &mPointerSimple.currentProperties,
3671 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003672 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003673 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003674 }
3675
3676 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003677 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3678 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3679 0, 0, metaState, mCurrentRawState.buttonState,
3680 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3681 &mPointerSimple.currentProperties,
3682 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003683 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003684 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003685 }
3686
3687 if (hovering) {
3688 if (!mPointerSimple.hovering) {
3689 mPointerSimple.hovering = true;
3690
3691 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003692 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3693 mSource, displayId, policyFlags,
3694 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3695 mCurrentRawState.buttonState, MotionClassification::NONE,
3696 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3697 &mPointerSimple.currentProperties,
3698 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003699 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003700 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003701 }
3702
3703 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003704 out.push_back(
3705 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3706 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3707 metaState, mCurrentRawState.buttonState,
3708 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3709 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003710 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003711 cursorPosition.y, mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003712 }
3713
3714 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3715 float vscroll = mCurrentRawState.rawVScroll;
3716 float hscroll = mCurrentRawState.rawHScroll;
3717 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3718 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3719
3720 // Send scroll.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003721 PointerCoords pointerCoords = mPointerSimple.currentCoords;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003722 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3723 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3724
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003725 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3726 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3727 0, 0, metaState, mCurrentRawState.buttonState,
3728 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3729 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003730 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3731 cursorPosition.y, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003732 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003733 }
3734
3735 // Save state.
3736 if (down || hovering) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003737 mPointerSimple.lastCoords = mPointerSimple.currentCoords;
3738 mPointerSimple.lastProperties = mPointerSimple.currentProperties;
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003739 mPointerSimple.displayId = displayId;
3740 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003741 mPointerSimple.lastCursorX = cursorPosition.x;
3742 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003743 } else {
3744 mPointerSimple.reset();
3745 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003746 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003747}
3748
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003749std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3750 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003751 std::list<NotifyArgs> out;
3752 if (mPointerSimple.down || mPointerSimple.hovering) {
3753 int32_t metaState = getContext()->getGlobalMetaState();
3754 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3755 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3756 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3757 metaState, mLastRawState.buttonState,
3758 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3759 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3760 mOrientedXPrecision, mOrientedYPrecision,
3761 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3762 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003763 /*videoFrames=*/{}));
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003764 if (mPointerController != nullptr) {
3765 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3766 }
3767 }
3768 mPointerSimple.reset();
3769 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003770}
3771
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003772NotifyMotionArgs TouchInputMapper::dispatchMotion(
3773 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3774 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003775 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3776 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003777 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003778 std::vector<PointerCoords> pointerCoords;
3779 std::vector<PointerProperties> pointerProperties;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003780 uint32_t pointerCount = 0;
3781 while (!idBits.isEmpty()) {
3782 uint32_t id = idBits.clearFirstMarkedBit();
3783 uint32_t index = idToIndex[id];
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003784 pointerProperties.push_back(properties[index]);
3785 pointerCoords.push_back(coords[index]);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003786
3787 if (changedId >= 0 && id == uint32_t(changedId)) {
3788 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3789 }
3790
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003791 pointerCount++;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003792 }
3793
3794 ALOG_ASSERT(pointerCount != 0);
3795
3796 if (changedId >= 0 && pointerCount == 1) {
3797 // Replace initial down and final up action.
3798 // We can compare the action without masking off the changed pointer index
3799 // because we know the index is 0.
3800 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3801 action = AMOTION_EVENT_ACTION_DOWN;
3802 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003803 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3804 action = AMOTION_EVENT_ACTION_CANCEL;
3805 } else {
3806 action = AMOTION_EVENT_ACTION_UP;
3807 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003808 } else {
3809 // Can't happen.
3810 ALOG_ASSERT(false);
3811 }
3812 }
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00003813 if (mCurrentStreamModifiedByExternalStylus) {
3814 source |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3815 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003816
3817 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3818 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003819 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003820 mPointerController && displayId != ADISPLAY_ID_NONE &&
3821 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003822 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003823 switch (action & AMOTION_EVENT_ACTION_MASK) {
3824 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3825 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3826 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003827 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003828 mPointerController
3829 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3830 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3831 .getY());
3832 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3833 break;
3834 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3835 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3836 break;
3837 }
3838 }
3839
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003840 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3841 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003842 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003843 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003844 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003845 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003846 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003847 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003848 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003849 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3850 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003851 classification, edgeFlags, pointerCount, pointerProperties.data(),
3852 pointerCoords.data(), xPrecision, yPrecision, xCursorPosition,
3853 yCursorPosition, downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003854}
3855
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003856std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3857 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003858 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3859 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003860 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003861}
3862
Prabir Pradhan1728b212021-10-19 16:00:03 -07003863bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003864 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003865 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003866 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003867}
3868
3869const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3870 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003871 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3872 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3873 "left=%d, top=%d, right=%d, bottom=%d",
3874 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3875 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003876
3877 if (virtualKey.isHit(x, y)) {
3878 return &virtualKey;
3879 }
3880 }
3881
3882 return nullptr;
3883}
3884
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003885void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3886 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3887 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003888
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003889 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003890
3891 if (currentPointerCount == 0) {
3892 // No pointers to assign.
3893 return;
3894 }
3895
3896 if (lastPointerCount == 0) {
3897 // All pointers are new.
3898 for (uint32_t i = 0; i < currentPointerCount; i++) {
3899 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003900 current.rawPointerData.pointers[i].id = id;
3901 current.rawPointerData.idToIndex[id] = i;
3902 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003903 }
3904 return;
3905 }
3906
3907 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003908 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003909 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003910 uint32_t id = last.rawPointerData.pointers[0].id;
3911 current.rawPointerData.pointers[0].id = id;
3912 current.rawPointerData.idToIndex[id] = 0;
3913 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003914 return;
3915 }
3916
3917 // General case.
3918 // We build a heap of squared euclidean distances between current and last pointers
3919 // associated with the current and last pointer indices. Then, we find the best
3920 // match (by distance) for each current pointer.
3921 // The pointers must have the same tool type but it is possible for them to
3922 // transition from hovering to touching or vice-versa while retaining the same id.
3923 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3924
3925 uint32_t heapSize = 0;
3926 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3927 currentPointerIndex++) {
3928 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3929 lastPointerIndex++) {
3930 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003931 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003932 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003933 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003934 if (currentPointer.toolType == lastPointer.toolType) {
3935 int64_t deltaX = currentPointer.x - lastPointer.x;
3936 int64_t deltaY = currentPointer.y - lastPointer.y;
3937
3938 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3939
3940 // Insert new element into the heap (sift up).
3941 heap[heapSize].currentPointerIndex = currentPointerIndex;
3942 heap[heapSize].lastPointerIndex = lastPointerIndex;
3943 heap[heapSize].distance = distance;
3944 heapSize += 1;
3945 }
3946 }
3947 }
3948
3949 // Heapify
3950 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3951 startIndex -= 1;
3952 for (uint32_t parentIndex = startIndex;;) {
3953 uint32_t childIndex = parentIndex * 2 + 1;
3954 if (childIndex >= heapSize) {
3955 break;
3956 }
3957
3958 if (childIndex + 1 < heapSize &&
3959 heap[childIndex + 1].distance < heap[childIndex].distance) {
3960 childIndex += 1;
3961 }
3962
3963 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3964 break;
3965 }
3966
3967 swap(heap[parentIndex], heap[childIndex]);
3968 parentIndex = childIndex;
3969 }
3970 }
3971
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003972 if (DEBUG_POINTER_ASSIGNMENT) {
3973 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3974 for (size_t i = 0; i < heapSize; i++) {
3975 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3976 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3977 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003978 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003979
3980 // Pull matches out by increasing order of distance.
3981 // To avoid reassigning pointers that have already been matched, the loop keeps track
3982 // of which last and current pointers have been matched using the matchedXXXBits variables.
3983 // It also tracks the used pointer id bits.
3984 BitSet32 matchedLastBits(0);
3985 BitSet32 matchedCurrentBits(0);
3986 BitSet32 usedIdBits(0);
3987 bool first = true;
3988 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3989 while (heapSize > 0) {
3990 if (first) {
3991 // The first time through the loop, we just consume the root element of
3992 // the heap (the one with smallest distance).
3993 first = false;
3994 } else {
3995 // Previous iterations consumed the root element of the heap.
3996 // Pop root element off of the heap (sift down).
3997 heap[0] = heap[heapSize];
3998 for (uint32_t parentIndex = 0;;) {
3999 uint32_t childIndex = parentIndex * 2 + 1;
4000 if (childIndex >= heapSize) {
4001 break;
4002 }
4003
4004 if (childIndex + 1 < heapSize &&
4005 heap[childIndex + 1].distance < heap[childIndex].distance) {
4006 childIndex += 1;
4007 }
4008
4009 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4010 break;
4011 }
4012
4013 swap(heap[parentIndex], heap[childIndex]);
4014 parentIndex = childIndex;
4015 }
4016
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004017 if (DEBUG_POINTER_ASSIGNMENT) {
4018 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4019 for (size_t j = 0; j < heapSize; j++) {
4020 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4021 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4022 heap[j].distance);
4023 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004024 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004025 }
4026
4027 heapSize -= 1;
4028
4029 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4030 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4031
4032 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4033 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4034
4035 matchedCurrentBits.markBit(currentPointerIndex);
4036 matchedLastBits.markBit(lastPointerIndex);
4037
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004038 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4039 current.rawPointerData.pointers[currentPointerIndex].id = id;
4040 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4041 current.rawPointerData.markIdBit(id,
4042 current.rawPointerData.isHovering(
4043 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004044 usedIdBits.markBit(id);
4045
Harry Cutts45483602022-08-24 14:36:48 +00004046 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4047 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4048 ", distance=%" PRIu64,
4049 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004050 break;
4051 }
4052 }
4053
4054 // Assign fresh ids to pointers that were not matched in the process.
4055 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4056 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4057 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4058
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004059 current.rawPointerData.pointers[currentPointerIndex].id = id;
4060 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4061 current.rawPointerData.markIdBit(id,
4062 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004063
Harry Cutts45483602022-08-24 14:36:48 +00004064 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4065 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4066 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004067 }
4068}
4069
4070int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4071 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4072 return AKEY_STATE_VIRTUAL;
4073 }
4074
4075 for (const VirtualKey& virtualKey : mVirtualKeys) {
4076 if (virtualKey.keyCode == keyCode) {
4077 return AKEY_STATE_UP;
4078 }
4079 }
4080
4081 return AKEY_STATE_UNKNOWN;
4082}
4083
4084int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4085 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4086 return AKEY_STATE_VIRTUAL;
4087 }
4088
4089 for (const VirtualKey& virtualKey : mVirtualKeys) {
4090 if (virtualKey.scanCode == scanCode) {
4091 return AKEY_STATE_UP;
4092 }
4093 }
4094
4095 return AKEY_STATE_UNKNOWN;
4096}
4097
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004098bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4099 const std::vector<int32_t>& keyCodes,
4100 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004101 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004102 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004103 if (virtualKey.keyCode == keyCodes[i]) {
4104 outFlags[i] = 1;
4105 }
4106 }
4107 }
4108
4109 return true;
4110}
4111
4112std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4113 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004114 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004115 return std::make_optional(mPointerController->getDisplayId());
4116 } else {
4117 return std::make_optional(mViewport.displayId);
4118 }
4119 }
4120 return std::nullopt;
4121}
4122
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004123} // namespace android