blob: 9a426bf0143eb20b2b5f8d6156f4efdfef5f1c69 [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
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800124TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
125 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000126 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700127 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100128 mDeviceMode(DeviceMode::DISABLED),
Michael Wrighta9cf4192022-12-01 23:46:39 +0000129 mInputDeviceOrientation(ui::ROTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700130
131TouchInputMapper::~TouchInputMapper() {}
132
Philip Junker4af3b3d2021-12-14 10:36:55 +0100133uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700134 return mSource;
135}
136
Harry Cuttsd02ea102023-03-17 18:21:30 +0000137void TouchInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700138 InputMapper::populateDeviceInfo(info);
139
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000140 if (mDeviceMode == DeviceMode::DISABLED) {
141 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700142 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000143
Harry Cuttsd02ea102023-03-17 18:21:30 +0000144 info.addMotionRange(mOrientedRanges.x);
145 info.addMotionRange(mOrientedRanges.y);
146 info.addMotionRange(mOrientedRanges.pressure);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000147
148 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
149 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
150 //
151 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
152 // motion, i.e. the hardware dimensions, as the finger could move completely across the
153 // touchpad in one sample cycle.
154 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
155 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
Harry Cuttsd02ea102023-03-17 18:21:30 +0000156 info.addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
157 x.resolution);
158 info.addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
159 y.resolution);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000160 }
161
162 if (mOrientedRanges.size) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000163 info.addMotionRange(*mOrientedRanges.size);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000164 }
165
166 if (mOrientedRanges.touchMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000167 info.addMotionRange(*mOrientedRanges.touchMajor);
168 info.addMotionRange(*mOrientedRanges.touchMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000169 }
170
171 if (mOrientedRanges.toolMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000172 info.addMotionRange(*mOrientedRanges.toolMajor);
173 info.addMotionRange(*mOrientedRanges.toolMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000174 }
175
176 if (mOrientedRanges.orientation) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000177 info.addMotionRange(*mOrientedRanges.orientation);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000178 }
179
180 if (mOrientedRanges.distance) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000181 info.addMotionRange(*mOrientedRanges.distance);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000182 }
183
184 if (mOrientedRanges.tilt) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000185 info.addMotionRange(*mOrientedRanges.tilt);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000186 }
187
188 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000189 info.addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000190 }
191 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000192 info.addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000193 }
Harry Cuttsd02ea102023-03-17 18:21:30 +0000194 info.setButtonUnderPad(mParameters.hasButtonUnderPad);
195 info.setUsiVersion(mParameters.usiVersion);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700196}
197
198void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700199 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800200 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700201 dumpParameters(dump);
202 dumpVirtualKeys(dump);
203 dumpRawPointerAxes(dump);
204 dumpCalibration(dump);
205 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700206 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700207
208 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000209 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000210 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
211 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
212 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700213 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
214 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
215 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
216 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
217 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
218 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
219 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
220 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
221 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
222 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
223
224 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
225 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
226 mLastRawState.rawPointerData.pointerCount);
227 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
228 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
229 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
230 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
231 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700232 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700233 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
234 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
235 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700236 pointer.distance, ftl::enum_string(pointer.toolType).c_str(),
237 toString(pointer.isHovering));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700238 }
239
240 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
241 mLastCookedState.buttonState);
242 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
243 mLastCookedState.cookedPointerData.pointerCount);
244 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
245 const PointerProperties& pointerProperties =
246 mLastCookedState.cookedPointerData.pointerProperties[i];
247 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000248 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
249 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
250 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700251 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700252 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700253 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000254 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
255 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700256 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
257 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
258 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
259 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
260 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
261 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
262 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
263 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700264 ftl::enum_string(pointerProperties.toolType).c_str(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700265 toString(mLastCookedState.cookedPointerData.isHovering(i)));
266 }
267
268 dump += INDENT3 "Stylus Fusion:\n";
269 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
270 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000271 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
272 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700273 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
274 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000275 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
276 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700277 dump += INDENT3 "External Stylus State:\n";
278 dumpStylusState(dump, mExternalStylusState);
279
Michael Wright227c5542020-07-02 18:30:52 +0100280 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700281 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
282 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
283 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
284 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
285 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
286 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
287 }
288}
289
Arpit Singh4be4eef2023-03-28 14:26:01 +0000290std::list<NotifyArgs> TouchInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000291 const InputReaderConfiguration& config,
Arpit Singh4be4eef2023-03-28 14:26:01 +0000292 uint32_t changes) {
293 std::list<NotifyArgs> out = InputMapper::reconfigure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700294
Arpit Singhed6c3de2023-04-05 19:24:37 +0000295 mConfig = config;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700296
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000297 // Full configuration should happen the first time configure is called and
298 // when the device type is changed. Changing a device type can affect
299 // various other parameters so should result in a reconfiguration.
300 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_TYPE)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700301 // Configure basic parameters.
302 configureParameters();
303
304 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800305 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000306 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700307
308 // Configure absolute axis information.
309 configureRawPointerAxes();
310
311 // Prepare input device calibration.
312 parseCalibration();
313 resolveCalibration();
314 }
315
316 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
317 // Update location calibration to reflect current settings
318 updateAffineTransformation();
319 }
320
321 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
322 // Update pointer speed.
323 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
324 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
325 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
326 }
327
328 bool resetNeeded = false;
329 if (!changes ||
330 (changes &
331 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800332 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700333 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
334 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000335 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE |
336 InputReaderConfiguration::CHANGE_DEVICE_TYPE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700337 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700338 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700339 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700340 }
341
342 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700343 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000344
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700345 // Send reset, unless this is the first time the device has been configured,
346 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000347 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700348 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700349 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350}
351
352void TouchInputMapper::resolveExternalStylusPresence() {
353 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800354 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700355 mExternalStylusConnected = !devices.empty();
356
357 if (!mExternalStylusConnected) {
358 resetExternalStylus();
359 }
360}
361
362void TouchInputMapper::configureParameters() {
363 // Use the pointer presentation mode for devices that do not support distinct
364 // multitouch. The spot-based presentation relies on being able to accurately
365 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800366 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100367 ? Parameters::GestureMode::SINGLE_TOUCH
368 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700369
Harry Cuttsf13161a2023-03-08 14:15:49 +0000370 const PropertyMap& config = getDeviceContext().getConfiguration();
371 std::optional<std::string> gestureModeString = config.getString("touch.gestureMode");
372 if (gestureModeString.has_value()) {
373 if (*gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100374 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000375 } else if (*gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100376 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000377 } else if (*gestureModeString != "default") {
378 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700379 }
380 }
381
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000382 configureDeviceType();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700383
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800384 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700385
Harry Cuttsf13161a2023-03-08 14:15:49 +0000386 mParameters.orientationAware =
387 config.getBool("touch.orientationAware")
388 .value_or(mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389
Michael Wrighta9cf4192022-12-01 23:46:39 +0000390 mParameters.orientation = ui::ROTATION_0;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000391 std::optional<std::string> orientationString = config.getString("touch.orientation");
392 if (orientationString.has_value()) {
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700393 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
394 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
Harry Cuttsf13161a2023-03-08 14:15:49 +0000395 } else if (*orientationString == "ORIENTATION_90") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000396 mParameters.orientation = ui::ROTATION_90;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000397 } else if (*orientationString == "ORIENTATION_180") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000398 mParameters.orientation = ui::ROTATION_180;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000399 } else if (*orientationString == "ORIENTATION_270") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000400 mParameters.orientation = ui::ROTATION_270;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000401 } else if (*orientationString != "ORIENTATION_0") {
402 ALOGW("Invalid value for touch.orientation: '%s'", orientationString->c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700403 }
404 }
405
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700406 mParameters.hasAssociatedDisplay = false;
407 mParameters.associatedDisplayIsExternal = false;
408 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100409 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000410 mParameters.deviceType == Parameters::DeviceType::POINTER ||
411 (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
412 getDeviceContext().getAssociatedViewport())) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700413 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100414 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800415 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Harry Cuttsf13161a2023-03-08 14:15:49 +0000416 mParameters.uniqueDisplayId = config.getString("touch.displayId").value_or("").c_str();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700417 }
418 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700420 mParameters.hasAssociatedDisplay = true;
421 }
422
423 // Initial downs on external touch devices should wake the device.
424 // Normally we don't do this for internal touch screens to prevent them from waking
425 // up in your pocket but you can enable it using the input device configuration.
Harry Cuttsf13161a2023-03-08 14:15:49 +0000426 mParameters.wake = config.getBool("touch.wake").value_or(getDeviceContext().isExternal());
Prabir Pradhan167c2702022-09-14 00:37:24 +0000427
Harry Cuttsf13161a2023-03-08 14:15:49 +0000428 std::optional<int32_t> usiVersionMajor = config.getInt("touch.usiVersionMajor");
429 std::optional<int32_t> usiVersionMinor = config.getInt("touch.usiVersionMinor");
430 if (usiVersionMajor.has_value() && usiVersionMinor.has_value()) {
431 mParameters.usiVersion = {
432 .majorVersion = *usiVersionMajor,
433 .minorVersion = *usiVersionMinor,
434 };
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000435 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700436
Harry Cuttsf13161a2023-03-08 14:15:49 +0000437 mParameters.enableForInactiveViewport =
438 config.getBool("touch.enableForInactiveViewport").value_or(false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439}
440
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000441void TouchInputMapper::configureDeviceType() {
442 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
443 // The device is a touch screen.
444 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
445 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
446 // The device is a pointing device like a track pad.
447 mParameters.deviceType = Parameters::DeviceType::POINTER;
448 } else {
449 // The device is a touch pad of unknown purpose.
450 mParameters.deviceType = Parameters::DeviceType::POINTER;
451 }
452
453 // Type association takes precedence over the device type found in the idc file.
454 std::string deviceTypeString = getDeviceContext().getDeviceTypeAssociation().value_or("");
455 if (deviceTypeString.empty()) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000456 deviceTypeString =
457 getDeviceContext().getConfiguration().getString("touch.deviceType").value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000458 }
459 if (deviceTypeString == "touchScreen") {
460 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
461 } else if (deviceTypeString == "touchNavigation") {
462 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
463 } else if (deviceTypeString == "pointer") {
464 mParameters.deviceType = Parameters::DeviceType::POINTER;
465 } else if (deviceTypeString != "default" && deviceTypeString != "") {
466 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
467 }
468}
469
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700470void TouchInputMapper::dumpParameters(std::string& dump) {
471 dump += INDENT3 "Parameters:\n";
472
Dominik Laskowski75788452021-02-09 18:51:25 -0800473 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700474
Dominik Laskowski75788452021-02-09 18:51:25 -0800475 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700476
477 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
478 "displayId='%s'\n",
479 toString(mParameters.hasAssociatedDisplay),
480 toString(mParameters.associatedDisplayIsExternal),
481 mParameters.uniqueDisplayId.c_str());
482 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800483 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000484 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
485 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700486 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
487 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700488}
489
490void TouchInputMapper::configureRawPointerAxes() {
491 mRawPointerAxes.clear();
492}
493
494void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
495 dump += INDENT3 "Raw Touch Axes:\n";
496 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
497 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
498 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
499 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
500 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
501 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
502 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
503 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
504 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
505 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
506 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
507 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
508 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
509}
510
511bool TouchInputMapper::hasExternalStylus() const {
512 return mExternalStylusConnected;
513}
514
515/**
516 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000517 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800518 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000519 * 3. Get the matching viewport by either unique id in idc file or by the display type
520 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800521 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700522 */
523std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800524 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000525 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800526 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700527 }
528
Christine Franks2a2293c2022-01-18 11:51:16 -0800529 const std::optional<std::string> associatedDisplayUniqueId =
530 getDeviceContext().getAssociatedDisplayUniqueId();
531 if (associatedDisplayUniqueId) {
532 return getDeviceContext().getAssociatedViewport();
533 }
534
Michael Wright227c5542020-07-02 18:30:52 +0100535 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800536 std::optional<DisplayViewport> viewport =
537 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
538 if (viewport) {
539 return viewport;
540 } else {
541 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
542 mConfig.defaultPointerDisplayId);
543 }
544 }
545
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700546 // Check if uniqueDisplayId is specified in idc file.
547 if (!mParameters.uniqueDisplayId.empty()) {
548 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
549 }
550
551 ViewportType viewportTypeToUse;
552 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100553 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700554 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100555 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700556 }
557
558 std::optional<DisplayViewport> viewport =
559 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100560 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700561 ALOGW("Input device %s should be associated with external display, "
562 "fallback to internal one for the external viewport is not found.",
563 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100564 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700565 }
566
567 return viewport;
568 }
569
570 // No associated display, return a non-display viewport.
571 DisplayViewport newViewport;
572 // Raw width and height in the natural orientation.
573 int32_t rawWidth = mRawPointerAxes.getRawWidth();
574 int32_t rawHeight = mRawPointerAxes.getRawHeight();
575 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
576 return std::make_optional(newViewport);
577}
578
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800579int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
580 if (resolution < 0) {
581 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
582 getDeviceName().c_str());
583 return 0;
584 }
585 return resolution;
586}
587
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800588void TouchInputMapper::initializeSizeRanges() {
589 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
590 mSizeScale = 0.0f;
591 return;
592 }
593
594 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000595 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800596
597 // Size factors.
598 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
599 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
600 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
601 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
602 } else {
603 mSizeScale = 0.0f;
604 }
605
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700606 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
607 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
608 .source = mSource,
609 .min = 0,
610 .max = diagonalSize,
611 .flat = 0,
612 .fuzz = 0,
613 .resolution = 0,
614 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800615
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800616 if (mRawPointerAxes.touchMajor.valid) {
617 mRawPointerAxes.touchMajor.resolution =
618 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700619 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800620 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800621
622 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700623 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800624 if (mRawPointerAxes.touchMinor.valid) {
625 mRawPointerAxes.touchMinor.resolution =
626 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700627 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800628 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800629
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700630 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
631 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
632 .source = mSource,
633 .min = 0,
634 .max = diagonalSize,
635 .flat = 0,
636 .fuzz = 0,
637 .resolution = 0,
638 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800639 if (mRawPointerAxes.toolMajor.valid) {
640 mRawPointerAxes.toolMajor.resolution =
641 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700642 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800643 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800644
645 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700646 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800647 if (mRawPointerAxes.toolMinor.valid) {
648 mRawPointerAxes.toolMinor.resolution =
649 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700650 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800651 }
652
653 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700654 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
655 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
656 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
657 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800658 } else {
659 // Support for other calibrations can be added here.
660 ALOGW("%s calibration is not supported for size ranges at the moment. "
661 "Using raw resolution instead",
662 ftl::enum_string(mCalibration.sizeCalibration).c_str());
663 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800664
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700665 mOrientedRanges.size = InputDeviceInfo::MotionRange{
666 .axis = AMOTION_EVENT_AXIS_SIZE,
667 .source = mSource,
668 .min = 0,
669 .max = 1.0,
670 .flat = 0,
671 .fuzz = 0,
672 .resolution = 0,
673 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800674}
675
676void TouchInputMapper::initializeOrientedRanges() {
677 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000678 const float orientedScaleX = mRawToDisplay.getScaleX();
679 const float orientedScaleY = mRawToDisplay.getScaleY();
680 mOrientedXPrecision = 1.0f / orientedScaleX;
681 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800682
683 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
684 mOrientedRanges.x.source = mSource;
685 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
686 mOrientedRanges.y.source = mSource;
687
688 // Scale factor for terms that are not oriented in a particular axis.
689 // If the pixels are square then xScale == yScale otherwise we fake it
690 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000691 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800692
693 initializeSizeRanges();
694
695 // Pressure factors.
696 mPressureScale = 0;
697 float pressureMax = 1.0;
698 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
699 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700700 if (mCalibration.pressureScale) {
701 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800702 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
703 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
704 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
705 }
706 }
707
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700708 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
709 .axis = AMOTION_EVENT_AXIS_PRESSURE,
710 .source = mSource,
711 .min = 0,
712 .max = pressureMax,
713 .flat = 0,
714 .fuzz = 0,
715 .resolution = 0,
716 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800717
718 // Tilt
719 mTiltXCenter = 0;
720 mTiltXScale = 0;
721 mTiltYCenter = 0;
722 mTiltYScale = 0;
723 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
724 if (mHaveTilt) {
725 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
726 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
727 mTiltXScale = M_PI / 180;
728 mTiltYScale = M_PI / 180;
729
730 if (mRawPointerAxes.tiltX.resolution) {
731 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
732 }
733 if (mRawPointerAxes.tiltY.resolution) {
734 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
735 }
736
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700737 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
738 .axis = AMOTION_EVENT_AXIS_TILT,
739 .source = mSource,
740 .min = 0,
741 .max = M_PI_2,
742 .flat = 0,
743 .fuzz = 0,
744 .resolution = 0,
745 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800746 }
747
748 // Orientation
749 mOrientationScale = 0;
750 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700751 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
752 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
753 .source = mSource,
754 .min = -M_PI,
755 .max = M_PI,
756 .flat = 0,
757 .fuzz = 0,
758 .resolution = 0,
759 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800760
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800761 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
762 if (mCalibration.orientationCalibration ==
763 Calibration::OrientationCalibration::INTERPOLATED) {
764 if (mRawPointerAxes.orientation.valid) {
765 if (mRawPointerAxes.orientation.maxValue > 0) {
766 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
767 } else if (mRawPointerAxes.orientation.minValue < 0) {
768 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
769 } else {
770 mOrientationScale = 0;
771 }
772 }
773 }
774
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700775 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
776 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
777 .source = mSource,
778 .min = -M_PI_2,
779 .max = M_PI_2,
780 .flat = 0,
781 .fuzz = 0,
782 .resolution = 0,
783 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800784 }
785
786 // Distance
787 mDistanceScale = 0;
788 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
789 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700790 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800791 }
792
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700793 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800794
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700795 .axis = AMOTION_EVENT_AXIS_DISTANCE,
796 .source = mSource,
797 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
798 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
799 .flat = 0,
800 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
801 .resolution = 0,
802 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800803 }
804
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000805 // Oriented X/Y range (in the rotated display's orientation)
806 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
807 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
808 .toFloatRect();
809 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
810 mOrientedRanges.x.min = orientedRangeRect.left;
811 mOrientedRanges.y.min = orientedRangeRect.top;
812 mOrientedRanges.x.max = orientedRangeRect.right;
813 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800814
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000815 // Oriented flat (in the rotated display's orientation)
816 const auto orientedFlat =
817 transformWithoutTranslation(mRawToRotatedDisplay,
818 {static_cast<float>(mRawPointerAxes.x.flat),
819 static_cast<float>(mRawPointerAxes.y.flat)});
820 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
821 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800822
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000823 // Oriented fuzz (in the rotated display's orientation)
824 const auto orientedFuzz =
825 transformWithoutTranslation(mRawToRotatedDisplay,
826 {static_cast<float>(mRawPointerAxes.x.fuzz),
827 static_cast<float>(mRawPointerAxes.y.fuzz)});
828 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
829 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800830
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000831 // Oriented resolution (in the rotated display's orientation)
832 const auto orientedRes =
833 transformWithoutTranslation(mRawToRotatedDisplay,
834 {static_cast<float>(mRawPointerAxes.x.resolution),
835 static_cast<float>(mRawPointerAxes.y.resolution)});
836 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
837 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800838}
839
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000840void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000841 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
842 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
843 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000844
Prabir Pradhan3e798762022-12-02 21:02:11 +0000845 // See notes about input coordinates in the inputflinger docs:
846 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000847
848 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000849 ui::Transform undoOffsetInRaw;
850 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000851
Prabir Pradhan3e798762022-12-02 21:02:11 +0000852 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
853 // will now be in the same orientation as the display in ROTATION_0.
854 // Note: Negating an ui::Rotation value will give its inverse rotation.
855 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
856 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
857 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
858 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
859 // When rotating raw values, account for the extra unit added when calculating the raw range.
860 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
861 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000862
Prabir Pradhan3e798762022-12-02 21:02:11 +0000863 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
864 // now be in the same orientation as the rotated display. There is no need to rotate the
865 // coordinates to the display rotation if the device is not orientation-aware.
866 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
867 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
868 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
869 : orientedRawSize;
870 // When rotating raw values, account for the extra unit added when calculating the raw range.
871 const auto rotateInRaw = mParameters.orientationAware
872 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
873 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000874
Prabir Pradhan3e798762022-12-02 21:02:11 +0000875 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000876 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
877 // the surface of the display panel. This is usually true for touchscreens.
878 // - In POINTER mode, we cannot assume that the display and the touch device have the same
879 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
880 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
881 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
882 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000883 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
884 // are in the continuous space of the logical display.
885 ui::Transform scaleRawToDisplay;
886 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
887 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000888 if (mDeviceMode == DeviceMode::DIRECT) {
889 scaleRawToDisplay.set(xScale, 0, 0, yScale);
890 } else if (mDeviceMode == DeviceMode::POINTER) {
891 const float fixedScale = std::max(xScale, yScale);
892 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
893 } else {
894 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
895 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000896
Prabir Pradhan3e798762022-12-02 21:02:11 +0000897 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
898 // that InputReader uses.
899 const auto undoRotateInDisplay =
900 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
901 .inverse();
902
903 // Now put it all together!
904 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
905 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
906 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000907}
908
Prabir Pradhan1728b212021-10-19 16:00:03 -0700909void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000910 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700911
912 resolveExternalStylusPresence();
913
914 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100915 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000916 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700917 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100918 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700919 if (hasStylus()) {
920 mSource |= AINPUT_SOURCE_STYLUS;
921 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800922 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700923 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100924 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700925 if (hasStylus()) {
926 mSource |= AINPUT_SOURCE_STYLUS;
927 }
928 if (hasExternalStylus()) {
929 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
930 }
Michael Wright227c5542020-07-02 18:30:52 +0100931 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700932 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100933 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700934 } else {
935 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100936 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700937 }
938
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000939 const std::optional<DisplayViewport> newViewportOpt = findViewport();
940
941 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700942 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
943 ALOGW("Touch device '%s' did not report support for X or Y axis! "
944 "The device will be inoperable.",
945 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100946 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000947 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700948 ALOGI("Touch device '%s' could not query the properties of its associated "
949 "display. The device will be inoperable until the display size "
950 "becomes available.",
951 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100952 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700953 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000954 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
955 getDeviceName().c_str(), getDeviceId());
956 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000957 }
958
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700959 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000960 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000961 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
962 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
963 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
964 const float rawMeanResolution =
965 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000967 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
968 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700969 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700970 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000971 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
972 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
973 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700974
Michael Wright227c5542020-07-02 18:30:52 +0100975 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000976 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700977
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000978 mDisplayBounds = getNaturalDisplaySize(mViewport);
979 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
980 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700981
Prabir Pradhan3e798762022-12-02 21:02:11 +0000982 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
983 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
984 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000985 // InputReader works in the un-rotated display coordinate space, so we don't need to do
986 // anything if the device is already orientation-aware. If the device is not
987 // orientation-aware, then we need to apply the inverse rotation of the display so that
988 // when the display rotation is applied later as a part of the per-window transform, we
989 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700990 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000991 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000992 : getInverseRotation(mViewport.orientation);
993 // For orientation-aware devices that work in the un-rotated coordinate space, the
994 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000995 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000996 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700997
998 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000999 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001000 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001001 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001002 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001003 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001004 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001005 mRawToDisplay.reset();
1006 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001007 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001008 }
1009 }
1010
1011 // If moving between pointer modes, need to reset some state.
1012 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1013 if (deviceModeChanged) {
1014 mOrientedRanges.clear();
1015 }
1016
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001017 // Create and preserve the pointer controller in the following cases:
1018 const bool isPointerControllerNeeded =
1019 // - when the device is in pointer mode, to show the mouse cursor;
1020 (mDeviceMode == DeviceMode::POINTER) ||
1021 // - when pointer capture is enabled, to preserve the mouse cursor position;
1022 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1023 mConfig.pointerCaptureRequest.enable) ||
1024 // - when we should be showing touches;
1025 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1026 // - when we should be showing a pointer icon for direct styluses.
1027 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1028 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001029 if (mPointerController == nullptr) {
1030 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001031 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001032 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001033 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1034 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001035 } else {
lilinnandef700b2022-06-17 19:32:01 +08001036 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1037 !mConfig.showTouches) {
1038 mPointerController->clearSpots();
1039 }
Michael Wright17db18e2020-06-26 20:51:44 +01001040 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001041 }
1042
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001043 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001044 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001045 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001046 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001047 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001048
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001049 configureVirtualKeys();
1050
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001051 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001052
1053 // Location
1054 updateAffineTransformation();
1055
Michael Wright227c5542020-07-02 18:30:52 +01001056 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001058 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1059 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001060
1061 // Scale movements such that one whole swipe of the touch pad covers a
1062 // given area relative to the diagonal size of the display when no acceleration
1063 // is applied.
1064 // Assume that the touch pad has a square aspect ratio such that movements in
1065 // X and Y of the same number of raw units cover the same physical distance.
1066 mPointerXMovementScale =
1067 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1068 mPointerYMovementScale = mPointerXMovementScale;
1069
1070 // Scale zooms to cover a smaller range of the display than movements do.
1071 // This value determines the area around the pointer that is affected by freeform
1072 // pointer gestures.
1073 mPointerXZoomScale =
1074 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1075 mPointerYZoomScale = mPointerXZoomScale;
1076
HQ Liue6983c72022-04-19 22:14:56 +00001077 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1078 // axis is non positive value.
1079 const float minFreeformGestureWidth =
1080 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1081
1082 mPointerGestureMaxSwipeWidth =
1083 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1084 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001085 }
1086
1087 // Inform the dispatcher about the changes.
1088 *outResetNeeded = true;
1089 bumpGeneration();
1090 }
1091}
1092
Prabir Pradhan1728b212021-10-19 16:00:03 -07001093void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001094 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001095 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001096 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1097 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001098 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001099}
1100
1101void TouchInputMapper::configureVirtualKeys() {
1102 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001103 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001104
1105 mVirtualKeys.clear();
1106
1107 if (virtualKeyDefinitions.size() == 0) {
1108 return;
1109 }
1110
1111 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1112 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1113 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1114 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1115
1116 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1117 VirtualKey virtualKey;
1118
1119 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1120 int32_t keyCode;
1121 int32_t dummyKeyMetaState;
1122 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001123 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1124 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001125 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1126 continue; // drop the key
1127 }
1128
1129 virtualKey.keyCode = keyCode;
1130 virtualKey.flags = flags;
1131
1132 // convert the key definition's display coordinates into touch coordinates for a hit box
1133 int32_t halfWidth = virtualKeyDefinition.width / 2;
1134 int32_t halfHeight = virtualKeyDefinition.height / 2;
1135
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001136 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1137 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001138 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001139 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1140 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001142 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1143 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001145 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1146 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 touchScreenTop;
1148 mVirtualKeys.push_back(virtualKey);
1149 }
1150}
1151
1152void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1153 if (!mVirtualKeys.empty()) {
1154 dump += INDENT3 "Virtual Keys:\n";
1155
1156 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1157 const VirtualKey& virtualKey = mVirtualKeys[i];
1158 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1159 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1160 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1161 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1162 }
1163 }
1164}
1165
1166void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001167 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 Calibration& out = mCalibration;
1169
1170 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001172 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1173 if (sizeCalibrationString.has_value()) {
1174 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001176 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001177 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001178 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001179 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001180 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001182 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001184 } else if (*sizeCalibrationString != "default") {
1185 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 }
1187 }
1188
Harry Cuttsf13161a2023-03-08 14:15:49 +00001189 out.sizeScale = in.getFloat("touch.size.scale");
1190 out.sizeBias = in.getFloat("touch.size.bias");
1191 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192
1193 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001194 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001195 std::optional<std::string> pressureCalibrationString =
1196 in.getString("touch.pressure.calibration");
1197 if (pressureCalibrationString.has_value()) {
1198 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001200 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001202 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001203 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001204 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001206 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 }
1208 }
1209
Harry Cuttsf13161a2023-03-08 14:15:49 +00001210 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211
1212 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001213 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001214 std::optional<std::string> orientationCalibrationString =
1215 in.getString("touch.orientation.calibration");
1216 if (orientationCalibrationString.has_value()) {
1217 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001218 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001219 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001220 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001221 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001223 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001224 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001225 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001226 }
1227 }
1228
1229 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001230 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001231 std::optional<std::string> distanceCalibrationString =
1232 in.getString("touch.distance.calibration");
1233 if (distanceCalibrationString.has_value()) {
1234 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001235 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001236 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001237 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001238 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001240 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241 }
1242 }
1243
Harry Cuttsf13161a2023-03-08 14:15:49 +00001244 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245}
1246
1247void TouchInputMapper::resolveCalibration() {
1248 // Size
1249 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001250 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1251 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252 }
1253 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001254 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256
1257 // Pressure
1258 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001259 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1260 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 }
1262 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001263 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265
1266 // Orientation
1267 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001268 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1269 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270 }
1271 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001272 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 }
1274
1275 // Distance
1276 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001277 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1278 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 }
1280 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001281 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283}
1284
1285void TouchInputMapper::dumpCalibration(std::string& dump) {
1286 dump += INDENT3 "Calibration:\n";
1287
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001288 dump += INDENT4 "touch.size.calibration: ";
1289 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001291 if (mCalibration.sizeScale) {
1292 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293 }
1294
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001295 if (mCalibration.sizeBias) {
1296 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 }
1298
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001299 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001301 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001302 }
1303
1304 // Pressure
1305 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001306 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.pressure.calibration: none\n";
1308 break;
Michael Wright227c5542020-07-02 18:30:52 +01001309 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.pressure.calibration: physical\n";
1311 break;
Michael Wright227c5542020-07-02 18:30:52 +01001312 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1314 break;
1315 default:
1316 ALOG_ASSERT(false);
1317 }
1318
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001319 if (mCalibration.pressureScale) {
1320 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001321 }
1322
1323 // Orientation
1324 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001325 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001326 dump += INDENT4 "touch.orientation.calibration: none\n";
1327 break;
Michael Wright227c5542020-07-02 18:30:52 +01001328 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1330 break;
Michael Wright227c5542020-07-02 18:30:52 +01001331 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 dump += INDENT4 "touch.orientation.calibration: vector\n";
1333 break;
1334 default:
1335 ALOG_ASSERT(false);
1336 }
1337
1338 // Distance
1339 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001340 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.distance.calibration: none\n";
1342 break;
Michael Wright227c5542020-07-02 18:30:52 +01001343 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.distance.calibration: scaled\n";
1345 break;
1346 default:
1347 ALOG_ASSERT(false);
1348 }
1349
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001350 if (mCalibration.distanceScale) {
1351 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001352 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353}
1354
1355void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1356 dump += INDENT3 "Affine Transformation:\n";
1357
1358 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1359 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1360 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1361 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1362 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1363 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1364}
1365
1366void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001367 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001368 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001369}
1370
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001371std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001372 std::list<NotifyArgs> out = cancelTouch(when, when);
1373 updateTouchSpots();
1374
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001375 mCursorButtonAccumulator.reset(getDeviceContext());
1376 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001377 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001378
1379 mPointerVelocityControl.reset();
1380 mWheelXVelocityControl.reset();
1381 mWheelYVelocityControl.reset();
1382
1383 mRawStatesPending.clear();
1384 mCurrentRawState.clear();
1385 mCurrentCookedState.clear();
1386 mLastRawState.clear();
1387 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001388 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001389 mSentHoverEnter = false;
1390 mHavePointerIds = false;
1391 mCurrentMotionAborted = false;
1392 mDownTime = 0;
1393
1394 mCurrentVirtualKey.down = false;
1395
1396 mPointerGesture.reset();
1397 mPointerSimple.reset();
1398 resetExternalStylus();
1399
1400 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001401 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001402 mPointerController->clearSpots();
1403 }
1404
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001405 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001406}
1407
1408void TouchInputMapper::resetExternalStylus() {
1409 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001410 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411 mExternalStylusFusionTimeout = LLONG_MAX;
1412 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001413 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001414}
1415
1416void TouchInputMapper::clearStylusDataPendingFlags() {
1417 mExternalStylusDataPending = false;
1418 mExternalStylusFusionTimeout = LLONG_MAX;
1419}
1420
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001421std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001422 mCursorButtonAccumulator.process(rawEvent);
1423 mCursorScrollAccumulator.process(rawEvent);
1424 mTouchButtonAccumulator.process(rawEvent);
1425
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001426 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001427 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001428 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001429 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001430 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431}
1432
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001433std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1434 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001435 if (mDeviceMode == DeviceMode::DISABLED) {
1436 // Only save the last pending state when the device is disabled.
1437 mRawStatesPending.clear();
1438 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001439 // Push a new state.
1440 mRawStatesPending.emplace_back();
1441
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001442 RawState& next = mRawStatesPending.back();
1443 next.clear();
1444 next.when = when;
1445 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001446
1447 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001448 next.buttonState = filterButtonState(mConfig,
1449 mTouchButtonAccumulator.getButtonState() |
1450 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451
1452 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001453 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1454 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455 mCursorScrollAccumulator.finishSync();
1456
1457 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001458 syncTouch(when, &next);
1459
1460 // The last RawState is the actually second to last, since we just added a new state
1461 const RawState& last =
1462 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001463
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001464 std::tie(next.when, next.readTime) =
1465 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1466 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001467
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001468 // Assign pointer ids.
1469 if (!mHavePointerIds) {
1470 assignPointerIds(last, next);
1471 }
1472
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001473 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001474 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1475 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1476 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1477 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1478 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1479 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001480
Arthur Hung9ad18942021-06-19 02:04:46 +00001481 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1482 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1483 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1484 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1485 next.rawPointerData.hoveringIdBits.value);
1486 }
1487
Harry Cutts33476232023-01-30 19:57:29 +00001488 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001489 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001490}
1491
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001492std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1493 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001494 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001495 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001496 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001497 }
1498
1499 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1500 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1501 // touching the current state will only observe the events that have been dispatched to the
1502 // rest of the pipeline.
1503 const size_t N = mRawStatesPending.size();
1504 size_t count;
1505 for (count = 0; count < N; count++) {
1506 const RawState& next = mRawStatesPending[count];
1507
1508 // A failure to assign the stylus id means that we're waiting on stylus data
1509 // and so should defer the rest of the pipeline.
1510 if (assignExternalStylusId(next, timeout)) {
1511 break;
1512 }
1513
1514 // All ready to go.
1515 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001516 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001517 if (mCurrentRawState.when < mLastRawState.when) {
1518 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001519 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001520 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001521 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522 }
1523 if (count != 0) {
1524 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1525 }
1526
1527 if (mExternalStylusDataPending) {
1528 if (timeout) {
1529 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1530 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001531 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001532 ALOGD_IF(DEBUG_STYLUS_FUSION,
1533 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001534 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001535 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001536 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1537 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1538 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1539 }
1540 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001541 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001542}
1543
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001544std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1545 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001546 // Always start with a clean state.
1547 mCurrentCookedState.clear();
1548
1549 // Apply stylus buttons to current raw state.
1550 applyExternalStylusButtonState(when);
1551
1552 // Handle policy on initial down or hover events.
1553 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1554 mCurrentRawState.rawPointerData.pointerCount != 0;
1555
1556 uint32_t policyFlags = 0;
1557 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1558 if (initialDown || buttonsPressed) {
1559 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001560 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001561 getContext()->fadePointer();
1562 }
1563
1564 if (mParameters.wake) {
1565 policyFlags |= POLICY_FLAG_WAKE;
1566 }
1567 }
1568
1569 // Consume raw off-screen touches before cooking pointer data.
1570 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001571 bool consumed;
1572 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1573 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001574 mCurrentRawState.rawPointerData.clear();
1575 }
1576
1577 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1578 // with cooked pointer data that has the same ids and indices as the raw data.
1579 // The following code can use either the raw or cooked data, as needed.
1580 cookPointerData();
1581
1582 // Apply stylus pressure to current cooked state.
1583 applyExternalStylusTouchState(when);
1584
1585 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001586 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1587 mSource, mViewport.displayId, policyFlags,
1588 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001589
1590 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001591 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001592 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1593 uint32_t id = idBits.clearFirstMarkedBit();
1594 const RawPointerData::Pointer& pointer =
1595 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001596 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001597 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001598 } else if (pointer.toolType == ToolType::FINGER ||
1599 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001600 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001601 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001602 mCurrentCookedState.mouseIdBits.markBit(id);
1603 }
1604 }
1605 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1606 uint32_t id = idBits.clearFirstMarkedBit();
1607 const RawPointerData::Pointer& pointer =
1608 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001609 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001610 mCurrentCookedState.stylusIdBits.markBit(id);
1611 }
1612 }
1613
1614 // Stylus takes precedence over all tools, then mouse, then finger.
1615 PointerUsage pointerUsage = mPointerUsage;
1616 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1617 mCurrentCookedState.mouseIdBits.clear();
1618 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001619 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001620 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1621 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001622 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001623 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1624 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001625 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001626 }
1627
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001628 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001629 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001631 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001632 out += dispatchButtonRelease(when, readTime, policyFlags);
1633 out += dispatchHoverExit(when, readTime, policyFlags);
1634 out += dispatchTouches(when, readTime, policyFlags);
1635 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1636 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001637 }
1638
1639 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1640 mCurrentMotionAborted = false;
1641 }
1642 }
1643
1644 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001645 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1646 mSource, mViewport.displayId, policyFlags,
1647 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001648
1649 // Clear some transient state.
1650 mCurrentRawState.rawVScroll = 0;
1651 mCurrentRawState.rawHScroll = 0;
1652
1653 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001654 mLastRawState = mCurrentRawState;
1655 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001656 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001657}
1658
Garfield Tanc734e4f2021-01-15 20:01:39 -08001659void TouchInputMapper::updateTouchSpots() {
1660 if (!mConfig.showTouches || mPointerController == nullptr) {
1661 return;
1662 }
1663
1664 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1665 // clear touch spots.
1666 if (mDeviceMode != DeviceMode::DIRECT &&
1667 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1668 return;
1669 }
1670
1671 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1672 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1673
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001674 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1675 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001676 mCurrentCookedState.cookedPointerData.touchingIdBits |
1677 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001678 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001679}
1680
1681bool TouchInputMapper::isTouchScreen() {
1682 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1683 mParameters.hasAssociatedDisplay;
1684}
1685
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001686void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001687 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1688 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001689 const int32_t pressedButtons =
1690 filterButtonState(mConfig,
1691 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001692 const int32_t releasedButtons =
1693 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1694
1695 mCurrentRawState.buttonState |= pressedButtons;
1696 mCurrentRawState.buttonState &= ~releasedButtons;
1697
1698 mExternalStylusButtonsApplied |= pressedButtons;
1699 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001700 }
1701}
1702
1703void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1704 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1705 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001706 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1707 return;
1708 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001709
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001710 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1711 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1712 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1713 : 0.f;
1714 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1715 pressure = *mExternalStylusState.pressure;
1716 }
1717 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1718 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001719
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001720 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001721 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001722 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001723 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001724 }
1725}
1726
1727bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001728 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001729 return false;
1730 }
1731
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001732 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001733 if (mFusedStylusPointerId &&
1734 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001735 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001736 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001737 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001738 }
1739
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001740 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1741 state.rawPointerData.pointerCount != 0;
1742 if (!initialDown) {
1743 return false;
1744 }
1745
1746 if (!mExternalStylusState.pressure) {
1747 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1748 return false;
1749 }
1750
1751 if (*mExternalStylusState.pressure != 0.0f) {
1752 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1753 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1754 return false;
1755 }
1756
1757 if (timeout) {
1758 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1759 mFusedStylusPointerId.reset();
1760 mExternalStylusFusionTimeout = LLONG_MAX;
1761 return false;
1762 }
1763
1764 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1765 // being processed until we either get pressure data or timeout.
1766 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1767 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1768 }
1769 ALOGD_IF(DEBUG_STYLUS_FUSION,
1770 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1771 mExternalStylusFusionTimeout);
1772 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1773 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001774}
1775
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001776std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1777 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001778 if (mDeviceMode == DeviceMode::POINTER) {
1779 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001780 // Since this is a synthetic event, we can consider its latency to be zero
1781 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001782 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001783 }
Michael Wright227c5542020-07-02 18:30:52 +01001784 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001785 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001786 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001787 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1788 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1789 }
1790 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001791 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001792}
1793
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001794std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1795 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001796 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001797 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001798 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001799 // The following three cases are handled here:
1800 // - We're in the middle of a fused stream of data;
1801 // - We're waiting on external stylus data before dispatching the initial down; or
1802 // - Only the button state, which is not reported through a specific pointer, has changed.
1803 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001804 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001805 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001806 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001807 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001808}
1809
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001810std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1811 uint32_t policyFlags, bool& outConsumed) {
1812 outConsumed = false;
1813 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001814 // Check for release of a virtual key.
1815 if (mCurrentVirtualKey.down) {
1816 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1817 // Pointer went up while virtual key was down.
1818 mCurrentVirtualKey.down = false;
1819 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001820 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1821 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1822 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001823 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1824 AKEY_EVENT_FLAG_FROM_SYSTEM |
1825 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001826 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001827 outConsumed = true;
1828 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001829 }
1830
1831 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1832 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1833 const RawPointerData::Pointer& pointer =
1834 mCurrentRawState.rawPointerData.pointerForId(id);
1835 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1836 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1837 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001838 outConsumed = true;
1839 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001840 }
1841 }
1842
1843 // Pointer left virtual key area or another pointer also went down.
1844 // Send key cancellation but do not consume the touch yet.
1845 // This is useful when the user swipes through from the virtual key area
1846 // into the main display surface.
1847 mCurrentVirtualKey.down = false;
1848 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001849 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1850 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001851 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1852 AKEY_EVENT_FLAG_FROM_SYSTEM |
1853 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1854 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001855 }
1856 }
1857
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001858 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
1859 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty() &&
1860 mDeviceMode != DeviceMode::UNSCALED) {
1861 // We have hovering pointers, and there are no touching pointers.
1862 bool hoveringPointersInFrame = false;
1863 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1864 while (!hoveringIds.isEmpty()) {
1865 uint32_t id = hoveringIds.clearFirstMarkedBit();
1866 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1867 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1868 hoveringPointersInFrame = true;
1869 break;
1870 }
1871 }
1872 if (!hoveringPointersInFrame) {
1873 // All hovering pointers are outside the physical frame.
1874 outConsumed = true;
1875 return out;
1876 }
1877 }
1878
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001879 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1880 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1881 // Pointer just went down. Check for virtual key press or off-screen touches.
1882 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1883 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001884 // Skip checking whether the pointer is inside the physical frame if the device is in
1885 // unscaled mode.
1886 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1887 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001888 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001889 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001890 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1891 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1892 if (virtualKey) {
1893 mCurrentVirtualKey.down = true;
1894 mCurrentVirtualKey.downTime = when;
1895 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1896 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1897 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001898 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1899 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001900
1901 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001902 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1903 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1904 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001905 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1906 AKEY_EVENT_ACTION_DOWN,
1907 AKEY_EVENT_FLAG_FROM_SYSTEM |
1908 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001909 }
1910 }
1911 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001912 outConsumed = true;
1913 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001914 }
1915 }
1916
1917 // Disable all virtual key touches that happen within a short time interval of the
1918 // most recent touch within the screen area. The idea is to filter out stray
1919 // virtual key presses when interacting with the touch screen.
1920 //
1921 // Problems we're trying to solve:
1922 //
1923 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1924 // virtual key area that is implemented by a separate touch panel and accidentally
1925 // triggers a virtual key.
1926 //
1927 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1928 // area and accidentally triggers a virtual key. This often happens when virtual keys
1929 // are layed out below the screen near to where the on screen keyboard's space bar
1930 // is displayed.
1931 if (mConfig.virtualKeyQuietTime > 0 &&
1932 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001933 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001934 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001935 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001936}
1937
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001938NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1939 uint32_t policyFlags, int32_t keyEventAction,
1940 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001941 int32_t keyCode = mCurrentVirtualKey.keyCode;
1942 int32_t scanCode = mCurrentVirtualKey.scanCode;
1943 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001944 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001945 policyFlags |= POLICY_FLAG_VIRTUAL;
1946
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001947 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1948 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1949 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001950}
1951
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001952std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1953 uint32_t policyFlags) {
1954 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001955 if (mCurrentMotionAborted) {
1956 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001957 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001958 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001959 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1960 if (!currentIdBits.isEmpty()) {
1961 int32_t metaState = getContext()->getGlobalMetaState();
1962 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001963 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001964 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1965 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001966 mCurrentCookedState.cookedPointerData.pointerProperties,
1967 mCurrentCookedState.cookedPointerData.pointerCoords,
1968 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1969 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1970 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001971 mCurrentMotionAborted = true;
1972 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001973 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001974}
1975
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001976// Updates pointer coords and properties for pointers with specified ids that have moved.
1977// Returns true if any of them changed.
1978static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1979 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1980 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1981 BitSet32 idBits) {
1982 bool changed = false;
1983 while (!idBits.isEmpty()) {
1984 uint32_t id = idBits.clearFirstMarkedBit();
1985 uint32_t inIndex = inIdToIndex[id];
1986 uint32_t outIndex = outIdToIndex[id];
1987
1988 const PointerProperties& curInProperties = inProperties[inIndex];
1989 const PointerCoords& curInCoords = inCoords[inIndex];
1990 PointerProperties& curOutProperties = outProperties[outIndex];
1991 PointerCoords& curOutCoords = outCoords[outIndex];
1992
1993 if (curInProperties != curOutProperties) {
1994 curOutProperties.copyFrom(curInProperties);
1995 changed = true;
1996 }
1997
1998 if (curInCoords != curOutCoords) {
1999 curOutCoords.copyFrom(curInCoords);
2000 changed = true;
2001 }
2002 }
2003 return changed;
2004}
2005
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002006std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
2007 uint32_t policyFlags) {
2008 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002009 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2010 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2011 int32_t metaState = getContext()->getGlobalMetaState();
2012 int32_t buttonState = mCurrentCookedState.buttonState;
2013
2014 if (currentIdBits == lastIdBits) {
2015 if (!currentIdBits.isEmpty()) {
2016 // No pointer id changes so this is a move event.
2017 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002018 out.push_back(
2019 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2020 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2021 mCurrentCookedState.cookedPointerData.pointerProperties,
2022 mCurrentCookedState.cookedPointerData.pointerCoords,
2023 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2024 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2025 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002026 }
2027 } else {
2028 // There may be pointers going up and pointers going down and pointers moving
2029 // all at the same time.
2030 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2031 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2032 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2033 BitSet32 dispatchedIdBits(lastIdBits.value);
2034
2035 // Update last coordinates of pointers that have moved so that we observe the new
2036 // pointer positions at the same time as other pointers that have just gone up.
2037 bool moveNeeded =
2038 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2039 mCurrentCookedState.cookedPointerData.pointerCoords,
2040 mCurrentCookedState.cookedPointerData.idToIndex,
2041 mLastCookedState.cookedPointerData.pointerProperties,
2042 mLastCookedState.cookedPointerData.pointerCoords,
2043 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2044 if (buttonState != mLastCookedState.buttonState) {
2045 moveNeeded = true;
2046 }
2047
2048 // Dispatch pointer up events.
2049 while (!upIdBits.isEmpty()) {
2050 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002051 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002052 if (isCanceled) {
2053 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2054 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002055 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2056 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2057 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2058 buttonState, 0,
2059 mLastCookedState.cookedPointerData.pointerProperties,
2060 mLastCookedState.cookedPointerData.pointerCoords,
2061 mLastCookedState.cookedPointerData.idToIndex,
2062 dispatchedIdBits, upId, mOrientedXPrecision,
2063 mOrientedYPrecision, mDownTime,
2064 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002065 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002066 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002067 }
2068
2069 // Dispatch move events if any of the remaining pointers moved from their old locations.
2070 // Although applications receive new locations as part of individual pointer up
2071 // events, they do not generally handle them except when presented in a move event.
2072 if (moveNeeded && !moveIdBits.isEmpty()) {
2073 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002074 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2075 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2076 mCurrentCookedState.cookedPointerData.pointerProperties,
2077 mCurrentCookedState.cookedPointerData.pointerCoords,
2078 mCurrentCookedState.cookedPointerData.idToIndex,
2079 dispatchedIdBits, -1, mOrientedXPrecision,
2080 mOrientedYPrecision, mDownTime,
2081 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002082 }
2083
2084 // Dispatch pointer down events using the new pointer locations.
2085 while (!downIdBits.isEmpty()) {
2086 uint32_t downId = downIdBits.clearFirstMarkedBit();
2087 dispatchedIdBits.markBit(downId);
2088
2089 if (dispatchedIdBits.count() == 1) {
2090 // First pointer is going down. Set down time.
2091 mDownTime = when;
2092 }
2093
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002094 out.push_back(
2095 dispatchMotion(when, readTime, policyFlags, mSource,
2096 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2097 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2098 mCurrentCookedState.cookedPointerData.pointerCoords,
2099 mCurrentCookedState.cookedPointerData.idToIndex,
2100 dispatchedIdBits, downId, mOrientedXPrecision,
2101 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002102 }
2103 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002104 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002105}
2106
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002107std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2108 uint32_t policyFlags) {
2109 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002110 if (mSentHoverEnter &&
2111 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2112 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2113 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002114 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2115 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2116 mLastCookedState.buttonState, 0,
2117 mLastCookedState.cookedPointerData.pointerProperties,
2118 mLastCookedState.cookedPointerData.pointerCoords,
2119 mLastCookedState.cookedPointerData.idToIndex,
2120 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2121 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2122 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002123 mSentHoverEnter = false;
2124 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002125 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002126}
2127
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002128std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2129 uint32_t policyFlags) {
2130 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002131 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2132 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2133 int32_t metaState = getContext()->getGlobalMetaState();
2134 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002135 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2136 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2137 mCurrentRawState.buttonState, 0,
2138 mCurrentCookedState.cookedPointerData.pointerProperties,
2139 mCurrentCookedState.cookedPointerData.pointerCoords,
2140 mCurrentCookedState.cookedPointerData.idToIndex,
2141 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2142 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2143 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002144 mSentHoverEnter = true;
2145 }
2146
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002147 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2148 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2149 mCurrentRawState.buttonState, 0,
2150 mCurrentCookedState.cookedPointerData.pointerProperties,
2151 mCurrentCookedState.cookedPointerData.pointerCoords,
2152 mCurrentCookedState.cookedPointerData.idToIndex,
2153 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2154 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2155 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002156 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002157 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002158}
2159
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002160std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2161 uint32_t policyFlags) {
2162 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002163 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2164 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2165 const int32_t metaState = getContext()->getGlobalMetaState();
2166 int32_t buttonState = mLastCookedState.buttonState;
2167 while (!releasedButtons.isEmpty()) {
2168 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2169 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002170 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2171 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2172 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002173 mLastCookedState.cookedPointerData.pointerProperties,
2174 mLastCookedState.cookedPointerData.pointerCoords,
2175 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002176 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2177 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002178 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002179 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002180}
2181
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002182std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2183 uint32_t policyFlags) {
2184 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002185 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2186 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2187 const int32_t metaState = getContext()->getGlobalMetaState();
2188 int32_t buttonState = mLastCookedState.buttonState;
2189 while (!pressedButtons.isEmpty()) {
2190 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2191 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002192 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2193 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2194 buttonState, 0,
2195 mCurrentCookedState.cookedPointerData.pointerProperties,
2196 mCurrentCookedState.cookedPointerData.pointerCoords,
2197 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2198 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2199 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002200 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002201 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002202}
2203
LiZhihong758eb562022-11-03 15:28:29 +08002204std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2205 uint32_t policyFlags,
2206 BitSet32 idBits,
2207 nsecs_t readTime) {
2208 std::list<NotifyArgs> out;
2209 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2210 const int32_t metaState = getContext()->getGlobalMetaState();
2211 int32_t buttonState = mLastCookedState.buttonState;
2212
2213 while (!releasedButtons.isEmpty()) {
2214 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2215 buttonState &= ~actionButton;
2216 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2217 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2218 metaState, buttonState, 0,
2219 mPointerGesture.lastGestureProperties,
2220 mPointerGesture.lastGestureCoords,
2221 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2222 mOrientedXPrecision, mOrientedYPrecision,
2223 mPointerGesture.downTime, MotionClassification::NONE));
2224 }
2225 return out;
2226}
2227
2228std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2229 uint32_t policyFlags,
2230 BitSet32 idBits,
2231 nsecs_t readTime) {
2232 std::list<NotifyArgs> out;
2233 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2234 const int32_t metaState = getContext()->getGlobalMetaState();
2235 int32_t buttonState = mLastCookedState.buttonState;
2236
2237 while (!pressedButtons.isEmpty()) {
2238 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2239 buttonState |= actionButton;
2240 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2241 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2242 buttonState, 0, mPointerGesture.currentGestureProperties,
2243 mPointerGesture.currentGestureCoords,
2244 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2245 mOrientedXPrecision, mOrientedYPrecision,
2246 mPointerGesture.downTime, MotionClassification::NONE));
2247 }
2248 return out;
2249}
2250
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002251const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2252 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2253 return cookedPointerData.touchingIdBits;
2254 }
2255 return cookedPointerData.hoveringIdBits;
2256}
2257
2258void TouchInputMapper::cookPointerData() {
2259 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2260
2261 mCurrentCookedState.cookedPointerData.clear();
2262 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2263 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2264 mCurrentRawState.rawPointerData.hoveringIdBits;
2265 mCurrentCookedState.cookedPointerData.touchingIdBits =
2266 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002267 mCurrentCookedState.cookedPointerData.canceledIdBits =
2268 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002269
2270 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2271 mCurrentCookedState.buttonState = 0;
2272 } else {
2273 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2274 }
2275
2276 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002277 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002278 for (uint32_t i = 0; i < currentPointerCount; i++) {
2279 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2280
2281 // Size
2282 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2283 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002284 case Calibration::SizeCalibration::GEOMETRIC:
2285 case Calibration::SizeCalibration::DIAMETER:
2286 case Calibration::SizeCalibration::BOX:
2287 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002288 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2289 touchMajor = in.touchMajor;
2290 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2291 toolMajor = in.toolMajor;
2292 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2293 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2294 : in.touchMajor;
2295 } else if (mRawPointerAxes.touchMajor.valid) {
2296 toolMajor = touchMajor = in.touchMajor;
2297 toolMinor = touchMinor =
2298 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2299 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2300 : in.touchMajor;
2301 } else if (mRawPointerAxes.toolMajor.valid) {
2302 touchMajor = toolMajor = in.toolMajor;
2303 touchMinor = toolMinor =
2304 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2305 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2306 : in.toolMajor;
2307 } else {
2308 ALOG_ASSERT(false,
2309 "No touch or tool axes. "
2310 "Size calibration should have been resolved to NONE.");
2311 touchMajor = 0;
2312 touchMinor = 0;
2313 toolMajor = 0;
2314 toolMinor = 0;
2315 size = 0;
2316 }
2317
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002318 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002319 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2320 if (touchingCount > 1) {
2321 touchMajor /= touchingCount;
2322 touchMinor /= touchingCount;
2323 toolMajor /= touchingCount;
2324 toolMinor /= touchingCount;
2325 size /= touchingCount;
2326 }
2327 }
2328
Michael Wright227c5542020-07-02 18:30:52 +01002329 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002330 touchMajor *= mGeometricScale;
2331 touchMinor *= mGeometricScale;
2332 toolMajor *= mGeometricScale;
2333 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002334 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002335 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2336 touchMinor = touchMajor;
2337 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2338 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002339 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002340 touchMinor = touchMajor;
2341 toolMinor = toolMajor;
2342 }
2343
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002344 mCalibration.applySizeScaleAndBias(touchMajor);
2345 mCalibration.applySizeScaleAndBias(touchMinor);
2346 mCalibration.applySizeScaleAndBias(toolMajor);
2347 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002348 size *= mSizeScale;
2349 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002350 case Calibration::SizeCalibration::DEFAULT:
2351 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2352 break;
2353 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354 touchMajor = 0;
2355 touchMinor = 0;
2356 toolMajor = 0;
2357 toolMinor = 0;
2358 size = 0;
2359 break;
2360 }
2361
2362 // Pressure
2363 float pressure;
2364 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002365 case Calibration::PressureCalibration::PHYSICAL:
2366 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002367 pressure = in.pressure * mPressureScale;
2368 break;
2369 default:
2370 pressure = in.isHovering ? 0 : 1;
2371 break;
2372 }
2373
2374 // Tilt and Orientation
2375 float tilt;
2376 float orientation;
2377 if (mHaveTilt) {
2378 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2379 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002380 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2382 } else {
2383 tilt = 0;
2384
2385 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002386 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002387 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 break;
Michael Wright227c5542020-07-02 18:30:52 +01002389 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2391 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2392 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002393 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 float confidence = hypotf(c1, c2);
2395 float scale = 1.0f + confidence / 16.0f;
2396 touchMajor *= scale;
2397 touchMinor /= scale;
2398 toolMajor *= scale;
2399 toolMinor /= scale;
2400 } else {
2401 orientation = 0;
2402 }
2403 break;
2404 }
2405 default:
2406 orientation = 0;
2407 }
2408 }
2409
2410 // Distance
2411 float distance;
2412 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002413 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002414 distance = in.distance * mDistanceScale;
2415 break;
2416 default:
2417 distance = 0;
2418 }
2419
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002420 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2421 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002422 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2423 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002424
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 // Write output coords.
2426 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2427 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002428 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2429 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002430 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2431 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2432 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2433 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2434 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2435 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2436 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002437 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2438 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002439
Chris Ye364fdb52020-08-05 15:07:56 -07002440 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002441 uint32_t id = in.id;
2442 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2443 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2444 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002445 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2446 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002447 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2448 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2449 }
2450
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002451 // Write output properties.
2452 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002453 properties.clear();
2454 properties.id = id;
2455 properties.toolType = in.toolType;
2456
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002457 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002459 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 }
2461}
2462
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002463std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2464 uint32_t policyFlags,
2465 PointerUsage pointerUsage) {
2466 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002468 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 mPointerUsage = pointerUsage;
2470 }
2471
2472 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002473 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002474 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002475 break;
Michael Wright227c5542020-07-02 18:30:52 +01002476 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002477 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 break;
Michael Wright227c5542020-07-02 18:30:52 +01002479 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002480 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002481 break;
Michael Wright227c5542020-07-02 18:30:52 +01002482 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002483 break;
2484 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002485 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486}
2487
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002488std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2489 uint32_t policyFlags) {
2490 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002491 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002492 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002493 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002494 break;
Michael Wright227c5542020-07-02 18:30:52 +01002495 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002496 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002497 break;
Michael Wright227c5542020-07-02 18:30:52 +01002498 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002499 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002500 break;
Michael Wright227c5542020-07-02 18:30:52 +01002501 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002502 break;
2503 }
2504
Michael Wright227c5542020-07-02 18:30:52 +01002505 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002506 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002507}
2508
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002509std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2510 uint32_t policyFlags,
2511 bool isTimeout) {
2512 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002513 // Update current gesture coordinates.
2514 bool cancelPreviousGesture, finishPreviousGesture;
2515 bool sendEvents =
2516 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2517 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002518 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002519 }
2520 if (finishPreviousGesture) {
2521 cancelPreviousGesture = false;
2522 }
2523
2524 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002525 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002526 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002527 if (finishPreviousGesture || cancelPreviousGesture) {
2528 mPointerController->clearSpots();
2529 }
2530
Michael Wright227c5542020-07-02 18:30:52 +01002531 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002532 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2533 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002534 mPointerGesture.currentGestureIdBits,
2535 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002536 }
2537 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002538 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002539 }
2540
2541 // Show or hide the pointer if needed.
2542 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002543 case PointerGesture::Mode::NEUTRAL:
2544 case PointerGesture::Mode::QUIET:
2545 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2546 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002547 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002548 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002549 }
2550 break;
Michael Wright227c5542020-07-02 18:30:52 +01002551 case PointerGesture::Mode::TAP:
2552 case PointerGesture::Mode::TAP_DRAG:
2553 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2554 case PointerGesture::Mode::HOVER:
2555 case PointerGesture::Mode::PRESS:
2556 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002557 // Unfade the pointer when the current gesture manipulates the
2558 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002559 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002560 break;
Michael Wright227c5542020-07-02 18:30:52 +01002561 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002562 // Fade the pointer when the current gesture manipulates a different
2563 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002564 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002565 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002566 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002567 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002568 }
2569 break;
2570 }
2571
2572 // Send events!
2573 int32_t metaState = getContext()->getGlobalMetaState();
2574 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002575 const MotionClassification classification =
2576 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2577 ? MotionClassification::TWO_FINGER_SWIPE
2578 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002579
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002580 uint32_t flags = 0;
2581
2582 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2583 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2584 }
2585
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002586 // Update last coordinates of pointers that have moved so that we observe the new
2587 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002588 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2589 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2590 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2591 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2592 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2593 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002594 bool moveNeeded = false;
2595 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2596 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2597 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2598 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2599 mPointerGesture.lastGestureIdBits.value);
2600 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2601 mPointerGesture.currentGestureCoords,
2602 mPointerGesture.currentGestureIdToIndex,
2603 mPointerGesture.lastGestureProperties,
2604 mPointerGesture.lastGestureCoords,
2605 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2606 if (buttonState != mLastCookedState.buttonState) {
2607 moveNeeded = true;
2608 }
2609 }
2610
2611 // Send motion events for all pointers that went up or were canceled.
2612 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2613 if (!dispatchedGestureIdBits.isEmpty()) {
2614 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002615 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002616 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002617 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002618 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2619 mPointerGesture.lastGestureProperties,
2620 mPointerGesture.lastGestureCoords,
2621 mPointerGesture.lastGestureIdToIndex,
2622 dispatchedGestureIdBits, -1, 0, 0,
2623 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002624
2625 dispatchedGestureIdBits.clear();
2626 } else {
2627 BitSet32 upGestureIdBits;
2628 if (finishPreviousGesture) {
2629 upGestureIdBits = dispatchedGestureIdBits;
2630 } else {
2631 upGestureIdBits.value =
2632 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2633 }
2634 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002635 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2636 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2637 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2638 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2639 readTime);
2640 }
2641 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002642 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2643 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2644 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2645 mPointerGesture.lastGestureProperties,
2646 mPointerGesture.lastGestureCoords,
2647 mPointerGesture.lastGestureIdToIndex,
2648 dispatchedGestureIdBits, id, 0, 0,
2649 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002650
2651 dispatchedGestureIdBits.clearBit(id);
2652 }
2653 }
2654 }
2655
2656 // Send motion events for all pointers that moved.
2657 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002658 out.push_back(
2659 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2660 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2661 mPointerGesture.currentGestureProperties,
2662 mPointerGesture.currentGestureCoords,
2663 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2664 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002665 }
2666
2667 // Send motion events for all pointers that went down.
2668 if (down) {
2669 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2670 ~dispatchedGestureIdBits.value);
2671 while (!downGestureIdBits.isEmpty()) {
2672 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2673 dispatchedGestureIdBits.markBit(id);
2674
2675 if (dispatchedGestureIdBits.count() == 1) {
2676 mPointerGesture.downTime = when;
2677 }
2678
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002679 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2680 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2681 buttonState, 0, mPointerGesture.currentGestureProperties,
2682 mPointerGesture.currentGestureCoords,
2683 mPointerGesture.currentGestureIdToIndex,
2684 dispatchedGestureIdBits, id, 0, 0,
2685 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002686 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2687 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2688 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2689 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2690 readTime);
2691 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002692 }
2693 }
2694
2695 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002696 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002697 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2698 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2699 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2700 mPointerGesture.currentGestureProperties,
2701 mPointerGesture.currentGestureCoords,
2702 mPointerGesture.currentGestureIdToIndex,
2703 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2704 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002705 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2706 // Synthesize a hover move event after all pointers go up to indicate that
2707 // the pointer is hovering again even if the user is not currently touching
2708 // the touch pad. This ensures that a view will receive a fresh hover enter
2709 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002710 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002711
2712 PointerProperties pointerProperties;
2713 pointerProperties.clear();
2714 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002715 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002716
2717 PointerCoords pointerCoords;
2718 pointerCoords.clear();
2719 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2720 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2721
2722 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002723 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2724 mSource, displayId, policyFlags,
2725 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2726 buttonState, MotionClassification::NONE,
2727 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2728 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2729 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002730 }
2731
2732 // Update state.
2733 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2734 if (!down) {
2735 mPointerGesture.lastGestureIdBits.clear();
2736 } else {
2737 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2738 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2739 uint32_t id = idBits.clearFirstMarkedBit();
2740 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2741 mPointerGesture.lastGestureProperties[index].copyFrom(
2742 mPointerGesture.currentGestureProperties[index]);
2743 mPointerGesture.lastGestureCoords[index].copyFrom(
2744 mPointerGesture.currentGestureCoords[index]);
2745 mPointerGesture.lastGestureIdToIndex[id] = index;
2746 }
2747 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002748 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002749}
2750
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002751std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2752 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002753 const MotionClassification classification =
2754 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2755 ? MotionClassification::TWO_FINGER_SWIPE
2756 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002757 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002758 // Cancel previously dispatches pointers.
2759 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2760 int32_t metaState = getContext()->getGlobalMetaState();
2761 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002762 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002763 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2764 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002765 mPointerGesture.lastGestureProperties,
2766 mPointerGesture.lastGestureCoords,
2767 mPointerGesture.lastGestureIdToIndex,
2768 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2769 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002770 }
2771
2772 // Reset the current pointer gesture.
2773 mPointerGesture.reset();
2774 mPointerVelocityControl.reset();
2775
2776 // Remove any current spots.
2777 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002778 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002779 mPointerController->clearSpots();
2780 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002781 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002782}
2783
2784bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2785 bool* outFinishPreviousGesture, bool isTimeout) {
2786 *outCancelPreviousGesture = false;
2787 *outFinishPreviousGesture = false;
2788
2789 // Handle TAP timeout.
2790 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002791 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002792
Michael Wright227c5542020-07-02 18:30:52 +01002793 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002794 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2795 // The tap/drag timeout has not yet expired.
2796 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2797 mConfig.pointerGestureTapDragInterval);
2798 } else {
2799 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002800 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002801 *outFinishPreviousGesture = true;
2802
2803 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002804 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002805 mPointerGesture.currentGestureIdBits.clear();
2806
2807 mPointerVelocityControl.reset();
2808 return true;
2809 }
2810 }
2811
2812 // We did not handle this timeout.
2813 return false;
2814 }
2815
2816 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2817 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2818
2819 // Update the velocity tracker.
2820 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002821 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002822 uint32_t id = idBits.clearFirstMarkedBit();
2823 const RawPointerData::Pointer& pointer =
2824 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002825 const float x = pointer.x * mPointerXMovementScale;
2826 const float y = pointer.y * mPointerYMovementScale;
2827 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2828 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002829 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 }
2831
2832 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2833 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002834 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2835 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2836 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002837 mPointerGesture.resetTap();
2838 }
2839
2840 // Pick a new active touch id if needed.
2841 // Choose an arbitrary pointer that just went down, if there is one.
2842 // Otherwise choose an arbitrary remaining pointer.
2843 // This guarantees we always have an active touch id when there is at least one pointer.
2844 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002845 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002846 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002847 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002848 mPointerGesture.firstTouchTime = when;
2849 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002850 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2851 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2852 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2853 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002855 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002856
2857 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002858 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002859 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002860 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2861 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2862 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002863 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002864 *outFinishPreviousGesture = true;
2865 }
2866
2867 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002868 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002869 mPointerGesture.currentGestureIdBits.clear();
2870
2871 mPointerVelocityControl.reset();
2872 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2873 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2874 // The pointer follows the active touch point.
2875 // Emit DOWN, MOVE, UP events at the pointer location.
2876 //
2877 // Only the active touch matters; other fingers are ignored. This policy helps
2878 // to handle the case where the user places a second finger on the touch pad
2879 // to apply the necessary force to depress an integrated button below the surface.
2880 // We don't want the second finger to be delivered to applications.
2881 //
2882 // For this to work well, we need to make sure to track the pointer that is really
2883 // active. If the user first puts one finger down to click then adds another
2884 // finger to drag then the active pointer should switch to the finger that is
2885 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002886 ALOGD_IF(DEBUG_GESTURES,
2887 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2888 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002889 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002890 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891 *outFinishPreviousGesture = true;
2892 mPointerGesture.activeGestureId = 0;
2893 }
2894
2895 // Switch pointers if needed.
2896 // Find the fastest pointer and follow it.
2897 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002898 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002899 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002900 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002901 ALOGD_IF(DEBUG_GESTURES,
2902 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2903 "bestSpeed=%0.3f",
2904 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002905 }
2906 }
2907
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002908 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002909 // When using spots, the click will occur at the position of the anchor
2910 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002911 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002912 } else {
2913 mPointerVelocityControl.reset();
2914 }
2915
Prabir Pradhan2719e822023-02-28 17:39:36 +00002916 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002917
Michael Wright227c5542020-07-02 18:30:52 +01002918 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 mPointerGesture.currentGestureIdBits.clear();
2920 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2921 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2922 mPointerGesture.currentGestureProperties[0].clear();
2923 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002924 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002925 mPointerGesture.currentGestureCoords[0].clear();
2926 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2927 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2928 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2929 } else if (currentFingerCount == 0) {
2930 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002931 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002932 *outFinishPreviousGesture = true;
2933 }
2934
2935 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2936 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2937 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002938 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2939 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002940 lastFingerCount == 1) {
2941 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002942 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002943 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2944 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002945 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002946
2947 mPointerGesture.tapUpTime = when;
2948 getContext()->requestTimeoutAtTime(when +
2949 mConfig.pointerGestureTapDragInterval);
2950
2951 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002952 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002953 mPointerGesture.currentGestureIdBits.clear();
2954 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2955 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2956 mPointerGesture.currentGestureProperties[0].clear();
2957 mPointerGesture.currentGestureProperties[0].id =
2958 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002959 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002960 mPointerGesture.currentGestureCoords[0].clear();
2961 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2962 mPointerGesture.tapX);
2963 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2964 mPointerGesture.tapY);
2965 mPointerGesture.currentGestureCoords[0]
2966 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2967
2968 tapped = true;
2969 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002970 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2971 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002972 }
2973 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002974 if (DEBUG_GESTURES) {
2975 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2976 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2977 (when - mPointerGesture.tapDownTime) * 0.000001f);
2978 } else {
2979 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2980 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002982 }
2983 }
2984
2985 mPointerVelocityControl.reset();
2986
2987 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002988 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002989 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002990 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002991 mPointerGesture.currentGestureIdBits.clear();
2992 }
2993 } else if (currentFingerCount == 1) {
2994 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2995 // The pointer follows the active touch point.
2996 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2997 // When in TAP_DRAG, emit MOVE events at the pointer location.
2998 ALOG_ASSERT(activeTouchId >= 0);
2999
Michael Wright227c5542020-07-02 18:30:52 +01003000 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3001 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003002 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003003 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003004 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3005 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003006 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003007 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003008 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3009 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003010 }
3011 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003012 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3013 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003014 }
Michael Wright227c5542020-07-02 18:30:52 +01003015 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3016 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003017 }
3018
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003019 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003020 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003021 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003022 } else {
3023 mPointerVelocityControl.reset();
3024 }
3025
3026 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003027 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003028 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003029 down = true;
3030 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003031 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003032 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003033 *outFinishPreviousGesture = true;
3034 }
3035 mPointerGesture.activeGestureId = 0;
3036 down = false;
3037 }
3038
Prabir Pradhan2719e822023-02-28 17:39:36 +00003039 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003040
3041 mPointerGesture.currentGestureIdBits.clear();
3042 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3043 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3044 mPointerGesture.currentGestureProperties[0].clear();
3045 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003046 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003047 mPointerGesture.currentGestureCoords[0].clear();
3048 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3049 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3050 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3051 down ? 1.0f : 0.0f);
3052
3053 if (lastFingerCount == 0 && currentFingerCount != 0) {
3054 mPointerGesture.resetTap();
3055 mPointerGesture.tapDownTime = when;
3056 mPointerGesture.tapX = x;
3057 mPointerGesture.tapY = y;
3058 }
3059 } else {
3060 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003061 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003062 }
3063
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003064 if (DEBUG_GESTURES) {
3065 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3066 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3067 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3068 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3069 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3070 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3071 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3072 uint32_t id = idBits.clearFirstMarkedBit();
3073 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3074 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3075 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003076 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003077 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003078 id, index, ftl::enum_string(properties.toolType).c_str(),
3079 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003080 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3081 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3082 }
3083 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3084 uint32_t id = idBits.clearFirstMarkedBit();
3085 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3086 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3087 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003088 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003089 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003090 id, index, ftl::enum_string(properties.toolType).c_str(),
3091 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003092 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3093 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3094 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003095 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003096 return true;
3097}
3098
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003099bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3100 if (mPointerGesture.activeTouchId < 0) {
3101 mPointerGesture.resetQuietTime();
3102 return false;
3103 }
3104
3105 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3106 return true;
3107 }
3108
3109 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3110 bool isQuietTime = false;
3111 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3112 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3113 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3114 currentFingerCount < 2) {
3115 // Enter quiet time when exiting swipe or freeform state.
3116 // This is to prevent accidentally entering the hover state and flinging the
3117 // pointer when finishing a swipe and there is still one pointer left onscreen.
3118 isQuietTime = true;
3119 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3120 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3121 // Enter quiet time when releasing the button and there are still two or more
3122 // fingers down. This may indicate that one finger was used to press the button
3123 // but it has not gone up yet.
3124 isQuietTime = true;
3125 }
3126 if (isQuietTime) {
3127 mPointerGesture.quietTime = when;
3128 }
3129 return isQuietTime;
3130}
3131
3132std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3133 int32_t bestId = -1;
3134 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3135 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3136 uint32_t id = idBits.clearFirstMarkedBit();
3137 std::optional<float> vx =
3138 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3139 std::optional<float> vy =
3140 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3141 if (vx && vy) {
3142 float speed = hypotf(*vx, *vy);
3143 if (speed > bestSpeed) {
3144 bestId = id;
3145 bestSpeed = speed;
3146 }
3147 }
3148 }
3149 return std::make_pair(bestId, bestSpeed);
3150}
3151
3152void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3153 bool* finishPreviousGesture) {
3154 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3155 // to move before deciding what to do.
3156 //
3157 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3158 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3159 // just a press or long-press at the pointer location.
3160 //
3161 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3162 // pointer location.
3163 //
3164 // When the two fingers move enough or when additional fingers are added, we make a decision to
3165 // transition into SWIPE or FREEFORM mode accordingly.
3166 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3167 ALOG_ASSERT(activeTouchId >= 0);
3168
3169 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3170 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3171 bool settled =
3172 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3173 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3174 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3175 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3176 *finishPreviousGesture = true;
3177 } else if (!settled && currentFingerCount > lastFingerCount) {
3178 // Additional pointers have gone down but not yet settled.
3179 // Reset the gesture.
3180 ALOGD_IF(DEBUG_GESTURES,
3181 "Gestures: Resetting gesture since additional pointers went down for "
3182 "MULTITOUCH, settle time remaining %0.3fms",
3183 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3184 when) * 0.000001f);
3185 *cancelPreviousGesture = true;
3186 } else {
3187 // Continue previous gesture.
3188 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3189 }
3190
3191 if (*finishPreviousGesture || *cancelPreviousGesture) {
3192 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3193 mPointerGesture.activeGestureId = 0;
3194 mPointerGesture.referenceIdBits.clear();
3195 mPointerVelocityControl.reset();
3196
3197 // Use the centroid and pointer location as the reference points for the gesture.
3198 ALOGD_IF(DEBUG_GESTURES,
3199 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3200 "%0.3fms",
3201 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3202 when) * 0.000001f);
3203 mCurrentRawState.rawPointerData
3204 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3205 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003206 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3207 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003208 }
3209
3210 // Clear the reference deltas for fingers not yet included in the reference calculation.
3211 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3212 ~mPointerGesture.referenceIdBits.value);
3213 !idBits.isEmpty();) {
3214 uint32_t id = idBits.clearFirstMarkedBit();
3215 mPointerGesture.referenceDeltas[id].dx = 0;
3216 mPointerGesture.referenceDeltas[id].dy = 0;
3217 }
3218 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3219
3220 // Add delta for all fingers and calculate a common movement delta.
3221 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3222 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3223 mCurrentCookedState.fingerIdBits.value);
3224 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3225 bool first = (idBits == commonIdBits);
3226 uint32_t id = idBits.clearFirstMarkedBit();
3227 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3228 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3229 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3230 delta.dx += cpd.x - lpd.x;
3231 delta.dy += cpd.y - lpd.y;
3232
3233 if (first) {
3234 commonDeltaRawX = delta.dx;
3235 commonDeltaRawY = delta.dy;
3236 } else {
3237 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3238 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3239 }
3240 }
3241
3242 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3243 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3244 float dist[MAX_POINTER_ID + 1];
3245 int32_t distOverThreshold = 0;
3246 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3247 uint32_t id = idBits.clearFirstMarkedBit();
3248 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3249 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3250 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3251 distOverThreshold += 1;
3252 }
3253 }
3254
3255 // Only transition when at least two pointers have moved further than
3256 // the minimum distance threshold.
3257 if (distOverThreshold >= 2) {
3258 if (currentFingerCount > 2) {
3259 // There are more than two pointers, switch to FREEFORM.
3260 ALOGD_IF(DEBUG_GESTURES,
3261 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3262 currentFingerCount);
3263 *cancelPreviousGesture = true;
3264 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3265 } else {
3266 // There are exactly two pointers.
3267 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3268 uint32_t id1 = idBits.clearFirstMarkedBit();
3269 uint32_t id2 = idBits.firstMarkedBit();
3270 const RawPointerData::Pointer& p1 =
3271 mCurrentRawState.rawPointerData.pointerForId(id1);
3272 const RawPointerData::Pointer& p2 =
3273 mCurrentRawState.rawPointerData.pointerForId(id2);
3274 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3275 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3276 // There are two pointers but they are too far apart for a SWIPE,
3277 // switch to FREEFORM.
3278 ALOGD_IF(DEBUG_GESTURES,
3279 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3280 mutualDistance, mPointerGestureMaxSwipeWidth);
3281 *cancelPreviousGesture = true;
3282 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3283 } else {
3284 // There are two pointers. Wait for both pointers to start moving
3285 // before deciding whether this is a SWIPE or FREEFORM gesture.
3286 float dist1 = dist[id1];
3287 float dist2 = dist[id2];
3288 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3289 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3290 // Calculate the dot product of the displacement vectors.
3291 // When the vectors are oriented in approximately the same direction,
3292 // the angle betweeen them is near zero and the cosine of the angle
3293 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3294 // mag(v2).
3295 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3296 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3297 float dx1 = delta1.dx * mPointerXZoomScale;
3298 float dy1 = delta1.dy * mPointerYZoomScale;
3299 float dx2 = delta2.dx * mPointerXZoomScale;
3300 float dy2 = delta2.dy * mPointerYZoomScale;
3301 float dot = dx1 * dx2 + dy1 * dy2;
3302 float cosine = dot / (dist1 * dist2); // denominator always > 0
3303 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3304 // Pointers are moving in the same direction. Switch to SWIPE.
3305 ALOGD_IF(DEBUG_GESTURES,
3306 "Gestures: PRESS transitioned to SWIPE, "
3307 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3308 "cosine %0.3f >= %0.3f",
3309 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3310 mConfig.pointerGestureMultitouchMinDistance, cosine,
3311 mConfig.pointerGestureSwipeTransitionAngleCosine);
3312 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3313 } else {
3314 // Pointers are moving in different directions. Switch to FREEFORM.
3315 ALOGD_IF(DEBUG_GESTURES,
3316 "Gestures: PRESS transitioned to FREEFORM, "
3317 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3318 "cosine %0.3f < %0.3f",
3319 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3320 mConfig.pointerGestureMultitouchMinDistance, cosine,
3321 mConfig.pointerGestureSwipeTransitionAngleCosine);
3322 *cancelPreviousGesture = true;
3323 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3324 }
3325 }
3326 }
3327 }
3328 }
3329 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3330 // Switch from SWIPE to FREEFORM if additional pointers go down.
3331 // Cancel previous gesture.
3332 if (currentFingerCount > 2) {
3333 ALOGD_IF(DEBUG_GESTURES,
3334 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3335 currentFingerCount);
3336 *cancelPreviousGesture = true;
3337 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3338 }
3339 }
3340
3341 // Move the reference points based on the overall group motion of the fingers
3342 // except in PRESS mode while waiting for a transition to occur.
3343 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3344 (commonDeltaRawX || commonDeltaRawY)) {
3345 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3346 uint32_t id = idBits.clearFirstMarkedBit();
3347 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3348 delta.dx = 0;
3349 delta.dy = 0;
3350 }
3351
3352 mPointerGesture.referenceTouchX += commonDeltaRawX;
3353 mPointerGesture.referenceTouchY += commonDeltaRawY;
3354
3355 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3356 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3357
3358 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3359 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3360
3361 mPointerGesture.referenceGestureX += commonDeltaX;
3362 mPointerGesture.referenceGestureY += commonDeltaY;
3363 }
3364
3365 // Report gestures.
3366 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3367 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3368 // PRESS or SWIPE mode.
3369 ALOGD_IF(DEBUG_GESTURES,
3370 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3371 "currentTouchPointerCount=%d",
3372 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3373 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3374
3375 mPointerGesture.currentGestureIdBits.clear();
3376 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3377 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3378 mPointerGesture.currentGestureProperties[0].clear();
3379 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003380 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003381 mPointerGesture.currentGestureCoords[0].clear();
3382 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3383 mPointerGesture.referenceGestureX);
3384 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3385 mPointerGesture.referenceGestureY);
3386 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3387 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3388 float xOffset = static_cast<float>(commonDeltaRawX) /
3389 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3390 float yOffset = static_cast<float>(commonDeltaRawY) /
3391 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3392 mPointerGesture.currentGestureCoords[0]
3393 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3394 mPointerGesture.currentGestureCoords[0]
3395 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3396 }
3397 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3398 // FREEFORM mode.
3399 ALOGD_IF(DEBUG_GESTURES,
3400 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3401 "currentTouchPointerCount=%d",
3402 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3403 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3404
3405 mPointerGesture.currentGestureIdBits.clear();
3406
3407 BitSet32 mappedTouchIdBits;
3408 BitSet32 usedGestureIdBits;
3409 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3410 // Initially, assign the active gesture id to the active touch point
3411 // if there is one. No other touch id bits are mapped yet.
3412 if (!*cancelPreviousGesture) {
3413 mappedTouchIdBits.markBit(activeTouchId);
3414 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3415 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3416 mPointerGesture.activeGestureId;
3417 } else {
3418 mPointerGesture.activeGestureId = -1;
3419 }
3420 } else {
3421 // Otherwise, assume we mapped all touches from the previous frame.
3422 // Reuse all mappings that are still applicable.
3423 mappedTouchIdBits.value =
3424 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3425 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3426
3427 // Check whether we need to choose a new active gesture id because the
3428 // current went went up.
3429 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3430 ~mCurrentCookedState.fingerIdBits.value);
3431 !upTouchIdBits.isEmpty();) {
3432 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3433 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3434 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3435 mPointerGesture.activeGestureId = -1;
3436 break;
3437 }
3438 }
3439 }
3440
3441 ALOGD_IF(DEBUG_GESTURES,
3442 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3443 "activeGestureId=%d",
3444 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3445
3446 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3447 for (uint32_t i = 0; i < currentFingerCount; i++) {
3448 uint32_t touchId = idBits.clearFirstMarkedBit();
3449 uint32_t gestureId;
3450 if (!mappedTouchIdBits.hasBit(touchId)) {
3451 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3452 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3453 ALOGD_IF(DEBUG_GESTURES,
3454 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3455 gestureId);
3456 } else {
3457 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3458 ALOGD_IF(DEBUG_GESTURES,
3459 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3460 touchId, gestureId);
3461 }
3462 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3463 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3464
3465 const RawPointerData::Pointer& pointer =
3466 mCurrentRawState.rawPointerData.pointerForId(touchId);
3467 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3468 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3469 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3470
3471 mPointerGesture.currentGestureProperties[i].clear();
3472 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003473 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003474 mPointerGesture.currentGestureCoords[i].clear();
3475 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3476 mPointerGesture.referenceGestureX +
3477 deltaX);
3478 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3479 mPointerGesture.referenceGestureY +
3480 deltaY);
3481 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3482 }
3483
3484 if (mPointerGesture.activeGestureId < 0) {
3485 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3486 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3487 mPointerGesture.activeGestureId);
3488 }
3489 }
3490}
3491
Harry Cutts714d1ad2022-08-24 16:36:43 +00003492void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3493 const RawPointerData::Pointer& currentPointer =
3494 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3495 const RawPointerData::Pointer& lastPointer =
3496 mLastRawState.rawPointerData.pointerForId(pointerId);
3497 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3498 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3499
3500 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3501 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3502
3503 mPointerController->move(deltaX, deltaY);
3504}
3505
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003506std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3507 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003508 mPointerSimple.currentCoords.clear();
3509 mPointerSimple.currentProperties.clear();
3510
3511 bool down, hovering;
3512 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3513 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3514 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3516 down = !hovering;
3517
Prabir Pradhane71e5702023-03-29 14:51:38 +00003518 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3519 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3520 // Styluses are configured specifically for one display. We only update the
3521 // PointerController for this stylus if the PointerController is configured for
3522 // the same display as this stylus,
3523 if (getAssociatedDisplayId() == mViewport.displayId) {
3524 mPointerController->setPosition(x, y);
3525 std::tie(x, y) = mPointerController->getPosition();
3526 }
3527
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003528 mPointerSimple.currentCoords.copyFrom(
3529 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3530 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3531 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3532 mPointerSimple.currentProperties.id = 0;
3533 mPointerSimple.currentProperties.toolType =
3534 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3535 } else {
3536 down = false;
3537 hovering = false;
3538 }
3539
Prabir Pradhane71e5702023-03-29 14:51:38 +00003540 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003541}
3542
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003543std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3544 uint32_t policyFlags) {
3545 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003546}
3547
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003548std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3549 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003550 mPointerSimple.currentCoords.clear();
3551 mPointerSimple.currentProperties.clear();
3552
3553 bool down, hovering;
3554 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3555 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003556 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003557 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003558 } else {
3559 mPointerVelocityControl.reset();
3560 }
3561
3562 down = isPointerDown(mCurrentRawState.buttonState);
3563 hovering = !down;
3564
Prabir Pradhan2719e822023-02-28 17:39:36 +00003565 const auto [x, y] = mPointerController->getPosition();
3566 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003567 mPointerSimple.currentCoords.copyFrom(
3568 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3569 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3570 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3571 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3572 hovering ? 0.0f : 1.0f);
3573 mPointerSimple.currentProperties.id = 0;
3574 mPointerSimple.currentProperties.toolType =
3575 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3576 } else {
3577 mPointerVelocityControl.reset();
3578
3579 down = false;
3580 hovering = false;
3581 }
3582
Prabir Pradhane71e5702023-03-29 14:51:38 +00003583 const int32_t displayId = mPointerController->getDisplayId();
3584 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003585}
3586
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003587std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3588 uint32_t policyFlags) {
3589 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003590
3591 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003592
3593 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003594}
3595
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003596std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3597 uint32_t policyFlags, bool down,
Prabir Pradhane71e5702023-03-29 14:51:38 +00003598 bool hovering, int32_t displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003599 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3600 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003601 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003602 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003603
3604 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003605 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003606 mPointerController->clearSpots();
Michael Wrightca5bede2020-07-02 00:00:29 +01003607 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003608 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003609 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003610 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003611
Prabir Pradhan2719e822023-02-28 17:39:36 +00003612 const auto [xCursorPosition, yCursorPosition] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003613
3614 if (mPointerSimple.down && !down) {
3615 mPointerSimple.down = false;
3616
3617 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003618 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3619 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3620 0, metaState, mLastRawState.buttonState,
3621 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3622 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3623 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3624 yCursorPosition, mPointerSimple.downTime,
3625 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003626 }
3627
3628 if (mPointerSimple.hovering && !hovering) {
3629 mPointerSimple.hovering = false;
3630
3631 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003632 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3633 mSource, displayId, policyFlags,
3634 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3635 mLastRawState.buttonState, MotionClassification::NONE,
3636 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3637 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3638 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3639 yCursorPosition, mPointerSimple.downTime,
3640 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003641 }
3642
3643 if (down) {
3644 if (!mPointerSimple.down) {
3645 mPointerSimple.down = true;
3646 mPointerSimple.downTime = when;
3647
3648 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003649 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3650 mSource, displayId, policyFlags,
3651 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3652 mCurrentRawState.buttonState, MotionClassification::NONE,
3653 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3654 &mPointerSimple.currentProperties,
3655 &mPointerSimple.currentCoords, mOrientedXPrecision,
3656 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3657 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003658 }
3659
3660 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003661 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3662 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3663 0, 0, metaState, mCurrentRawState.buttonState,
3664 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3665 &mPointerSimple.currentProperties,
3666 &mPointerSimple.currentCoords, mOrientedXPrecision,
3667 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3668 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003669 }
3670
3671 if (hovering) {
3672 if (!mPointerSimple.hovering) {
3673 mPointerSimple.hovering = true;
3674
3675 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003676 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3677 mSource, displayId, policyFlags,
3678 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3679 mCurrentRawState.buttonState, MotionClassification::NONE,
3680 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3681 &mPointerSimple.currentProperties,
3682 &mPointerSimple.currentCoords, mOrientedXPrecision,
3683 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3684 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003685 }
3686
3687 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003688 out.push_back(
3689 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3690 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3691 metaState, mCurrentRawState.buttonState,
3692 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3693 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3694 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3695 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003696 }
3697
3698 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3699 float vscroll = mCurrentRawState.rawVScroll;
3700 float hscroll = mCurrentRawState.rawHScroll;
3701 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3702 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3703
3704 // Send scroll.
3705 PointerCoords pointerCoords;
3706 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3707 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3708 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3709
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003710 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3711 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3712 0, 0, metaState, mCurrentRawState.buttonState,
3713 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3714 &mPointerSimple.currentProperties, &pointerCoords,
3715 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3716 yCursorPosition, mPointerSimple.downTime,
3717 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003718 }
3719
3720 // Save state.
3721 if (down || hovering) {
3722 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3723 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003724 mPointerSimple.displayId = displayId;
3725 mPointerSimple.source = mSource;
3726 mPointerSimple.lastCursorX = xCursorPosition;
3727 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003728 } else {
3729 mPointerSimple.reset();
3730 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003731 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003732}
3733
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003734std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3735 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003736 std::list<NotifyArgs> out;
3737 if (mPointerSimple.down || mPointerSimple.hovering) {
3738 int32_t metaState = getContext()->getGlobalMetaState();
3739 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3740 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3741 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3742 metaState, mLastRawState.buttonState,
3743 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3744 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3745 mOrientedXPrecision, mOrientedYPrecision,
3746 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3747 mPointerSimple.downTime,
3748 /* videoFrames */ {}));
3749 if (mPointerController != nullptr) {
3750 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3751 }
3752 }
3753 mPointerSimple.reset();
3754 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003755}
3756
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003757static bool isStylusEvent(uint32_t source, int32_t action, const PointerProperties* properties) {
3758 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
3759 return false;
3760 }
3761 const auto actionIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3762 return isStylusToolType(properties[actionIndex].toolType);
3763}
3764
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003765NotifyMotionArgs TouchInputMapper::dispatchMotion(
3766 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3767 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003768 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3769 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003770 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003771 PointerCoords pointerCoords[MAX_POINTERS];
3772 PointerProperties pointerProperties[MAX_POINTERS];
3773 uint32_t pointerCount = 0;
3774 while (!idBits.isEmpty()) {
3775 uint32_t id = idBits.clearFirstMarkedBit();
3776 uint32_t index = idToIndex[id];
3777 pointerProperties[pointerCount].copyFrom(properties[index]);
3778 pointerCoords[pointerCount].copyFrom(coords[index]);
3779
3780 if (changedId >= 0 && id == uint32_t(changedId)) {
3781 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3782 }
3783
3784 pointerCount += 1;
3785 }
3786
3787 ALOG_ASSERT(pointerCount != 0);
3788
3789 if (changedId >= 0 && pointerCount == 1) {
3790 // Replace initial down and final up action.
3791 // We can compare the action without masking off the changed pointer index
3792 // because we know the index is 0.
3793 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3794 action = AMOTION_EVENT_ACTION_DOWN;
3795 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003796 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3797 action = AMOTION_EVENT_ACTION_CANCEL;
3798 } else {
3799 action = AMOTION_EVENT_ACTION_UP;
3800 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003801 } else {
3802 // Can't happen.
3803 ALOG_ASSERT(false);
3804 }
3805 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003806
3807 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3808 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
3809 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, action, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003810 mPointerController && displayId != ADISPLAY_ID_NONE &&
3811 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003812 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003813 switch (action & AMOTION_EVENT_ACTION_MASK) {
3814 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3815 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3816 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003817 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003818 mPointerController
3819 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3820 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3821 .getY());
3822 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3823 break;
3824 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3825 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3826 break;
3827 }
3828 }
3829
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003830 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3831 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003832 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003833 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003834 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003835 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003836 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003837 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003838 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003839 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3840 policyFlags, action, actionButton, flags, metaState, buttonState,
3841 classification, edgeFlags, pointerCount, pointerProperties,
3842 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3843 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003844}
3845
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003846std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3847 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003848 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3849 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003850 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003851}
3852
Prabir Pradhan1728b212021-10-19 16:00:03 -07003853bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003854 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003855 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003856 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003857}
3858
3859const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3860 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003861 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3862 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3863 "left=%d, top=%d, right=%d, bottom=%d",
3864 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3865 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003866
3867 if (virtualKey.isHit(x, y)) {
3868 return &virtualKey;
3869 }
3870 }
3871
3872 return nullptr;
3873}
3874
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003875void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3876 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3877 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003878
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003879 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003880
3881 if (currentPointerCount == 0) {
3882 // No pointers to assign.
3883 return;
3884 }
3885
3886 if (lastPointerCount == 0) {
3887 // All pointers are new.
3888 for (uint32_t i = 0; i < currentPointerCount; i++) {
3889 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003890 current.rawPointerData.pointers[i].id = id;
3891 current.rawPointerData.idToIndex[id] = i;
3892 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003893 }
3894 return;
3895 }
3896
3897 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003898 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003899 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003900 uint32_t id = last.rawPointerData.pointers[0].id;
3901 current.rawPointerData.pointers[0].id = id;
3902 current.rawPointerData.idToIndex[id] = 0;
3903 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003904 return;
3905 }
3906
3907 // General case.
3908 // We build a heap of squared euclidean distances between current and last pointers
3909 // associated with the current and last pointer indices. Then, we find the best
3910 // match (by distance) for each current pointer.
3911 // The pointers must have the same tool type but it is possible for them to
3912 // transition from hovering to touching or vice-versa while retaining the same id.
3913 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3914
3915 uint32_t heapSize = 0;
3916 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3917 currentPointerIndex++) {
3918 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3919 lastPointerIndex++) {
3920 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003921 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003922 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003923 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003924 if (currentPointer.toolType == lastPointer.toolType) {
3925 int64_t deltaX = currentPointer.x - lastPointer.x;
3926 int64_t deltaY = currentPointer.y - lastPointer.y;
3927
3928 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3929
3930 // Insert new element into the heap (sift up).
3931 heap[heapSize].currentPointerIndex = currentPointerIndex;
3932 heap[heapSize].lastPointerIndex = lastPointerIndex;
3933 heap[heapSize].distance = distance;
3934 heapSize += 1;
3935 }
3936 }
3937 }
3938
3939 // Heapify
3940 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3941 startIndex -= 1;
3942 for (uint32_t parentIndex = startIndex;;) {
3943 uint32_t childIndex = parentIndex * 2 + 1;
3944 if (childIndex >= heapSize) {
3945 break;
3946 }
3947
3948 if (childIndex + 1 < heapSize &&
3949 heap[childIndex + 1].distance < heap[childIndex].distance) {
3950 childIndex += 1;
3951 }
3952
3953 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3954 break;
3955 }
3956
3957 swap(heap[parentIndex], heap[childIndex]);
3958 parentIndex = childIndex;
3959 }
3960 }
3961
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003962 if (DEBUG_POINTER_ASSIGNMENT) {
3963 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3964 for (size_t i = 0; i < heapSize; i++) {
3965 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3966 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3967 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003968 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003969
3970 // Pull matches out by increasing order of distance.
3971 // To avoid reassigning pointers that have already been matched, the loop keeps track
3972 // of which last and current pointers have been matched using the matchedXXXBits variables.
3973 // It also tracks the used pointer id bits.
3974 BitSet32 matchedLastBits(0);
3975 BitSet32 matchedCurrentBits(0);
3976 BitSet32 usedIdBits(0);
3977 bool first = true;
3978 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3979 while (heapSize > 0) {
3980 if (first) {
3981 // The first time through the loop, we just consume the root element of
3982 // the heap (the one with smallest distance).
3983 first = false;
3984 } else {
3985 // Previous iterations consumed the root element of the heap.
3986 // Pop root element off of the heap (sift down).
3987 heap[0] = heap[heapSize];
3988 for (uint32_t parentIndex = 0;;) {
3989 uint32_t childIndex = parentIndex * 2 + 1;
3990 if (childIndex >= heapSize) {
3991 break;
3992 }
3993
3994 if (childIndex + 1 < heapSize &&
3995 heap[childIndex + 1].distance < heap[childIndex].distance) {
3996 childIndex += 1;
3997 }
3998
3999 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4000 break;
4001 }
4002
4003 swap(heap[parentIndex], heap[childIndex]);
4004 parentIndex = childIndex;
4005 }
4006
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004007 if (DEBUG_POINTER_ASSIGNMENT) {
4008 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4009 for (size_t j = 0; j < heapSize; j++) {
4010 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4011 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4012 heap[j].distance);
4013 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004014 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004015 }
4016
4017 heapSize -= 1;
4018
4019 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4020 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4021
4022 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4023 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4024
4025 matchedCurrentBits.markBit(currentPointerIndex);
4026 matchedLastBits.markBit(lastPointerIndex);
4027
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004028 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4029 current.rawPointerData.pointers[currentPointerIndex].id = id;
4030 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4031 current.rawPointerData.markIdBit(id,
4032 current.rawPointerData.isHovering(
4033 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004034 usedIdBits.markBit(id);
4035
Harry Cutts45483602022-08-24 14:36:48 +00004036 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4037 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4038 ", distance=%" PRIu64,
4039 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004040 break;
4041 }
4042 }
4043
4044 // Assign fresh ids to pointers that were not matched in the process.
4045 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4046 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4047 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4048
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004049 current.rawPointerData.pointers[currentPointerIndex].id = id;
4050 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4051 current.rawPointerData.markIdBit(id,
4052 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004053
Harry Cutts45483602022-08-24 14:36:48 +00004054 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4055 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4056 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004057 }
4058}
4059
4060int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4061 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4062 return AKEY_STATE_VIRTUAL;
4063 }
4064
4065 for (const VirtualKey& virtualKey : mVirtualKeys) {
4066 if (virtualKey.keyCode == keyCode) {
4067 return AKEY_STATE_UP;
4068 }
4069 }
4070
4071 return AKEY_STATE_UNKNOWN;
4072}
4073
4074int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4075 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4076 return AKEY_STATE_VIRTUAL;
4077 }
4078
4079 for (const VirtualKey& virtualKey : mVirtualKeys) {
4080 if (virtualKey.scanCode == scanCode) {
4081 return AKEY_STATE_UP;
4082 }
4083 }
4084
4085 return AKEY_STATE_UNKNOWN;
4086}
4087
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004088bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4089 const std::vector<int32_t>& keyCodes,
4090 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004091 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004092 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004093 if (virtualKey.keyCode == keyCodes[i]) {
4094 outFlags[i] = 1;
4095 }
4096 }
4097 }
4098
4099 return true;
4100}
4101
4102std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4103 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004104 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004105 return std::make_optional(mPointerController->getDisplayId());
4106 } else {
4107 return std::make_optional(mViewport.displayId);
4108 }
4109 }
4110 return std::nullopt;
4111}
4112
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004113} // namespace android