blob: d09bc6590f27d1dc632a89e3119e9ef39cbc9205 [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),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700128 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100129 mDeviceMode(DeviceMode::DISABLED),
Michael Wrighta9cf4192022-12-01 23:46:39 +0000130 mInputDeviceOrientation(ui::ROTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700131
132TouchInputMapper::~TouchInputMapper() {}
133
Philip Junker4af3b3d2021-12-14 10:36:55 +0100134uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700135 return mSource;
136}
137
Harry Cuttsd02ea102023-03-17 18:21:30 +0000138void TouchInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700139 InputMapper::populateDeviceInfo(info);
140
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000141 if (mDeviceMode == DeviceMode::DISABLED) {
142 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700143 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000144
Harry Cuttsd02ea102023-03-17 18:21:30 +0000145 info.addMotionRange(mOrientedRanges.x);
146 info.addMotionRange(mOrientedRanges.y);
147 info.addMotionRange(mOrientedRanges.pressure);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000148
149 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
150 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
151 //
152 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
153 // motion, i.e. the hardware dimensions, as the finger could move completely across the
154 // touchpad in one sample cycle.
155 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
156 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
Harry Cuttsd02ea102023-03-17 18:21:30 +0000157 info.addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
158 x.resolution);
159 info.addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
160 y.resolution);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000161 }
162
163 if (mOrientedRanges.size) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000164 info.addMotionRange(*mOrientedRanges.size);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000165 }
166
167 if (mOrientedRanges.touchMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000168 info.addMotionRange(*mOrientedRanges.touchMajor);
169 info.addMotionRange(*mOrientedRanges.touchMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000170 }
171
172 if (mOrientedRanges.toolMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000173 info.addMotionRange(*mOrientedRanges.toolMajor);
174 info.addMotionRange(*mOrientedRanges.toolMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000175 }
176
177 if (mOrientedRanges.orientation) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000178 info.addMotionRange(*mOrientedRanges.orientation);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000179 }
180
181 if (mOrientedRanges.distance) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000182 info.addMotionRange(*mOrientedRanges.distance);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000183 }
184
185 if (mOrientedRanges.tilt) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000186 info.addMotionRange(*mOrientedRanges.tilt);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000187 }
188
189 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000190 info.addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000191 }
192 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000193 info.addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000194 }
Harry Cuttsd02ea102023-03-17 18:21:30 +0000195 info.setButtonUnderPad(mParameters.hasButtonUnderPad);
196 info.setUsiVersion(mParameters.usiVersion);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700197}
198
199void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700200 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800201 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700202 dumpParameters(dump);
203 dumpVirtualKeys(dump);
204 dumpRawPointerAxes(dump);
205 dumpCalibration(dump);
206 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700207 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700208
209 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000210 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000211 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
212 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
213 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700214 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
215 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
216 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
217 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
218 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
219 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
220 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
221 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
222 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
223 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
224
225 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
226 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
227 mLastRawState.rawPointerData.pointerCount);
228 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
229 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
230 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
231 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
232 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700233 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700234 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
235 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
236 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700237 pointer.distance, ftl::enum_string(pointer.toolType).c_str(),
238 toString(pointer.isHovering));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700239 }
240
241 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
242 mLastCookedState.buttonState);
243 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
244 mLastCookedState.cookedPointerData.pointerCount);
245 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
246 const PointerProperties& pointerProperties =
247 mLastCookedState.cookedPointerData.pointerProperties[i];
248 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000249 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
250 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
251 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700252 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700253 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700254 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000255 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
256 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700257 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
258 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
259 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
260 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
261 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
262 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
263 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
264 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700265 ftl::enum_string(pointerProperties.toolType).c_str(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700266 toString(mLastCookedState.cookedPointerData.isHovering(i)));
267 }
268
269 dump += INDENT3 "Stylus Fusion:\n";
270 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
271 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000272 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
273 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700274 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
275 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000276 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
277 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700278 dump += INDENT3 "External Stylus State:\n";
279 dumpStylusState(dump, mExternalStylusState);
280
Michael Wright227c5542020-07-02 18:30:52 +0100281 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700282 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
283 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
284 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
285 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
286 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
287 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
288 }
289}
290
Arpit Singh4be4eef2023-03-28 14:26:01 +0000291std::list<NotifyArgs> TouchInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000292 const InputReaderConfiguration& config,
Arpit Singh4be4eef2023-03-28 14:26:01 +0000293 uint32_t changes) {
294 std::list<NotifyArgs> out = InputMapper::reconfigure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700295
Arpit Singhed6c3de2023-04-05 19:24:37 +0000296 mConfig = config;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700297
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000298 // Full configuration should happen the first time configure is called and
299 // when the device type is changed. Changing a device type can affect
300 // various other parameters so should result in a reconfiguration.
301 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_TYPE)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700302 // Configure basic parameters.
303 configureParameters();
304
305 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800306 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000307 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700308
309 // Configure absolute axis information.
310 configureRawPointerAxes();
311
312 // Prepare input device calibration.
313 parseCalibration();
314 resolveCalibration();
315 }
316
317 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
318 // Update location calibration to reflect current settings
319 updateAffineTransformation();
320 }
321
322 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
323 // Update pointer speed.
324 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
325 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
326 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
327 }
328
329 bool resetNeeded = false;
330 if (!changes ||
331 (changes &
332 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800333 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700334 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
335 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000336 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE |
337 InputReaderConfiguration::CHANGE_DEVICE_TYPE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700338 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700339 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700340 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 }
342
343 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700344 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000345
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700346 // Send reset, unless this is the first time the device has been configured,
347 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000348 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700349 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700350 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351}
352
353void TouchInputMapper::resolveExternalStylusPresence() {
354 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800355 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700356 mExternalStylusConnected = !devices.empty();
357
358 if (!mExternalStylusConnected) {
359 resetExternalStylus();
360 }
361}
362
363void TouchInputMapper::configureParameters() {
364 // Use the pointer presentation mode for devices that do not support distinct
365 // multitouch. The spot-based presentation relies on being able to accurately
366 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800367 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100368 ? Parameters::GestureMode::SINGLE_TOUCH
369 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700370
Harry Cuttsf13161a2023-03-08 14:15:49 +0000371 const PropertyMap& config = getDeviceContext().getConfiguration();
372 std::optional<std::string> gestureModeString = config.getString("touch.gestureMode");
373 if (gestureModeString.has_value()) {
374 if (*gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100375 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000376 } else if (*gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100377 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000378 } else if (*gestureModeString != "default") {
379 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700380 }
381 }
382
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000383 configureDeviceType();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800385 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700386
Harry Cuttsf13161a2023-03-08 14:15:49 +0000387 mParameters.orientationAware =
388 config.getBool("touch.orientationAware")
389 .value_or(mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700390
Michael Wrighta9cf4192022-12-01 23:46:39 +0000391 mParameters.orientation = ui::ROTATION_0;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000392 std::optional<std::string> orientationString = config.getString("touch.orientation");
393 if (orientationString.has_value()) {
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700394 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
395 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
Harry Cuttsf13161a2023-03-08 14:15:49 +0000396 } else if (*orientationString == "ORIENTATION_90") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000397 mParameters.orientation = ui::ROTATION_90;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000398 } else if (*orientationString == "ORIENTATION_180") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000399 mParameters.orientation = ui::ROTATION_180;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000400 } else if (*orientationString == "ORIENTATION_270") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000401 mParameters.orientation = ui::ROTATION_270;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000402 } else if (*orientationString != "ORIENTATION_0") {
403 ALOGW("Invalid value for touch.orientation: '%s'", orientationString->c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700404 }
405 }
406
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700407 mParameters.hasAssociatedDisplay = false;
408 mParameters.associatedDisplayIsExternal = false;
409 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100410 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000411 mParameters.deviceType == Parameters::DeviceType::POINTER ||
412 (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
413 getDeviceContext().getAssociatedViewport())) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700414 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100415 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800416 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Harry Cuttsf13161a2023-03-08 14:15:49 +0000417 mParameters.uniqueDisplayId = config.getString("touch.displayId").value_or("").c_str();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700418 }
419 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800420 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700421 mParameters.hasAssociatedDisplay = true;
422 }
423
424 // Initial downs on external touch devices should wake the device.
425 // Normally we don't do this for internal touch screens to prevent them from waking
426 // up in your pocket but you can enable it using the input device configuration.
Harry Cuttsf13161a2023-03-08 14:15:49 +0000427 mParameters.wake = config.getBool("touch.wake").value_or(getDeviceContext().isExternal());
Prabir Pradhan167c2702022-09-14 00:37:24 +0000428
Harry Cuttsf13161a2023-03-08 14:15:49 +0000429 std::optional<int32_t> usiVersionMajor = config.getInt("touch.usiVersionMajor");
430 std::optional<int32_t> usiVersionMinor = config.getInt("touch.usiVersionMinor");
431 if (usiVersionMajor.has_value() && usiVersionMinor.has_value()) {
432 mParameters.usiVersion = {
433 .majorVersion = *usiVersionMajor,
434 .minorVersion = *usiVersionMinor,
435 };
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000436 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700437
Harry Cuttsf13161a2023-03-08 14:15:49 +0000438 mParameters.enableForInactiveViewport =
439 config.getBool("touch.enableForInactiveViewport").value_or(false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700440}
441
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000442void TouchInputMapper::configureDeviceType() {
443 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
444 // The device is a touch screen.
445 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
446 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
447 // The device is a pointing device like a track pad.
448 mParameters.deviceType = Parameters::DeviceType::POINTER;
449 } else {
450 // The device is a touch pad of unknown purpose.
451 mParameters.deviceType = Parameters::DeviceType::POINTER;
452 }
453
454 // Type association takes precedence over the device type found in the idc file.
455 std::string deviceTypeString = getDeviceContext().getDeviceTypeAssociation().value_or("");
456 if (deviceTypeString.empty()) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000457 deviceTypeString =
458 getDeviceContext().getConfiguration().getString("touch.deviceType").value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000459 }
460 if (deviceTypeString == "touchScreen") {
461 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
462 } else if (deviceTypeString == "touchNavigation") {
463 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
464 } else if (deviceTypeString == "pointer") {
465 mParameters.deviceType = Parameters::DeviceType::POINTER;
466 } else if (deviceTypeString != "default" && deviceTypeString != "") {
467 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
468 }
469}
470
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700471void TouchInputMapper::dumpParameters(std::string& dump) {
472 dump += INDENT3 "Parameters:\n";
473
Dominik Laskowski75788452021-02-09 18:51:25 -0800474 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700475
Dominik Laskowski75788452021-02-09 18:51:25 -0800476 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700477
478 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
479 "displayId='%s'\n",
480 toString(mParameters.hasAssociatedDisplay),
481 toString(mParameters.associatedDisplayIsExternal),
482 mParameters.uniqueDisplayId.c_str());
483 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800484 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000485 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
486 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700487 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
488 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700489}
490
491void TouchInputMapper::configureRawPointerAxes() {
492 mRawPointerAxes.clear();
493}
494
495void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
496 dump += INDENT3 "Raw Touch Axes:\n";
497 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
498 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
499 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
500 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
501 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
502 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
503 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
504 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
505 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
506 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
507 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
508 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
509 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
510}
511
512bool TouchInputMapper::hasExternalStylus() const {
513 return mExternalStylusConnected;
514}
515
516/**
517 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000518 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800519 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000520 * 3. Get the matching viewport by either unique id in idc file or by the display type
521 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800522 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700523 */
524std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800525 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000526 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800527 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700528 }
529
Christine Franks2a2293c2022-01-18 11:51:16 -0800530 const std::optional<std::string> associatedDisplayUniqueId =
531 getDeviceContext().getAssociatedDisplayUniqueId();
532 if (associatedDisplayUniqueId) {
533 return getDeviceContext().getAssociatedViewport();
534 }
535
Michael Wright227c5542020-07-02 18:30:52 +0100536 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800537 std::optional<DisplayViewport> viewport =
538 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
539 if (viewport) {
540 return viewport;
541 } else {
542 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
543 mConfig.defaultPointerDisplayId);
544 }
545 }
546
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700547 // Check if uniqueDisplayId is specified in idc file.
548 if (!mParameters.uniqueDisplayId.empty()) {
549 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
550 }
551
552 ViewportType viewportTypeToUse;
553 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100554 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700555 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100556 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700557 }
558
559 std::optional<DisplayViewport> viewport =
560 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100561 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700562 ALOGW("Input device %s should be associated with external display, "
563 "fallback to internal one for the external viewport is not found.",
564 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100565 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 }
567
568 return viewport;
569 }
570
571 // No associated display, return a non-display viewport.
572 DisplayViewport newViewport;
573 // Raw width and height in the natural orientation.
574 int32_t rawWidth = mRawPointerAxes.getRawWidth();
575 int32_t rawHeight = mRawPointerAxes.getRawHeight();
576 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
577 return std::make_optional(newViewport);
578}
579
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800580int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
581 if (resolution < 0) {
582 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
583 getDeviceName().c_str());
584 return 0;
585 }
586 return resolution;
587}
588
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800589void TouchInputMapper::initializeSizeRanges() {
590 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
591 mSizeScale = 0.0f;
592 return;
593 }
594
595 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000596 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800597
598 // Size factors.
599 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
600 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
601 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
602 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
603 } else {
604 mSizeScale = 0.0f;
605 }
606
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700607 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
608 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
609 .source = mSource,
610 .min = 0,
611 .max = diagonalSize,
612 .flat = 0,
613 .fuzz = 0,
614 .resolution = 0,
615 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800616
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800617 if (mRawPointerAxes.touchMajor.valid) {
618 mRawPointerAxes.touchMajor.resolution =
619 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700620 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800621 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800622
623 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700624 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800625 if (mRawPointerAxes.touchMinor.valid) {
626 mRawPointerAxes.touchMinor.resolution =
627 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700628 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800629 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800630
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700631 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
632 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
633 .source = mSource,
634 .min = 0,
635 .max = diagonalSize,
636 .flat = 0,
637 .fuzz = 0,
638 .resolution = 0,
639 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800640 if (mRawPointerAxes.toolMajor.valid) {
641 mRawPointerAxes.toolMajor.resolution =
642 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700643 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800644 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800645
646 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700647 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800648 if (mRawPointerAxes.toolMinor.valid) {
649 mRawPointerAxes.toolMinor.resolution =
650 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700651 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800652 }
653
654 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700655 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
656 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
657 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
658 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800659 } else {
660 // Support for other calibrations can be added here.
661 ALOGW("%s calibration is not supported for size ranges at the moment. "
662 "Using raw resolution instead",
663 ftl::enum_string(mCalibration.sizeCalibration).c_str());
664 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800665
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700666 mOrientedRanges.size = InputDeviceInfo::MotionRange{
667 .axis = AMOTION_EVENT_AXIS_SIZE,
668 .source = mSource,
669 .min = 0,
670 .max = 1.0,
671 .flat = 0,
672 .fuzz = 0,
673 .resolution = 0,
674 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800675}
676
677void TouchInputMapper::initializeOrientedRanges() {
678 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000679 const float orientedScaleX = mRawToDisplay.getScaleX();
680 const float orientedScaleY = mRawToDisplay.getScaleY();
681 mOrientedXPrecision = 1.0f / orientedScaleX;
682 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800683
684 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
685 mOrientedRanges.x.source = mSource;
686 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
687 mOrientedRanges.y.source = mSource;
688
689 // Scale factor for terms that are not oriented in a particular axis.
690 // If the pixels are square then xScale == yScale otherwise we fake it
691 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000692 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800693
694 initializeSizeRanges();
695
696 // Pressure factors.
697 mPressureScale = 0;
698 float pressureMax = 1.0;
699 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
700 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700701 if (mCalibration.pressureScale) {
702 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800703 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
704 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
705 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
706 }
707 }
708
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700709 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
710 .axis = AMOTION_EVENT_AXIS_PRESSURE,
711 .source = mSource,
712 .min = 0,
713 .max = pressureMax,
714 .flat = 0,
715 .fuzz = 0,
716 .resolution = 0,
717 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800718
719 // Tilt
720 mTiltXCenter = 0;
721 mTiltXScale = 0;
722 mTiltYCenter = 0;
723 mTiltYScale = 0;
724 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
725 if (mHaveTilt) {
726 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
727 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
728 mTiltXScale = M_PI / 180;
729 mTiltYScale = M_PI / 180;
730
731 if (mRawPointerAxes.tiltX.resolution) {
732 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
733 }
734 if (mRawPointerAxes.tiltY.resolution) {
735 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
736 }
737
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700738 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
739 .axis = AMOTION_EVENT_AXIS_TILT,
740 .source = mSource,
741 .min = 0,
742 .max = M_PI_2,
743 .flat = 0,
744 .fuzz = 0,
745 .resolution = 0,
746 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800747 }
748
749 // Orientation
750 mOrientationScale = 0;
751 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700752 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
753 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
754 .source = mSource,
755 .min = -M_PI,
756 .max = M_PI,
757 .flat = 0,
758 .fuzz = 0,
759 .resolution = 0,
760 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800761
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800762 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
763 if (mCalibration.orientationCalibration ==
764 Calibration::OrientationCalibration::INTERPOLATED) {
765 if (mRawPointerAxes.orientation.valid) {
766 if (mRawPointerAxes.orientation.maxValue > 0) {
767 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
768 } else if (mRawPointerAxes.orientation.minValue < 0) {
769 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
770 } else {
771 mOrientationScale = 0;
772 }
773 }
774 }
775
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700776 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
777 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
778 .source = mSource,
779 .min = -M_PI_2,
780 .max = M_PI_2,
781 .flat = 0,
782 .fuzz = 0,
783 .resolution = 0,
784 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800785 }
786
787 // Distance
788 mDistanceScale = 0;
789 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
790 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700791 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800792 }
793
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700794 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800795
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700796 .axis = AMOTION_EVENT_AXIS_DISTANCE,
797 .source = mSource,
798 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
799 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
800 .flat = 0,
801 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
802 .resolution = 0,
803 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800804 }
805
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000806 // Oriented X/Y range (in the rotated display's orientation)
807 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
808 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
809 .toFloatRect();
810 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
811 mOrientedRanges.x.min = orientedRangeRect.left;
812 mOrientedRanges.y.min = orientedRangeRect.top;
813 mOrientedRanges.x.max = orientedRangeRect.right;
814 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800815
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000816 // Oriented flat (in the rotated display's orientation)
817 const auto orientedFlat =
818 transformWithoutTranslation(mRawToRotatedDisplay,
819 {static_cast<float>(mRawPointerAxes.x.flat),
820 static_cast<float>(mRawPointerAxes.y.flat)});
821 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
822 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800823
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000824 // Oriented fuzz (in the rotated display's orientation)
825 const auto orientedFuzz =
826 transformWithoutTranslation(mRawToRotatedDisplay,
827 {static_cast<float>(mRawPointerAxes.x.fuzz),
828 static_cast<float>(mRawPointerAxes.y.fuzz)});
829 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
830 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800831
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000832 // Oriented resolution (in the rotated display's orientation)
833 const auto orientedRes =
834 transformWithoutTranslation(mRawToRotatedDisplay,
835 {static_cast<float>(mRawPointerAxes.x.resolution),
836 static_cast<float>(mRawPointerAxes.y.resolution)});
837 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
838 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800839}
840
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000841void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000842 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
843 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
844 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000845
Prabir Pradhan3e798762022-12-02 21:02:11 +0000846 // See notes about input coordinates in the inputflinger docs:
847 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000848
849 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000850 ui::Transform undoOffsetInRaw;
851 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000852
Prabir Pradhan3e798762022-12-02 21:02:11 +0000853 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
854 // will now be in the same orientation as the display in ROTATION_0.
855 // Note: Negating an ui::Rotation value will give its inverse rotation.
856 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
857 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
858 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
859 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
860 // When rotating raw values, account for the extra unit added when calculating the raw range.
861 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
862 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000863
Prabir Pradhan3e798762022-12-02 21:02:11 +0000864 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
865 // now be in the same orientation as the rotated display. There is no need to rotate the
866 // coordinates to the display rotation if the device is not orientation-aware.
867 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
868 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
869 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
870 : orientedRawSize;
871 // When rotating raw values, account for the extra unit added when calculating the raw range.
872 const auto rotateInRaw = mParameters.orientationAware
873 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
874 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000875
Prabir Pradhan3e798762022-12-02 21:02:11 +0000876 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000877 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
878 // the surface of the display panel. This is usually true for touchscreens.
879 // - In POINTER mode, we cannot assume that the display and the touch device have the same
880 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
881 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
882 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
883 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000884 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
885 // are in the continuous space of the logical display.
886 ui::Transform scaleRawToDisplay;
887 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
888 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000889 if (mDeviceMode == DeviceMode::DIRECT) {
890 scaleRawToDisplay.set(xScale, 0, 0, yScale);
891 } else if (mDeviceMode == DeviceMode::POINTER) {
892 const float fixedScale = std::max(xScale, yScale);
893 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
894 } else {
895 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
896 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000897
Prabir Pradhan3e798762022-12-02 21:02:11 +0000898 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
899 // that InputReader uses.
900 const auto undoRotateInDisplay =
901 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
902 .inverse();
903
904 // Now put it all together!
905 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
906 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
907 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000908}
909
Prabir Pradhan1728b212021-10-19 16:00:03 -0700910void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000911 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700912
913 resolveExternalStylusPresence();
914
915 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100916 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000917 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700918 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100919 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700920 if (hasStylus()) {
921 mSource |= AINPUT_SOURCE_STYLUS;
922 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800923 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700924 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100925 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700926 if (hasStylus()) {
927 mSource |= AINPUT_SOURCE_STYLUS;
928 }
929 if (hasExternalStylus()) {
930 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
931 }
Michael Wright227c5542020-07-02 18:30:52 +0100932 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700933 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100934 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700935 } else {
936 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100937 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700938 }
939
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000940 const std::optional<DisplayViewport> newViewportOpt = findViewport();
941
942 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700943 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
944 ALOGW("Touch device '%s' did not report support for X or Y axis! "
945 "The device will be inoperable.",
946 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100947 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000948 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700949 ALOGI("Touch device '%s' could not query the properties of its associated "
950 "display. The device will be inoperable until the display size "
951 "becomes available.",
952 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100953 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700954 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000955 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
956 getDeviceName().c_str(), getDeviceId());
957 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000958 }
959
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700960 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000961 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000962 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
963 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
964 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
965 const float rawMeanResolution =
966 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700967
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000968 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
969 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700970 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700971 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000972 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
973 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
974 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700975
Michael Wright227c5542020-07-02 18:30:52 +0100976 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000977 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700978
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000979 mDisplayBounds = getNaturalDisplaySize(mViewport);
980 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
981 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700982
Prabir Pradhan3e798762022-12-02 21:02:11 +0000983 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
984 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
985 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000986 // InputReader works in the un-rotated display coordinate space, so we don't need to do
987 // anything if the device is already orientation-aware. If the device is not
988 // orientation-aware, then we need to apply the inverse rotation of the display so that
989 // when the display rotation is applied later as a part of the per-window transform, we
990 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700991 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000992 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000993 : getInverseRotation(mViewport.orientation);
994 // For orientation-aware devices that work in the un-rotated coordinate space, the
995 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000996 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000997 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700998
999 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001000 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001001 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001002 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001003 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001004 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001005 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001006 mRawToDisplay.reset();
1007 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001008 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001009 }
1010 }
1011
1012 // If moving between pointer modes, need to reset some state.
1013 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1014 if (deviceModeChanged) {
1015 mOrientedRanges.clear();
1016 }
1017
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001018 // Create and preserve the pointer controller in the following cases:
1019 const bool isPointerControllerNeeded =
1020 // - when the device is in pointer mode, to show the mouse cursor;
1021 (mDeviceMode == DeviceMode::POINTER) ||
1022 // - when pointer capture is enabled, to preserve the mouse cursor position;
1023 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1024 mConfig.pointerCaptureRequest.enable) ||
1025 // - when we should be showing touches;
1026 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1027 // - when we should be showing a pointer icon for direct styluses.
1028 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1029 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001030 if (mPointerController == nullptr) {
1031 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001032 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001033 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001034 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1035 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001036 } else {
lilinnandef700b2022-06-17 19:32:01 +08001037 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1038 !mConfig.showTouches) {
1039 mPointerController->clearSpots();
1040 }
Michael Wright17db18e2020-06-26 20:51:44 +01001041 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001042 }
1043
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001044 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001045 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001046 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001047 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001048 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001049
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001050 configureVirtualKeys();
1051
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001052 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001053
1054 // Location
1055 updateAffineTransformation();
1056
Michael Wright227c5542020-07-02 18:30:52 +01001057 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001058 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001059 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1060 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001061
1062 // Scale movements such that one whole swipe of the touch pad covers a
1063 // given area relative to the diagonal size of the display when no acceleration
1064 // is applied.
1065 // Assume that the touch pad has a square aspect ratio such that movements in
1066 // X and Y of the same number of raw units cover the same physical distance.
1067 mPointerXMovementScale =
1068 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1069 mPointerYMovementScale = mPointerXMovementScale;
1070
1071 // Scale zooms to cover a smaller range of the display than movements do.
1072 // This value determines the area around the pointer that is affected by freeform
1073 // pointer gestures.
1074 mPointerXZoomScale =
1075 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1076 mPointerYZoomScale = mPointerXZoomScale;
1077
HQ Liue6983c72022-04-19 22:14:56 +00001078 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1079 // axis is non positive value.
1080 const float minFreeformGestureWidth =
1081 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1082
1083 mPointerGestureMaxSwipeWidth =
1084 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1085 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086 }
1087
1088 // Inform the dispatcher about the changes.
1089 *outResetNeeded = true;
1090 bumpGeneration();
1091 }
1092}
1093
Prabir Pradhan1728b212021-10-19 16:00:03 -07001094void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001095 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001096 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001097 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1098 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001099 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001100}
1101
1102void TouchInputMapper::configureVirtualKeys() {
1103 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001104 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001105
1106 mVirtualKeys.clear();
1107
1108 if (virtualKeyDefinitions.size() == 0) {
1109 return;
1110 }
1111
1112 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1113 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1114 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1115 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1116
1117 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1118 VirtualKey virtualKey;
1119
1120 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1121 int32_t keyCode;
1122 int32_t dummyKeyMetaState;
1123 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001124 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1125 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1127 continue; // drop the key
1128 }
1129
1130 virtualKey.keyCode = keyCode;
1131 virtualKey.flags = flags;
1132
1133 // convert the key definition's display coordinates into touch coordinates for a hit box
1134 int32_t halfWidth = virtualKeyDefinition.width / 2;
1135 int32_t halfHeight = virtualKeyDefinition.height / 2;
1136
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001137 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1138 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001140 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1141 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001143 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1144 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001146 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1147 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 touchScreenTop;
1149 mVirtualKeys.push_back(virtualKey);
1150 }
1151}
1152
1153void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1154 if (!mVirtualKeys.empty()) {
1155 dump += INDENT3 "Virtual Keys:\n";
1156
1157 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1158 const VirtualKey& virtualKey = mVirtualKeys[i];
1159 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1160 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1161 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1162 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1163 }
1164 }
1165}
1166
1167void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001168 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 Calibration& out = mCalibration;
1170
1171 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001172 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001173 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1174 if (sizeCalibrationString.has_value()) {
1175 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001176 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001177 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001178 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001179 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001180 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001181 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001182 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001183 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001185 } else if (*sizeCalibrationString != "default") {
1186 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001187 }
1188 }
1189
Harry Cuttsf13161a2023-03-08 14:15:49 +00001190 out.sizeScale = in.getFloat("touch.size.scale");
1191 out.sizeBias = in.getFloat("touch.size.bias");
1192 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193
1194 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001195 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001196 std::optional<std::string> pressureCalibrationString =
1197 in.getString("touch.pressure.calibration");
1198 if (pressureCalibrationString.has_value()) {
1199 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001201 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001202 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001203 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001205 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001206 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001207 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001208 }
1209 }
1210
Harry Cuttsf13161a2023-03-08 14:15:49 +00001211 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212
1213 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001214 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001215 std::optional<std::string> orientationCalibrationString =
1216 in.getString("touch.orientation.calibration");
1217 if (orientationCalibrationString.has_value()) {
1218 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001219 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001220 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001221 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001222 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001223 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001224 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001226 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 }
1228 }
1229
1230 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001231 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001232 std::optional<std::string> distanceCalibrationString =
1233 in.getString("touch.distance.calibration");
1234 if (distanceCalibrationString.has_value()) {
1235 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001236 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001237 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001238 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001239 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001241 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 }
1243 }
1244
Harry Cuttsf13161a2023-03-08 14:15:49 +00001245 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246}
1247
1248void TouchInputMapper::resolveCalibration() {
1249 // Size
1250 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001251 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1252 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253 }
1254 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001255 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001256 }
1257
1258 // Pressure
1259 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001260 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1261 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 }
1263 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001264 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 }
1266
1267 // Orientation
1268 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001269 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1270 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 }
1272 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001273 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001274 }
1275
1276 // Distance
1277 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001278 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1279 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 }
1281 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001282 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284}
1285
1286void TouchInputMapper::dumpCalibration(std::string& dump) {
1287 dump += INDENT3 "Calibration:\n";
1288
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001289 dump += INDENT4 "touch.size.calibration: ";
1290 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001292 if (mCalibration.sizeScale) {
1293 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 }
1295
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001296 if (mCalibration.sizeBias) {
1297 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 }
1299
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001300 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001302 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 }
1304
1305 // Pressure
1306 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001307 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 dump += INDENT4 "touch.pressure.calibration: none\n";
1309 break;
Michael Wright227c5542020-07-02 18:30:52 +01001310 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 dump += INDENT4 "touch.pressure.calibration: physical\n";
1312 break;
Michael Wright227c5542020-07-02 18:30:52 +01001313 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001314 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1315 break;
1316 default:
1317 ALOG_ASSERT(false);
1318 }
1319
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001320 if (mCalibration.pressureScale) {
1321 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 }
1323
1324 // Orientation
1325 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001326 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001327 dump += INDENT4 "touch.orientation.calibration: none\n";
1328 break;
Michael Wright227c5542020-07-02 18:30:52 +01001329 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1331 break;
Michael Wright227c5542020-07-02 18:30:52 +01001332 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001333 dump += INDENT4 "touch.orientation.calibration: vector\n";
1334 break;
1335 default:
1336 ALOG_ASSERT(false);
1337 }
1338
1339 // Distance
1340 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001341 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001342 dump += INDENT4 "touch.distance.calibration: none\n";
1343 break;
Michael Wright227c5542020-07-02 18:30:52 +01001344 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001345 dump += INDENT4 "touch.distance.calibration: scaled\n";
1346 break;
1347 default:
1348 ALOG_ASSERT(false);
1349 }
1350
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001351 if (mCalibration.distanceScale) {
1352 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001354}
1355
1356void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1357 dump += INDENT3 "Affine Transformation:\n";
1358
1359 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1360 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1361 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1362 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1363 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1364 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1365}
1366
1367void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001368 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001369 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001370}
1371
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001372std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001373 std::list<NotifyArgs> out = cancelTouch(when, when);
1374 updateTouchSpots();
1375
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001376 mCursorButtonAccumulator.reset(getDeviceContext());
1377 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001378 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001379
1380 mPointerVelocityControl.reset();
1381 mWheelXVelocityControl.reset();
1382 mWheelYVelocityControl.reset();
1383
1384 mRawStatesPending.clear();
1385 mCurrentRawState.clear();
1386 mCurrentCookedState.clear();
1387 mLastRawState.clear();
1388 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001389 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001390 mSentHoverEnter = false;
1391 mHavePointerIds = false;
1392 mCurrentMotionAborted = false;
1393 mDownTime = 0;
1394
1395 mCurrentVirtualKey.down = false;
1396
1397 mPointerGesture.reset();
1398 mPointerSimple.reset();
1399 resetExternalStylus();
1400
1401 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001402 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001403 mPointerController->clearSpots();
1404 }
1405
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001406 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407}
1408
1409void TouchInputMapper::resetExternalStylus() {
1410 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001411 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001412 mExternalStylusFusionTimeout = LLONG_MAX;
1413 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001414 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001415}
1416
1417void TouchInputMapper::clearStylusDataPendingFlags() {
1418 mExternalStylusDataPending = false;
1419 mExternalStylusFusionTimeout = LLONG_MAX;
1420}
1421
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001422std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001423 mCursorButtonAccumulator.process(rawEvent);
1424 mCursorScrollAccumulator.process(rawEvent);
1425 mTouchButtonAccumulator.process(rawEvent);
1426
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001427 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001428 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001429 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001430 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001431 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001432}
1433
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001434std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1435 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001436 if (mDeviceMode == DeviceMode::DISABLED) {
1437 // Only save the last pending state when the device is disabled.
1438 mRawStatesPending.clear();
1439 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440 // Push a new state.
1441 mRawStatesPending.emplace_back();
1442
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001443 RawState& next = mRawStatesPending.back();
1444 next.clear();
1445 next.when = when;
1446 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001447
1448 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001449 next.buttonState = filterButtonState(mConfig,
1450 mTouchButtonAccumulator.getButtonState() |
1451 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001452
1453 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001454 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1455 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001456 mCursorScrollAccumulator.finishSync();
1457
1458 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001459 syncTouch(when, &next);
1460
1461 // The last RawState is the actually second to last, since we just added a new state
1462 const RawState& last =
1463 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001464
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001465 std::tie(next.when, next.readTime) =
1466 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1467 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001468
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001469 // Assign pointer ids.
1470 if (!mHavePointerIds) {
1471 assignPointerIds(last, next);
1472 }
1473
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001474 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001475 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1476 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1477 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1478 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1479 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1480 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001481
Arthur Hung9ad18942021-06-19 02:04:46 +00001482 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1483 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1484 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1485 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1486 next.rawPointerData.hoveringIdBits.value);
1487 }
1488
Harry Cutts33476232023-01-30 19:57:29 +00001489 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001490 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001491}
1492
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001493std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1494 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001495 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001496 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001497 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498 }
1499
1500 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1501 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1502 // touching the current state will only observe the events that have been dispatched to the
1503 // rest of the pipeline.
1504 const size_t N = mRawStatesPending.size();
1505 size_t count;
1506 for (count = 0; count < N; count++) {
1507 const RawState& next = mRawStatesPending[count];
1508
1509 // A failure to assign the stylus id means that we're waiting on stylus data
1510 // and so should defer the rest of the pipeline.
1511 if (assignExternalStylusId(next, timeout)) {
1512 break;
1513 }
1514
1515 // All ready to go.
1516 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001517 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001518 if (mCurrentRawState.when < mLastRawState.when) {
1519 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001520 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001521 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001522 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001523 }
1524 if (count != 0) {
1525 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1526 }
1527
1528 if (mExternalStylusDataPending) {
1529 if (timeout) {
1530 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1531 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001532 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001533 ALOGD_IF(DEBUG_STYLUS_FUSION,
1534 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001535 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001536 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001537 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1538 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1539 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1540 }
1541 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001542 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001543}
1544
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001545std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1546 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001547 // Always start with a clean state.
1548 mCurrentCookedState.clear();
1549
1550 // Apply stylus buttons to current raw state.
1551 applyExternalStylusButtonState(when);
1552
1553 // Handle policy on initial down or hover events.
1554 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1555 mCurrentRawState.rawPointerData.pointerCount != 0;
1556
1557 uint32_t policyFlags = 0;
1558 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1559 if (initialDown || buttonsPressed) {
1560 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001561 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001562 getContext()->fadePointer();
1563 }
1564
1565 if (mParameters.wake) {
1566 policyFlags |= POLICY_FLAG_WAKE;
1567 }
1568 }
1569
1570 // Consume raw off-screen touches before cooking pointer data.
1571 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001572 bool consumed;
1573 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1574 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001575 mCurrentRawState.rawPointerData.clear();
1576 }
1577
1578 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1579 // with cooked pointer data that has the same ids and indices as the raw data.
1580 // The following code can use either the raw or cooked data, as needed.
1581 cookPointerData();
1582
1583 // Apply stylus pressure to current cooked state.
1584 applyExternalStylusTouchState(when);
1585
1586 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001587 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1588 mSource, mViewport.displayId, policyFlags,
1589 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001590
1591 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001592 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001593 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1594 uint32_t id = idBits.clearFirstMarkedBit();
1595 const RawPointerData::Pointer& pointer =
1596 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001597 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001598 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001599 } else if (pointer.toolType == ToolType::FINGER ||
1600 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001601 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001602 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001603 mCurrentCookedState.mouseIdBits.markBit(id);
1604 }
1605 }
1606 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1607 uint32_t id = idBits.clearFirstMarkedBit();
1608 const RawPointerData::Pointer& pointer =
1609 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001610 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001611 mCurrentCookedState.stylusIdBits.markBit(id);
1612 }
1613 }
1614
1615 // Stylus takes precedence over all tools, then mouse, then finger.
1616 PointerUsage pointerUsage = mPointerUsage;
1617 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1618 mCurrentCookedState.mouseIdBits.clear();
1619 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001620 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001621 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1622 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001623 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1625 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001626 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001627 }
1628
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001629 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001631 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001632 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001633 out += dispatchButtonRelease(when, readTime, policyFlags);
1634 out += dispatchHoverExit(when, readTime, policyFlags);
1635 out += dispatchTouches(when, readTime, policyFlags);
1636 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1637 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001638 }
1639
1640 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1641 mCurrentMotionAborted = false;
1642 }
1643 }
1644
1645 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001646 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1647 mSource, mViewport.displayId, policyFlags,
1648 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001649
1650 // Clear some transient state.
1651 mCurrentRawState.rawVScroll = 0;
1652 mCurrentRawState.rawHScroll = 0;
1653
1654 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001655 mLastRawState = mCurrentRawState;
1656 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001657 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001658}
1659
Garfield Tanc734e4f2021-01-15 20:01:39 -08001660void TouchInputMapper::updateTouchSpots() {
1661 if (!mConfig.showTouches || mPointerController == nullptr) {
1662 return;
1663 }
1664
1665 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1666 // clear touch spots.
1667 if (mDeviceMode != DeviceMode::DIRECT &&
1668 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1669 return;
1670 }
1671
1672 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1673 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1674
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001675 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1676 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001677 mCurrentCookedState.cookedPointerData.touchingIdBits |
1678 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001679 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001680}
1681
1682bool TouchInputMapper::isTouchScreen() {
1683 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1684 mParameters.hasAssociatedDisplay;
1685}
1686
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001687void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001688 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1689 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001690 const int32_t pressedButtons =
1691 filterButtonState(mConfig,
1692 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001693 const int32_t releasedButtons =
1694 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1695
1696 mCurrentRawState.buttonState |= pressedButtons;
1697 mCurrentRawState.buttonState &= ~releasedButtons;
1698
1699 mExternalStylusButtonsApplied |= pressedButtons;
1700 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001701 }
1702}
1703
1704void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1705 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1706 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001707 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1708 return;
1709 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001710
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001711 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1712 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1713 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1714 : 0.f;
1715 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1716 pressure = *mExternalStylusState.pressure;
1717 }
1718 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1719 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001720
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001721 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001722 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001723 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001724 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001725 }
1726}
1727
1728bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001729 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001730 return false;
1731 }
1732
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001733 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001734 if (mFusedStylusPointerId &&
1735 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001736 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001737 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001738 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001739 }
1740
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001741 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1742 state.rawPointerData.pointerCount != 0;
1743 if (!initialDown) {
1744 return false;
1745 }
1746
1747 if (!mExternalStylusState.pressure) {
1748 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1749 return false;
1750 }
1751
1752 if (*mExternalStylusState.pressure != 0.0f) {
1753 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1754 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1755 return false;
1756 }
1757
1758 if (timeout) {
1759 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1760 mFusedStylusPointerId.reset();
1761 mExternalStylusFusionTimeout = LLONG_MAX;
1762 return false;
1763 }
1764
1765 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1766 // being processed until we either get pressure data or timeout.
1767 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1768 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1769 }
1770 ALOGD_IF(DEBUG_STYLUS_FUSION,
1771 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1772 mExternalStylusFusionTimeout);
1773 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1774 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001775}
1776
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001777std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1778 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001779 if (mDeviceMode == DeviceMode::POINTER) {
1780 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001781 // Since this is a synthetic event, we can consider its latency to be zero
1782 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001783 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001784 }
Michael Wright227c5542020-07-02 18:30:52 +01001785 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001786 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001787 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001788 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1789 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1790 }
1791 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001792 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001793}
1794
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001795std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1796 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001797 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001798 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001799 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001800 // The following three cases are handled here:
1801 // - We're in the middle of a fused stream of data;
1802 // - We're waiting on external stylus data before dispatching the initial down; or
1803 // - Only the button state, which is not reported through a specific pointer, has changed.
1804 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001805 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001806 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001807 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001808 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001809}
1810
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001811std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1812 uint32_t policyFlags, bool& outConsumed) {
1813 outConsumed = false;
1814 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001815 // Check for release of a virtual key.
1816 if (mCurrentVirtualKey.down) {
1817 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1818 // Pointer went up while virtual key was down.
1819 mCurrentVirtualKey.down = false;
1820 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001821 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1822 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1823 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001824 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1825 AKEY_EVENT_FLAG_FROM_SYSTEM |
1826 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001827 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001828 outConsumed = true;
1829 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001830 }
1831
1832 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1833 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1834 const RawPointerData::Pointer& pointer =
1835 mCurrentRawState.rawPointerData.pointerForId(id);
1836 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1837 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1838 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001839 outConsumed = true;
1840 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001841 }
1842 }
1843
1844 // Pointer left virtual key area or another pointer also went down.
1845 // Send key cancellation but do not consume the touch yet.
1846 // This is useful when the user swipes through from the virtual key area
1847 // into the main display surface.
1848 mCurrentVirtualKey.down = false;
1849 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001850 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1851 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001852 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1853 AKEY_EVENT_FLAG_FROM_SYSTEM |
1854 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1855 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001856 }
1857 }
1858
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001859 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
1860 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty() &&
1861 mDeviceMode != DeviceMode::UNSCALED) {
1862 // We have hovering pointers, and there are no touching pointers.
1863 bool hoveringPointersInFrame = false;
1864 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1865 while (!hoveringIds.isEmpty()) {
1866 uint32_t id = hoveringIds.clearFirstMarkedBit();
1867 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1868 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1869 hoveringPointersInFrame = true;
1870 break;
1871 }
1872 }
1873 if (!hoveringPointersInFrame) {
1874 // All hovering pointers are outside the physical frame.
1875 outConsumed = true;
1876 return out;
1877 }
1878 }
1879
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001880 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1881 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1882 // Pointer just went down. Check for virtual key press or off-screen touches.
1883 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1884 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001885 // Skip checking whether the pointer is inside the physical frame if the device is in
1886 // unscaled mode.
1887 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1888 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001889 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001890 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001891 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1892 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1893 if (virtualKey) {
1894 mCurrentVirtualKey.down = true;
1895 mCurrentVirtualKey.downTime = when;
1896 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1897 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1898 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001899 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1900 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001901
1902 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001903 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1904 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1905 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001906 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1907 AKEY_EVENT_ACTION_DOWN,
1908 AKEY_EVENT_FLAG_FROM_SYSTEM |
1909 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001910 }
1911 }
1912 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001913 outConsumed = true;
1914 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001915 }
1916 }
1917
1918 // Disable all virtual key touches that happen within a short time interval of the
1919 // most recent touch within the screen area. The idea is to filter out stray
1920 // virtual key presses when interacting with the touch screen.
1921 //
1922 // Problems we're trying to solve:
1923 //
1924 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1925 // virtual key area that is implemented by a separate touch panel and accidentally
1926 // triggers a virtual key.
1927 //
1928 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1929 // area and accidentally triggers a virtual key. This often happens when virtual keys
1930 // are layed out below the screen near to where the on screen keyboard's space bar
1931 // is displayed.
1932 if (mConfig.virtualKeyQuietTime > 0 &&
1933 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001934 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001935 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001936 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001937}
1938
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001939NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1940 uint32_t policyFlags, int32_t keyEventAction,
1941 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001942 int32_t keyCode = mCurrentVirtualKey.keyCode;
1943 int32_t scanCode = mCurrentVirtualKey.scanCode;
1944 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001945 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001946 policyFlags |= POLICY_FLAG_VIRTUAL;
1947
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001948 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1949 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1950 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001951}
1952
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001953std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1954 uint32_t policyFlags) {
1955 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001956 if (mCurrentMotionAborted) {
1957 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001958 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001959 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001960 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1961 if (!currentIdBits.isEmpty()) {
1962 int32_t metaState = getContext()->getGlobalMetaState();
1963 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001964 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001965 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1966 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001967 mCurrentCookedState.cookedPointerData.pointerProperties,
1968 mCurrentCookedState.cookedPointerData.pointerCoords,
1969 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1970 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1971 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001972 mCurrentMotionAborted = true;
1973 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001974 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001975}
1976
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001977// Updates pointer coords and properties for pointers with specified ids that have moved.
1978// Returns true if any of them changed.
1979static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1980 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1981 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1982 BitSet32 idBits) {
1983 bool changed = false;
1984 while (!idBits.isEmpty()) {
1985 uint32_t id = idBits.clearFirstMarkedBit();
1986 uint32_t inIndex = inIdToIndex[id];
1987 uint32_t outIndex = outIdToIndex[id];
1988
1989 const PointerProperties& curInProperties = inProperties[inIndex];
1990 const PointerCoords& curInCoords = inCoords[inIndex];
1991 PointerProperties& curOutProperties = outProperties[outIndex];
1992 PointerCoords& curOutCoords = outCoords[outIndex];
1993
1994 if (curInProperties != curOutProperties) {
1995 curOutProperties.copyFrom(curInProperties);
1996 changed = true;
1997 }
1998
1999 if (curInCoords != curOutCoords) {
2000 curOutCoords.copyFrom(curInCoords);
2001 changed = true;
2002 }
2003 }
2004 return changed;
2005}
2006
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002007std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
2008 uint32_t policyFlags) {
2009 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002010 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2011 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2012 int32_t metaState = getContext()->getGlobalMetaState();
2013 int32_t buttonState = mCurrentCookedState.buttonState;
2014
2015 if (currentIdBits == lastIdBits) {
2016 if (!currentIdBits.isEmpty()) {
2017 // No pointer id changes so this is a move event.
2018 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002019 out.push_back(
2020 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2021 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2022 mCurrentCookedState.cookedPointerData.pointerProperties,
2023 mCurrentCookedState.cookedPointerData.pointerCoords,
2024 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2025 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2026 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002027 }
2028 } else {
2029 // There may be pointers going up and pointers going down and pointers moving
2030 // all at the same time.
2031 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2032 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2033 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2034 BitSet32 dispatchedIdBits(lastIdBits.value);
2035
2036 // Update last coordinates of pointers that have moved so that we observe the new
2037 // pointer positions at the same time as other pointers that have just gone up.
2038 bool moveNeeded =
2039 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2040 mCurrentCookedState.cookedPointerData.pointerCoords,
2041 mCurrentCookedState.cookedPointerData.idToIndex,
2042 mLastCookedState.cookedPointerData.pointerProperties,
2043 mLastCookedState.cookedPointerData.pointerCoords,
2044 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2045 if (buttonState != mLastCookedState.buttonState) {
2046 moveNeeded = true;
2047 }
2048
2049 // Dispatch pointer up events.
2050 while (!upIdBits.isEmpty()) {
2051 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002052 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002053 if (isCanceled) {
2054 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2055 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002056 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2057 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2058 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2059 buttonState, 0,
2060 mLastCookedState.cookedPointerData.pointerProperties,
2061 mLastCookedState.cookedPointerData.pointerCoords,
2062 mLastCookedState.cookedPointerData.idToIndex,
2063 dispatchedIdBits, upId, mOrientedXPrecision,
2064 mOrientedYPrecision, mDownTime,
2065 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002066 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002067 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002068 }
2069
2070 // Dispatch move events if any of the remaining pointers moved from their old locations.
2071 // Although applications receive new locations as part of individual pointer up
2072 // events, they do not generally handle them except when presented in a move event.
2073 if (moveNeeded && !moveIdBits.isEmpty()) {
2074 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002075 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2076 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2077 mCurrentCookedState.cookedPointerData.pointerProperties,
2078 mCurrentCookedState.cookedPointerData.pointerCoords,
2079 mCurrentCookedState.cookedPointerData.idToIndex,
2080 dispatchedIdBits, -1, mOrientedXPrecision,
2081 mOrientedYPrecision, mDownTime,
2082 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002083 }
2084
2085 // Dispatch pointer down events using the new pointer locations.
2086 while (!downIdBits.isEmpty()) {
2087 uint32_t downId = downIdBits.clearFirstMarkedBit();
2088 dispatchedIdBits.markBit(downId);
2089
2090 if (dispatchedIdBits.count() == 1) {
2091 // First pointer is going down. Set down time.
2092 mDownTime = when;
2093 }
2094
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002095 out.push_back(
2096 dispatchMotion(when, readTime, policyFlags, mSource,
2097 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2098 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2099 mCurrentCookedState.cookedPointerData.pointerCoords,
2100 mCurrentCookedState.cookedPointerData.idToIndex,
2101 dispatchedIdBits, downId, mOrientedXPrecision,
2102 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002103 }
2104 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002105 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002106}
2107
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002108std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2109 uint32_t policyFlags) {
2110 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002111 if (mSentHoverEnter &&
2112 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2113 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2114 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002115 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2116 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2117 mLastCookedState.buttonState, 0,
2118 mLastCookedState.cookedPointerData.pointerProperties,
2119 mLastCookedState.cookedPointerData.pointerCoords,
2120 mLastCookedState.cookedPointerData.idToIndex,
2121 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2122 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2123 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002124 mSentHoverEnter = false;
2125 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002126 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002127}
2128
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002129std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2130 uint32_t policyFlags) {
2131 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002132 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2133 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2134 int32_t metaState = getContext()->getGlobalMetaState();
2135 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002136 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2137 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2138 mCurrentRawState.buttonState, 0,
2139 mCurrentCookedState.cookedPointerData.pointerProperties,
2140 mCurrentCookedState.cookedPointerData.pointerCoords,
2141 mCurrentCookedState.cookedPointerData.idToIndex,
2142 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2143 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2144 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002145 mSentHoverEnter = true;
2146 }
2147
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002148 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2149 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2150 mCurrentRawState.buttonState, 0,
2151 mCurrentCookedState.cookedPointerData.pointerProperties,
2152 mCurrentCookedState.cookedPointerData.pointerCoords,
2153 mCurrentCookedState.cookedPointerData.idToIndex,
2154 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2155 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2156 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002157 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002158 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002159}
2160
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002161std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2162 uint32_t policyFlags) {
2163 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002164 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2165 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2166 const int32_t metaState = getContext()->getGlobalMetaState();
2167 int32_t buttonState = mLastCookedState.buttonState;
2168 while (!releasedButtons.isEmpty()) {
2169 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2170 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002171 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2172 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2173 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002174 mLastCookedState.cookedPointerData.pointerProperties,
2175 mLastCookedState.cookedPointerData.pointerCoords,
2176 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002177 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2178 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002179 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002180 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002181}
2182
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002183std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2184 uint32_t policyFlags) {
2185 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002186 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2187 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2188 const int32_t metaState = getContext()->getGlobalMetaState();
2189 int32_t buttonState = mLastCookedState.buttonState;
2190 while (!pressedButtons.isEmpty()) {
2191 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2192 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002193 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2194 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2195 buttonState, 0,
2196 mCurrentCookedState.cookedPointerData.pointerProperties,
2197 mCurrentCookedState.cookedPointerData.pointerCoords,
2198 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2199 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2200 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002201 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002202 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002203}
2204
LiZhihong758eb562022-11-03 15:28:29 +08002205std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2206 uint32_t policyFlags,
2207 BitSet32 idBits,
2208 nsecs_t readTime) {
2209 std::list<NotifyArgs> out;
2210 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2211 const int32_t metaState = getContext()->getGlobalMetaState();
2212 int32_t buttonState = mLastCookedState.buttonState;
2213
2214 while (!releasedButtons.isEmpty()) {
2215 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2216 buttonState &= ~actionButton;
2217 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2218 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2219 metaState, buttonState, 0,
2220 mPointerGesture.lastGestureProperties,
2221 mPointerGesture.lastGestureCoords,
2222 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2223 mOrientedXPrecision, mOrientedYPrecision,
2224 mPointerGesture.downTime, MotionClassification::NONE));
2225 }
2226 return out;
2227}
2228
2229std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2230 uint32_t policyFlags,
2231 BitSet32 idBits,
2232 nsecs_t readTime) {
2233 std::list<NotifyArgs> out;
2234 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2235 const int32_t metaState = getContext()->getGlobalMetaState();
2236 int32_t buttonState = mLastCookedState.buttonState;
2237
2238 while (!pressedButtons.isEmpty()) {
2239 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2240 buttonState |= actionButton;
2241 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2242 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2243 buttonState, 0, mPointerGesture.currentGestureProperties,
2244 mPointerGesture.currentGestureCoords,
2245 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2246 mOrientedXPrecision, mOrientedYPrecision,
2247 mPointerGesture.downTime, MotionClassification::NONE));
2248 }
2249 return out;
2250}
2251
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002252const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2253 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2254 return cookedPointerData.touchingIdBits;
2255 }
2256 return cookedPointerData.hoveringIdBits;
2257}
2258
2259void TouchInputMapper::cookPointerData() {
2260 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2261
2262 mCurrentCookedState.cookedPointerData.clear();
2263 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2264 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2265 mCurrentRawState.rawPointerData.hoveringIdBits;
2266 mCurrentCookedState.cookedPointerData.touchingIdBits =
2267 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002268 mCurrentCookedState.cookedPointerData.canceledIdBits =
2269 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002270
2271 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2272 mCurrentCookedState.buttonState = 0;
2273 } else {
2274 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2275 }
2276
2277 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002278 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002279 for (uint32_t i = 0; i < currentPointerCount; i++) {
2280 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2281
2282 // Size
2283 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2284 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002285 case Calibration::SizeCalibration::GEOMETRIC:
2286 case Calibration::SizeCalibration::DIAMETER:
2287 case Calibration::SizeCalibration::BOX:
2288 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002289 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2290 touchMajor = in.touchMajor;
2291 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2292 toolMajor = in.toolMajor;
2293 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2294 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2295 : in.touchMajor;
2296 } else if (mRawPointerAxes.touchMajor.valid) {
2297 toolMajor = touchMajor = in.touchMajor;
2298 toolMinor = touchMinor =
2299 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2300 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2301 : in.touchMajor;
2302 } else if (mRawPointerAxes.toolMajor.valid) {
2303 touchMajor = toolMajor = in.toolMajor;
2304 touchMinor = toolMinor =
2305 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2306 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2307 : in.toolMajor;
2308 } else {
2309 ALOG_ASSERT(false,
2310 "No touch or tool axes. "
2311 "Size calibration should have been resolved to NONE.");
2312 touchMajor = 0;
2313 touchMinor = 0;
2314 toolMajor = 0;
2315 toolMinor = 0;
2316 size = 0;
2317 }
2318
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002319 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002320 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2321 if (touchingCount > 1) {
2322 touchMajor /= touchingCount;
2323 touchMinor /= touchingCount;
2324 toolMajor /= touchingCount;
2325 toolMinor /= touchingCount;
2326 size /= touchingCount;
2327 }
2328 }
2329
Michael Wright227c5542020-07-02 18:30:52 +01002330 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002331 touchMajor *= mGeometricScale;
2332 touchMinor *= mGeometricScale;
2333 toolMajor *= mGeometricScale;
2334 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002335 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002336 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2337 touchMinor = touchMajor;
2338 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2339 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002340 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002341 touchMinor = touchMajor;
2342 toolMinor = toolMajor;
2343 }
2344
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002345 mCalibration.applySizeScaleAndBias(touchMajor);
2346 mCalibration.applySizeScaleAndBias(touchMinor);
2347 mCalibration.applySizeScaleAndBias(toolMajor);
2348 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 size *= mSizeScale;
2350 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002351 case Calibration::SizeCalibration::DEFAULT:
2352 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2353 break;
2354 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 touchMajor = 0;
2356 touchMinor = 0;
2357 toolMajor = 0;
2358 toolMinor = 0;
2359 size = 0;
2360 break;
2361 }
2362
2363 // Pressure
2364 float pressure;
2365 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002366 case Calibration::PressureCalibration::PHYSICAL:
2367 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 pressure = in.pressure * mPressureScale;
2369 break;
2370 default:
2371 pressure = in.isHovering ? 0 : 1;
2372 break;
2373 }
2374
2375 // Tilt and Orientation
2376 float tilt;
2377 float orientation;
2378 if (mHaveTilt) {
2379 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2380 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002381 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2383 } else {
2384 tilt = 0;
2385
2386 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002387 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002388 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 break;
Michael Wright227c5542020-07-02 18:30:52 +01002390 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2392 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2393 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002394 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002395 float confidence = hypotf(c1, c2);
2396 float scale = 1.0f + confidence / 16.0f;
2397 touchMajor *= scale;
2398 touchMinor /= scale;
2399 toolMajor *= scale;
2400 toolMinor /= scale;
2401 } else {
2402 orientation = 0;
2403 }
2404 break;
2405 }
2406 default:
2407 orientation = 0;
2408 }
2409 }
2410
2411 // Distance
2412 float distance;
2413 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002414 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 distance = in.distance * mDistanceScale;
2416 break;
2417 default:
2418 distance = 0;
2419 }
2420
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002421 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2422 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002423 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2424 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002426 // Write output coords.
2427 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2428 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002429 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2430 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002431 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2432 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2433 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2434 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2435 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2436 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2437 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002438 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2439 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440
Chris Ye364fdb52020-08-05 15:07:56 -07002441 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002442 uint32_t id = in.id;
2443 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2444 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2445 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002446 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2447 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002448 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2449 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2450 }
2451
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452 // Write output properties.
2453 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002454 properties.clear();
2455 properties.id = id;
2456 properties.toolType = in.toolType;
2457
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002458 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002459 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002460 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 }
2462}
2463
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002464std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2465 uint32_t policyFlags,
2466 PointerUsage pointerUsage) {
2467 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002469 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470 mPointerUsage = pointerUsage;
2471 }
2472
2473 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002474 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002475 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002476 break;
Michael Wright227c5542020-07-02 18:30:52 +01002477 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002478 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 break;
Michael Wright227c5542020-07-02 18:30:52 +01002480 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002481 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002482 break;
Michael Wright227c5542020-07-02 18:30:52 +01002483 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002484 break;
2485 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002486 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002487}
2488
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002489std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2490 uint32_t policyFlags) {
2491 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002492 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002493 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002494 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002495 break;
Michael Wright227c5542020-07-02 18:30:52 +01002496 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002497 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002498 break;
Michael Wright227c5542020-07-02 18:30:52 +01002499 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002500 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002501 break;
Michael Wright227c5542020-07-02 18:30:52 +01002502 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 break;
2504 }
2505
Michael Wright227c5542020-07-02 18:30:52 +01002506 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002507 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002508}
2509
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002510std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2511 uint32_t policyFlags,
2512 bool isTimeout) {
2513 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514 // Update current gesture coordinates.
2515 bool cancelPreviousGesture, finishPreviousGesture;
2516 bool sendEvents =
2517 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2518 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002519 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002520 }
2521 if (finishPreviousGesture) {
2522 cancelPreviousGesture = false;
2523 }
2524
2525 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002526 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002527 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002528 if (finishPreviousGesture || cancelPreviousGesture) {
2529 mPointerController->clearSpots();
2530 }
2531
Michael Wright227c5542020-07-02 18:30:52 +01002532 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002533 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2534 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002535 mPointerGesture.currentGestureIdBits,
2536 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002537 }
2538 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002539 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002540 }
2541
2542 // Show or hide the pointer if needed.
2543 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002544 case PointerGesture::Mode::NEUTRAL:
2545 case PointerGesture::Mode::QUIET:
2546 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2547 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002548 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002549 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002550 }
2551 break;
Michael Wright227c5542020-07-02 18:30:52 +01002552 case PointerGesture::Mode::TAP:
2553 case PointerGesture::Mode::TAP_DRAG:
2554 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2555 case PointerGesture::Mode::HOVER:
2556 case PointerGesture::Mode::PRESS:
2557 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002558 // Unfade the pointer when the current gesture manipulates the
2559 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002560 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002561 break;
Michael Wright227c5542020-07-02 18:30:52 +01002562 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002563 // Fade the pointer when the current gesture manipulates a different
2564 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002565 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002566 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002567 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002568 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002569 }
2570 break;
2571 }
2572
2573 // Send events!
2574 int32_t metaState = getContext()->getGlobalMetaState();
2575 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002576 const MotionClassification classification =
2577 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2578 ? MotionClassification::TWO_FINGER_SWIPE
2579 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002580
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002581 uint32_t flags = 0;
2582
2583 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2584 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2585 }
2586
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002587 // Update last coordinates of pointers that have moved so that we observe the new
2588 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002589 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2590 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2591 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2592 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2593 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2594 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002595 bool moveNeeded = false;
2596 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2597 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2598 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2599 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2600 mPointerGesture.lastGestureIdBits.value);
2601 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2602 mPointerGesture.currentGestureCoords,
2603 mPointerGesture.currentGestureIdToIndex,
2604 mPointerGesture.lastGestureProperties,
2605 mPointerGesture.lastGestureCoords,
2606 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2607 if (buttonState != mLastCookedState.buttonState) {
2608 moveNeeded = true;
2609 }
2610 }
2611
2612 // Send motion events for all pointers that went up or were canceled.
2613 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2614 if (!dispatchedGestureIdBits.isEmpty()) {
2615 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002616 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002617 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002618 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002619 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2620 mPointerGesture.lastGestureProperties,
2621 mPointerGesture.lastGestureCoords,
2622 mPointerGesture.lastGestureIdToIndex,
2623 dispatchedGestureIdBits, -1, 0, 0,
2624 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002625
2626 dispatchedGestureIdBits.clear();
2627 } else {
2628 BitSet32 upGestureIdBits;
2629 if (finishPreviousGesture) {
2630 upGestureIdBits = dispatchedGestureIdBits;
2631 } else {
2632 upGestureIdBits.value =
2633 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2634 }
2635 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002636 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2637 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2638 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2639 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2640 readTime);
2641 }
2642 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002643 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2644 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2645 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2646 mPointerGesture.lastGestureProperties,
2647 mPointerGesture.lastGestureCoords,
2648 mPointerGesture.lastGestureIdToIndex,
2649 dispatchedGestureIdBits, id, 0, 0,
2650 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002651
2652 dispatchedGestureIdBits.clearBit(id);
2653 }
2654 }
2655 }
2656
2657 // Send motion events for all pointers that moved.
2658 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002659 out.push_back(
2660 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2661 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2662 mPointerGesture.currentGestureProperties,
2663 mPointerGesture.currentGestureCoords,
2664 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2665 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002666 }
2667
2668 // Send motion events for all pointers that went down.
2669 if (down) {
2670 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2671 ~dispatchedGestureIdBits.value);
2672 while (!downGestureIdBits.isEmpty()) {
2673 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2674 dispatchedGestureIdBits.markBit(id);
2675
2676 if (dispatchedGestureIdBits.count() == 1) {
2677 mPointerGesture.downTime = when;
2678 }
2679
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002680 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2681 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2682 buttonState, 0, mPointerGesture.currentGestureProperties,
2683 mPointerGesture.currentGestureCoords,
2684 mPointerGesture.currentGestureIdToIndex,
2685 dispatchedGestureIdBits, id, 0, 0,
2686 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002687 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2688 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2689 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2690 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2691 readTime);
2692 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002693 }
2694 }
2695
2696 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002697 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002698 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2699 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2700 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2701 mPointerGesture.currentGestureProperties,
2702 mPointerGesture.currentGestureCoords,
2703 mPointerGesture.currentGestureIdToIndex,
2704 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2705 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002706 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2707 // Synthesize a hover move event after all pointers go up to indicate that
2708 // the pointer is hovering again even if the user is not currently touching
2709 // the touch pad. This ensures that a view will receive a fresh hover enter
2710 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002711 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002712
2713 PointerProperties pointerProperties;
2714 pointerProperties.clear();
2715 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002716 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002717
2718 PointerCoords pointerCoords;
2719 pointerCoords.clear();
2720 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2721 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2722
2723 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002724 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2725 mSource, displayId, policyFlags,
2726 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2727 buttonState, MotionClassification::NONE,
2728 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2729 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2730 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002731 }
2732
2733 // Update state.
2734 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2735 if (!down) {
2736 mPointerGesture.lastGestureIdBits.clear();
2737 } else {
2738 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2739 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2740 uint32_t id = idBits.clearFirstMarkedBit();
2741 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2742 mPointerGesture.lastGestureProperties[index].copyFrom(
2743 mPointerGesture.currentGestureProperties[index]);
2744 mPointerGesture.lastGestureCoords[index].copyFrom(
2745 mPointerGesture.currentGestureCoords[index]);
2746 mPointerGesture.lastGestureIdToIndex[id] = index;
2747 }
2748 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002749 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002750}
2751
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002752std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2753 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002754 const MotionClassification classification =
2755 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2756 ? MotionClassification::TWO_FINGER_SWIPE
2757 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002758 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002759 // Cancel previously dispatches pointers.
2760 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2761 int32_t metaState = getContext()->getGlobalMetaState();
2762 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002763 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002764 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2765 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002766 mPointerGesture.lastGestureProperties,
2767 mPointerGesture.lastGestureCoords,
2768 mPointerGesture.lastGestureIdToIndex,
2769 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2770 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002771 }
2772
2773 // Reset the current pointer gesture.
2774 mPointerGesture.reset();
2775 mPointerVelocityControl.reset();
2776
2777 // Remove any current spots.
2778 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002779 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002780 mPointerController->clearSpots();
2781 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002782 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002783}
2784
2785bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2786 bool* outFinishPreviousGesture, bool isTimeout) {
2787 *outCancelPreviousGesture = false;
2788 *outFinishPreviousGesture = false;
2789
2790 // Handle TAP timeout.
2791 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002792 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002793
Michael Wright227c5542020-07-02 18:30:52 +01002794 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002795 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2796 // The tap/drag timeout has not yet expired.
2797 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2798 mConfig.pointerGestureTapDragInterval);
2799 } else {
2800 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002801 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002802 *outFinishPreviousGesture = true;
2803
2804 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002805 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806 mPointerGesture.currentGestureIdBits.clear();
2807
2808 mPointerVelocityControl.reset();
2809 return true;
2810 }
2811 }
2812
2813 // We did not handle this timeout.
2814 return false;
2815 }
2816
2817 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2818 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2819
2820 // Update the velocity tracker.
2821 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002822 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002823 uint32_t id = idBits.clearFirstMarkedBit();
2824 const RawPointerData::Pointer& pointer =
2825 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002826 const float x = pointer.x * mPointerXMovementScale;
2827 const float y = pointer.y * mPointerYMovementScale;
2828 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2829 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002831 }
2832
2833 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2834 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002835 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2836 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2837 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002838 mPointerGesture.resetTap();
2839 }
2840
2841 // Pick a new active touch id if needed.
2842 // Choose an arbitrary pointer that just went down, if there is one.
2843 // Otherwise choose an arbitrary remaining pointer.
2844 // This guarantees we always have an active touch id when there is at least one pointer.
2845 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002846 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002847 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002848 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002849 mPointerGesture.firstTouchTime = when;
2850 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002851 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2852 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2853 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2854 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002855 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002856 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002857
2858 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002859 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002860 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002861 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2862 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2863 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002864 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002865 *outFinishPreviousGesture = true;
2866 }
2867
2868 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002869 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002870 mPointerGesture.currentGestureIdBits.clear();
2871
2872 mPointerVelocityControl.reset();
2873 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2874 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2875 // The pointer follows the active touch point.
2876 // Emit DOWN, MOVE, UP events at the pointer location.
2877 //
2878 // Only the active touch matters; other fingers are ignored. This policy helps
2879 // to handle the case where the user places a second finger on the touch pad
2880 // to apply the necessary force to depress an integrated button below the surface.
2881 // We don't want the second finger to be delivered to applications.
2882 //
2883 // For this to work well, we need to make sure to track the pointer that is really
2884 // active. If the user first puts one finger down to click then adds another
2885 // finger to drag then the active pointer should switch to the finger that is
2886 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002887 ALOGD_IF(DEBUG_GESTURES,
2888 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2889 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002890 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002891 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892 *outFinishPreviousGesture = true;
2893 mPointerGesture.activeGestureId = 0;
2894 }
2895
2896 // Switch pointers if needed.
2897 // Find the fastest pointer and follow it.
2898 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002899 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002900 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002901 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002902 ALOGD_IF(DEBUG_GESTURES,
2903 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2904 "bestSpeed=%0.3f",
2905 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002906 }
2907 }
2908
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002909 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002910 // When using spots, the click will occur at the position of the anchor
2911 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002912 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002913 } else {
2914 mPointerVelocityControl.reset();
2915 }
2916
Prabir Pradhan2719e822023-02-28 17:39:36 +00002917 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002918
Michael Wright227c5542020-07-02 18:30:52 +01002919 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002920 mPointerGesture.currentGestureIdBits.clear();
2921 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2922 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2923 mPointerGesture.currentGestureProperties[0].clear();
2924 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002925 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002926 mPointerGesture.currentGestureCoords[0].clear();
2927 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2928 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2929 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2930 } else if (currentFingerCount == 0) {
2931 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002932 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002933 *outFinishPreviousGesture = true;
2934 }
2935
2936 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2937 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2938 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002939 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2940 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002941 lastFingerCount == 1) {
2942 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002943 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2945 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002946 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002947
2948 mPointerGesture.tapUpTime = when;
2949 getContext()->requestTimeoutAtTime(when +
2950 mConfig.pointerGestureTapDragInterval);
2951
2952 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002953 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002954 mPointerGesture.currentGestureIdBits.clear();
2955 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2956 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2957 mPointerGesture.currentGestureProperties[0].clear();
2958 mPointerGesture.currentGestureProperties[0].id =
2959 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002960 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002961 mPointerGesture.currentGestureCoords[0].clear();
2962 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2963 mPointerGesture.tapX);
2964 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2965 mPointerGesture.tapY);
2966 mPointerGesture.currentGestureCoords[0]
2967 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2968
2969 tapped = true;
2970 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002971 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2972 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002973 }
2974 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002975 if (DEBUG_GESTURES) {
2976 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2977 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2978 (when - mPointerGesture.tapDownTime) * 0.000001f);
2979 } else {
2980 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2981 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002982 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002983 }
2984 }
2985
2986 mPointerVelocityControl.reset();
2987
2988 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002989 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002990 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002991 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002992 mPointerGesture.currentGestureIdBits.clear();
2993 }
2994 } else if (currentFingerCount == 1) {
2995 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2996 // The pointer follows the active touch point.
2997 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2998 // When in TAP_DRAG, emit MOVE events at the pointer location.
2999 ALOG_ASSERT(activeTouchId >= 0);
3000
Michael Wright227c5542020-07-02 18:30:52 +01003001 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3002 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003004 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003005 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3006 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003007 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003008 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003009 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3010 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003011 }
3012 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003013 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3014 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003015 }
Michael Wright227c5542020-07-02 18:30:52 +01003016 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3017 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003018 }
3019
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003020 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003021 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003022 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003023 } else {
3024 mPointerVelocityControl.reset();
3025 }
3026
3027 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003028 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003029 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003030 down = true;
3031 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003032 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003033 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003034 *outFinishPreviousGesture = true;
3035 }
3036 mPointerGesture.activeGestureId = 0;
3037 down = false;
3038 }
3039
Prabir Pradhan2719e822023-02-28 17:39:36 +00003040 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003041
3042 mPointerGesture.currentGestureIdBits.clear();
3043 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3044 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3045 mPointerGesture.currentGestureProperties[0].clear();
3046 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003047 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003048 mPointerGesture.currentGestureCoords[0].clear();
3049 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3050 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3051 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3052 down ? 1.0f : 0.0f);
3053
3054 if (lastFingerCount == 0 && currentFingerCount != 0) {
3055 mPointerGesture.resetTap();
3056 mPointerGesture.tapDownTime = when;
3057 mPointerGesture.tapX = x;
3058 mPointerGesture.tapY = y;
3059 }
3060 } else {
3061 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003062 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003063 }
3064
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003065 if (DEBUG_GESTURES) {
3066 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3067 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3068 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3069 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3070 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3071 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3072 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3073 uint32_t id = idBits.clearFirstMarkedBit();
3074 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3075 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3076 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003077 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003078 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003079 id, index, ftl::enum_string(properties.toolType).c_str(),
3080 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003081 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3082 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3083 }
3084 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3085 uint32_t id = idBits.clearFirstMarkedBit();
3086 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3087 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3088 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003089 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003090 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003091 id, index, ftl::enum_string(properties.toolType).c_str(),
3092 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003093 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3094 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3095 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003096 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003097 return true;
3098}
3099
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003100bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3101 if (mPointerGesture.activeTouchId < 0) {
3102 mPointerGesture.resetQuietTime();
3103 return false;
3104 }
3105
3106 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3107 return true;
3108 }
3109
3110 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3111 bool isQuietTime = false;
3112 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3113 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3114 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3115 currentFingerCount < 2) {
3116 // Enter quiet time when exiting swipe or freeform state.
3117 // This is to prevent accidentally entering the hover state and flinging the
3118 // pointer when finishing a swipe and there is still one pointer left onscreen.
3119 isQuietTime = true;
3120 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3121 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3122 // Enter quiet time when releasing the button and there are still two or more
3123 // fingers down. This may indicate that one finger was used to press the button
3124 // but it has not gone up yet.
3125 isQuietTime = true;
3126 }
3127 if (isQuietTime) {
3128 mPointerGesture.quietTime = when;
3129 }
3130 return isQuietTime;
3131}
3132
3133std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3134 int32_t bestId = -1;
3135 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3136 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3137 uint32_t id = idBits.clearFirstMarkedBit();
3138 std::optional<float> vx =
3139 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3140 std::optional<float> vy =
3141 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3142 if (vx && vy) {
3143 float speed = hypotf(*vx, *vy);
3144 if (speed > bestSpeed) {
3145 bestId = id;
3146 bestSpeed = speed;
3147 }
3148 }
3149 }
3150 return std::make_pair(bestId, bestSpeed);
3151}
3152
3153void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3154 bool* finishPreviousGesture) {
3155 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3156 // to move before deciding what to do.
3157 //
3158 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3159 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3160 // just a press or long-press at the pointer location.
3161 //
3162 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3163 // pointer location.
3164 //
3165 // When the two fingers move enough or when additional fingers are added, we make a decision to
3166 // transition into SWIPE or FREEFORM mode accordingly.
3167 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3168 ALOG_ASSERT(activeTouchId >= 0);
3169
3170 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3171 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3172 bool settled =
3173 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3174 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3175 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3176 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3177 *finishPreviousGesture = true;
3178 } else if (!settled && currentFingerCount > lastFingerCount) {
3179 // Additional pointers have gone down but not yet settled.
3180 // Reset the gesture.
3181 ALOGD_IF(DEBUG_GESTURES,
3182 "Gestures: Resetting gesture since additional pointers went down for "
3183 "MULTITOUCH, settle time remaining %0.3fms",
3184 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3185 when) * 0.000001f);
3186 *cancelPreviousGesture = true;
3187 } else {
3188 // Continue previous gesture.
3189 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3190 }
3191
3192 if (*finishPreviousGesture || *cancelPreviousGesture) {
3193 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3194 mPointerGesture.activeGestureId = 0;
3195 mPointerGesture.referenceIdBits.clear();
3196 mPointerVelocityControl.reset();
3197
3198 // Use the centroid and pointer location as the reference points for the gesture.
3199 ALOGD_IF(DEBUG_GESTURES,
3200 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3201 "%0.3fms",
3202 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3203 when) * 0.000001f);
3204 mCurrentRawState.rawPointerData
3205 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3206 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003207 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3208 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003209 }
3210
3211 // Clear the reference deltas for fingers not yet included in the reference calculation.
3212 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3213 ~mPointerGesture.referenceIdBits.value);
3214 !idBits.isEmpty();) {
3215 uint32_t id = idBits.clearFirstMarkedBit();
3216 mPointerGesture.referenceDeltas[id].dx = 0;
3217 mPointerGesture.referenceDeltas[id].dy = 0;
3218 }
3219 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3220
3221 // Add delta for all fingers and calculate a common movement delta.
3222 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3223 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3224 mCurrentCookedState.fingerIdBits.value);
3225 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3226 bool first = (idBits == commonIdBits);
3227 uint32_t id = idBits.clearFirstMarkedBit();
3228 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3229 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3230 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3231 delta.dx += cpd.x - lpd.x;
3232 delta.dy += cpd.y - lpd.y;
3233
3234 if (first) {
3235 commonDeltaRawX = delta.dx;
3236 commonDeltaRawY = delta.dy;
3237 } else {
3238 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3239 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3240 }
3241 }
3242
3243 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3244 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3245 float dist[MAX_POINTER_ID + 1];
3246 int32_t distOverThreshold = 0;
3247 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3248 uint32_t id = idBits.clearFirstMarkedBit();
3249 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3250 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3251 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3252 distOverThreshold += 1;
3253 }
3254 }
3255
3256 // Only transition when at least two pointers have moved further than
3257 // the minimum distance threshold.
3258 if (distOverThreshold >= 2) {
3259 if (currentFingerCount > 2) {
3260 // There are more than two pointers, switch to FREEFORM.
3261 ALOGD_IF(DEBUG_GESTURES,
3262 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3263 currentFingerCount);
3264 *cancelPreviousGesture = true;
3265 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3266 } else {
3267 // There are exactly two pointers.
3268 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3269 uint32_t id1 = idBits.clearFirstMarkedBit();
3270 uint32_t id2 = idBits.firstMarkedBit();
3271 const RawPointerData::Pointer& p1 =
3272 mCurrentRawState.rawPointerData.pointerForId(id1);
3273 const RawPointerData::Pointer& p2 =
3274 mCurrentRawState.rawPointerData.pointerForId(id2);
3275 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3276 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3277 // There are two pointers but they are too far apart for a SWIPE,
3278 // switch to FREEFORM.
3279 ALOGD_IF(DEBUG_GESTURES,
3280 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3281 mutualDistance, mPointerGestureMaxSwipeWidth);
3282 *cancelPreviousGesture = true;
3283 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3284 } else {
3285 // There are two pointers. Wait for both pointers to start moving
3286 // before deciding whether this is a SWIPE or FREEFORM gesture.
3287 float dist1 = dist[id1];
3288 float dist2 = dist[id2];
3289 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3290 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3291 // Calculate the dot product of the displacement vectors.
3292 // When the vectors are oriented in approximately the same direction,
3293 // the angle betweeen them is near zero and the cosine of the angle
3294 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3295 // mag(v2).
3296 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3297 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3298 float dx1 = delta1.dx * mPointerXZoomScale;
3299 float dy1 = delta1.dy * mPointerYZoomScale;
3300 float dx2 = delta2.dx * mPointerXZoomScale;
3301 float dy2 = delta2.dy * mPointerYZoomScale;
3302 float dot = dx1 * dx2 + dy1 * dy2;
3303 float cosine = dot / (dist1 * dist2); // denominator always > 0
3304 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3305 // Pointers are moving in the same direction. Switch to SWIPE.
3306 ALOGD_IF(DEBUG_GESTURES,
3307 "Gestures: PRESS transitioned to SWIPE, "
3308 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3309 "cosine %0.3f >= %0.3f",
3310 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3311 mConfig.pointerGestureMultitouchMinDistance, cosine,
3312 mConfig.pointerGestureSwipeTransitionAngleCosine);
3313 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3314 } else {
3315 // Pointers are moving in different directions. Switch to FREEFORM.
3316 ALOGD_IF(DEBUG_GESTURES,
3317 "Gestures: PRESS transitioned to FREEFORM, "
3318 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3319 "cosine %0.3f < %0.3f",
3320 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3321 mConfig.pointerGestureMultitouchMinDistance, cosine,
3322 mConfig.pointerGestureSwipeTransitionAngleCosine);
3323 *cancelPreviousGesture = true;
3324 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3325 }
3326 }
3327 }
3328 }
3329 }
3330 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3331 // Switch from SWIPE to FREEFORM if additional pointers go down.
3332 // Cancel previous gesture.
3333 if (currentFingerCount > 2) {
3334 ALOGD_IF(DEBUG_GESTURES,
3335 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3336 currentFingerCount);
3337 *cancelPreviousGesture = true;
3338 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3339 }
3340 }
3341
3342 // Move the reference points based on the overall group motion of the fingers
3343 // except in PRESS mode while waiting for a transition to occur.
3344 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3345 (commonDeltaRawX || commonDeltaRawY)) {
3346 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3347 uint32_t id = idBits.clearFirstMarkedBit();
3348 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3349 delta.dx = 0;
3350 delta.dy = 0;
3351 }
3352
3353 mPointerGesture.referenceTouchX += commonDeltaRawX;
3354 mPointerGesture.referenceTouchY += commonDeltaRawY;
3355
3356 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3357 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3358
3359 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3360 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3361
3362 mPointerGesture.referenceGestureX += commonDeltaX;
3363 mPointerGesture.referenceGestureY += commonDeltaY;
3364 }
3365
3366 // Report gestures.
3367 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3368 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3369 // PRESS or SWIPE mode.
3370 ALOGD_IF(DEBUG_GESTURES,
3371 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3372 "currentTouchPointerCount=%d",
3373 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3374 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3375
3376 mPointerGesture.currentGestureIdBits.clear();
3377 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3378 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3379 mPointerGesture.currentGestureProperties[0].clear();
3380 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003381 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003382 mPointerGesture.currentGestureCoords[0].clear();
3383 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3384 mPointerGesture.referenceGestureX);
3385 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3386 mPointerGesture.referenceGestureY);
3387 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3388 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3389 float xOffset = static_cast<float>(commonDeltaRawX) /
3390 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3391 float yOffset = static_cast<float>(commonDeltaRawY) /
3392 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3393 mPointerGesture.currentGestureCoords[0]
3394 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3395 mPointerGesture.currentGestureCoords[0]
3396 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3397 }
3398 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3399 // FREEFORM mode.
3400 ALOGD_IF(DEBUG_GESTURES,
3401 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3402 "currentTouchPointerCount=%d",
3403 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3404 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3405
3406 mPointerGesture.currentGestureIdBits.clear();
3407
3408 BitSet32 mappedTouchIdBits;
3409 BitSet32 usedGestureIdBits;
3410 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3411 // Initially, assign the active gesture id to the active touch point
3412 // if there is one. No other touch id bits are mapped yet.
3413 if (!*cancelPreviousGesture) {
3414 mappedTouchIdBits.markBit(activeTouchId);
3415 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3416 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3417 mPointerGesture.activeGestureId;
3418 } else {
3419 mPointerGesture.activeGestureId = -1;
3420 }
3421 } else {
3422 // Otherwise, assume we mapped all touches from the previous frame.
3423 // Reuse all mappings that are still applicable.
3424 mappedTouchIdBits.value =
3425 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3426 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3427
3428 // Check whether we need to choose a new active gesture id because the
3429 // current went went up.
3430 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3431 ~mCurrentCookedState.fingerIdBits.value);
3432 !upTouchIdBits.isEmpty();) {
3433 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3434 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3435 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3436 mPointerGesture.activeGestureId = -1;
3437 break;
3438 }
3439 }
3440 }
3441
3442 ALOGD_IF(DEBUG_GESTURES,
3443 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3444 "activeGestureId=%d",
3445 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3446
3447 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3448 for (uint32_t i = 0; i < currentFingerCount; i++) {
3449 uint32_t touchId = idBits.clearFirstMarkedBit();
3450 uint32_t gestureId;
3451 if (!mappedTouchIdBits.hasBit(touchId)) {
3452 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3453 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3454 ALOGD_IF(DEBUG_GESTURES,
3455 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3456 gestureId);
3457 } else {
3458 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3459 ALOGD_IF(DEBUG_GESTURES,
3460 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3461 touchId, gestureId);
3462 }
3463 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3464 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3465
3466 const RawPointerData::Pointer& pointer =
3467 mCurrentRawState.rawPointerData.pointerForId(touchId);
3468 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3469 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3470 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3471
3472 mPointerGesture.currentGestureProperties[i].clear();
3473 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003474 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003475 mPointerGesture.currentGestureCoords[i].clear();
3476 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3477 mPointerGesture.referenceGestureX +
3478 deltaX);
3479 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3480 mPointerGesture.referenceGestureY +
3481 deltaY);
3482 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3483 }
3484
3485 if (mPointerGesture.activeGestureId < 0) {
3486 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3487 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3488 mPointerGesture.activeGestureId);
3489 }
3490 }
3491}
3492
Harry Cutts714d1ad2022-08-24 16:36:43 +00003493void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3494 const RawPointerData::Pointer& currentPointer =
3495 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3496 const RawPointerData::Pointer& lastPointer =
3497 mLastRawState.rawPointerData.pointerForId(pointerId);
3498 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3499 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3500
3501 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3502 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3503
3504 mPointerController->move(deltaX, deltaY);
3505}
3506
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003507std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3508 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509 mPointerSimple.currentCoords.clear();
3510 mPointerSimple.currentProperties.clear();
3511
3512 bool down, hovering;
3513 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3514 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3515 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003516 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3517 down = !hovering;
3518
Prabir Pradhane71e5702023-03-29 14:51:38 +00003519 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3520 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3521 // Styluses are configured specifically for one display. We only update the
3522 // PointerController for this stylus if the PointerController is configured for
3523 // the same display as this stylus,
3524 if (getAssociatedDisplayId() == mViewport.displayId) {
3525 mPointerController->setPosition(x, y);
3526 std::tie(x, y) = mPointerController->getPosition();
3527 }
3528
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003529 mPointerSimple.currentCoords.copyFrom(
3530 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3531 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3532 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3533 mPointerSimple.currentProperties.id = 0;
3534 mPointerSimple.currentProperties.toolType =
3535 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3536 } else {
3537 down = false;
3538 hovering = false;
3539 }
3540
Prabir Pradhane71e5702023-03-29 14:51:38 +00003541 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003542}
3543
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003544std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3545 uint32_t policyFlags) {
3546 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003547}
3548
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003549std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3550 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003551 mPointerSimple.currentCoords.clear();
3552 mPointerSimple.currentProperties.clear();
3553
3554 bool down, hovering;
3555 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3556 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003557 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003558 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003559 } else {
3560 mPointerVelocityControl.reset();
3561 }
3562
3563 down = isPointerDown(mCurrentRawState.buttonState);
3564 hovering = !down;
3565
Prabir Pradhan2719e822023-02-28 17:39:36 +00003566 const auto [x, y] = mPointerController->getPosition();
3567 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003568 mPointerSimple.currentCoords.copyFrom(
3569 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3570 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3571 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3572 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3573 hovering ? 0.0f : 1.0f);
3574 mPointerSimple.currentProperties.id = 0;
3575 mPointerSimple.currentProperties.toolType =
3576 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3577 } else {
3578 mPointerVelocityControl.reset();
3579
3580 down = false;
3581 hovering = false;
3582 }
3583
Prabir Pradhane71e5702023-03-29 14:51:38 +00003584 const int32_t displayId = mPointerController->getDisplayId();
3585 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003586}
3587
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003588std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3589 uint32_t policyFlags) {
3590 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003591
3592 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003593
3594 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003595}
3596
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003597std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3598 uint32_t policyFlags, bool down,
Prabir Pradhane71e5702023-03-29 14:51:38 +00003599 bool hovering, int32_t displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003600 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3601 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003602 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003603 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003604
3605 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003606 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003607 mPointerController->clearSpots();
Michael Wrightca5bede2020-07-02 00:00:29 +01003608 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003609 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003610 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003611 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003612
Prabir Pradhan2719e822023-02-28 17:39:36 +00003613 const auto [xCursorPosition, yCursorPosition] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003614
3615 if (mPointerSimple.down && !down) {
3616 mPointerSimple.down = false;
3617
3618 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003619 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3620 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3621 0, metaState, mLastRawState.buttonState,
3622 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3623 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3624 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3625 yCursorPosition, mPointerSimple.downTime,
3626 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003627 }
3628
3629 if (mPointerSimple.hovering && !hovering) {
3630 mPointerSimple.hovering = false;
3631
3632 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003633 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3634 mSource, displayId, policyFlags,
3635 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3636 mLastRawState.buttonState, MotionClassification::NONE,
3637 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3638 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3639 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3640 yCursorPosition, mPointerSimple.downTime,
3641 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003642 }
3643
3644 if (down) {
3645 if (!mPointerSimple.down) {
3646 mPointerSimple.down = true;
3647 mPointerSimple.downTime = when;
3648
3649 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003650 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3651 mSource, displayId, policyFlags,
3652 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3653 mCurrentRawState.buttonState, MotionClassification::NONE,
3654 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3655 &mPointerSimple.currentProperties,
3656 &mPointerSimple.currentCoords, mOrientedXPrecision,
3657 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3658 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003659 }
3660
3661 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003662 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3663 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3664 0, 0, metaState, mCurrentRawState.buttonState,
3665 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3666 &mPointerSimple.currentProperties,
3667 &mPointerSimple.currentCoords, mOrientedXPrecision,
3668 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3669 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003670 }
3671
3672 if (hovering) {
3673 if (!mPointerSimple.hovering) {
3674 mPointerSimple.hovering = true;
3675
3676 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003677 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3678 mSource, displayId, policyFlags,
3679 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3680 mCurrentRawState.buttonState, MotionClassification::NONE,
3681 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3682 &mPointerSimple.currentProperties,
3683 &mPointerSimple.currentCoords, mOrientedXPrecision,
3684 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3685 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003686 }
3687
3688 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003689 out.push_back(
3690 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3691 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3692 metaState, mCurrentRawState.buttonState,
3693 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3694 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3695 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3696 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003697 }
3698
3699 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3700 float vscroll = mCurrentRawState.rawVScroll;
3701 float hscroll = mCurrentRawState.rawHScroll;
3702 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3703 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3704
3705 // Send scroll.
3706 PointerCoords pointerCoords;
3707 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3708 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3709 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3710
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003711 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3712 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3713 0, 0, metaState, mCurrentRawState.buttonState,
3714 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3715 &mPointerSimple.currentProperties, &pointerCoords,
3716 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3717 yCursorPosition, mPointerSimple.downTime,
3718 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003719 }
3720
3721 // Save state.
3722 if (down || hovering) {
3723 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3724 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003725 mPointerSimple.displayId = displayId;
3726 mPointerSimple.source = mSource;
3727 mPointerSimple.lastCursorX = xCursorPosition;
3728 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003729 } else {
3730 mPointerSimple.reset();
3731 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003732 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003733}
3734
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003735std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3736 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003737 std::list<NotifyArgs> out;
3738 if (mPointerSimple.down || mPointerSimple.hovering) {
3739 int32_t metaState = getContext()->getGlobalMetaState();
3740 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3741 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3742 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3743 metaState, mLastRawState.buttonState,
3744 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3745 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3746 mOrientedXPrecision, mOrientedYPrecision,
3747 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3748 mPointerSimple.downTime,
3749 /* videoFrames */ {}));
3750 if (mPointerController != nullptr) {
3751 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3752 }
3753 }
3754 mPointerSimple.reset();
3755 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003756}
3757
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003758static bool isStylusEvent(uint32_t source, int32_t action, const PointerProperties* properties) {
3759 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
3760 return false;
3761 }
3762 const auto actionIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3763 return isStylusToolType(properties[actionIndex].toolType);
3764}
3765
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003766NotifyMotionArgs TouchInputMapper::dispatchMotion(
3767 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3768 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003769 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3770 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003771 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003772 PointerCoords pointerCoords[MAX_POINTERS];
3773 PointerProperties pointerProperties[MAX_POINTERS];
3774 uint32_t pointerCount = 0;
3775 while (!idBits.isEmpty()) {
3776 uint32_t id = idBits.clearFirstMarkedBit();
3777 uint32_t index = idToIndex[id];
3778 pointerProperties[pointerCount].copyFrom(properties[index]);
3779 pointerCoords[pointerCount].copyFrom(coords[index]);
3780
3781 if (changedId >= 0 && id == uint32_t(changedId)) {
3782 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3783 }
3784
3785 pointerCount += 1;
3786 }
3787
3788 ALOG_ASSERT(pointerCount != 0);
3789
3790 if (changedId >= 0 && pointerCount == 1) {
3791 // Replace initial down and final up action.
3792 // We can compare the action without masking off the changed pointer index
3793 // because we know the index is 0.
3794 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3795 action = AMOTION_EVENT_ACTION_DOWN;
3796 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003797 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3798 action = AMOTION_EVENT_ACTION_CANCEL;
3799 } else {
3800 action = AMOTION_EVENT_ACTION_UP;
3801 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003802 } else {
3803 // Can't happen.
3804 ALOG_ASSERT(false);
3805 }
3806 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003807
3808 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3809 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
3810 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, action, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003811 mPointerController && displayId != ADISPLAY_ID_NONE &&
3812 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003813 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003814 switch (action & AMOTION_EVENT_ACTION_MASK) {
3815 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3816 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3817 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003818 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003819 mPointerController
3820 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3821 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3822 .getY());
3823 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3824 break;
3825 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3826 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3827 break;
3828 }
3829 }
3830
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003831 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3832 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003833 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003834 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003835 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003836 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003837 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003838 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003839 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003840 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3841 policyFlags, action, actionButton, flags, metaState, buttonState,
3842 classification, edgeFlags, pointerCount, pointerProperties,
3843 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3844 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003845}
3846
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003847std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3848 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003849 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3850 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003851 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003852}
3853
Prabir Pradhan1728b212021-10-19 16:00:03 -07003854bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003855 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003856 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003857 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003858}
3859
3860const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3861 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003862 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3863 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3864 "left=%d, top=%d, right=%d, bottom=%d",
3865 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3866 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003867
3868 if (virtualKey.isHit(x, y)) {
3869 return &virtualKey;
3870 }
3871 }
3872
3873 return nullptr;
3874}
3875
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003876void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3877 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3878 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003879
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003880 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003881
3882 if (currentPointerCount == 0) {
3883 // No pointers to assign.
3884 return;
3885 }
3886
3887 if (lastPointerCount == 0) {
3888 // All pointers are new.
3889 for (uint32_t i = 0; i < currentPointerCount; i++) {
3890 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003891 current.rawPointerData.pointers[i].id = id;
3892 current.rawPointerData.idToIndex[id] = i;
3893 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003894 }
3895 return;
3896 }
3897
3898 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003899 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003900 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003901 uint32_t id = last.rawPointerData.pointers[0].id;
3902 current.rawPointerData.pointers[0].id = id;
3903 current.rawPointerData.idToIndex[id] = 0;
3904 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003905 return;
3906 }
3907
3908 // General case.
3909 // We build a heap of squared euclidean distances between current and last pointers
3910 // associated with the current and last pointer indices. Then, we find the best
3911 // match (by distance) for each current pointer.
3912 // The pointers must have the same tool type but it is possible for them to
3913 // transition from hovering to touching or vice-versa while retaining the same id.
3914 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3915
3916 uint32_t heapSize = 0;
3917 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3918 currentPointerIndex++) {
3919 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3920 lastPointerIndex++) {
3921 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003922 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003923 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003924 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003925 if (currentPointer.toolType == lastPointer.toolType) {
3926 int64_t deltaX = currentPointer.x - lastPointer.x;
3927 int64_t deltaY = currentPointer.y - lastPointer.y;
3928
3929 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3930
3931 // Insert new element into the heap (sift up).
3932 heap[heapSize].currentPointerIndex = currentPointerIndex;
3933 heap[heapSize].lastPointerIndex = lastPointerIndex;
3934 heap[heapSize].distance = distance;
3935 heapSize += 1;
3936 }
3937 }
3938 }
3939
3940 // Heapify
3941 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3942 startIndex -= 1;
3943 for (uint32_t parentIndex = startIndex;;) {
3944 uint32_t childIndex = parentIndex * 2 + 1;
3945 if (childIndex >= heapSize) {
3946 break;
3947 }
3948
3949 if (childIndex + 1 < heapSize &&
3950 heap[childIndex + 1].distance < heap[childIndex].distance) {
3951 childIndex += 1;
3952 }
3953
3954 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3955 break;
3956 }
3957
3958 swap(heap[parentIndex], heap[childIndex]);
3959 parentIndex = childIndex;
3960 }
3961 }
3962
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003963 if (DEBUG_POINTER_ASSIGNMENT) {
3964 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3965 for (size_t i = 0; i < heapSize; i++) {
3966 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3967 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3968 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003969 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003970
3971 // Pull matches out by increasing order of distance.
3972 // To avoid reassigning pointers that have already been matched, the loop keeps track
3973 // of which last and current pointers have been matched using the matchedXXXBits variables.
3974 // It also tracks the used pointer id bits.
3975 BitSet32 matchedLastBits(0);
3976 BitSet32 matchedCurrentBits(0);
3977 BitSet32 usedIdBits(0);
3978 bool first = true;
3979 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3980 while (heapSize > 0) {
3981 if (first) {
3982 // The first time through the loop, we just consume the root element of
3983 // the heap (the one with smallest distance).
3984 first = false;
3985 } else {
3986 // Previous iterations consumed the root element of the heap.
3987 // Pop root element off of the heap (sift down).
3988 heap[0] = heap[heapSize];
3989 for (uint32_t parentIndex = 0;;) {
3990 uint32_t childIndex = parentIndex * 2 + 1;
3991 if (childIndex >= heapSize) {
3992 break;
3993 }
3994
3995 if (childIndex + 1 < heapSize &&
3996 heap[childIndex + 1].distance < heap[childIndex].distance) {
3997 childIndex += 1;
3998 }
3999
4000 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4001 break;
4002 }
4003
4004 swap(heap[parentIndex], heap[childIndex]);
4005 parentIndex = childIndex;
4006 }
4007
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004008 if (DEBUG_POINTER_ASSIGNMENT) {
4009 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4010 for (size_t j = 0; j < heapSize; j++) {
4011 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4012 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4013 heap[j].distance);
4014 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004015 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004016 }
4017
4018 heapSize -= 1;
4019
4020 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4021 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4022
4023 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4024 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4025
4026 matchedCurrentBits.markBit(currentPointerIndex);
4027 matchedLastBits.markBit(lastPointerIndex);
4028
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004029 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4030 current.rawPointerData.pointers[currentPointerIndex].id = id;
4031 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4032 current.rawPointerData.markIdBit(id,
4033 current.rawPointerData.isHovering(
4034 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004035 usedIdBits.markBit(id);
4036
Harry Cutts45483602022-08-24 14:36:48 +00004037 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4038 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4039 ", distance=%" PRIu64,
4040 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004041 break;
4042 }
4043 }
4044
4045 // Assign fresh ids to pointers that were not matched in the process.
4046 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4047 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4048 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4049
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004050 current.rawPointerData.pointers[currentPointerIndex].id = id;
4051 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4052 current.rawPointerData.markIdBit(id,
4053 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004054
Harry Cutts45483602022-08-24 14:36:48 +00004055 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4056 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4057 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004058 }
4059}
4060
4061int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4062 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4063 return AKEY_STATE_VIRTUAL;
4064 }
4065
4066 for (const VirtualKey& virtualKey : mVirtualKeys) {
4067 if (virtualKey.keyCode == keyCode) {
4068 return AKEY_STATE_UP;
4069 }
4070 }
4071
4072 return AKEY_STATE_UNKNOWN;
4073}
4074
4075int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4076 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4077 return AKEY_STATE_VIRTUAL;
4078 }
4079
4080 for (const VirtualKey& virtualKey : mVirtualKeys) {
4081 if (virtualKey.scanCode == scanCode) {
4082 return AKEY_STATE_UP;
4083 }
4084 }
4085
4086 return AKEY_STATE_UNKNOWN;
4087}
4088
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004089bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4090 const std::vector<int32_t>& keyCodes,
4091 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004092 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004093 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004094 if (virtualKey.keyCode == keyCodes[i]) {
4095 outFlags[i] = 1;
4096 }
4097 }
4098 }
4099
4100 return true;
4101}
4102
4103std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4104 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004105 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004106 return std::make_optional(mPointerController->getDisplayId());
4107 } else {
4108 return std::make_optional(mViewport.displayId);
4109 }
4110 }
4111 return std::nullopt;
4112}
4113
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004114} // namespace android