blob: 66d3849e5c7c5d97b9a9075f60f1d09fdee8bedc [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,
291 const InputReaderConfiguration* config,
292 uint32_t changes) {
293 std::list<NotifyArgs> out = InputMapper::reconfigure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700294
295 mConfig = *config;
296
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.
876 // - Here, we assume that the raw surface of the touch device maps perfectly to the surface
877 // of the display panel. This is usually true for touchscreens.
878 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
879 // are in the continuous space of the logical display.
880 ui::Transform scaleRawToDisplay;
881 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
882 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
883 scaleRawToDisplay.set(xScale, 0, 0, yScale);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000884
Prabir Pradhan3e798762022-12-02 21:02:11 +0000885 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
886 // that InputReader uses.
887 const auto undoRotateInDisplay =
888 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
889 .inverse();
890
891 // Now put it all together!
892 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
893 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
894 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000895}
896
Prabir Pradhan1728b212021-10-19 16:00:03 -0700897void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000898 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700899
900 resolveExternalStylusPresence();
901
902 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100903 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000904 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700905 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100906 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700907 if (hasStylus()) {
908 mSource |= AINPUT_SOURCE_STYLUS;
909 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800910 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700911 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100912 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700913 if (hasStylus()) {
914 mSource |= AINPUT_SOURCE_STYLUS;
915 }
916 if (hasExternalStylus()) {
917 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
918 }
Michael Wright227c5542020-07-02 18:30:52 +0100919 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700920 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100921 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700922 } else {
923 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100924 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700925 }
926
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000927 const std::optional<DisplayViewport> newViewportOpt = findViewport();
928
929 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700930 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
931 ALOGW("Touch device '%s' did not report support for X or Y axis! "
932 "The device will be inoperable.",
933 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100934 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000935 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700936 ALOGI("Touch device '%s' could not query the properties of its associated "
937 "display. The device will be inoperable until the display size "
938 "becomes available.",
939 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100940 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700941 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000942 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
943 getDeviceName().c_str(), getDeviceId());
944 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000945 }
946
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700947 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000948 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000949 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
950 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
951 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
952 const float rawMeanResolution =
953 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700954
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000955 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
956 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700957 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700958 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000959 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
960 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
961 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700962
Michael Wright227c5542020-07-02 18:30:52 +0100963 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000964 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700965
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000966 mDisplayBounds = getNaturalDisplaySize(mViewport);
967 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
968 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700969
Prabir Pradhan3e798762022-12-02 21:02:11 +0000970 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
971 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
972 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000973 // InputReader works in the un-rotated display coordinate space, so we don't need to do
974 // anything if the device is already orientation-aware. If the device is not
975 // orientation-aware, then we need to apply the inverse rotation of the display so that
976 // when the display rotation is applied later as a part of the per-window transform, we
977 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700978 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000979 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000980 : getInverseRotation(mViewport.orientation);
981 // For orientation-aware devices that work in the un-rotated coordinate space, the
982 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000983 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000984 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700985
986 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000987 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000988 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700989 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000990 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000991 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000992 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000993 mRawToDisplay.reset();
994 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000995 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700996 }
997 }
998
999 // If moving between pointer modes, need to reset some state.
1000 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1001 if (deviceModeChanged) {
1002 mOrientedRanges.clear();
1003 }
1004
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001005 // Create and preserve the pointer controller in the following cases:
1006 const bool isPointerControllerNeeded =
1007 // - when the device is in pointer mode, to show the mouse cursor;
1008 (mDeviceMode == DeviceMode::POINTER) ||
1009 // - when pointer capture is enabled, to preserve the mouse cursor position;
1010 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1011 mConfig.pointerCaptureRequest.enable) ||
1012 // - when we should be showing touches;
1013 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1014 // - when we should be showing a pointer icon for direct styluses.
1015 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1016 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001017 if (mPointerController == nullptr) {
1018 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001019 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001020 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001021 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1022 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001023 } else {
lilinnandef700b2022-06-17 19:32:01 +08001024 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1025 !mConfig.showTouches) {
1026 mPointerController->clearSpots();
1027 }
Michael Wright17db18e2020-06-26 20:51:44 +01001028 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001029 }
1030
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001031 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001032 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001033 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001034 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001035 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001036
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001037 configureVirtualKeys();
1038
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001039 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001040
1041 // Location
1042 updateAffineTransformation();
1043
Michael Wright227c5542020-07-02 18:30:52 +01001044 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001045 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001046 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1047 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001048
1049 // Scale movements such that one whole swipe of the touch pad covers a
1050 // given area relative to the diagonal size of the display when no acceleration
1051 // is applied.
1052 // Assume that the touch pad has a square aspect ratio such that movements in
1053 // X and Y of the same number of raw units cover the same physical distance.
1054 mPointerXMovementScale =
1055 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1056 mPointerYMovementScale = mPointerXMovementScale;
1057
1058 // Scale zooms to cover a smaller range of the display than movements do.
1059 // This value determines the area around the pointer that is affected by freeform
1060 // pointer gestures.
1061 mPointerXZoomScale =
1062 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1063 mPointerYZoomScale = mPointerXZoomScale;
1064
HQ Liue6983c72022-04-19 22:14:56 +00001065 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1066 // axis is non positive value.
1067 const float minFreeformGestureWidth =
1068 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1069
1070 mPointerGestureMaxSwipeWidth =
1071 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1072 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001073 }
1074
1075 // Inform the dispatcher about the changes.
1076 *outResetNeeded = true;
1077 bumpGeneration();
1078 }
1079}
1080
Prabir Pradhan1728b212021-10-19 16:00:03 -07001081void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001082 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001083 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001084 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1085 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001086 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001087}
1088
1089void TouchInputMapper::configureVirtualKeys() {
1090 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001091 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001092
1093 mVirtualKeys.clear();
1094
1095 if (virtualKeyDefinitions.size() == 0) {
1096 return;
1097 }
1098
1099 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1100 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1101 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1102 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1103
1104 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1105 VirtualKey virtualKey;
1106
1107 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1108 int32_t keyCode;
1109 int32_t dummyKeyMetaState;
1110 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001111 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1112 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1114 continue; // drop the key
1115 }
1116
1117 virtualKey.keyCode = keyCode;
1118 virtualKey.flags = flags;
1119
1120 // convert the key definition's display coordinates into touch coordinates for a hit box
1121 int32_t halfWidth = virtualKeyDefinition.width / 2;
1122 int32_t halfHeight = virtualKeyDefinition.height / 2;
1123
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001124 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1125 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001127 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1128 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001129 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001130 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1131 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001132 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001133 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1134 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 touchScreenTop;
1136 mVirtualKeys.push_back(virtualKey);
1137 }
1138}
1139
1140void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1141 if (!mVirtualKeys.empty()) {
1142 dump += INDENT3 "Virtual Keys:\n";
1143
1144 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1145 const VirtualKey& virtualKey = mVirtualKeys[i];
1146 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1147 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1148 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1149 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1150 }
1151 }
1152}
1153
1154void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001155 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001156 Calibration& out = mCalibration;
1157
1158 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001159 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001160 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1161 if (sizeCalibrationString.has_value()) {
1162 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001163 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001164 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001165 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001166 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001168 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001170 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001172 } else if (*sizeCalibrationString != "default") {
1173 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 }
1175 }
1176
Harry Cuttsf13161a2023-03-08 14:15:49 +00001177 out.sizeScale = in.getFloat("touch.size.scale");
1178 out.sizeBias = in.getFloat("touch.size.bias");
1179 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001180
1181 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001182 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001183 std::optional<std::string> pressureCalibrationString =
1184 in.getString("touch.pressure.calibration");
1185 if (pressureCalibrationString.has_value()) {
1186 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001188 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001190 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001191 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001192 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001194 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195 }
1196 }
1197
Harry Cuttsf13161a2023-03-08 14:15:49 +00001198 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199
1200 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001202 std::optional<std::string> orientationCalibrationString =
1203 in.getString("touch.orientation.calibration");
1204 if (orientationCalibrationString.has_value()) {
1205 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001207 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001209 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001210 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001211 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001213 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 }
1215 }
1216
1217 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001218 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001219 std::optional<std::string> distanceCalibrationString =
1220 in.getString("touch.distance.calibration");
1221 if (distanceCalibrationString.has_value()) {
1222 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001223 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001224 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001225 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001226 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001228 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 }
1230 }
1231
Harry Cuttsf13161a2023-03-08 14:15:49 +00001232 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233}
1234
1235void TouchInputMapper::resolveCalibration() {
1236 // Size
1237 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001238 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1239 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 }
1241 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001242 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243 }
1244
1245 // Pressure
1246 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001247 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1248 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 }
1250 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001251 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252 }
1253
1254 // Orientation
1255 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001256 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1257 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 }
1259 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001260 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 }
1262
1263 // Distance
1264 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001265 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1266 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 }
1268 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001269 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271}
1272
1273void TouchInputMapper::dumpCalibration(std::string& dump) {
1274 dump += INDENT3 "Calibration:\n";
1275
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001276 dump += INDENT4 "touch.size.calibration: ";
1277 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001279 if (mCalibration.sizeScale) {
1280 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 }
1282
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001283 if (mCalibration.sizeBias) {
1284 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 }
1286
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001287 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001289 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290 }
1291
1292 // Pressure
1293 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001294 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 dump += INDENT4 "touch.pressure.calibration: none\n";
1296 break;
Michael Wright227c5542020-07-02 18:30:52 +01001297 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 dump += INDENT4 "touch.pressure.calibration: physical\n";
1299 break;
Michael Wright227c5542020-07-02 18:30:52 +01001300 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1302 break;
1303 default:
1304 ALOG_ASSERT(false);
1305 }
1306
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001307 if (mCalibration.pressureScale) {
1308 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001309 }
1310
1311 // Orientation
1312 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001313 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001314 dump += INDENT4 "touch.orientation.calibration: none\n";
1315 break;
Michael Wright227c5542020-07-02 18:30:52 +01001316 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1318 break;
Michael Wright227c5542020-07-02 18:30:52 +01001319 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 dump += INDENT4 "touch.orientation.calibration: vector\n";
1321 break;
1322 default:
1323 ALOG_ASSERT(false);
1324 }
1325
1326 // Distance
1327 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001328 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329 dump += INDENT4 "touch.distance.calibration: none\n";
1330 break;
Michael Wright227c5542020-07-02 18:30:52 +01001331 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 dump += INDENT4 "touch.distance.calibration: scaled\n";
1333 break;
1334 default:
1335 ALOG_ASSERT(false);
1336 }
1337
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001338 if (mCalibration.distanceScale) {
1339 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001340 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341}
1342
1343void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1344 dump += INDENT3 "Affine Transformation:\n";
1345
1346 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1347 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1348 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1349 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1350 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1351 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1352}
1353
1354void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001355 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001356 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357}
1358
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001359std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001360 std::list<NotifyArgs> out = cancelTouch(when, when);
1361 updateTouchSpots();
1362
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001363 mCursorButtonAccumulator.reset(getDeviceContext());
1364 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001365 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001366
1367 mPointerVelocityControl.reset();
1368 mWheelXVelocityControl.reset();
1369 mWheelYVelocityControl.reset();
1370
1371 mRawStatesPending.clear();
1372 mCurrentRawState.clear();
1373 mCurrentCookedState.clear();
1374 mLastRawState.clear();
1375 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001376 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001377 mSentHoverEnter = false;
1378 mHavePointerIds = false;
1379 mCurrentMotionAborted = false;
1380 mDownTime = 0;
1381
1382 mCurrentVirtualKey.down = false;
1383
1384 mPointerGesture.reset();
1385 mPointerSimple.reset();
1386 resetExternalStylus();
1387
1388 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001389 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001390 mPointerController->clearSpots();
1391 }
1392
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001393 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001394}
1395
1396void TouchInputMapper::resetExternalStylus() {
1397 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001398 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001399 mExternalStylusFusionTimeout = LLONG_MAX;
1400 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001401 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001402}
1403
1404void TouchInputMapper::clearStylusDataPendingFlags() {
1405 mExternalStylusDataPending = false;
1406 mExternalStylusFusionTimeout = LLONG_MAX;
1407}
1408
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001409std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001410 mCursorButtonAccumulator.process(rawEvent);
1411 mCursorScrollAccumulator.process(rawEvent);
1412 mTouchButtonAccumulator.process(rawEvent);
1413
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001414 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001415 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001416 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001417 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001418 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001419}
1420
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001421std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1422 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001423 if (mDeviceMode == DeviceMode::DISABLED) {
1424 // Only save the last pending state when the device is disabled.
1425 mRawStatesPending.clear();
1426 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001427 // Push a new state.
1428 mRawStatesPending.emplace_back();
1429
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001430 RawState& next = mRawStatesPending.back();
1431 next.clear();
1432 next.when = when;
1433 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001434
1435 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001436 next.buttonState = filterButtonState(mConfig,
1437 mTouchButtonAccumulator.getButtonState() |
1438 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001439
1440 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001441 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1442 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001443 mCursorScrollAccumulator.finishSync();
1444
1445 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001446 syncTouch(when, &next);
1447
1448 // The last RawState is the actually second to last, since we just added a new state
1449 const RawState& last =
1450 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001452 std::tie(next.when, next.readTime) =
1453 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1454 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001455
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001456 // Assign pointer ids.
1457 if (!mHavePointerIds) {
1458 assignPointerIds(last, next);
1459 }
1460
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001461 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001462 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1463 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1464 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1465 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1466 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1467 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001468
Arthur Hung9ad18942021-06-19 02:04:46 +00001469 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1470 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1471 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1472 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1473 next.rawPointerData.hoveringIdBits.value);
1474 }
1475
Harry Cutts33476232023-01-30 19:57:29 +00001476 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001477 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001478}
1479
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001480std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1481 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001482 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001483 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001484 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001485 }
1486
1487 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1488 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1489 // touching the current state will only observe the events that have been dispatched to the
1490 // rest of the pipeline.
1491 const size_t N = mRawStatesPending.size();
1492 size_t count;
1493 for (count = 0; count < N; count++) {
1494 const RawState& next = mRawStatesPending[count];
1495
1496 // A failure to assign the stylus id means that we're waiting on stylus data
1497 // and so should defer the rest of the pipeline.
1498 if (assignExternalStylusId(next, timeout)) {
1499 break;
1500 }
1501
1502 // All ready to go.
1503 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001504 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001505 if (mCurrentRawState.when < mLastRawState.when) {
1506 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001507 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001508 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001509 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001510 }
1511 if (count != 0) {
1512 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1513 }
1514
1515 if (mExternalStylusDataPending) {
1516 if (timeout) {
1517 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1518 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001519 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001520 ALOGD_IF(DEBUG_STYLUS_FUSION,
1521 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001522 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001523 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1525 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1526 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1527 }
1528 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001529 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001530}
1531
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001532std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1533 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001534 // Always start with a clean state.
1535 mCurrentCookedState.clear();
1536
1537 // Apply stylus buttons to current raw state.
1538 applyExternalStylusButtonState(when);
1539
1540 // Handle policy on initial down or hover events.
1541 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1542 mCurrentRawState.rawPointerData.pointerCount != 0;
1543
1544 uint32_t policyFlags = 0;
1545 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1546 if (initialDown || buttonsPressed) {
1547 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001548 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001549 getContext()->fadePointer();
1550 }
1551
1552 if (mParameters.wake) {
1553 policyFlags |= POLICY_FLAG_WAKE;
1554 }
1555 }
1556
1557 // Consume raw off-screen touches before cooking pointer data.
1558 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001559 bool consumed;
1560 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1561 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001562 mCurrentRawState.rawPointerData.clear();
1563 }
1564
1565 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1566 // with cooked pointer data that has the same ids and indices as the raw data.
1567 // The following code can use either the raw or cooked data, as needed.
1568 cookPointerData();
1569
1570 // Apply stylus pressure to current cooked state.
1571 applyExternalStylusTouchState(when);
1572
1573 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001574 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1575 mSource, mViewport.displayId, policyFlags,
1576 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001577
1578 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001579 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001580 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1581 uint32_t id = idBits.clearFirstMarkedBit();
1582 const RawPointerData::Pointer& pointer =
1583 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001584 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001585 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001586 } else if (pointer.toolType == ToolType::FINGER ||
1587 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001588 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001589 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001590 mCurrentCookedState.mouseIdBits.markBit(id);
1591 }
1592 }
1593 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1594 uint32_t id = idBits.clearFirstMarkedBit();
1595 const RawPointerData::Pointer& pointer =
1596 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001597 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001598 mCurrentCookedState.stylusIdBits.markBit(id);
1599 }
1600 }
1601
1602 // Stylus takes precedence over all tools, then mouse, then finger.
1603 PointerUsage pointerUsage = mPointerUsage;
1604 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1605 mCurrentCookedState.mouseIdBits.clear();
1606 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001607 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001608 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1609 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001610 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001611 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1612 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001613 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001614 }
1615
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001616 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001618 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001619 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001620 out += dispatchButtonRelease(when, readTime, policyFlags);
1621 out += dispatchHoverExit(when, readTime, policyFlags);
1622 out += dispatchTouches(when, readTime, policyFlags);
1623 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1624 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001625 }
1626
1627 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1628 mCurrentMotionAborted = false;
1629 }
1630 }
1631
1632 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001633 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1634 mSource, mViewport.displayId, policyFlags,
1635 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001636
1637 // Clear some transient state.
1638 mCurrentRawState.rawVScroll = 0;
1639 mCurrentRawState.rawHScroll = 0;
1640
1641 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001642 mLastRawState = mCurrentRawState;
1643 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001644 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001645}
1646
Garfield Tanc734e4f2021-01-15 20:01:39 -08001647void TouchInputMapper::updateTouchSpots() {
1648 if (!mConfig.showTouches || mPointerController == nullptr) {
1649 return;
1650 }
1651
1652 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1653 // clear touch spots.
1654 if (mDeviceMode != DeviceMode::DIRECT &&
1655 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1656 return;
1657 }
1658
1659 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1660 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1661
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001662 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1663 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001664 mCurrentCookedState.cookedPointerData.touchingIdBits |
1665 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001666 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001667}
1668
1669bool TouchInputMapper::isTouchScreen() {
1670 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1671 mParameters.hasAssociatedDisplay;
1672}
1673
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001674void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001675 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1676 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001677 const int32_t pressedButtons =
1678 filterButtonState(mConfig,
1679 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001680 const int32_t releasedButtons =
1681 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1682
1683 mCurrentRawState.buttonState |= pressedButtons;
1684 mCurrentRawState.buttonState &= ~releasedButtons;
1685
1686 mExternalStylusButtonsApplied |= pressedButtons;
1687 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001688 }
1689}
1690
1691void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1692 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1693 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001694 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1695 return;
1696 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001697
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001698 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1699 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1700 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1701 : 0.f;
1702 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1703 pressure = *mExternalStylusState.pressure;
1704 }
1705 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1706 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001707
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001708 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001709 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001710 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001711 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001712 }
1713}
1714
1715bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001716 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001717 return false;
1718 }
1719
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001720 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001721 if (mFusedStylusPointerId &&
1722 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001723 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001724 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001725 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001726 }
1727
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001728 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1729 state.rawPointerData.pointerCount != 0;
1730 if (!initialDown) {
1731 return false;
1732 }
1733
1734 if (!mExternalStylusState.pressure) {
1735 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1736 return false;
1737 }
1738
1739 if (*mExternalStylusState.pressure != 0.0f) {
1740 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1741 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1742 return false;
1743 }
1744
1745 if (timeout) {
1746 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1747 mFusedStylusPointerId.reset();
1748 mExternalStylusFusionTimeout = LLONG_MAX;
1749 return false;
1750 }
1751
1752 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1753 // being processed until we either get pressure data or timeout.
1754 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1755 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1756 }
1757 ALOGD_IF(DEBUG_STYLUS_FUSION,
1758 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1759 mExternalStylusFusionTimeout);
1760 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1761 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001762}
1763
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001764std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1765 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001766 if (mDeviceMode == DeviceMode::POINTER) {
1767 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001768 // Since this is a synthetic event, we can consider its latency to be zero
1769 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001770 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001771 }
Michael Wright227c5542020-07-02 18:30:52 +01001772 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001773 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001774 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001775 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1776 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1777 }
1778 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001779 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780}
1781
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001782std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1783 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001784 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001785 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001786 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001787 // The following three cases are handled here:
1788 // - We're in the middle of a fused stream of data;
1789 // - We're waiting on external stylus data before dispatching the initial down; or
1790 // - Only the button state, which is not reported through a specific pointer, has changed.
1791 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001792 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001793 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001794 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001795 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001796}
1797
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001798std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1799 uint32_t policyFlags, bool& outConsumed) {
1800 outConsumed = false;
1801 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001802 // Check for release of a virtual key.
1803 if (mCurrentVirtualKey.down) {
1804 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1805 // Pointer went up while virtual key was down.
1806 mCurrentVirtualKey.down = false;
1807 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001808 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1809 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1810 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001811 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1812 AKEY_EVENT_FLAG_FROM_SYSTEM |
1813 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001814 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001815 outConsumed = true;
1816 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001817 }
1818
1819 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1820 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1821 const RawPointerData::Pointer& pointer =
1822 mCurrentRawState.rawPointerData.pointerForId(id);
1823 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1824 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1825 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001826 outConsumed = true;
1827 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001828 }
1829 }
1830
1831 // Pointer left virtual key area or another pointer also went down.
1832 // Send key cancellation but do not consume the touch yet.
1833 // This is useful when the user swipes through from the virtual key area
1834 // into the main display surface.
1835 mCurrentVirtualKey.down = false;
1836 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001837 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1838 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001839 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1840 AKEY_EVENT_FLAG_FROM_SYSTEM |
1841 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1842 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001843 }
1844 }
1845
1846 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1847 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1848 // Pointer just went down. Check for virtual key press or off-screen touches.
1849 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1850 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001851 // Skip checking whether the pointer is inside the physical frame if the device is in
1852 // unscaled mode.
1853 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1854 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001855 // If exactly one pointer went down, check for virtual key hit.
1856 // Otherwise we will drop the entire stroke.
1857 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1858 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1859 if (virtualKey) {
1860 mCurrentVirtualKey.down = true;
1861 mCurrentVirtualKey.downTime = when;
1862 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1863 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1864 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001865 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1866 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001867
1868 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001869 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1870 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1871 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001872 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1873 AKEY_EVENT_ACTION_DOWN,
1874 AKEY_EVENT_FLAG_FROM_SYSTEM |
1875 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001876 }
1877 }
1878 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001879 outConsumed = true;
1880 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001881 }
1882 }
1883
1884 // Disable all virtual key touches that happen within a short time interval of the
1885 // most recent touch within the screen area. The idea is to filter out stray
1886 // virtual key presses when interacting with the touch screen.
1887 //
1888 // Problems we're trying to solve:
1889 //
1890 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1891 // virtual key area that is implemented by a separate touch panel and accidentally
1892 // triggers a virtual key.
1893 //
1894 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1895 // area and accidentally triggers a virtual key. This often happens when virtual keys
1896 // are layed out below the screen near to where the on screen keyboard's space bar
1897 // is displayed.
1898 if (mConfig.virtualKeyQuietTime > 0 &&
1899 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001900 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001901 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001902 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001903}
1904
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001905NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1906 uint32_t policyFlags, int32_t keyEventAction,
1907 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001908 int32_t keyCode = mCurrentVirtualKey.keyCode;
1909 int32_t scanCode = mCurrentVirtualKey.scanCode;
1910 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001911 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001912 policyFlags |= POLICY_FLAG_VIRTUAL;
1913
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001914 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1915 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1916 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001917}
1918
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001919std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1920 uint32_t policyFlags) {
1921 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001922 if (mCurrentMotionAborted) {
1923 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001924 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001925 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001926 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1927 if (!currentIdBits.isEmpty()) {
1928 int32_t metaState = getContext()->getGlobalMetaState();
1929 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001930 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001931 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1932 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001933 mCurrentCookedState.cookedPointerData.pointerProperties,
1934 mCurrentCookedState.cookedPointerData.pointerCoords,
1935 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1936 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1937 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001938 mCurrentMotionAborted = true;
1939 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001940 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001941}
1942
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001943// Updates pointer coords and properties for pointers with specified ids that have moved.
1944// Returns true if any of them changed.
1945static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1946 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1947 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1948 BitSet32 idBits) {
1949 bool changed = false;
1950 while (!idBits.isEmpty()) {
1951 uint32_t id = idBits.clearFirstMarkedBit();
1952 uint32_t inIndex = inIdToIndex[id];
1953 uint32_t outIndex = outIdToIndex[id];
1954
1955 const PointerProperties& curInProperties = inProperties[inIndex];
1956 const PointerCoords& curInCoords = inCoords[inIndex];
1957 PointerProperties& curOutProperties = outProperties[outIndex];
1958 PointerCoords& curOutCoords = outCoords[outIndex];
1959
1960 if (curInProperties != curOutProperties) {
1961 curOutProperties.copyFrom(curInProperties);
1962 changed = true;
1963 }
1964
1965 if (curInCoords != curOutCoords) {
1966 curOutCoords.copyFrom(curInCoords);
1967 changed = true;
1968 }
1969 }
1970 return changed;
1971}
1972
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001973std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1974 uint32_t policyFlags) {
1975 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001976 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1977 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1978 int32_t metaState = getContext()->getGlobalMetaState();
1979 int32_t buttonState = mCurrentCookedState.buttonState;
1980
1981 if (currentIdBits == lastIdBits) {
1982 if (!currentIdBits.isEmpty()) {
1983 // No pointer id changes so this is a move event.
1984 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001985 out.push_back(
1986 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1987 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1988 mCurrentCookedState.cookedPointerData.pointerProperties,
1989 mCurrentCookedState.cookedPointerData.pointerCoords,
1990 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1991 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1992 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001993 }
1994 } else {
1995 // There may be pointers going up and pointers going down and pointers moving
1996 // all at the same time.
1997 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1998 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1999 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2000 BitSet32 dispatchedIdBits(lastIdBits.value);
2001
2002 // Update last coordinates of pointers that have moved so that we observe the new
2003 // pointer positions at the same time as other pointers that have just gone up.
2004 bool moveNeeded =
2005 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2006 mCurrentCookedState.cookedPointerData.pointerCoords,
2007 mCurrentCookedState.cookedPointerData.idToIndex,
2008 mLastCookedState.cookedPointerData.pointerProperties,
2009 mLastCookedState.cookedPointerData.pointerCoords,
2010 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2011 if (buttonState != mLastCookedState.buttonState) {
2012 moveNeeded = true;
2013 }
2014
2015 // Dispatch pointer up events.
2016 while (!upIdBits.isEmpty()) {
2017 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002018 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002019 if (isCanceled) {
2020 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2021 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002022 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2023 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2024 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2025 buttonState, 0,
2026 mLastCookedState.cookedPointerData.pointerProperties,
2027 mLastCookedState.cookedPointerData.pointerCoords,
2028 mLastCookedState.cookedPointerData.idToIndex,
2029 dispatchedIdBits, upId, mOrientedXPrecision,
2030 mOrientedYPrecision, mDownTime,
2031 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002032 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002033 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002034 }
2035
2036 // Dispatch move events if any of the remaining pointers moved from their old locations.
2037 // Although applications receive new locations as part of individual pointer up
2038 // events, they do not generally handle them except when presented in a move event.
2039 if (moveNeeded && !moveIdBits.isEmpty()) {
2040 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002041 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2042 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2043 mCurrentCookedState.cookedPointerData.pointerProperties,
2044 mCurrentCookedState.cookedPointerData.pointerCoords,
2045 mCurrentCookedState.cookedPointerData.idToIndex,
2046 dispatchedIdBits, -1, mOrientedXPrecision,
2047 mOrientedYPrecision, mDownTime,
2048 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002049 }
2050
2051 // Dispatch pointer down events using the new pointer locations.
2052 while (!downIdBits.isEmpty()) {
2053 uint32_t downId = downIdBits.clearFirstMarkedBit();
2054 dispatchedIdBits.markBit(downId);
2055
2056 if (dispatchedIdBits.count() == 1) {
2057 // First pointer is going down. Set down time.
2058 mDownTime = when;
2059 }
2060
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002061 out.push_back(
2062 dispatchMotion(when, readTime, policyFlags, mSource,
2063 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2064 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2065 mCurrentCookedState.cookedPointerData.pointerCoords,
2066 mCurrentCookedState.cookedPointerData.idToIndex,
2067 dispatchedIdBits, downId, mOrientedXPrecision,
2068 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002069 }
2070 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002071 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002072}
2073
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002074std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2075 uint32_t policyFlags) {
2076 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002077 if (mSentHoverEnter &&
2078 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2079 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2080 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002081 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2082 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2083 mLastCookedState.buttonState, 0,
2084 mLastCookedState.cookedPointerData.pointerProperties,
2085 mLastCookedState.cookedPointerData.pointerCoords,
2086 mLastCookedState.cookedPointerData.idToIndex,
2087 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2088 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2089 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002090 mSentHoverEnter = false;
2091 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002092 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002093}
2094
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002095std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2096 uint32_t policyFlags) {
2097 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002098 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2099 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2100 int32_t metaState = getContext()->getGlobalMetaState();
2101 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002102 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2103 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2104 mCurrentRawState.buttonState, 0,
2105 mCurrentCookedState.cookedPointerData.pointerProperties,
2106 mCurrentCookedState.cookedPointerData.pointerCoords,
2107 mCurrentCookedState.cookedPointerData.idToIndex,
2108 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2109 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2110 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002111 mSentHoverEnter = true;
2112 }
2113
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002114 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2115 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2116 mCurrentRawState.buttonState, 0,
2117 mCurrentCookedState.cookedPointerData.pointerProperties,
2118 mCurrentCookedState.cookedPointerData.pointerCoords,
2119 mCurrentCookedState.cookedPointerData.idToIndex,
2120 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2121 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2122 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002123 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002124 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002125}
2126
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002127std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2128 uint32_t policyFlags) {
2129 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002130 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2131 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2132 const int32_t metaState = getContext()->getGlobalMetaState();
2133 int32_t buttonState = mLastCookedState.buttonState;
2134 while (!releasedButtons.isEmpty()) {
2135 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2136 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002137 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2138 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2139 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002140 mLastCookedState.cookedPointerData.pointerProperties,
2141 mLastCookedState.cookedPointerData.pointerCoords,
2142 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002143 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2144 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002145 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002146 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002147}
2148
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002149std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2150 uint32_t policyFlags) {
2151 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002152 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2153 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2154 const int32_t metaState = getContext()->getGlobalMetaState();
2155 int32_t buttonState = mLastCookedState.buttonState;
2156 while (!pressedButtons.isEmpty()) {
2157 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2158 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002159 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2160 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2161 buttonState, 0,
2162 mCurrentCookedState.cookedPointerData.pointerProperties,
2163 mCurrentCookedState.cookedPointerData.pointerCoords,
2164 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2165 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2166 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002167 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002168 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002169}
2170
LiZhihong758eb562022-11-03 15:28:29 +08002171std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2172 uint32_t policyFlags,
2173 BitSet32 idBits,
2174 nsecs_t readTime) {
2175 std::list<NotifyArgs> out;
2176 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2177 const int32_t metaState = getContext()->getGlobalMetaState();
2178 int32_t buttonState = mLastCookedState.buttonState;
2179
2180 while (!releasedButtons.isEmpty()) {
2181 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2182 buttonState &= ~actionButton;
2183 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2184 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2185 metaState, buttonState, 0,
2186 mPointerGesture.lastGestureProperties,
2187 mPointerGesture.lastGestureCoords,
2188 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2189 mOrientedXPrecision, mOrientedYPrecision,
2190 mPointerGesture.downTime, MotionClassification::NONE));
2191 }
2192 return out;
2193}
2194
2195std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2196 uint32_t policyFlags,
2197 BitSet32 idBits,
2198 nsecs_t readTime) {
2199 std::list<NotifyArgs> out;
2200 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2201 const int32_t metaState = getContext()->getGlobalMetaState();
2202 int32_t buttonState = mLastCookedState.buttonState;
2203
2204 while (!pressedButtons.isEmpty()) {
2205 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2206 buttonState |= actionButton;
2207 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2208 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2209 buttonState, 0, mPointerGesture.currentGestureProperties,
2210 mPointerGesture.currentGestureCoords,
2211 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2212 mOrientedXPrecision, mOrientedYPrecision,
2213 mPointerGesture.downTime, MotionClassification::NONE));
2214 }
2215 return out;
2216}
2217
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002218const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2219 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2220 return cookedPointerData.touchingIdBits;
2221 }
2222 return cookedPointerData.hoveringIdBits;
2223}
2224
2225void TouchInputMapper::cookPointerData() {
2226 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2227
2228 mCurrentCookedState.cookedPointerData.clear();
2229 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2230 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2231 mCurrentRawState.rawPointerData.hoveringIdBits;
2232 mCurrentCookedState.cookedPointerData.touchingIdBits =
2233 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002234 mCurrentCookedState.cookedPointerData.canceledIdBits =
2235 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002236
2237 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2238 mCurrentCookedState.buttonState = 0;
2239 } else {
2240 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2241 }
2242
2243 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002244 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002245 for (uint32_t i = 0; i < currentPointerCount; i++) {
2246 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2247
2248 // Size
2249 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2250 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002251 case Calibration::SizeCalibration::GEOMETRIC:
2252 case Calibration::SizeCalibration::DIAMETER:
2253 case Calibration::SizeCalibration::BOX:
2254 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002255 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2256 touchMajor = in.touchMajor;
2257 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2258 toolMajor = in.toolMajor;
2259 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2260 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2261 : in.touchMajor;
2262 } else if (mRawPointerAxes.touchMajor.valid) {
2263 toolMajor = touchMajor = in.touchMajor;
2264 toolMinor = touchMinor =
2265 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2266 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2267 : in.touchMajor;
2268 } else if (mRawPointerAxes.toolMajor.valid) {
2269 touchMajor = toolMajor = in.toolMajor;
2270 touchMinor = toolMinor =
2271 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2272 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2273 : in.toolMajor;
2274 } else {
2275 ALOG_ASSERT(false,
2276 "No touch or tool axes. "
2277 "Size calibration should have been resolved to NONE.");
2278 touchMajor = 0;
2279 touchMinor = 0;
2280 toolMajor = 0;
2281 toolMinor = 0;
2282 size = 0;
2283 }
2284
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002285 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002286 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2287 if (touchingCount > 1) {
2288 touchMajor /= touchingCount;
2289 touchMinor /= touchingCount;
2290 toolMajor /= touchingCount;
2291 toolMinor /= touchingCount;
2292 size /= touchingCount;
2293 }
2294 }
2295
Michael Wright227c5542020-07-02 18:30:52 +01002296 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297 touchMajor *= mGeometricScale;
2298 touchMinor *= mGeometricScale;
2299 toolMajor *= mGeometricScale;
2300 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002301 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002302 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2303 touchMinor = touchMajor;
2304 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2305 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002306 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002307 touchMinor = touchMajor;
2308 toolMinor = toolMajor;
2309 }
2310
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002311 mCalibration.applySizeScaleAndBias(touchMajor);
2312 mCalibration.applySizeScaleAndBias(touchMinor);
2313 mCalibration.applySizeScaleAndBias(toolMajor);
2314 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 size *= mSizeScale;
2316 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002317 case Calibration::SizeCalibration::DEFAULT:
2318 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2319 break;
2320 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002321 touchMajor = 0;
2322 touchMinor = 0;
2323 toolMajor = 0;
2324 toolMinor = 0;
2325 size = 0;
2326 break;
2327 }
2328
2329 // Pressure
2330 float pressure;
2331 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002332 case Calibration::PressureCalibration::PHYSICAL:
2333 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002334 pressure = in.pressure * mPressureScale;
2335 break;
2336 default:
2337 pressure = in.isHovering ? 0 : 1;
2338 break;
2339 }
2340
2341 // Tilt and Orientation
2342 float tilt;
2343 float orientation;
2344 if (mHaveTilt) {
2345 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2346 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002347 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002348 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2349 } else {
2350 tilt = 0;
2351
2352 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002353 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002354 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 break;
Michael Wright227c5542020-07-02 18:30:52 +01002356 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002357 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2358 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2359 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002360 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 float confidence = hypotf(c1, c2);
2362 float scale = 1.0f + confidence / 16.0f;
2363 touchMajor *= scale;
2364 touchMinor /= scale;
2365 toolMajor *= scale;
2366 toolMinor /= scale;
2367 } else {
2368 orientation = 0;
2369 }
2370 break;
2371 }
2372 default:
2373 orientation = 0;
2374 }
2375 }
2376
2377 // Distance
2378 float distance;
2379 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002380 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 distance = in.distance * mDistanceScale;
2382 break;
2383 default:
2384 distance = 0;
2385 }
2386
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002387 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2388 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002389 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2390 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002392 // Write output coords.
2393 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2394 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002395 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2396 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2398 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2399 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2400 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2401 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2402 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2403 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002404 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2405 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406
Chris Ye364fdb52020-08-05 15:07:56 -07002407 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002408 uint32_t id = in.id;
2409 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2410 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2411 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002412 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2413 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002414 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2415 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2416 }
2417
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002418 // Write output properties.
2419 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002420 properties.clear();
2421 properties.id = id;
2422 properties.toolType = in.toolType;
2423
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002424 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002426 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 }
2428}
2429
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002430std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2431 uint32_t policyFlags,
2432 PointerUsage pointerUsage) {
2433 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002435 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 mPointerUsage = pointerUsage;
2437 }
2438
2439 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002440 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002441 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 break;
Michael Wright227c5542020-07-02 18:30:52 +01002443 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002444 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 break;
Michael Wright227c5542020-07-02 18:30:52 +01002446 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002447 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002448 break;
Michael Wright227c5542020-07-02 18:30:52 +01002449 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 break;
2451 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002452 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002453}
2454
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002455std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2456 uint32_t policyFlags) {
2457 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002459 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002460 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 break;
Michael Wright227c5542020-07-02 18:30:52 +01002462 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002463 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464 break;
Michael Wright227c5542020-07-02 18:30:52 +01002465 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002466 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 break;
Michael Wright227c5542020-07-02 18:30:52 +01002468 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 break;
2470 }
2471
Michael Wright227c5542020-07-02 18:30:52 +01002472 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002473 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474}
2475
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002476std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2477 uint32_t policyFlags,
2478 bool isTimeout) {
2479 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002480 // Update current gesture coordinates.
2481 bool cancelPreviousGesture, finishPreviousGesture;
2482 bool sendEvents =
2483 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2484 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002485 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486 }
2487 if (finishPreviousGesture) {
2488 cancelPreviousGesture = false;
2489 }
2490
2491 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002492 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002493 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002494 if (finishPreviousGesture || cancelPreviousGesture) {
2495 mPointerController->clearSpots();
2496 }
2497
Michael Wright227c5542020-07-02 18:30:52 +01002498 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002499 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2500 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002501 mPointerGesture.currentGestureIdBits,
2502 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 }
2504 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002505 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002506 }
2507
2508 // Show or hide the pointer if needed.
2509 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002510 case PointerGesture::Mode::NEUTRAL:
2511 case PointerGesture::Mode::QUIET:
2512 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2513 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002515 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002516 }
2517 break;
Michael Wright227c5542020-07-02 18:30:52 +01002518 case PointerGesture::Mode::TAP:
2519 case PointerGesture::Mode::TAP_DRAG:
2520 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2521 case PointerGesture::Mode::HOVER:
2522 case PointerGesture::Mode::PRESS:
2523 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 // Unfade the pointer when the current gesture manipulates the
2525 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002526 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002527 break;
Michael Wright227c5542020-07-02 18:30:52 +01002528 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002529 // Fade the pointer when the current gesture manipulates a different
2530 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002531 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002532 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002533 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002534 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002535 }
2536 break;
2537 }
2538
2539 // Send events!
2540 int32_t metaState = getContext()->getGlobalMetaState();
2541 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002542 const MotionClassification classification =
2543 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2544 ? MotionClassification::TWO_FINGER_SWIPE
2545 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002546
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002547 uint32_t flags = 0;
2548
2549 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2550 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2551 }
2552
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553 // Update last coordinates of pointers that have moved so that we observe the new
2554 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002555 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2556 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2557 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2558 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2559 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2560 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002561 bool moveNeeded = false;
2562 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2563 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2564 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2565 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2566 mPointerGesture.lastGestureIdBits.value);
2567 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2568 mPointerGesture.currentGestureCoords,
2569 mPointerGesture.currentGestureIdToIndex,
2570 mPointerGesture.lastGestureProperties,
2571 mPointerGesture.lastGestureCoords,
2572 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2573 if (buttonState != mLastCookedState.buttonState) {
2574 moveNeeded = true;
2575 }
2576 }
2577
2578 // Send motion events for all pointers that went up or were canceled.
2579 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2580 if (!dispatchedGestureIdBits.isEmpty()) {
2581 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002582 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002583 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002584 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002585 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2586 mPointerGesture.lastGestureProperties,
2587 mPointerGesture.lastGestureCoords,
2588 mPointerGesture.lastGestureIdToIndex,
2589 dispatchedGestureIdBits, -1, 0, 0,
2590 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002591
2592 dispatchedGestureIdBits.clear();
2593 } else {
2594 BitSet32 upGestureIdBits;
2595 if (finishPreviousGesture) {
2596 upGestureIdBits = dispatchedGestureIdBits;
2597 } else {
2598 upGestureIdBits.value =
2599 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2600 }
2601 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002602 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2603 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2604 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2605 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2606 readTime);
2607 }
2608 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002609 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2610 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2611 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2612 mPointerGesture.lastGestureProperties,
2613 mPointerGesture.lastGestureCoords,
2614 mPointerGesture.lastGestureIdToIndex,
2615 dispatchedGestureIdBits, id, 0, 0,
2616 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002617
2618 dispatchedGestureIdBits.clearBit(id);
2619 }
2620 }
2621 }
2622
2623 // Send motion events for all pointers that moved.
2624 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002625 out.push_back(
2626 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2627 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2628 mPointerGesture.currentGestureProperties,
2629 mPointerGesture.currentGestureCoords,
2630 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2631 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002632 }
2633
2634 // Send motion events for all pointers that went down.
2635 if (down) {
2636 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2637 ~dispatchedGestureIdBits.value);
2638 while (!downGestureIdBits.isEmpty()) {
2639 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2640 dispatchedGestureIdBits.markBit(id);
2641
2642 if (dispatchedGestureIdBits.count() == 1) {
2643 mPointerGesture.downTime = when;
2644 }
2645
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002646 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2647 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2648 buttonState, 0, mPointerGesture.currentGestureProperties,
2649 mPointerGesture.currentGestureCoords,
2650 mPointerGesture.currentGestureIdToIndex,
2651 dispatchedGestureIdBits, id, 0, 0,
2652 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002653 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2654 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2655 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2656 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2657 readTime);
2658 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002659 }
2660 }
2661
2662 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002663 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002664 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2665 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2666 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2667 mPointerGesture.currentGestureProperties,
2668 mPointerGesture.currentGestureCoords,
2669 mPointerGesture.currentGestureIdToIndex,
2670 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2671 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002672 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2673 // Synthesize a hover move event after all pointers go up to indicate that
2674 // the pointer is hovering again even if the user is not currently touching
2675 // the touch pad. This ensures that a view will receive a fresh hover enter
2676 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002677 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002678
2679 PointerProperties pointerProperties;
2680 pointerProperties.clear();
2681 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002682 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002683
2684 PointerCoords pointerCoords;
2685 pointerCoords.clear();
2686 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2687 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2688
2689 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002690 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2691 mSource, displayId, policyFlags,
2692 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2693 buttonState, MotionClassification::NONE,
2694 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2695 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2696 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002697 }
2698
2699 // Update state.
2700 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2701 if (!down) {
2702 mPointerGesture.lastGestureIdBits.clear();
2703 } else {
2704 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2705 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2706 uint32_t id = idBits.clearFirstMarkedBit();
2707 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2708 mPointerGesture.lastGestureProperties[index].copyFrom(
2709 mPointerGesture.currentGestureProperties[index]);
2710 mPointerGesture.lastGestureCoords[index].copyFrom(
2711 mPointerGesture.currentGestureCoords[index]);
2712 mPointerGesture.lastGestureIdToIndex[id] = index;
2713 }
2714 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002715 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002716}
2717
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002718std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2719 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002720 const MotionClassification classification =
2721 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2722 ? MotionClassification::TWO_FINGER_SWIPE
2723 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002724 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002725 // Cancel previously dispatches pointers.
2726 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2727 int32_t metaState = getContext()->getGlobalMetaState();
2728 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002729 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002730 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2731 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002732 mPointerGesture.lastGestureProperties,
2733 mPointerGesture.lastGestureCoords,
2734 mPointerGesture.lastGestureIdToIndex,
2735 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2736 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002737 }
2738
2739 // Reset the current pointer gesture.
2740 mPointerGesture.reset();
2741 mPointerVelocityControl.reset();
2742
2743 // Remove any current spots.
2744 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002745 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002746 mPointerController->clearSpots();
2747 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002748 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002749}
2750
2751bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2752 bool* outFinishPreviousGesture, bool isTimeout) {
2753 *outCancelPreviousGesture = false;
2754 *outFinishPreviousGesture = false;
2755
2756 // Handle TAP timeout.
2757 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002758 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002759
Michael Wright227c5542020-07-02 18:30:52 +01002760 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002761 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2762 // The tap/drag timeout has not yet expired.
2763 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2764 mConfig.pointerGestureTapDragInterval);
2765 } else {
2766 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002767 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002768 *outFinishPreviousGesture = true;
2769
2770 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002771 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002772 mPointerGesture.currentGestureIdBits.clear();
2773
2774 mPointerVelocityControl.reset();
2775 return true;
2776 }
2777 }
2778
2779 // We did not handle this timeout.
2780 return false;
2781 }
2782
2783 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2784 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2785
2786 // Update the velocity tracker.
2787 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002788 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002789 uint32_t id = idBits.clearFirstMarkedBit();
2790 const RawPointerData::Pointer& pointer =
2791 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002792 const float x = pointer.x * mPointerXMovementScale;
2793 const float y = pointer.y * mPointerYMovementScale;
2794 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2795 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002796 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002797 }
2798
2799 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2800 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002801 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2802 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2803 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002804 mPointerGesture.resetTap();
2805 }
2806
2807 // Pick a new active touch id if needed.
2808 // Choose an arbitrary pointer that just went down, if there is one.
2809 // Otherwise choose an arbitrary remaining pointer.
2810 // This guarantees we always have an active touch id when there is at least one pointer.
2811 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002812 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002813 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002814 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002815 mPointerGesture.firstTouchTime = when;
2816 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002817 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2818 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2819 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2820 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002821 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002822 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002823
2824 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002825 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002826 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002827 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2828 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2829 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002830 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002831 *outFinishPreviousGesture = true;
2832 }
2833
2834 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002835 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002836 mPointerGesture.currentGestureIdBits.clear();
2837
2838 mPointerVelocityControl.reset();
2839 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2840 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2841 // The pointer follows the active touch point.
2842 // Emit DOWN, MOVE, UP events at the pointer location.
2843 //
2844 // Only the active touch matters; other fingers are ignored. This policy helps
2845 // to handle the case where the user places a second finger on the touch pad
2846 // to apply the necessary force to depress an integrated button below the surface.
2847 // We don't want the second finger to be delivered to applications.
2848 //
2849 // For this to work well, we need to make sure to track the pointer that is really
2850 // active. If the user first puts one finger down to click then adds another
2851 // finger to drag then the active pointer should switch to the finger that is
2852 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002853 ALOGD_IF(DEBUG_GESTURES,
2854 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2855 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002856 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002857 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002858 *outFinishPreviousGesture = true;
2859 mPointerGesture.activeGestureId = 0;
2860 }
2861
2862 // Switch pointers if needed.
2863 // Find the fastest pointer and follow it.
2864 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002865 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002866 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002867 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002868 ALOGD_IF(DEBUG_GESTURES,
2869 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2870 "bestSpeed=%0.3f",
2871 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 }
2873 }
2874
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002876 // When using spots, the click will occur at the position of the anchor
2877 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002878 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002879 } else {
2880 mPointerVelocityControl.reset();
2881 }
2882
Prabir Pradhan2719e822023-02-28 17:39:36 +00002883 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884
Michael Wright227c5542020-07-02 18:30:52 +01002885 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002886 mPointerGesture.currentGestureIdBits.clear();
2887 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2888 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2889 mPointerGesture.currentGestureProperties[0].clear();
2890 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002891 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892 mPointerGesture.currentGestureCoords[0].clear();
2893 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2894 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2895 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2896 } else if (currentFingerCount == 0) {
2897 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002898 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002899 *outFinishPreviousGesture = true;
2900 }
2901
2902 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2903 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2904 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002905 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2906 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907 lastFingerCount == 1) {
2908 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002909 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002910 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2911 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002912 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002913
2914 mPointerGesture.tapUpTime = when;
2915 getContext()->requestTimeoutAtTime(when +
2916 mConfig.pointerGestureTapDragInterval);
2917
2918 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002919 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002920 mPointerGesture.currentGestureIdBits.clear();
2921 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2922 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2923 mPointerGesture.currentGestureProperties[0].clear();
2924 mPointerGesture.currentGestureProperties[0].id =
2925 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002926 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002927 mPointerGesture.currentGestureCoords[0].clear();
2928 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2929 mPointerGesture.tapX);
2930 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2931 mPointerGesture.tapY);
2932 mPointerGesture.currentGestureCoords[0]
2933 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2934
2935 tapped = true;
2936 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002937 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2938 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002939 }
2940 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002941 if (DEBUG_GESTURES) {
2942 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2943 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2944 (when - mPointerGesture.tapDownTime) * 0.000001f);
2945 } else {
2946 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2947 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002948 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002949 }
2950 }
2951
2952 mPointerVelocityControl.reset();
2953
2954 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002955 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002956 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002957 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002958 mPointerGesture.currentGestureIdBits.clear();
2959 }
2960 } else if (currentFingerCount == 1) {
2961 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2962 // The pointer follows the active touch point.
2963 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2964 // When in TAP_DRAG, emit MOVE events at the pointer location.
2965 ALOG_ASSERT(activeTouchId >= 0);
2966
Michael Wright227c5542020-07-02 18:30:52 +01002967 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2968 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002969 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002970 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002971 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2972 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002973 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002974 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002975 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2976 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002977 }
2978 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002979 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2980 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 }
Michael Wright227c5542020-07-02 18:30:52 +01002982 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2983 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002984 }
2985
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002986 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002987 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002988 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002989 } else {
2990 mPointerVelocityControl.reset();
2991 }
2992
2993 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002994 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002995 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002996 down = true;
2997 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002998 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002999 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003000 *outFinishPreviousGesture = true;
3001 }
3002 mPointerGesture.activeGestureId = 0;
3003 down = false;
3004 }
3005
Prabir Pradhan2719e822023-02-28 17:39:36 +00003006 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003007
3008 mPointerGesture.currentGestureIdBits.clear();
3009 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3010 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3011 mPointerGesture.currentGestureProperties[0].clear();
3012 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003013 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003014 mPointerGesture.currentGestureCoords[0].clear();
3015 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3016 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3017 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3018 down ? 1.0f : 0.0f);
3019
3020 if (lastFingerCount == 0 && currentFingerCount != 0) {
3021 mPointerGesture.resetTap();
3022 mPointerGesture.tapDownTime = when;
3023 mPointerGesture.tapX = x;
3024 mPointerGesture.tapY = y;
3025 }
3026 } else {
3027 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003028 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003029 }
3030
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003031 if (DEBUG_GESTURES) {
3032 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3033 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3034 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3035 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3036 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3037 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3038 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3039 uint32_t id = idBits.clearFirstMarkedBit();
3040 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3041 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3042 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003043 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003044 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003045 id, index, ftl::enum_string(properties.toolType).c_str(),
3046 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003047 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3048 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3049 }
3050 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3051 uint32_t id = idBits.clearFirstMarkedBit();
3052 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3053 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3054 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003055 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003056 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003057 id, index, ftl::enum_string(properties.toolType).c_str(),
3058 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003059 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3060 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3061 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003062 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003063 return true;
3064}
3065
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003066bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3067 if (mPointerGesture.activeTouchId < 0) {
3068 mPointerGesture.resetQuietTime();
3069 return false;
3070 }
3071
3072 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3073 return true;
3074 }
3075
3076 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3077 bool isQuietTime = false;
3078 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3079 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3080 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3081 currentFingerCount < 2) {
3082 // Enter quiet time when exiting swipe or freeform state.
3083 // This is to prevent accidentally entering the hover state and flinging the
3084 // pointer when finishing a swipe and there is still one pointer left onscreen.
3085 isQuietTime = true;
3086 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3087 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3088 // Enter quiet time when releasing the button and there are still two or more
3089 // fingers down. This may indicate that one finger was used to press the button
3090 // but it has not gone up yet.
3091 isQuietTime = true;
3092 }
3093 if (isQuietTime) {
3094 mPointerGesture.quietTime = when;
3095 }
3096 return isQuietTime;
3097}
3098
3099std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3100 int32_t bestId = -1;
3101 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3102 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3103 uint32_t id = idBits.clearFirstMarkedBit();
3104 std::optional<float> vx =
3105 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3106 std::optional<float> vy =
3107 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3108 if (vx && vy) {
3109 float speed = hypotf(*vx, *vy);
3110 if (speed > bestSpeed) {
3111 bestId = id;
3112 bestSpeed = speed;
3113 }
3114 }
3115 }
3116 return std::make_pair(bestId, bestSpeed);
3117}
3118
3119void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3120 bool* finishPreviousGesture) {
3121 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3122 // to move before deciding what to do.
3123 //
3124 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3125 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3126 // just a press or long-press at the pointer location.
3127 //
3128 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3129 // pointer location.
3130 //
3131 // When the two fingers move enough or when additional fingers are added, we make a decision to
3132 // transition into SWIPE or FREEFORM mode accordingly.
3133 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3134 ALOG_ASSERT(activeTouchId >= 0);
3135
3136 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3137 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3138 bool settled =
3139 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3140 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3141 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3142 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3143 *finishPreviousGesture = true;
3144 } else if (!settled && currentFingerCount > lastFingerCount) {
3145 // Additional pointers have gone down but not yet settled.
3146 // Reset the gesture.
3147 ALOGD_IF(DEBUG_GESTURES,
3148 "Gestures: Resetting gesture since additional pointers went down for "
3149 "MULTITOUCH, settle time remaining %0.3fms",
3150 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3151 when) * 0.000001f);
3152 *cancelPreviousGesture = true;
3153 } else {
3154 // Continue previous gesture.
3155 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3156 }
3157
3158 if (*finishPreviousGesture || *cancelPreviousGesture) {
3159 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3160 mPointerGesture.activeGestureId = 0;
3161 mPointerGesture.referenceIdBits.clear();
3162 mPointerVelocityControl.reset();
3163
3164 // Use the centroid and pointer location as the reference points for the gesture.
3165 ALOGD_IF(DEBUG_GESTURES,
3166 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3167 "%0.3fms",
3168 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3169 when) * 0.000001f);
3170 mCurrentRawState.rawPointerData
3171 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3172 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003173 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3174 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003175 }
3176
3177 // Clear the reference deltas for fingers not yet included in the reference calculation.
3178 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3179 ~mPointerGesture.referenceIdBits.value);
3180 !idBits.isEmpty();) {
3181 uint32_t id = idBits.clearFirstMarkedBit();
3182 mPointerGesture.referenceDeltas[id].dx = 0;
3183 mPointerGesture.referenceDeltas[id].dy = 0;
3184 }
3185 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3186
3187 // Add delta for all fingers and calculate a common movement delta.
3188 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3189 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3190 mCurrentCookedState.fingerIdBits.value);
3191 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3192 bool first = (idBits == commonIdBits);
3193 uint32_t id = idBits.clearFirstMarkedBit();
3194 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3195 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3196 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3197 delta.dx += cpd.x - lpd.x;
3198 delta.dy += cpd.y - lpd.y;
3199
3200 if (first) {
3201 commonDeltaRawX = delta.dx;
3202 commonDeltaRawY = delta.dy;
3203 } else {
3204 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3205 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3206 }
3207 }
3208
3209 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3210 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3211 float dist[MAX_POINTER_ID + 1];
3212 int32_t distOverThreshold = 0;
3213 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3214 uint32_t id = idBits.clearFirstMarkedBit();
3215 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3216 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3217 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3218 distOverThreshold += 1;
3219 }
3220 }
3221
3222 // Only transition when at least two pointers have moved further than
3223 // the minimum distance threshold.
3224 if (distOverThreshold >= 2) {
3225 if (currentFingerCount > 2) {
3226 // There are more than two pointers, switch to FREEFORM.
3227 ALOGD_IF(DEBUG_GESTURES,
3228 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3229 currentFingerCount);
3230 *cancelPreviousGesture = true;
3231 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3232 } else {
3233 // There are exactly two pointers.
3234 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3235 uint32_t id1 = idBits.clearFirstMarkedBit();
3236 uint32_t id2 = idBits.firstMarkedBit();
3237 const RawPointerData::Pointer& p1 =
3238 mCurrentRawState.rawPointerData.pointerForId(id1);
3239 const RawPointerData::Pointer& p2 =
3240 mCurrentRawState.rawPointerData.pointerForId(id2);
3241 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3242 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3243 // There are two pointers but they are too far apart for a SWIPE,
3244 // switch to FREEFORM.
3245 ALOGD_IF(DEBUG_GESTURES,
3246 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3247 mutualDistance, mPointerGestureMaxSwipeWidth);
3248 *cancelPreviousGesture = true;
3249 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3250 } else {
3251 // There are two pointers. Wait for both pointers to start moving
3252 // before deciding whether this is a SWIPE or FREEFORM gesture.
3253 float dist1 = dist[id1];
3254 float dist2 = dist[id2];
3255 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3256 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3257 // Calculate the dot product of the displacement vectors.
3258 // When the vectors are oriented in approximately the same direction,
3259 // the angle betweeen them is near zero and the cosine of the angle
3260 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3261 // mag(v2).
3262 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3263 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3264 float dx1 = delta1.dx * mPointerXZoomScale;
3265 float dy1 = delta1.dy * mPointerYZoomScale;
3266 float dx2 = delta2.dx * mPointerXZoomScale;
3267 float dy2 = delta2.dy * mPointerYZoomScale;
3268 float dot = dx1 * dx2 + dy1 * dy2;
3269 float cosine = dot / (dist1 * dist2); // denominator always > 0
3270 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3271 // Pointers are moving in the same direction. Switch to SWIPE.
3272 ALOGD_IF(DEBUG_GESTURES,
3273 "Gestures: PRESS transitioned to SWIPE, "
3274 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3275 "cosine %0.3f >= %0.3f",
3276 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3277 mConfig.pointerGestureMultitouchMinDistance, cosine,
3278 mConfig.pointerGestureSwipeTransitionAngleCosine);
3279 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3280 } else {
3281 // Pointers are moving in different directions. Switch to FREEFORM.
3282 ALOGD_IF(DEBUG_GESTURES,
3283 "Gestures: PRESS transitioned to FREEFORM, "
3284 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3285 "cosine %0.3f < %0.3f",
3286 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3287 mConfig.pointerGestureMultitouchMinDistance, cosine,
3288 mConfig.pointerGestureSwipeTransitionAngleCosine);
3289 *cancelPreviousGesture = true;
3290 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3291 }
3292 }
3293 }
3294 }
3295 }
3296 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3297 // Switch from SWIPE to FREEFORM if additional pointers go down.
3298 // Cancel previous gesture.
3299 if (currentFingerCount > 2) {
3300 ALOGD_IF(DEBUG_GESTURES,
3301 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3302 currentFingerCount);
3303 *cancelPreviousGesture = true;
3304 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3305 }
3306 }
3307
3308 // Move the reference points based on the overall group motion of the fingers
3309 // except in PRESS mode while waiting for a transition to occur.
3310 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3311 (commonDeltaRawX || commonDeltaRawY)) {
3312 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3313 uint32_t id = idBits.clearFirstMarkedBit();
3314 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3315 delta.dx = 0;
3316 delta.dy = 0;
3317 }
3318
3319 mPointerGesture.referenceTouchX += commonDeltaRawX;
3320 mPointerGesture.referenceTouchY += commonDeltaRawY;
3321
3322 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3323 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3324
3325 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3326 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3327
3328 mPointerGesture.referenceGestureX += commonDeltaX;
3329 mPointerGesture.referenceGestureY += commonDeltaY;
3330 }
3331
3332 // Report gestures.
3333 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3334 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3335 // PRESS or SWIPE mode.
3336 ALOGD_IF(DEBUG_GESTURES,
3337 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3338 "currentTouchPointerCount=%d",
3339 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3340 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3341
3342 mPointerGesture.currentGestureIdBits.clear();
3343 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3344 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3345 mPointerGesture.currentGestureProperties[0].clear();
3346 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003347 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003348 mPointerGesture.currentGestureCoords[0].clear();
3349 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3350 mPointerGesture.referenceGestureX);
3351 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3352 mPointerGesture.referenceGestureY);
3353 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3354 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3355 float xOffset = static_cast<float>(commonDeltaRawX) /
3356 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3357 float yOffset = static_cast<float>(commonDeltaRawY) /
3358 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3359 mPointerGesture.currentGestureCoords[0]
3360 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3361 mPointerGesture.currentGestureCoords[0]
3362 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3363 }
3364 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3365 // FREEFORM mode.
3366 ALOGD_IF(DEBUG_GESTURES,
3367 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3368 "currentTouchPointerCount=%d",
3369 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3370 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3371
3372 mPointerGesture.currentGestureIdBits.clear();
3373
3374 BitSet32 mappedTouchIdBits;
3375 BitSet32 usedGestureIdBits;
3376 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3377 // Initially, assign the active gesture id to the active touch point
3378 // if there is one. No other touch id bits are mapped yet.
3379 if (!*cancelPreviousGesture) {
3380 mappedTouchIdBits.markBit(activeTouchId);
3381 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3382 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3383 mPointerGesture.activeGestureId;
3384 } else {
3385 mPointerGesture.activeGestureId = -1;
3386 }
3387 } else {
3388 // Otherwise, assume we mapped all touches from the previous frame.
3389 // Reuse all mappings that are still applicable.
3390 mappedTouchIdBits.value =
3391 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3392 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3393
3394 // Check whether we need to choose a new active gesture id because the
3395 // current went went up.
3396 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3397 ~mCurrentCookedState.fingerIdBits.value);
3398 !upTouchIdBits.isEmpty();) {
3399 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3400 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3401 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3402 mPointerGesture.activeGestureId = -1;
3403 break;
3404 }
3405 }
3406 }
3407
3408 ALOGD_IF(DEBUG_GESTURES,
3409 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3410 "activeGestureId=%d",
3411 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3412
3413 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3414 for (uint32_t i = 0; i < currentFingerCount; i++) {
3415 uint32_t touchId = idBits.clearFirstMarkedBit();
3416 uint32_t gestureId;
3417 if (!mappedTouchIdBits.hasBit(touchId)) {
3418 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3419 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3420 ALOGD_IF(DEBUG_GESTURES,
3421 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3422 gestureId);
3423 } else {
3424 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3425 ALOGD_IF(DEBUG_GESTURES,
3426 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3427 touchId, gestureId);
3428 }
3429 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3430 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3431
3432 const RawPointerData::Pointer& pointer =
3433 mCurrentRawState.rawPointerData.pointerForId(touchId);
3434 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3435 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3436 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3437
3438 mPointerGesture.currentGestureProperties[i].clear();
3439 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003440 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003441 mPointerGesture.currentGestureCoords[i].clear();
3442 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3443 mPointerGesture.referenceGestureX +
3444 deltaX);
3445 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3446 mPointerGesture.referenceGestureY +
3447 deltaY);
3448 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3449 }
3450
3451 if (mPointerGesture.activeGestureId < 0) {
3452 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3453 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3454 mPointerGesture.activeGestureId);
3455 }
3456 }
3457}
3458
Harry Cutts714d1ad2022-08-24 16:36:43 +00003459void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3460 const RawPointerData::Pointer& currentPointer =
3461 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3462 const RawPointerData::Pointer& lastPointer =
3463 mLastRawState.rawPointerData.pointerForId(pointerId);
3464 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3465 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3466
3467 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3468 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3469
3470 mPointerController->move(deltaX, deltaY);
3471}
3472
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003473std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3474 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003475 mPointerSimple.currentCoords.clear();
3476 mPointerSimple.currentProperties.clear();
3477
3478 bool down, hovering;
3479 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3480 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3481 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003482 mPointerController
3483 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3484 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003485
3486 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3487 down = !hovering;
3488
Prabir Pradhan2719e822023-02-28 17:39:36 +00003489 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003490 mPointerSimple.currentCoords.copyFrom(
3491 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3492 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3493 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3494 mPointerSimple.currentProperties.id = 0;
3495 mPointerSimple.currentProperties.toolType =
3496 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3497 } else {
3498 down = false;
3499 hovering = false;
3500 }
3501
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003502 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003503}
3504
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003505std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3506 uint32_t policyFlags) {
3507 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003508}
3509
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003510std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3511 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003512 mPointerSimple.currentCoords.clear();
3513 mPointerSimple.currentProperties.clear();
3514
3515 bool down, hovering;
3516 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3517 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003518 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003519 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003520 } else {
3521 mPointerVelocityControl.reset();
3522 }
3523
3524 down = isPointerDown(mCurrentRawState.buttonState);
3525 hovering = !down;
3526
Prabir Pradhan2719e822023-02-28 17:39:36 +00003527 const auto [x, y] = mPointerController->getPosition();
3528 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003529 mPointerSimple.currentCoords.copyFrom(
3530 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3531 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3532 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3533 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3534 hovering ? 0.0f : 1.0f);
3535 mPointerSimple.currentProperties.id = 0;
3536 mPointerSimple.currentProperties.toolType =
3537 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3538 } else {
3539 mPointerVelocityControl.reset();
3540
3541 down = false;
3542 hovering = false;
3543 }
3544
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003545 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003546}
3547
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003548std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3549 uint32_t policyFlags) {
3550 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003551
3552 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003553
3554 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003555}
3556
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003557std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3558 uint32_t policyFlags, bool down,
3559 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003560 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3561 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003562 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003563 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003564
3565 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003566 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003567 mPointerController->clearSpots();
Michael Wrightca5bede2020-07-02 00:00:29 +01003568 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003569 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003570 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003571 }
Garfield Tan9514d782020-11-10 16:37:23 -08003572 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003573
Prabir Pradhan2719e822023-02-28 17:39:36 +00003574 const auto [xCursorPosition, yCursorPosition] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003575
3576 if (mPointerSimple.down && !down) {
3577 mPointerSimple.down = false;
3578
3579 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003580 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3581 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3582 0, metaState, mLastRawState.buttonState,
3583 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3584 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3585 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3586 yCursorPosition, mPointerSimple.downTime,
3587 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003588 }
3589
3590 if (mPointerSimple.hovering && !hovering) {
3591 mPointerSimple.hovering = false;
3592
3593 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003594 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3595 mSource, displayId, policyFlags,
3596 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3597 mLastRawState.buttonState, MotionClassification::NONE,
3598 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3599 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3600 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3601 yCursorPosition, mPointerSimple.downTime,
3602 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003603 }
3604
3605 if (down) {
3606 if (!mPointerSimple.down) {
3607 mPointerSimple.down = true;
3608 mPointerSimple.downTime = when;
3609
3610 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003611 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3612 mSource, displayId, policyFlags,
3613 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3614 mCurrentRawState.buttonState, MotionClassification::NONE,
3615 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3616 &mPointerSimple.currentProperties,
3617 &mPointerSimple.currentCoords, mOrientedXPrecision,
3618 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3619 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003620 }
3621
3622 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003623 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3624 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3625 0, 0, metaState, mCurrentRawState.buttonState,
3626 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3627 &mPointerSimple.currentProperties,
3628 &mPointerSimple.currentCoords, mOrientedXPrecision,
3629 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3630 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003631 }
3632
3633 if (hovering) {
3634 if (!mPointerSimple.hovering) {
3635 mPointerSimple.hovering = true;
3636
3637 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003638 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3639 mSource, displayId, policyFlags,
3640 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3641 mCurrentRawState.buttonState, MotionClassification::NONE,
3642 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3643 &mPointerSimple.currentProperties,
3644 &mPointerSimple.currentCoords, mOrientedXPrecision,
3645 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3646 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003647 }
3648
3649 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003650 out.push_back(
3651 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3652 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3653 metaState, mCurrentRawState.buttonState,
3654 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3655 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3656 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3657 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003658 }
3659
3660 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3661 float vscroll = mCurrentRawState.rawVScroll;
3662 float hscroll = mCurrentRawState.rawHScroll;
3663 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3664 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3665
3666 // Send scroll.
3667 PointerCoords pointerCoords;
3668 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3669 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3670 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3671
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003672 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3673 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3674 0, 0, metaState, mCurrentRawState.buttonState,
3675 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3676 &mPointerSimple.currentProperties, &pointerCoords,
3677 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3678 yCursorPosition, mPointerSimple.downTime,
3679 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003680 }
3681
3682 // Save state.
3683 if (down || hovering) {
3684 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3685 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003686 mPointerSimple.displayId = displayId;
3687 mPointerSimple.source = mSource;
3688 mPointerSimple.lastCursorX = xCursorPosition;
3689 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003690 } else {
3691 mPointerSimple.reset();
3692 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003693 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003694}
3695
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003696std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3697 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003698 std::list<NotifyArgs> out;
3699 if (mPointerSimple.down || mPointerSimple.hovering) {
3700 int32_t metaState = getContext()->getGlobalMetaState();
3701 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3702 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3703 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3704 metaState, mLastRawState.buttonState,
3705 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3706 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3707 mOrientedXPrecision, mOrientedYPrecision,
3708 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3709 mPointerSimple.downTime,
3710 /* videoFrames */ {}));
3711 if (mPointerController != nullptr) {
3712 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3713 }
3714 }
3715 mPointerSimple.reset();
3716 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003717}
3718
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003719static bool isStylusEvent(uint32_t source, int32_t action, const PointerProperties* properties) {
3720 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
3721 return false;
3722 }
3723 const auto actionIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3724 return isStylusToolType(properties[actionIndex].toolType);
3725}
3726
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003727NotifyMotionArgs TouchInputMapper::dispatchMotion(
3728 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3729 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003730 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3731 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003732 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003733 PointerCoords pointerCoords[MAX_POINTERS];
3734 PointerProperties pointerProperties[MAX_POINTERS];
3735 uint32_t pointerCount = 0;
3736 while (!idBits.isEmpty()) {
3737 uint32_t id = idBits.clearFirstMarkedBit();
3738 uint32_t index = idToIndex[id];
3739 pointerProperties[pointerCount].copyFrom(properties[index]);
3740 pointerCoords[pointerCount].copyFrom(coords[index]);
3741
3742 if (changedId >= 0 && id == uint32_t(changedId)) {
3743 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3744 }
3745
3746 pointerCount += 1;
3747 }
3748
3749 ALOG_ASSERT(pointerCount != 0);
3750
3751 if (changedId >= 0 && pointerCount == 1) {
3752 // Replace initial down and final up action.
3753 // We can compare the action without masking off the changed pointer index
3754 // because we know the index is 0.
3755 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3756 action = AMOTION_EVENT_ACTION_DOWN;
3757 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003758 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3759 action = AMOTION_EVENT_ACTION_CANCEL;
3760 } else {
3761 action = AMOTION_EVENT_ACTION_UP;
3762 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003763 } else {
3764 // Can't happen.
3765 ALOG_ASSERT(false);
3766 }
3767 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003768
3769 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3770 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
3771 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, action, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003772 mPointerController && displayId != ADISPLAY_ID_NONE &&
3773 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003774 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003775 switch (action & AMOTION_EVENT_ACTION_MASK) {
3776 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3777 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3778 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003779 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003780 mPointerController
3781 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3782 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3783 .getY());
3784 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3785 break;
3786 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3787 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3788 break;
3789 }
3790 }
3791
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003792 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3793 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003794 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003795 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003796 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003797 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003798 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003799 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003800 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003801 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3802 policyFlags, action, actionButton, flags, metaState, buttonState,
3803 classification, edgeFlags, pointerCount, pointerProperties,
3804 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3805 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003806}
3807
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003808std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3809 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003810 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3811 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003812 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003813}
3814
Prabir Pradhan1728b212021-10-19 16:00:03 -07003815bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003816 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003817 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003818 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003819}
3820
3821const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3822 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003823 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3824 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3825 "left=%d, top=%d, right=%d, bottom=%d",
3826 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3827 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003828
3829 if (virtualKey.isHit(x, y)) {
3830 return &virtualKey;
3831 }
3832 }
3833
3834 return nullptr;
3835}
3836
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003837void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3838 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3839 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003840
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003841 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003842
3843 if (currentPointerCount == 0) {
3844 // No pointers to assign.
3845 return;
3846 }
3847
3848 if (lastPointerCount == 0) {
3849 // All pointers are new.
3850 for (uint32_t i = 0; i < currentPointerCount; i++) {
3851 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003852 current.rawPointerData.pointers[i].id = id;
3853 current.rawPointerData.idToIndex[id] = i;
3854 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003855 }
3856 return;
3857 }
3858
3859 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003860 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003861 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003862 uint32_t id = last.rawPointerData.pointers[0].id;
3863 current.rawPointerData.pointers[0].id = id;
3864 current.rawPointerData.idToIndex[id] = 0;
3865 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003866 return;
3867 }
3868
3869 // General case.
3870 // We build a heap of squared euclidean distances between current and last pointers
3871 // associated with the current and last pointer indices. Then, we find the best
3872 // match (by distance) for each current pointer.
3873 // The pointers must have the same tool type but it is possible for them to
3874 // transition from hovering to touching or vice-versa while retaining the same id.
3875 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3876
3877 uint32_t heapSize = 0;
3878 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3879 currentPointerIndex++) {
3880 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3881 lastPointerIndex++) {
3882 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003883 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003884 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003885 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003886 if (currentPointer.toolType == lastPointer.toolType) {
3887 int64_t deltaX = currentPointer.x - lastPointer.x;
3888 int64_t deltaY = currentPointer.y - lastPointer.y;
3889
3890 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3891
3892 // Insert new element into the heap (sift up).
3893 heap[heapSize].currentPointerIndex = currentPointerIndex;
3894 heap[heapSize].lastPointerIndex = lastPointerIndex;
3895 heap[heapSize].distance = distance;
3896 heapSize += 1;
3897 }
3898 }
3899 }
3900
3901 // Heapify
3902 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3903 startIndex -= 1;
3904 for (uint32_t parentIndex = startIndex;;) {
3905 uint32_t childIndex = parentIndex * 2 + 1;
3906 if (childIndex >= heapSize) {
3907 break;
3908 }
3909
3910 if (childIndex + 1 < heapSize &&
3911 heap[childIndex + 1].distance < heap[childIndex].distance) {
3912 childIndex += 1;
3913 }
3914
3915 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3916 break;
3917 }
3918
3919 swap(heap[parentIndex], heap[childIndex]);
3920 parentIndex = childIndex;
3921 }
3922 }
3923
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003924 if (DEBUG_POINTER_ASSIGNMENT) {
3925 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3926 for (size_t i = 0; i < heapSize; i++) {
3927 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3928 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3929 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003930 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003931
3932 // Pull matches out by increasing order of distance.
3933 // To avoid reassigning pointers that have already been matched, the loop keeps track
3934 // of which last and current pointers have been matched using the matchedXXXBits variables.
3935 // It also tracks the used pointer id bits.
3936 BitSet32 matchedLastBits(0);
3937 BitSet32 matchedCurrentBits(0);
3938 BitSet32 usedIdBits(0);
3939 bool first = true;
3940 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3941 while (heapSize > 0) {
3942 if (first) {
3943 // The first time through the loop, we just consume the root element of
3944 // the heap (the one with smallest distance).
3945 first = false;
3946 } else {
3947 // Previous iterations consumed the root element of the heap.
3948 // Pop root element off of the heap (sift down).
3949 heap[0] = heap[heapSize];
3950 for (uint32_t parentIndex = 0;;) {
3951 uint32_t childIndex = parentIndex * 2 + 1;
3952 if (childIndex >= heapSize) {
3953 break;
3954 }
3955
3956 if (childIndex + 1 < heapSize &&
3957 heap[childIndex + 1].distance < heap[childIndex].distance) {
3958 childIndex += 1;
3959 }
3960
3961 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3962 break;
3963 }
3964
3965 swap(heap[parentIndex], heap[childIndex]);
3966 parentIndex = childIndex;
3967 }
3968
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003969 if (DEBUG_POINTER_ASSIGNMENT) {
3970 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3971 for (size_t j = 0; j < heapSize; j++) {
3972 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3973 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3974 heap[j].distance);
3975 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003976 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003977 }
3978
3979 heapSize -= 1;
3980
3981 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3982 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3983
3984 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3985 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3986
3987 matchedCurrentBits.markBit(currentPointerIndex);
3988 matchedLastBits.markBit(lastPointerIndex);
3989
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003990 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3991 current.rawPointerData.pointers[currentPointerIndex].id = id;
3992 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3993 current.rawPointerData.markIdBit(id,
3994 current.rawPointerData.isHovering(
3995 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003996 usedIdBits.markBit(id);
3997
Harry Cutts45483602022-08-24 14:36:48 +00003998 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3999 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4000 ", distance=%" PRIu64,
4001 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004002 break;
4003 }
4004 }
4005
4006 // Assign fresh ids to pointers that were not matched in the process.
4007 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4008 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4009 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4010
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004011 current.rawPointerData.pointers[currentPointerIndex].id = id;
4012 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4013 current.rawPointerData.markIdBit(id,
4014 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004015
Harry Cutts45483602022-08-24 14:36:48 +00004016 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4017 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4018 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004019 }
4020}
4021
4022int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4023 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4024 return AKEY_STATE_VIRTUAL;
4025 }
4026
4027 for (const VirtualKey& virtualKey : mVirtualKeys) {
4028 if (virtualKey.keyCode == keyCode) {
4029 return AKEY_STATE_UP;
4030 }
4031 }
4032
4033 return AKEY_STATE_UNKNOWN;
4034}
4035
4036int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4037 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4038 return AKEY_STATE_VIRTUAL;
4039 }
4040
4041 for (const VirtualKey& virtualKey : mVirtualKeys) {
4042 if (virtualKey.scanCode == scanCode) {
4043 return AKEY_STATE_UP;
4044 }
4045 }
4046
4047 return AKEY_STATE_UNKNOWN;
4048}
4049
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004050bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4051 const std::vector<int32_t>& keyCodes,
4052 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004053 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004054 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004055 if (virtualKey.keyCode == keyCodes[i]) {
4056 outFlags[i] = 1;
4057 }
4058 }
4059 }
4060
4061 return true;
4062}
4063
4064std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4065 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004066 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004067 return std::make_optional(mPointerController->getDisplayId());
4068 } else {
4069 return std::make_optional(mViewport.displayId);
4070 }
4071 }
4072 return std::nullopt;
4073}
4074
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004075} // namespace android