blob: 7d27d4a9ced8829c245762719006ddf1fd7bc808 [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
Prabir Pradhan8d9ba912022-11-11 22:26:33 +000024#include <input/PrintTools.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080025
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070026#include "CursorButtonAccumulator.h"
27#include "CursorScrollAccumulator.h"
28#include "TouchButtonAccumulator.h"
29#include "TouchCursorInputMapperCommon.h"
Michael Wrighta9cf4192022-12-01 23:46:39 +000030#include "ui/Rotation.h"
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070031
32namespace android {
33
34// --- Constants ---
35
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070036// Artificial latency on synthetic events created from stylus data without corresponding touch
37// data.
38static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
39
HQ Liue6983c72022-04-19 22:14:56 +000040// Minimum width between two pointers to determine a gesture as freeform gesture in mm
41static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070042// --- Static Definitions ---
43
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000044static const DisplayViewport kUninitializedViewport;
45
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000046static std::string toString(const Rect& rect) {
47 return base::StringPrintf("Rect{%d, %d, %d, %d}", rect.left, rect.top, rect.right, rect.bottom);
48}
49
50static std::string toString(const ui::Size& size) {
51 return base::StringPrintf("%dx%d", size.width, size.height);
52}
53
Prabir Pradhan675f25a2022-11-10 22:04:07 +000054static bool isPointInRect(const Rect& rect, vec2 p) {
55 return p.x >= rect.left && p.x < rect.right && p.y >= rect.top && p.y < rect.bottom;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000056}
57
Prabir Pradhane04ffaa2022-12-13 23:04:04 +000058static std::string toString(const InputDeviceUsiVersion& v) {
59 return base::StringPrintf("%d.%d", v.majorVersion, v.minorVersion);
60}
61
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070062template <typename T>
63inline static void swap(T& a, T& b) {
64 T temp = a;
65 a = b;
66 b = temp;
67}
68
69static float calculateCommonVector(float a, float b) {
70 if (a > 0 && b > 0) {
71 return a < b ? a : b;
72 } else if (a < 0 && b < 0) {
73 return a > b ? a : b;
74 } else {
75 return 0;
76 }
77}
78
79inline static float distance(float x1, float y1, float x2, float y2) {
80 return hypotf(x1 - x2, y1 - y2);
81}
82
83inline static int32_t signExtendNybble(int32_t value) {
84 return value >= 8 ? value - 16 : value;
85}
86
Prabir Pradhan675f25a2022-11-10 22:04:07 +000087static ui::Size getNaturalDisplaySize(const DisplayViewport& viewport) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000088 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +000089 if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000090 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
91 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +000092 return rotatedDisplaySize;
Prabir Pradhan2d613f42022-11-10 20:22:06 +000093}
94
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +000095static int32_t filterButtonState(InputReaderConfiguration& config, int32_t buttonState) {
96 if (!config.stylusButtonMotionEventsEnabled) {
97 buttonState &=
98 ~(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY | AMOTION_EVENT_BUTTON_STYLUS_SECONDARY);
99 }
100 return buttonState;
101}
102
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700103// --- RawPointerData ---
104
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700105void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
106 float x = 0, y = 0;
107 uint32_t count = touchingIdBits.count();
108 if (count) {
109 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
110 uint32_t id = idBits.clearFirstMarkedBit();
111 const Pointer& pointer = pointerForId(id);
112 x += pointer.x;
113 y += pointer.y;
114 }
115 x /= count;
116 y /= count;
117 }
118 *outX = x;
119 *outY = y;
120}
121
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700122// --- TouchInputMapper ---
123
Arpit Singh8e6fb252023-04-06 11:49:17 +0000124TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext,
125 const InputReaderConfiguration& readerConfig)
126 : InputMapper(deviceContext, readerConfig),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000127 mTouchButtonAccumulator(deviceContext),
Arpit Singha8c236b2023-04-25 13:56:05 +0000128 mConfig(readerConfig) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700129
130TouchInputMapper::~TouchInputMapper() {}
131
Philip Junker4af3b3d2021-12-14 10:36:55 +0100132uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanb08a0e82023-09-14 22:28:32 +0000133 // The SOURCE_BLUETOOTH_STYLUS is added to events dynamically if the current stream is modified
134 // by the external stylus state. That's why we don't add it directly to mSource during
135 // configuration.
136 return mSource | (hasExternalStylus() ? AINPUT_SOURCE_BLUETOOTH_STYLUS : 0);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700137}
138
Harry Cuttsd02ea102023-03-17 18:21:30 +0000139void TouchInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700140 InputMapper::populateDeviceInfo(info);
141
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000142 if (mDeviceMode == DeviceMode::DISABLED) {
143 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700144 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000145
Harry Cuttsd02ea102023-03-17 18:21:30 +0000146 info.addMotionRange(mOrientedRanges.x);
147 info.addMotionRange(mOrientedRanges.y);
148 info.addMotionRange(mOrientedRanges.pressure);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000149
150 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
151 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
152 //
153 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
154 // motion, i.e. the hardware dimensions, as the finger could move completely across the
155 // touchpad in one sample cycle.
156 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
157 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
Harry Cuttsd02ea102023-03-17 18:21:30 +0000158 info.addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
159 x.resolution);
160 info.addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
161 y.resolution);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000162 }
163
164 if (mOrientedRanges.size) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000165 info.addMotionRange(*mOrientedRanges.size);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000166 }
167
168 if (mOrientedRanges.touchMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000169 info.addMotionRange(*mOrientedRanges.touchMajor);
170 info.addMotionRange(*mOrientedRanges.touchMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000171 }
172
173 if (mOrientedRanges.toolMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000174 info.addMotionRange(*mOrientedRanges.toolMajor);
175 info.addMotionRange(*mOrientedRanges.toolMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000176 }
177
178 if (mOrientedRanges.orientation) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000179 info.addMotionRange(*mOrientedRanges.orientation);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000180 }
181
182 if (mOrientedRanges.distance) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000183 info.addMotionRange(*mOrientedRanges.distance);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000184 }
185
186 if (mOrientedRanges.tilt) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000187 info.addMotionRange(*mOrientedRanges.tilt);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000188 }
189
190 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000191 info.addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000192 }
193 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000194 info.addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000195 }
Harry Cuttsd02ea102023-03-17 18:21:30 +0000196 info.setButtonUnderPad(mParameters.hasButtonUnderPad);
197 info.setUsiVersion(mParameters.usiVersion);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700198}
199
200void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700201 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800202 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700203 dumpParameters(dump);
204 dumpVirtualKeys(dump);
205 dumpRawPointerAxes(dump);
206 dumpCalibration(dump);
207 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700208 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700209
210 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000211 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000212 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
213 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
214 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700215 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
216 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
217 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
218 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
219 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
220 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
221 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
222 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
223 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
224 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
225
226 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
227 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
228 mLastRawState.rawPointerData.pointerCount);
229 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
230 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
231 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
232 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
233 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700234 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700235 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
236 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
237 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700238 pointer.distance, ftl::enum_string(pointer.toolType).c_str(),
239 toString(pointer.isHovering));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700240 }
241
242 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
243 mLastCookedState.buttonState);
244 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
245 mLastCookedState.cookedPointerData.pointerCount);
246 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
247 const PointerProperties& pointerProperties =
248 mLastCookedState.cookedPointerData.pointerProperties[i];
249 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000250 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
251 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
252 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700253 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700254 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700255 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000256 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
257 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700258 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
259 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
260 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
261 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
262 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
263 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
264 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
265 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700266 ftl::enum_string(pointerProperties.toolType).c_str(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700267 toString(mLastCookedState.cookedPointerData.isHovering(i)));
268 }
269
270 dump += INDENT3 "Stylus Fusion:\n";
271 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
272 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000273 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
274 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700275 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
276 mExternalStylusFusionTimeout);
Harry Cutts1ee05b62023-06-19 13:49:06 +0000277 dump += StringPrintf(INDENT4 "External Stylus Buttons Applied: 0x%08x\n",
Prabir Pradhan124ea442022-10-28 20:27:44 +0000278 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700279 dump += INDENT3 "External Stylus State:\n";
280 dumpStylusState(dump, mExternalStylusState);
281
Michael Wright227c5542020-07-02 18:30:52 +0100282 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700283 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
284 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
285 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
286 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
287 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
288 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
289 }
290}
291
Arpit Singh4be4eef2023-03-28 14:26:01 +0000292std::list<NotifyArgs> TouchInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000293 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000294 ConfigurationChanges changes) {
Arpit Singh4be4eef2023-03-28 14:26:01 +0000295 std::list<NotifyArgs> out = InputMapper::reconfigure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700296
Arpit Singhed6c3de2023-04-05 19:24:37 +0000297 mConfig = config;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700298
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000299 // Full configuration should happen the first time configure is called and
300 // when the device type is changed. Changing a device type can affect
301 // various other parameters so should result in a reconfiguration.
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000302 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700303 // Configure basic parameters.
Arpit Singh403e53c2023-04-18 11:46:56 +0000304 mParameters = computeParameters(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700305
306 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800307 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000308 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700309
310 // Configure absolute axis information.
311 configureRawPointerAxes();
312
313 // Prepare input device calibration.
314 parseCalibration();
315 resolveCalibration();
316 }
317
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000318 if (!changes.any() ||
319 changes.test(InputReaderConfiguration::Change::TOUCH_AFFINE_TRANSFORMATION)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700320 // Update location calibration to reflect current settings
321 updateAffineTransformation();
322 }
323
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000324 if (!changes.any() || changes.test(InputReaderConfiguration::Change::POINTER_SPEED)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700325 // Update pointer speed.
326 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
327 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
328 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
329 }
330
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000331 using namespace ftl::flag_operators;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700332 bool resetNeeded = false;
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000333 if (!changes.any() ||
334 changes.any(InputReaderConfiguration::Change::DISPLAY_INFO |
335 InputReaderConfiguration::Change::POINTER_CAPTURE |
336 InputReaderConfiguration::Change::POINTER_GESTURE_ENABLEMENT |
337 InputReaderConfiguration::Change::SHOW_TOUCHES |
338 InputReaderConfiguration::Change::EXTERNAL_STYLUS_PRESENCE |
339 InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700340 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700342 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700343 }
344
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000345 if (changes.any() && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700346 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000347
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700348 // Send reset, unless this is the first time the device has been configured,
349 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000350 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700352 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700353}
354
355void TouchInputMapper::resolveExternalStylusPresence() {
356 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800357 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700358 mExternalStylusConnected = !devices.empty();
359
360 if (!mExternalStylusConnected) {
361 resetExternalStylus();
362 }
363}
364
Arpit Singh403e53c2023-04-18 11:46:56 +0000365TouchInputMapper::Parameters TouchInputMapper::computeParameters(
366 const InputDeviceContext& deviceContext) {
367 Parameters parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700368 // Use the pointer presentation mode for devices that do not support distinct
369 // multitouch. The spot-based presentation relies on being able to accurately
370 // locate two or more fingers on the touch pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000371 parameters.gestureMode = deviceContext.hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100372 ? Parameters::GestureMode::SINGLE_TOUCH
373 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374
Arpit Singh403e53c2023-04-18 11:46:56 +0000375 const PropertyMap& config = deviceContext.getConfiguration();
Harry Cuttsf13161a2023-03-08 14:15:49 +0000376 std::optional<std::string> gestureModeString = config.getString("touch.gestureMode");
377 if (gestureModeString.has_value()) {
378 if (*gestureModeString == "single-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000379 parameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000380 } else if (*gestureModeString == "multi-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000381 parameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000382 } else if (*gestureModeString != "default") {
383 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384 }
385 }
386
Arpit Singh403e53c2023-04-18 11:46:56 +0000387 parameters.deviceType = computeDeviceType(deviceContext);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700388
Arpit Singh403e53c2023-04-18 11:46:56 +0000389 parameters.hasButtonUnderPad = deviceContext.hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700390
Arpit Singh403e53c2023-04-18 11:46:56 +0000391 parameters.orientationAware =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000392 config.getBool("touch.orientationAware")
Arpit Singh403e53c2023-04-18 11:46:56 +0000393 .value_or(parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700394
Arpit Singh403e53c2023-04-18 11:46:56 +0000395 parameters.orientation = ui::ROTATION_0;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000396 std::optional<std::string> orientationString = config.getString("touch.orientation");
397 if (orientationString.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000398 if (parameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700399 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
Harry Cuttsf13161a2023-03-08 14:15:49 +0000400 } else if (*orientationString == "ORIENTATION_90") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000401 parameters.orientation = ui::ROTATION_90;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000402 } else if (*orientationString == "ORIENTATION_180") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000403 parameters.orientation = ui::ROTATION_180;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000404 } else if (*orientationString == "ORIENTATION_270") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000405 parameters.orientation = ui::ROTATION_270;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000406 } else if (*orientationString != "ORIENTATION_0") {
407 ALOGW("Invalid value for touch.orientation: '%s'", orientationString->c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700408 }
409 }
410
Arpit Singh403e53c2023-04-18 11:46:56 +0000411 parameters.hasAssociatedDisplay = false;
412 parameters.associatedDisplayIsExternal = false;
413 if (parameters.orientationAware ||
414 parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
415 parameters.deviceType == Parameters::DeviceType::POINTER ||
416 (parameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
417 deviceContext.getAssociatedViewport())) {
418 parameters.hasAssociatedDisplay = true;
419 if (parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
420 parameters.associatedDisplayIsExternal = deviceContext.isExternal();
421 parameters.uniqueDisplayId = config.getString("touch.displayId").value_or("").c_str();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700422 }
423 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000424 if (deviceContext.getAssociatedDisplayPort()) {
425 parameters.hasAssociatedDisplay = true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426 }
427
428 // Initial downs on external touch devices should wake the device.
429 // Normally we don't do this for internal touch screens to prevent them from waking
430 // up in your pocket but you can enable it using the input device configuration.
Arpit Singh403e53c2023-04-18 11:46:56 +0000431 parameters.wake = config.getBool("touch.wake").value_or(deviceContext.isExternal());
Prabir Pradhan167c2702022-09-14 00:37:24 +0000432
Harry Cuttsf13161a2023-03-08 14:15:49 +0000433 std::optional<int32_t> usiVersionMajor = config.getInt("touch.usiVersionMajor");
434 std::optional<int32_t> usiVersionMinor = config.getInt("touch.usiVersionMinor");
435 if (usiVersionMajor.has_value() && usiVersionMinor.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000436 parameters.usiVersion = {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000437 .majorVersion = *usiVersionMajor,
438 .minorVersion = *usiVersionMinor,
439 };
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000440 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700441
Arpit Singh403e53c2023-04-18 11:46:56 +0000442 parameters.enableForInactiveViewport =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000443 config.getBool("touch.enableForInactiveViewport").value_or(false);
Arpit Singh403e53c2023-04-18 11:46:56 +0000444
445 return parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700446}
447
Arpit Singh403e53c2023-04-18 11:46:56 +0000448TouchInputMapper::Parameters::DeviceType TouchInputMapper::computeDeviceType(
449 const InputDeviceContext& deviceContext) {
450 Parameters::DeviceType deviceType;
451 if (deviceContext.hasInputProperty(INPUT_PROP_DIRECT)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000452 // The device is a touch screen.
Arpit Singh403e53c2023-04-18 11:46:56 +0000453 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
454 } else if (deviceContext.hasInputProperty(INPUT_PROP_POINTER)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000455 // The device is a pointing device like a track pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000456 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000457 } else {
458 // The device is a touch pad of unknown purpose.
Arpit Singh403e53c2023-04-18 11:46:56 +0000459 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000460 }
461
462 // Type association takes precedence over the device type found in the idc file.
Arpit Singh403e53c2023-04-18 11:46:56 +0000463 std::string deviceTypeString = deviceContext.getDeviceTypeAssociation().value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000464 if (deviceTypeString.empty()) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000465 deviceTypeString =
Arpit Singh403e53c2023-04-18 11:46:56 +0000466 deviceContext.getConfiguration().getString("touch.deviceType").value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000467 }
468 if (deviceTypeString == "touchScreen") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000469 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000470 } else if (deviceTypeString == "touchNavigation") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000471 deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000472 } else if (deviceTypeString == "pointer") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000473 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000474 } else if (deviceTypeString != "default" && deviceTypeString != "") {
475 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
476 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000477 return deviceType;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000478}
479
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700480void TouchInputMapper::dumpParameters(std::string& dump) {
481 dump += INDENT3 "Parameters:\n";
482
Dominik Laskowski75788452021-02-09 18:51:25 -0800483 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484
Dominik Laskowski75788452021-02-09 18:51:25 -0800485 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700486
487 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
488 "displayId='%s'\n",
489 toString(mParameters.hasAssociatedDisplay),
490 toString(mParameters.associatedDisplayIsExternal),
491 mParameters.uniqueDisplayId.c_str());
492 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800493 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000494 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
495 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700496 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
497 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700498}
499
500void TouchInputMapper::configureRawPointerAxes() {
501 mRawPointerAxes.clear();
502}
503
504void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
505 dump += INDENT3 "Raw Touch Axes:\n";
506 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
507 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
508 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
509 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
510 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
511 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
512 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
513 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
514 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
515 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
516 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
517 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
518 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
519}
520
521bool TouchInputMapper::hasExternalStylus() const {
522 return mExternalStylusConnected;
523}
524
525/**
526 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000527 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800528 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000529 * 3. Get the matching viewport by either unique id in idc file or by the display type
530 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800531 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700532 */
533std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800534 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000535 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800536 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700537 }
538
Christine Franks2a2293c2022-01-18 11:51:16 -0800539 const std::optional<std::string> associatedDisplayUniqueId =
540 getDeviceContext().getAssociatedDisplayUniqueId();
541 if (associatedDisplayUniqueId) {
542 return getDeviceContext().getAssociatedViewport();
543 }
544
Michael Wright227c5542020-07-02 18:30:52 +0100545 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800546 std::optional<DisplayViewport> viewport =
547 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
548 if (viewport) {
549 return viewport;
550 } else {
551 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
552 mConfig.defaultPointerDisplayId);
553 }
554 }
555
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700556 // Check if uniqueDisplayId is specified in idc file.
557 if (!mParameters.uniqueDisplayId.empty()) {
558 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
559 }
560
561 ViewportType viewportTypeToUse;
562 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100563 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700564 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100565 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 }
567
568 std::optional<DisplayViewport> viewport =
569 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100570 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700571 ALOGW("Input device %s should be associated with external display, "
572 "fallback to internal one for the external viewport is not found.",
573 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100574 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700575 }
576
577 return viewport;
578 }
579
580 // No associated display, return a non-display viewport.
581 DisplayViewport newViewport;
582 // Raw width and height in the natural orientation.
583 int32_t rawWidth = mRawPointerAxes.getRawWidth();
584 int32_t rawHeight = mRawPointerAxes.getRawHeight();
585 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
586 return std::make_optional(newViewport);
587}
588
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800589int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
590 if (resolution < 0) {
591 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
592 getDeviceName().c_str());
593 return 0;
594 }
595 return resolution;
596}
597
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800598void TouchInputMapper::initializeSizeRanges() {
599 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
600 mSizeScale = 0.0f;
601 return;
602 }
603
604 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000605 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800606
607 // Size factors.
608 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
609 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
610 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
611 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
612 } else {
613 mSizeScale = 0.0f;
614 }
615
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700616 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
617 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
618 .source = mSource,
619 .min = 0,
620 .max = diagonalSize,
621 .flat = 0,
622 .fuzz = 0,
623 .resolution = 0,
624 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800625
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800626 if (mRawPointerAxes.touchMajor.valid) {
627 mRawPointerAxes.touchMajor.resolution =
628 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700629 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800630 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800631
632 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700633 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800634 if (mRawPointerAxes.touchMinor.valid) {
635 mRawPointerAxes.touchMinor.resolution =
636 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700637 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800638 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800639
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700640 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
641 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
642 .source = mSource,
643 .min = 0,
644 .max = diagonalSize,
645 .flat = 0,
646 .fuzz = 0,
647 .resolution = 0,
648 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800649 if (mRawPointerAxes.toolMajor.valid) {
650 mRawPointerAxes.toolMajor.resolution =
651 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700652 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800653 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800654
655 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700656 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800657 if (mRawPointerAxes.toolMinor.valid) {
658 mRawPointerAxes.toolMinor.resolution =
659 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700660 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800661 }
662
663 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700664 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
665 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
666 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
667 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800668 } else {
669 // Support for other calibrations can be added here.
670 ALOGW("%s calibration is not supported for size ranges at the moment. "
671 "Using raw resolution instead",
672 ftl::enum_string(mCalibration.sizeCalibration).c_str());
673 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800674
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700675 mOrientedRanges.size = InputDeviceInfo::MotionRange{
676 .axis = AMOTION_EVENT_AXIS_SIZE,
677 .source = mSource,
678 .min = 0,
679 .max = 1.0,
680 .flat = 0,
681 .fuzz = 0,
682 .resolution = 0,
683 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800684}
685
686void TouchInputMapper::initializeOrientedRanges() {
687 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000688 const float orientedScaleX = mRawToDisplay.getScaleX();
689 const float orientedScaleY = mRawToDisplay.getScaleY();
690 mOrientedXPrecision = 1.0f / orientedScaleX;
691 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800692
693 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
694 mOrientedRanges.x.source = mSource;
695 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
696 mOrientedRanges.y.source = mSource;
697
698 // Scale factor for terms that are not oriented in a particular axis.
699 // If the pixels are square then xScale == yScale otherwise we fake it
700 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000701 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800702
703 initializeSizeRanges();
704
705 // Pressure factors.
706 mPressureScale = 0;
707 float pressureMax = 1.0;
708 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
709 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700710 if (mCalibration.pressureScale) {
711 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800712 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
713 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
714 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
715 }
716 }
717
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700718 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
719 .axis = AMOTION_EVENT_AXIS_PRESSURE,
720 .source = mSource,
721 .min = 0,
722 .max = pressureMax,
723 .flat = 0,
724 .fuzz = 0,
725 .resolution = 0,
726 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800727
728 // Tilt
729 mTiltXCenter = 0;
730 mTiltXScale = 0;
731 mTiltYCenter = 0;
732 mTiltYScale = 0;
733 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
734 if (mHaveTilt) {
735 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
736 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
737 mTiltXScale = M_PI / 180;
738 mTiltYScale = M_PI / 180;
739
740 if (mRawPointerAxes.tiltX.resolution) {
741 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
742 }
743 if (mRawPointerAxes.tiltY.resolution) {
744 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
745 }
746
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700747 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
748 .axis = AMOTION_EVENT_AXIS_TILT,
749 .source = mSource,
750 .min = 0,
751 .max = M_PI_2,
752 .flat = 0,
753 .fuzz = 0,
754 .resolution = 0,
755 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800756 }
757
758 // Orientation
759 mOrientationScale = 0;
760 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700761 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
762 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
763 .source = mSource,
764 .min = -M_PI,
765 .max = M_PI,
766 .flat = 0,
767 .fuzz = 0,
768 .resolution = 0,
769 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800770
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800771 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
772 if (mCalibration.orientationCalibration ==
773 Calibration::OrientationCalibration::INTERPOLATED) {
774 if (mRawPointerAxes.orientation.valid) {
775 if (mRawPointerAxes.orientation.maxValue > 0) {
776 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
777 } else if (mRawPointerAxes.orientation.minValue < 0) {
778 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
779 } else {
780 mOrientationScale = 0;
781 }
782 }
783 }
784
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700785 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
786 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
787 .source = mSource,
788 .min = -M_PI_2,
789 .max = M_PI_2,
790 .flat = 0,
791 .fuzz = 0,
792 .resolution = 0,
793 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800794 }
795
796 // Distance
797 mDistanceScale = 0;
798 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
799 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700800 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800801 }
802
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700803 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800804
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700805 .axis = AMOTION_EVENT_AXIS_DISTANCE,
806 .source = mSource,
807 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
808 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
809 .flat = 0,
810 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
811 .resolution = 0,
812 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800813 }
814
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000815 // Oriented X/Y range (in the rotated display's orientation)
816 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
817 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
818 .toFloatRect();
819 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
820 mOrientedRanges.x.min = orientedRangeRect.left;
821 mOrientedRanges.y.min = orientedRangeRect.top;
822 mOrientedRanges.x.max = orientedRangeRect.right;
823 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800824
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000825 // Oriented flat (in the rotated display's orientation)
826 const auto orientedFlat =
827 transformWithoutTranslation(mRawToRotatedDisplay,
828 {static_cast<float>(mRawPointerAxes.x.flat),
829 static_cast<float>(mRawPointerAxes.y.flat)});
830 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
831 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800832
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000833 // Oriented fuzz (in the rotated display's orientation)
834 const auto orientedFuzz =
835 transformWithoutTranslation(mRawToRotatedDisplay,
836 {static_cast<float>(mRawPointerAxes.x.fuzz),
837 static_cast<float>(mRawPointerAxes.y.fuzz)});
838 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
839 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800840
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000841 // Oriented resolution (in the rotated display's orientation)
842 const auto orientedRes =
843 transformWithoutTranslation(mRawToRotatedDisplay,
844 {static_cast<float>(mRawPointerAxes.x.resolution),
845 static_cast<float>(mRawPointerAxes.y.resolution)});
846 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
847 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800848}
849
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000850void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000851 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
852 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
853 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000854
Prabir Pradhan3e798762022-12-02 21:02:11 +0000855 // See notes about input coordinates in the inputflinger docs:
856 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000857
858 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000859 ui::Transform undoOffsetInRaw;
860 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000861
Prabir Pradhan3e798762022-12-02 21:02:11 +0000862 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
863 // will now be in the same orientation as the display in ROTATION_0.
864 // Note: Negating an ui::Rotation value will give its inverse rotation.
865 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
866 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
867 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
868 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
869 // When rotating raw values, account for the extra unit added when calculating the raw range.
870 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
871 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000872
Prabir Pradhan3e798762022-12-02 21:02:11 +0000873 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
874 // now be in the same orientation as the rotated display. There is no need to rotate the
875 // coordinates to the display rotation if the device is not orientation-aware.
876 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
877 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
878 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
879 : orientedRawSize;
880 // When rotating raw values, account for the extra unit added when calculating the raw range.
881 const auto rotateInRaw = mParameters.orientationAware
882 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
883 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000884
Prabir Pradhan3e798762022-12-02 21:02:11 +0000885 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000886 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
887 // the surface of the display panel. This is usually true for touchscreens.
888 // - In POINTER mode, we cannot assume that the display and the touch device have the same
889 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
890 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
891 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
892 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000893 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
894 // are in the continuous space of the logical display.
895 ui::Transform scaleRawToDisplay;
896 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
897 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000898 if (mDeviceMode == DeviceMode::DIRECT) {
899 scaleRawToDisplay.set(xScale, 0, 0, yScale);
900 } else if (mDeviceMode == DeviceMode::POINTER) {
901 const float fixedScale = std::max(xScale, yScale);
902 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
903 } else {
904 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
905 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000906
Prabir Pradhan3e798762022-12-02 21:02:11 +0000907 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
908 // that InputReader uses.
909 const auto undoRotateInDisplay =
910 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
911 .inverse();
912
913 // Now put it all together!
914 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
915 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
916 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000917}
918
Prabir Pradhan1728b212021-10-19 16:00:03 -0700919void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000920 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700921
922 resolveExternalStylusPresence();
923
924 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100925 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +0900926 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700927 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100928 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700929 if (hasStylus()) {
930 mSource |= AINPUT_SOURCE_STYLUS;
931 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800932 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700933 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100934 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700935 if (hasStylus()) {
936 mSource |= AINPUT_SOURCE_STYLUS;
937 }
Michael Wright227c5542020-07-02 18:30:52 +0100938 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700939 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100940 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700941 } else {
942 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100943 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700944 }
945
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000946 const std::optional<DisplayViewport> newViewportOpt = findViewport();
947
948 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700949 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
950 ALOGW("Touch device '%s' did not report support for X or Y axis! "
951 "The device will be inoperable.",
952 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100953 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000954 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700955 ALOGI("Touch device '%s' could not query the properties of its associated "
956 "display. The device will be inoperable until the display size "
957 "becomes available.",
958 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100959 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700960 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000961 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
962 getDeviceName().c_str(), getDeviceId());
963 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000964 }
965
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000967 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000968 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
969 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
970 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
971 const float rawMeanResolution =
972 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700973
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000974 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
Josh Thielene986aed2023-06-01 14:17:30 +0000975 bool viewportChanged;
976 if (mParameters.enableForInactiveViewport) {
977 // When touch is enabled for an inactive viewport, ignore the
978 // viewport active status when checking whether the viewport has
979 // changed.
980 DisplayViewport tempViewport = mViewport;
981 tempViewport.isActive = newViewport.isActive;
982 viewportChanged = tempViewport != newViewport;
983 } else {
984 viewportChanged = mViewport != newViewport;
985 }
986
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700987 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700988 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000989 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
990 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
991 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700992
Michael Wright227c5542020-07-02 18:30:52 +0100993 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000994 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700995
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000996 mDisplayBounds = getNaturalDisplaySize(mViewport);
997 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
998 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700999
Prabir Pradhan3e798762022-12-02 21:02:11 +00001000 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
1001 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
1002 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001003 // InputReader works in the un-rotated display coordinate space, so we don't need to do
1004 // anything if the device is already orientation-aware. If the device is not
1005 // orientation-aware, then we need to apply the inverse rotation of the display so that
1006 // when the display rotation is applied later as a part of the per-window transform, we
1007 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001008 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +00001009 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001010 : getInverseRotation(mViewport.orientation);
1011 // For orientation-aware devices that work in the un-rotated coordinate space, the
1012 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001013 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001014 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001015
1016 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001017 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001018 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001019 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001020 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001021 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001022 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001023 mRawToDisplay.reset();
1024 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001025 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001026 }
1027 }
1028
1029 // If moving between pointer modes, need to reset some state.
1030 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1031 if (deviceModeChanged) {
1032 mOrientedRanges.clear();
1033 }
1034
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001035 // Create and preserve the pointer controller in the following cases:
1036 const bool isPointerControllerNeeded =
1037 // - when the device is in pointer mode, to show the mouse cursor;
1038 (mDeviceMode == DeviceMode::POINTER) ||
1039 // - when pointer capture is enabled, to preserve the mouse cursor position;
1040 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +09001041 mConfig.pointerCaptureRequest.isEnable()) ||
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001042 // - when we should be showing touches;
1043 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1044 // - when we should be showing a pointer icon for direct styluses.
1045 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1046 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001047 if (mPointerController == nullptr) {
1048 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001049 }
Hiroki Sato25040232024-02-22 17:21:22 +09001050 if (mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001051 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1052 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001053 } else {
lilinnandef700b2022-06-17 19:32:01 +08001054 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1055 !mConfig.showTouches) {
1056 mPointerController->clearSpots();
1057 }
Michael Wright17db18e2020-06-26 20:51:44 +01001058 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001059 }
1060
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001061 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001062 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001063 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001064 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001065 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001066
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001067 configureVirtualKeys();
1068
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001069 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001070
1071 // Location
1072 updateAffineTransformation();
1073
Michael Wright227c5542020-07-02 18:30:52 +01001074 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001075 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001076 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1077 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001078
1079 // Scale movements such that one whole swipe of the touch pad covers a
1080 // given area relative to the diagonal size of the display when no acceleration
1081 // is applied.
1082 // Assume that the touch pad has a square aspect ratio such that movements in
1083 // X and Y of the same number of raw units cover the same physical distance.
1084 mPointerXMovementScale =
1085 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1086 mPointerYMovementScale = mPointerXMovementScale;
1087
1088 // Scale zooms to cover a smaller range of the display than movements do.
1089 // This value determines the area around the pointer that is affected by freeform
1090 // pointer gestures.
1091 mPointerXZoomScale =
1092 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1093 mPointerYZoomScale = mPointerXZoomScale;
1094
HQ Liue6983c72022-04-19 22:14:56 +00001095 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1096 // axis is non positive value.
1097 const float minFreeformGestureWidth =
1098 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1099
1100 mPointerGestureMaxSwipeWidth =
1101 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1102 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001103 }
1104
1105 // Inform the dispatcher about the changes.
1106 *outResetNeeded = true;
1107 bumpGeneration();
1108 }
1109}
1110
Prabir Pradhan1728b212021-10-19 16:00:03 -07001111void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001112 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001113 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001114 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1115 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001116 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001117}
1118
1119void TouchInputMapper::configureVirtualKeys() {
1120 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001121 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001122
1123 mVirtualKeys.clear();
1124
1125 if (virtualKeyDefinitions.size() == 0) {
1126 return;
1127 }
1128
1129 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1130 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1131 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1132 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1133
1134 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1135 VirtualKey virtualKey;
1136
1137 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1138 int32_t keyCode;
1139 int32_t dummyKeyMetaState;
1140 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001141 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1142 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1144 continue; // drop the key
1145 }
1146
1147 virtualKey.keyCode = keyCode;
1148 virtualKey.flags = flags;
1149
1150 // convert the key definition's display coordinates into touch coordinates for a hit box
1151 int32_t halfWidth = virtualKeyDefinition.width / 2;
1152 int32_t halfHeight = virtualKeyDefinition.height / 2;
1153
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001154 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1155 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001156 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001157 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1158 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001159 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001160 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1161 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001162 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001163 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1164 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165 touchScreenTop;
1166 mVirtualKeys.push_back(virtualKey);
1167 }
1168}
1169
1170void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1171 if (!mVirtualKeys.empty()) {
1172 dump += INDENT3 "Virtual Keys:\n";
1173
1174 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1175 const VirtualKey& virtualKey = mVirtualKeys[i];
1176 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1177 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1178 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1179 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1180 }
1181 }
1182}
1183
1184void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001185 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 Calibration& out = mCalibration;
1187
1188 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001190 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1191 if (sizeCalibrationString.has_value()) {
1192 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001193 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001194 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001195 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001196 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001197 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001198 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001200 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001202 } else if (*sizeCalibrationString != "default") {
1203 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 }
1205 }
1206
Harry Cuttsf13161a2023-03-08 14:15:49 +00001207 out.sizeScale = in.getFloat("touch.size.scale");
1208 out.sizeBias = in.getFloat("touch.size.bias");
1209 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210
1211 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001212 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001213 std::optional<std::string> pressureCalibrationString =
1214 in.getString("touch.pressure.calibration");
1215 if (pressureCalibrationString.has_value()) {
1216 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001217 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001218 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001219 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001220 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001221 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001222 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001224 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 }
1226 }
1227
Harry Cuttsf13161a2023-03-08 14:15:49 +00001228 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229
1230 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001231 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001232 std::optional<std::string> orientationCalibrationString =
1233 in.getString("touch.orientation.calibration");
1234 if (orientationCalibrationString.has_value()) {
1235 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001236 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001237 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001238 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001239 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001240 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001241 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001243 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 }
1245 }
1246
1247 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001248 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001249 std::optional<std::string> distanceCalibrationString =
1250 in.getString("touch.distance.calibration");
1251 if (distanceCalibrationString.has_value()) {
1252 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001253 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001254 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001255 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001256 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001258 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260 }
1261
Harry Cuttsf13161a2023-03-08 14:15:49 +00001262 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263}
1264
1265void TouchInputMapper::resolveCalibration() {
1266 // Size
1267 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001268 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1269 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270 }
1271 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001272 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 }
1274
1275 // Pressure
1276 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001277 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1278 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 }
1280 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001281 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 }
1283
1284 // Orientation
1285 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001286 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1287 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288 }
1289 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001290 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291 }
1292
1293 // Distance
1294 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001295 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1296 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 }
1298 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001299 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301}
1302
1303void TouchInputMapper::dumpCalibration(std::string& dump) {
1304 dump += INDENT3 "Calibration:\n";
1305
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001306 dump += INDENT4 "touch.size.calibration: ";
1307 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001309 if (mCalibration.sizeScale) {
1310 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 }
1312
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001313 if (mCalibration.sizeBias) {
1314 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 }
1316
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001317 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001319 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 }
1321
1322 // Pressure
1323 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001324 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 dump += INDENT4 "touch.pressure.calibration: none\n";
1326 break;
Michael Wright227c5542020-07-02 18:30:52 +01001327 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 dump += INDENT4 "touch.pressure.calibration: physical\n";
1329 break;
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1332 break;
1333 default:
1334 ALOG_ASSERT(false);
1335 }
1336
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001337 if (mCalibration.pressureScale) {
1338 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001339 }
1340
1341 // Orientation
1342 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001343 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.orientation.calibration: none\n";
1345 break;
Michael Wright227c5542020-07-02 18:30:52 +01001346 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001347 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1348 break;
Michael Wright227c5542020-07-02 18:30:52 +01001349 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350 dump += INDENT4 "touch.orientation.calibration: vector\n";
1351 break;
1352 default:
1353 ALOG_ASSERT(false);
1354 }
1355
1356 // Distance
1357 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001358 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001359 dump += INDENT4 "touch.distance.calibration: none\n";
1360 break;
Michael Wright227c5542020-07-02 18:30:52 +01001361 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001362 dump += INDENT4 "touch.distance.calibration: scaled\n";
1363 break;
1364 default:
1365 ALOG_ASSERT(false);
1366 }
1367
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001368 if (mCalibration.distanceScale) {
1369 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001370 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001371}
1372
1373void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1374 dump += INDENT3 "Affine Transformation:\n";
1375
1376 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1377 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1378 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1379 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1380 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1381 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1382}
1383
1384void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001385 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001386 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001387}
1388
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001389std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001390 std::list<NotifyArgs> out = cancelTouch(when, when);
1391 updateTouchSpots();
1392
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001393 mCursorButtonAccumulator.reset(getDeviceContext());
1394 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001395 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001396
1397 mPointerVelocityControl.reset();
1398 mWheelXVelocityControl.reset();
1399 mWheelYVelocityControl.reset();
1400
1401 mRawStatesPending.clear();
1402 mCurrentRawState.clear();
1403 mCurrentCookedState.clear();
1404 mLastRawState.clear();
1405 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001406 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407 mSentHoverEnter = false;
1408 mHavePointerIds = false;
1409 mCurrentMotionAborted = false;
1410 mDownTime = 0;
1411
1412 mCurrentVirtualKey.down = false;
1413
1414 mPointerGesture.reset();
1415 mPointerSimple.reset();
1416 resetExternalStylus();
1417
1418 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001419 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001420 mPointerController->clearSpots();
1421 }
1422
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001423 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001424}
1425
1426void TouchInputMapper::resetExternalStylus() {
1427 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001428 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001429 mExternalStylusFusionTimeout = LLONG_MAX;
1430 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001431 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001432}
1433
1434void TouchInputMapper::clearStylusDataPendingFlags() {
1435 mExternalStylusDataPending = false;
1436 mExternalStylusFusionTimeout = LLONG_MAX;
1437}
1438
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001439std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440 mCursorButtonAccumulator.process(rawEvent);
1441 mCursorScrollAccumulator.process(rawEvent);
1442 mTouchButtonAccumulator.process(rawEvent);
1443
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001444 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001445 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001446 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001447 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001448 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001449}
1450
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001451std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1452 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001453 if (mDeviceMode == DeviceMode::DISABLED) {
1454 // Only save the last pending state when the device is disabled.
1455 mRawStatesPending.clear();
1456 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001457 // Push a new state.
1458 mRawStatesPending.emplace_back();
1459
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001460 RawState& next = mRawStatesPending.back();
1461 next.clear();
1462 next.when = when;
1463 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001464
1465 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001466 next.buttonState = filterButtonState(mConfig,
1467 mTouchButtonAccumulator.getButtonState() |
1468 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001469
1470 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001471 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1472 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001473 mCursorScrollAccumulator.finishSync();
1474
1475 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001476 syncTouch(when, &next);
1477
1478 // The last RawState is the actually second to last, since we just added a new state
1479 const RawState& last =
1480 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001481
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001482 std::tie(next.when, next.readTime) =
1483 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1484 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001485
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001486 // Assign pointer ids.
1487 if (!mHavePointerIds) {
1488 assignPointerIds(last, next);
1489 }
1490
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001491 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001492 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1493 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1494 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1495 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1496 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1497 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498
Arthur Hung9ad18942021-06-19 02:04:46 +00001499 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1500 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1501 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1502 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1503 next.rawPointerData.hoveringIdBits.value);
1504 }
1505
Harry Cutts33476232023-01-30 19:57:29 +00001506 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001507 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001508}
1509
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001510std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1511 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001512 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001513 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001514 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001515 }
1516
1517 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1518 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1519 // touching the current state will only observe the events that have been dispatched to the
1520 // rest of the pipeline.
1521 const size_t N = mRawStatesPending.size();
1522 size_t count;
1523 for (count = 0; count < N; count++) {
1524 const RawState& next = mRawStatesPending[count];
1525
1526 // A failure to assign the stylus id means that we're waiting on stylus data
1527 // and so should defer the rest of the pipeline.
1528 if (assignExternalStylusId(next, timeout)) {
1529 break;
1530 }
1531
1532 // All ready to go.
1533 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001534 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001535 if (mCurrentRawState.when < mLastRawState.when) {
1536 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001537 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001538 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001539 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001540 }
1541 if (count != 0) {
1542 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1543 }
1544
1545 if (mExternalStylusDataPending) {
1546 if (timeout) {
1547 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1548 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001549 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001550 ALOGD_IF(DEBUG_STYLUS_FUSION,
1551 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001552 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001553 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001554 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1555 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1556 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1557 }
1558 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001559 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001560}
1561
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001562std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1563 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001564 // Always start with a clean state.
1565 mCurrentCookedState.clear();
1566
1567 // Apply stylus buttons to current raw state.
1568 applyExternalStylusButtonState(when);
1569
1570 // Handle policy on initial down or hover events.
1571 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1572 mCurrentRawState.rawPointerData.pointerCount != 0;
1573
1574 uint32_t policyFlags = 0;
1575 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1576 if (initialDown || buttonsPressed) {
1577 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001578 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001579 getContext()->fadePointer();
1580 }
1581
1582 if (mParameters.wake) {
1583 policyFlags |= POLICY_FLAG_WAKE;
1584 }
1585 }
1586
1587 // Consume raw off-screen touches before cooking pointer data.
1588 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001589 bool consumed;
1590 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1591 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001592 mCurrentRawState.rawPointerData.clear();
1593 }
1594
1595 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1596 // with cooked pointer data that has the same ids and indices as the raw data.
1597 // The following code can use either the raw or cooked data, as needed.
1598 cookPointerData();
1599
1600 // Apply stylus pressure to current cooked state.
1601 applyExternalStylusTouchState(when);
1602
1603 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001604 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1605 mSource, mViewport.displayId, policyFlags,
1606 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001607
1608 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001609 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001610 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1611 uint32_t id = idBits.clearFirstMarkedBit();
1612 const RawPointerData::Pointer& pointer =
1613 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001614 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001615 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001616 } else if (pointer.toolType == ToolType::FINGER ||
1617 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001618 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001619 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001620 mCurrentCookedState.mouseIdBits.markBit(id);
1621 }
1622 }
1623 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1624 uint32_t id = idBits.clearFirstMarkedBit();
1625 const RawPointerData::Pointer& pointer =
1626 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001627 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001628 mCurrentCookedState.stylusIdBits.markBit(id);
1629 }
1630 }
1631
1632 // Stylus takes precedence over all tools, then mouse, then finger.
1633 PointerUsage pointerUsage = mPointerUsage;
1634 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1635 mCurrentCookedState.mouseIdBits.clear();
1636 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001637 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001638 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1639 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001640 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001641 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1642 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001643 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001644 }
1645
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001646 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001647 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001648 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001649 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001650 out += dispatchButtonRelease(when, readTime, policyFlags);
1651 out += dispatchHoverExit(when, readTime, policyFlags);
1652 out += dispatchTouches(when, readTime, policyFlags);
1653 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1654 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001655 }
1656
1657 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1658 mCurrentMotionAborted = false;
1659 }
1660 }
1661
1662 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001663 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1664 mSource, mViewport.displayId, policyFlags,
1665 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001666
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001667 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1668 mCurrentStreamModifiedByExternalStylus = false;
1669 }
1670
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001671 // Clear some transient state.
1672 mCurrentRawState.rawVScroll = 0;
1673 mCurrentRawState.rawHScroll = 0;
1674
1675 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001676 mLastRawState = mCurrentRawState;
1677 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001678 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001679}
1680
Garfield Tanc734e4f2021-01-15 20:01:39 -08001681void TouchInputMapper::updateTouchSpots() {
1682 if (!mConfig.showTouches || mPointerController == nullptr) {
1683 return;
1684 }
1685
1686 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1687 // clear touch spots.
1688 if (mDeviceMode != DeviceMode::DIRECT &&
1689 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1690 return;
1691 }
1692
1693 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1694 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1695
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001696 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1697 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001698 mCurrentCookedState.cookedPointerData.touchingIdBits |
1699 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001700 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001701}
1702
1703bool TouchInputMapper::isTouchScreen() {
1704 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1705 mParameters.hasAssociatedDisplay;
1706}
1707
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001708void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001709 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1710 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001711 const int32_t pressedButtons =
1712 filterButtonState(mConfig,
1713 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001714 const int32_t releasedButtons =
1715 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1716
1717 mCurrentRawState.buttonState |= pressedButtons;
1718 mCurrentRawState.buttonState &= ~releasedButtons;
1719
1720 mExternalStylusButtonsApplied |= pressedButtons;
1721 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001722
1723 if (mExternalStylusButtonsApplied != 0 || releasedButtons != 0) {
1724 mCurrentStreamModifiedByExternalStylus = true;
1725 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001726 }
1727}
1728
1729void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1730 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1731 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001732 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1733 return;
1734 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001735
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001736 mCurrentStreamModifiedByExternalStylus = true;
1737
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001738 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1739 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1740 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1741 : 0.f;
1742 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1743 pressure = *mExternalStylusState.pressure;
1744 }
1745 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1746 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001747
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001748 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001749 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001750 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001751 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001752 }
1753}
1754
1755bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001756 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001757 return false;
1758 }
1759
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001760 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001761 if (mFusedStylusPointerId &&
1762 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001763 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001764 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001765 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001766 }
1767
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001768 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1769 state.rawPointerData.pointerCount != 0;
1770 if (!initialDown) {
1771 return false;
1772 }
1773
1774 if (!mExternalStylusState.pressure) {
1775 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1776 return false;
1777 }
1778
1779 if (*mExternalStylusState.pressure != 0.0f) {
1780 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1781 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1782 return false;
1783 }
1784
1785 if (timeout) {
1786 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1787 mFusedStylusPointerId.reset();
1788 mExternalStylusFusionTimeout = LLONG_MAX;
1789 return false;
1790 }
1791
1792 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1793 // being processed until we either get pressure data or timeout.
1794 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1795 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1796 }
1797 ALOGD_IF(DEBUG_STYLUS_FUSION,
1798 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1799 mExternalStylusFusionTimeout);
1800 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1801 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001802}
1803
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001804std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1805 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001806 if (mDeviceMode == DeviceMode::POINTER) {
1807 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001808 // Since this is a synthetic event, we can consider its latency to be zero
1809 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001810 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001811 }
Michael Wright227c5542020-07-02 18:30:52 +01001812 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001813 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001814 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001815 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1816 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1817 }
1818 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001819 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001820}
1821
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001822std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1823 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001824 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001825 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001826 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001827 // The following three cases are handled here:
1828 // - We're in the middle of a fused stream of data;
1829 // - We're waiting on external stylus data before dispatching the initial down; or
1830 // - Only the button state, which is not reported through a specific pointer, has changed.
1831 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001832 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001833 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001834 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001835 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001836}
1837
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001838std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1839 uint32_t policyFlags, bool& outConsumed) {
1840 outConsumed = false;
1841 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001842 // Check for release of a virtual key.
1843 if (mCurrentVirtualKey.down) {
1844 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1845 // Pointer went up while virtual key was down.
1846 mCurrentVirtualKey.down = false;
1847 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001848 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1849 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1850 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001851 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1852 AKEY_EVENT_FLAG_FROM_SYSTEM |
1853 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001854 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001855 outConsumed = true;
1856 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001857 }
1858
1859 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1860 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1861 const RawPointerData::Pointer& pointer =
1862 mCurrentRawState.rawPointerData.pointerForId(id);
1863 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1864 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1865 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001866 outConsumed = true;
1867 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001868 }
1869 }
1870
1871 // Pointer left virtual key area or another pointer also went down.
1872 // Send key cancellation but do not consume the touch yet.
1873 // This is useful when the user swipes through from the virtual key area
1874 // into the main display surface.
1875 mCurrentVirtualKey.down = false;
1876 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001877 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1878 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001879 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1880 AKEY_EVENT_FLAG_FROM_SYSTEM |
1881 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1882 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001883 }
1884 }
1885
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001886 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
1887 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty() &&
1888 mDeviceMode != DeviceMode::UNSCALED) {
1889 // We have hovering pointers, and there are no touching pointers.
1890 bool hoveringPointersInFrame = false;
1891 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1892 while (!hoveringIds.isEmpty()) {
1893 uint32_t id = hoveringIds.clearFirstMarkedBit();
1894 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1895 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1896 hoveringPointersInFrame = true;
1897 break;
1898 }
1899 }
1900 if (!hoveringPointersInFrame) {
1901 // All hovering pointers are outside the physical frame.
1902 outConsumed = true;
1903 return out;
1904 }
1905 }
1906
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001907 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1908 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1909 // Pointer just went down. Check for virtual key press or off-screen touches.
1910 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1911 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001912 // Skip checking whether the pointer is inside the physical frame if the device is in
Harry Cutts1db43992023-06-19 17:05:07 +00001913 // unscaled or pointer mode.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001914 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
Harry Cutts1db43992023-06-19 17:05:07 +00001915 mDeviceMode != DeviceMode::UNSCALED && mDeviceMode != DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001916 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001917 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001918 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1919 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1920 if (virtualKey) {
1921 mCurrentVirtualKey.down = true;
1922 mCurrentVirtualKey.downTime = when;
1923 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1924 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1925 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001926 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1927 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001928
1929 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001930 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1931 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1932 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001933 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1934 AKEY_EVENT_ACTION_DOWN,
1935 AKEY_EVENT_FLAG_FROM_SYSTEM |
1936 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001937 }
1938 }
1939 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001940 outConsumed = true;
1941 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001942 }
1943 }
1944
1945 // Disable all virtual key touches that happen within a short time interval of the
1946 // most recent touch within the screen area. The idea is to filter out stray
1947 // virtual key presses when interacting with the touch screen.
1948 //
1949 // Problems we're trying to solve:
1950 //
1951 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1952 // virtual key area that is implemented by a separate touch panel and accidentally
1953 // triggers a virtual key.
1954 //
1955 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1956 // area and accidentally triggers a virtual key. This often happens when virtual keys
1957 // are layed out below the screen near to where the on screen keyboard's space bar
1958 // is displayed.
1959 if (mConfig.virtualKeyQuietTime > 0 &&
1960 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001961 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001962 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001963 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001964}
1965
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001966NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1967 uint32_t policyFlags, int32_t keyEventAction,
1968 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001969 int32_t keyCode = mCurrentVirtualKey.keyCode;
1970 int32_t scanCode = mCurrentVirtualKey.scanCode;
1971 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001972 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001973 policyFlags |= POLICY_FLAG_VIRTUAL;
1974
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001975 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1976 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1977 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001978}
1979
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001980std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1981 uint32_t policyFlags) {
1982 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001983 if (mCurrentMotionAborted) {
1984 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001985 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001986 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001987 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1988 if (!currentIdBits.isEmpty()) {
1989 int32_t metaState = getContext()->getGlobalMetaState();
1990 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001991 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001992 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1993 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001994 mCurrentCookedState.cookedPointerData.pointerProperties,
1995 mCurrentCookedState.cookedPointerData.pointerCoords,
1996 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1997 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1998 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001999 mCurrentMotionAborted = true;
2000 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002001 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002002}
2003
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002004// Updates pointer coords and properties for pointers with specified ids that have moved.
2005// Returns true if any of them changed.
2006static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
2007 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
2008 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
2009 BitSet32 idBits) {
2010 bool changed = false;
2011 while (!idBits.isEmpty()) {
2012 uint32_t id = idBits.clearFirstMarkedBit();
2013 uint32_t inIndex = inIdToIndex[id];
2014 uint32_t outIndex = outIdToIndex[id];
2015
2016 const PointerProperties& curInProperties = inProperties[inIndex];
2017 const PointerCoords& curInCoords = inCoords[inIndex];
2018 PointerProperties& curOutProperties = outProperties[outIndex];
2019 PointerCoords& curOutCoords = outCoords[outIndex];
2020
2021 if (curInProperties != curOutProperties) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002022 curOutProperties = curInProperties;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002023 changed = true;
2024 }
2025
2026 if (curInCoords != curOutCoords) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002027 curOutCoords = curInCoords;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002028 changed = true;
2029 }
2030 }
2031 return changed;
2032}
2033
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002034std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
2035 uint32_t policyFlags) {
2036 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002037 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2038 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2039 int32_t metaState = getContext()->getGlobalMetaState();
2040 int32_t buttonState = mCurrentCookedState.buttonState;
2041
2042 if (currentIdBits == lastIdBits) {
2043 if (!currentIdBits.isEmpty()) {
2044 // No pointer id changes so this is a move event.
2045 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002046 out.push_back(
2047 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2048 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2049 mCurrentCookedState.cookedPointerData.pointerProperties,
2050 mCurrentCookedState.cookedPointerData.pointerCoords,
2051 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2052 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2053 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002054 }
2055 } else {
2056 // There may be pointers going up and pointers going down and pointers moving
2057 // all at the same time.
2058 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2059 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2060 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2061 BitSet32 dispatchedIdBits(lastIdBits.value);
2062
2063 // Update last coordinates of pointers that have moved so that we observe the new
2064 // pointer positions at the same time as other pointers that have just gone up.
2065 bool moveNeeded =
2066 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2067 mCurrentCookedState.cookedPointerData.pointerCoords,
2068 mCurrentCookedState.cookedPointerData.idToIndex,
2069 mLastCookedState.cookedPointerData.pointerProperties,
2070 mLastCookedState.cookedPointerData.pointerCoords,
2071 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2072 if (buttonState != mLastCookedState.buttonState) {
2073 moveNeeded = true;
2074 }
2075
2076 // Dispatch pointer up events.
2077 while (!upIdBits.isEmpty()) {
2078 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002079 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002080 if (isCanceled) {
2081 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2082 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002083 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2084 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2085 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2086 buttonState, 0,
2087 mLastCookedState.cookedPointerData.pointerProperties,
2088 mLastCookedState.cookedPointerData.pointerCoords,
2089 mLastCookedState.cookedPointerData.idToIndex,
2090 dispatchedIdBits, upId, mOrientedXPrecision,
2091 mOrientedYPrecision, mDownTime,
2092 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002093 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002094 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002095 }
2096
2097 // Dispatch move events if any of the remaining pointers moved from their old locations.
2098 // Although applications receive new locations as part of individual pointer up
2099 // events, they do not generally handle them except when presented in a move event.
2100 if (moveNeeded && !moveIdBits.isEmpty()) {
2101 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002102 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2103 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2104 mCurrentCookedState.cookedPointerData.pointerProperties,
2105 mCurrentCookedState.cookedPointerData.pointerCoords,
2106 mCurrentCookedState.cookedPointerData.idToIndex,
2107 dispatchedIdBits, -1, mOrientedXPrecision,
2108 mOrientedYPrecision, mDownTime,
2109 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002110 }
2111
2112 // Dispatch pointer down events using the new pointer locations.
2113 while (!downIdBits.isEmpty()) {
2114 uint32_t downId = downIdBits.clearFirstMarkedBit();
2115 dispatchedIdBits.markBit(downId);
2116
2117 if (dispatchedIdBits.count() == 1) {
2118 // First pointer is going down. Set down time.
2119 mDownTime = when;
2120 }
2121
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002122 out.push_back(
2123 dispatchMotion(when, readTime, policyFlags, mSource,
2124 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2125 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2126 mCurrentCookedState.cookedPointerData.pointerCoords,
2127 mCurrentCookedState.cookedPointerData.idToIndex,
2128 dispatchedIdBits, downId, mOrientedXPrecision,
2129 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002130 }
2131 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002132 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002133}
2134
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002135std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2136 uint32_t policyFlags) {
2137 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002138 if (mSentHoverEnter &&
2139 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2140 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2141 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002142 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2143 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2144 mLastCookedState.buttonState, 0,
2145 mLastCookedState.cookedPointerData.pointerProperties,
2146 mLastCookedState.cookedPointerData.pointerCoords,
2147 mLastCookedState.cookedPointerData.idToIndex,
2148 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2149 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2150 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002151 mSentHoverEnter = false;
2152 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002153 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002154}
2155
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002156std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2157 uint32_t policyFlags) {
2158 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002159 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2160 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2161 int32_t metaState = getContext()->getGlobalMetaState();
2162 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002163 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2164 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2165 mCurrentRawState.buttonState, 0,
2166 mCurrentCookedState.cookedPointerData.pointerProperties,
2167 mCurrentCookedState.cookedPointerData.pointerCoords,
2168 mCurrentCookedState.cookedPointerData.idToIndex,
2169 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2170 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2171 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002172 mSentHoverEnter = true;
2173 }
2174
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002175 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2176 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2177 mCurrentRawState.buttonState, 0,
2178 mCurrentCookedState.cookedPointerData.pointerProperties,
2179 mCurrentCookedState.cookedPointerData.pointerCoords,
2180 mCurrentCookedState.cookedPointerData.idToIndex,
2181 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2182 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2183 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002184 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002185 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002186}
2187
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002188std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2189 uint32_t policyFlags) {
2190 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002191 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2192 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2193 const int32_t metaState = getContext()->getGlobalMetaState();
2194 int32_t buttonState = mLastCookedState.buttonState;
2195 while (!releasedButtons.isEmpty()) {
2196 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2197 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002198 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2199 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2200 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002201 mLastCookedState.cookedPointerData.pointerProperties,
2202 mLastCookedState.cookedPointerData.pointerCoords,
2203 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002204 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2205 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002206 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002207 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002208}
2209
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002210std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2211 uint32_t policyFlags) {
2212 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002213 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2214 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2215 const int32_t metaState = getContext()->getGlobalMetaState();
2216 int32_t buttonState = mLastCookedState.buttonState;
2217 while (!pressedButtons.isEmpty()) {
2218 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2219 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002220 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2221 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2222 buttonState, 0,
2223 mCurrentCookedState.cookedPointerData.pointerProperties,
2224 mCurrentCookedState.cookedPointerData.pointerCoords,
2225 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2226 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2227 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002228 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002229 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002230}
2231
LiZhihong758eb562022-11-03 15:28:29 +08002232std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2233 uint32_t policyFlags,
2234 BitSet32 idBits,
2235 nsecs_t readTime) {
2236 std::list<NotifyArgs> out;
2237 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2238 const int32_t metaState = getContext()->getGlobalMetaState();
2239 int32_t buttonState = mLastCookedState.buttonState;
2240
2241 while (!releasedButtons.isEmpty()) {
2242 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2243 buttonState &= ~actionButton;
2244 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2245 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2246 metaState, buttonState, 0,
2247 mPointerGesture.lastGestureProperties,
2248 mPointerGesture.lastGestureCoords,
2249 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2250 mOrientedXPrecision, mOrientedYPrecision,
2251 mPointerGesture.downTime, MotionClassification::NONE));
2252 }
2253 return out;
2254}
2255
2256std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2257 uint32_t policyFlags,
2258 BitSet32 idBits,
2259 nsecs_t readTime) {
2260 std::list<NotifyArgs> out;
2261 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2262 const int32_t metaState = getContext()->getGlobalMetaState();
2263 int32_t buttonState = mLastCookedState.buttonState;
2264
2265 while (!pressedButtons.isEmpty()) {
2266 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2267 buttonState |= actionButton;
2268 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2269 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2270 buttonState, 0, mPointerGesture.currentGestureProperties,
2271 mPointerGesture.currentGestureCoords,
2272 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2273 mOrientedXPrecision, mOrientedYPrecision,
2274 mPointerGesture.downTime, MotionClassification::NONE));
2275 }
2276 return out;
2277}
2278
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002279const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2280 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2281 return cookedPointerData.touchingIdBits;
2282 }
2283 return cookedPointerData.hoveringIdBits;
2284}
2285
2286void TouchInputMapper::cookPointerData() {
2287 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2288
2289 mCurrentCookedState.cookedPointerData.clear();
2290 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2291 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2292 mCurrentRawState.rawPointerData.hoveringIdBits;
2293 mCurrentCookedState.cookedPointerData.touchingIdBits =
2294 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002295 mCurrentCookedState.cookedPointerData.canceledIdBits =
2296 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297
2298 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2299 mCurrentCookedState.buttonState = 0;
2300 } else {
2301 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2302 }
2303
2304 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002305 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002306 for (uint32_t i = 0; i < currentPointerCount; i++) {
2307 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2308
2309 // Size
2310 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2311 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002312 case Calibration::SizeCalibration::GEOMETRIC:
2313 case Calibration::SizeCalibration::DIAMETER:
2314 case Calibration::SizeCalibration::BOX:
2315 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002316 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2317 touchMajor = in.touchMajor;
2318 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2319 toolMajor = in.toolMajor;
2320 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2321 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2322 : in.touchMajor;
2323 } else if (mRawPointerAxes.touchMajor.valid) {
2324 toolMajor = touchMajor = in.touchMajor;
2325 toolMinor = touchMinor =
2326 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2327 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2328 : in.touchMajor;
2329 } else if (mRawPointerAxes.toolMajor.valid) {
2330 touchMajor = toolMajor = in.toolMajor;
2331 touchMinor = toolMinor =
2332 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2333 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2334 : in.toolMajor;
2335 } else {
2336 ALOG_ASSERT(false,
2337 "No touch or tool axes. "
2338 "Size calibration should have been resolved to NONE.");
2339 touchMajor = 0;
2340 touchMinor = 0;
2341 toolMajor = 0;
2342 toolMinor = 0;
2343 size = 0;
2344 }
2345
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002346 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2348 if (touchingCount > 1) {
2349 touchMajor /= touchingCount;
2350 touchMinor /= touchingCount;
2351 toolMajor /= touchingCount;
2352 toolMinor /= touchingCount;
2353 size /= touchingCount;
2354 }
2355 }
2356
Michael Wright227c5542020-07-02 18:30:52 +01002357 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358 touchMajor *= mGeometricScale;
2359 touchMinor *= mGeometricScale;
2360 toolMajor *= mGeometricScale;
2361 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002362 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002363 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2364 touchMinor = touchMajor;
2365 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2366 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002367 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 touchMinor = touchMajor;
2369 toolMinor = toolMajor;
2370 }
2371
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002372 mCalibration.applySizeScaleAndBias(touchMajor);
2373 mCalibration.applySizeScaleAndBias(touchMinor);
2374 mCalibration.applySizeScaleAndBias(toolMajor);
2375 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002376 size *= mSizeScale;
2377 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002378 case Calibration::SizeCalibration::DEFAULT:
2379 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2380 break;
2381 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 touchMajor = 0;
2383 touchMinor = 0;
2384 toolMajor = 0;
2385 toolMinor = 0;
2386 size = 0;
2387 break;
2388 }
2389
2390 // Pressure
2391 float pressure;
2392 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002393 case Calibration::PressureCalibration::PHYSICAL:
2394 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002395 pressure = in.pressure * mPressureScale;
2396 break;
2397 default:
2398 pressure = in.isHovering ? 0 : 1;
2399 break;
2400 }
2401
2402 // Tilt and Orientation
2403 float tilt;
2404 float orientation;
2405 if (mHaveTilt) {
2406 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2407 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002408 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2410 } else {
2411 tilt = 0;
2412
2413 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002414 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002415 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002416 break;
Michael Wright227c5542020-07-02 18:30:52 +01002417 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002418 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2419 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2420 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002421 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002422 float confidence = hypotf(c1, c2);
2423 float scale = 1.0f + confidence / 16.0f;
2424 touchMajor *= scale;
2425 touchMinor /= scale;
2426 toolMajor *= scale;
2427 toolMinor /= scale;
2428 } else {
2429 orientation = 0;
2430 }
2431 break;
2432 }
2433 default:
2434 orientation = 0;
2435 }
2436 }
2437
2438 // Distance
2439 float distance;
2440 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002441 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 distance = in.distance * mDistanceScale;
2443 break;
2444 default:
2445 distance = 0;
2446 }
2447
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002448 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2449 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002450 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2451 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002453 // Write output coords.
2454 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2455 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002456 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2457 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2459 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2460 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2461 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2462 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2463 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2464 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002465 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2466 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467
Chris Ye364fdb52020-08-05 15:07:56 -07002468 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002469 uint32_t id = in.id;
2470 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2471 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2472 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002473 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2474 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002475 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2476 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2477 }
2478
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 // Write output properties.
2480 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002481 properties.clear();
2482 properties.id = id;
2483 properties.toolType = in.toolType;
2484
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002485 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002487 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002488 }
2489}
2490
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002491std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2492 uint32_t policyFlags,
2493 PointerUsage pointerUsage) {
2494 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002495 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002496 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002497 mPointerUsage = pointerUsage;
2498 }
2499
2500 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002501 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002502 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 break;
Michael Wright227c5542020-07-02 18:30:52 +01002504 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002505 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002506 break;
Michael Wright227c5542020-07-02 18:30:52 +01002507 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002508 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 break;
Michael Wright227c5542020-07-02 18:30:52 +01002510 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002511 break;
2512 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002513 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514}
2515
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002516std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2517 uint32_t policyFlags) {
2518 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002519 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002520 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002521 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 break;
Michael Wright227c5542020-07-02 18:30:52 +01002523 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002524 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002525 break;
Michael Wright227c5542020-07-02 18:30:52 +01002526 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002527 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002528 break;
Michael Wright227c5542020-07-02 18:30:52 +01002529 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002530 break;
2531 }
2532
Michael Wright227c5542020-07-02 18:30:52 +01002533 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002534 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002535}
2536
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002537std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2538 uint32_t policyFlags,
2539 bool isTimeout) {
2540 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002541 // Update current gesture coordinates.
2542 bool cancelPreviousGesture, finishPreviousGesture;
2543 bool sendEvents =
2544 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2545 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002546 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002547 }
2548 if (finishPreviousGesture) {
2549 cancelPreviousGesture = false;
2550 }
2551
2552 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002553 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002554 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002555 if (finishPreviousGesture || cancelPreviousGesture) {
2556 mPointerController->clearSpots();
2557 }
2558
Michael Wright227c5542020-07-02 18:30:52 +01002559 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002560 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2561 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002562 mPointerGesture.currentGestureIdBits,
2563 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002564 }
2565 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002566 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002567 }
2568
2569 // Show or hide the pointer if needed.
2570 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002571 case PointerGesture::Mode::NEUTRAL:
2572 case PointerGesture::Mode::QUIET:
2573 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2574 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002575 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002576 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002577 }
2578 break;
Michael Wright227c5542020-07-02 18:30:52 +01002579 case PointerGesture::Mode::TAP:
2580 case PointerGesture::Mode::TAP_DRAG:
2581 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2582 case PointerGesture::Mode::HOVER:
2583 case PointerGesture::Mode::PRESS:
2584 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002585 // Unfade the pointer when the current gesture manipulates the
2586 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002587 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002588 break;
Michael Wright227c5542020-07-02 18:30:52 +01002589 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002590 // Fade the pointer when the current gesture manipulates a different
2591 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002592 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002593 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002594 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002595 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002596 }
2597 break;
2598 }
2599
2600 // Send events!
2601 int32_t metaState = getContext()->getGlobalMetaState();
2602 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002603 const MotionClassification classification =
2604 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2605 ? MotionClassification::TWO_FINGER_SWIPE
2606 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002607
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002608 uint32_t flags = 0;
2609
2610 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2611 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2612 }
2613
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002614 // Update last coordinates of pointers that have moved so that we observe the new
2615 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002616 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2617 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2618 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2619 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2620 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2621 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002622 bool moveNeeded = false;
2623 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2624 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2625 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2626 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2627 mPointerGesture.lastGestureIdBits.value);
2628 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2629 mPointerGesture.currentGestureCoords,
2630 mPointerGesture.currentGestureIdToIndex,
2631 mPointerGesture.lastGestureProperties,
2632 mPointerGesture.lastGestureCoords,
2633 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2634 if (buttonState != mLastCookedState.buttonState) {
2635 moveNeeded = true;
2636 }
2637 }
2638
2639 // Send motion events for all pointers that went up or were canceled.
2640 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2641 if (!dispatchedGestureIdBits.isEmpty()) {
2642 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002643 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002644 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002645 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002646 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2647 mPointerGesture.lastGestureProperties,
2648 mPointerGesture.lastGestureCoords,
2649 mPointerGesture.lastGestureIdToIndex,
2650 dispatchedGestureIdBits, -1, 0, 0,
2651 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002652
2653 dispatchedGestureIdBits.clear();
2654 } else {
2655 BitSet32 upGestureIdBits;
2656 if (finishPreviousGesture) {
2657 upGestureIdBits = dispatchedGestureIdBits;
2658 } else {
2659 upGestureIdBits.value =
2660 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2661 }
2662 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002663 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2664 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2665 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2666 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2667 readTime);
2668 }
2669 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002670 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2671 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2672 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2673 mPointerGesture.lastGestureProperties,
2674 mPointerGesture.lastGestureCoords,
2675 mPointerGesture.lastGestureIdToIndex,
2676 dispatchedGestureIdBits, id, 0, 0,
2677 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002678
2679 dispatchedGestureIdBits.clearBit(id);
2680 }
2681 }
2682 }
2683
2684 // Send motion events for all pointers that moved.
2685 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002686 out.push_back(
2687 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2688 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2689 mPointerGesture.currentGestureProperties,
2690 mPointerGesture.currentGestureCoords,
2691 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2692 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002693 }
2694
2695 // Send motion events for all pointers that went down.
2696 if (down) {
2697 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2698 ~dispatchedGestureIdBits.value);
2699 while (!downGestureIdBits.isEmpty()) {
2700 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2701 dispatchedGestureIdBits.markBit(id);
2702
2703 if (dispatchedGestureIdBits.count() == 1) {
2704 mPointerGesture.downTime = when;
2705 }
2706
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002707 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2708 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2709 buttonState, 0, mPointerGesture.currentGestureProperties,
2710 mPointerGesture.currentGestureCoords,
2711 mPointerGesture.currentGestureIdToIndex,
2712 dispatchedGestureIdBits, id, 0, 0,
2713 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002714 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2715 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2716 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2717 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2718 readTime);
2719 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002720 }
2721 }
2722
2723 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002724 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002725 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2726 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2727 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2728 mPointerGesture.currentGestureProperties,
2729 mPointerGesture.currentGestureCoords,
2730 mPointerGesture.currentGestureIdToIndex,
2731 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2732 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002733 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2734 // Synthesize a hover move event after all pointers go up to indicate that
2735 // the pointer is hovering again even if the user is not currently touching
2736 // the touch pad. This ensures that a view will receive a fresh hover enter
2737 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002738 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002739
2740 PointerProperties pointerProperties;
2741 pointerProperties.clear();
2742 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002743 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002744
2745 PointerCoords pointerCoords;
2746 pointerCoords.clear();
2747 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2748 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2749
2750 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002751 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2752 mSource, displayId, policyFlags,
2753 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2754 buttonState, MotionClassification::NONE,
2755 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2756 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00002757 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002758 }
2759
2760 // Update state.
2761 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2762 if (!down) {
2763 mPointerGesture.lastGestureIdBits.clear();
2764 } else {
2765 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2766 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2767 uint32_t id = idBits.clearFirstMarkedBit();
2768 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002769 mPointerGesture.lastGestureProperties[index] =
2770 mPointerGesture.currentGestureProperties[index];
2771 mPointerGesture.lastGestureCoords[index] = mPointerGesture.currentGestureCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002772 mPointerGesture.lastGestureIdToIndex[id] = index;
2773 }
2774 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002775 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002776}
2777
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002778std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2779 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002780 const MotionClassification classification =
2781 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2782 ? MotionClassification::TWO_FINGER_SWIPE
2783 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002784 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002785 // Cancel previously dispatches pointers.
2786 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2787 int32_t metaState = getContext()->getGlobalMetaState();
2788 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002789 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002790 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2791 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002792 mPointerGesture.lastGestureProperties,
2793 mPointerGesture.lastGestureCoords,
2794 mPointerGesture.lastGestureIdToIndex,
2795 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2796 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002797 }
2798
2799 // Reset the current pointer gesture.
2800 mPointerGesture.reset();
2801 mPointerVelocityControl.reset();
2802
2803 // Remove any current spots.
2804 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002805 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806 mPointerController->clearSpots();
2807 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002808 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002809}
2810
2811bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2812 bool* outFinishPreviousGesture, bool isTimeout) {
2813 *outCancelPreviousGesture = false;
2814 *outFinishPreviousGesture = false;
2815
2816 // Handle TAP timeout.
2817 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002818 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002819
Michael Wright227c5542020-07-02 18:30:52 +01002820 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002821 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2822 // The tap/drag timeout has not yet expired.
2823 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2824 mConfig.pointerGestureTapDragInterval);
2825 } else {
2826 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002827 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002828 *outFinishPreviousGesture = true;
2829
2830 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002831 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002832 mPointerGesture.currentGestureIdBits.clear();
2833
2834 mPointerVelocityControl.reset();
2835 return true;
2836 }
2837 }
2838
2839 // We did not handle this timeout.
2840 return false;
2841 }
2842
2843 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2844 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2845
2846 // Update the velocity tracker.
2847 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002848 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002849 uint32_t id = idBits.clearFirstMarkedBit();
2850 const RawPointerData::Pointer& pointer =
2851 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002852 const float x = pointer.x * mPointerXMovementScale;
2853 const float y = pointer.y * mPointerYMovementScale;
2854 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2855 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002856 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002857 }
2858
2859 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2860 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002861 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2862 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2863 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002864 mPointerGesture.resetTap();
2865 }
2866
2867 // Pick a new active touch id if needed.
2868 // Choose an arbitrary pointer that just went down, if there is one.
2869 // Otherwise choose an arbitrary remaining pointer.
2870 // This guarantees we always have an active touch id when there is at least one pointer.
2871 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002872 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002873 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002874 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 mPointerGesture.firstTouchTime = when;
2876 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002877 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2878 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2879 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2880 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002881 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002882 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002883
2884 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002885 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002886 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002887 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2888 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2889 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002890 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891 *outFinishPreviousGesture = true;
2892 }
2893
2894 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002895 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002896 mPointerGesture.currentGestureIdBits.clear();
2897
2898 mPointerVelocityControl.reset();
2899 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2900 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2901 // The pointer follows the active touch point.
2902 // Emit DOWN, MOVE, UP events at the pointer location.
2903 //
2904 // Only the active touch matters; other fingers are ignored. This policy helps
2905 // to handle the case where the user places a second finger on the touch pad
2906 // to apply the necessary force to depress an integrated button below the surface.
2907 // We don't want the second finger to be delivered to applications.
2908 //
2909 // For this to work well, we need to make sure to track the pointer that is really
2910 // active. If the user first puts one finger down to click then adds another
2911 // finger to drag then the active pointer should switch to the finger that is
2912 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002913 ALOGD_IF(DEBUG_GESTURES,
2914 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2915 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002916 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002917 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002918 *outFinishPreviousGesture = true;
2919 mPointerGesture.activeGestureId = 0;
2920 }
2921
2922 // Switch pointers if needed.
2923 // Find the fastest pointer and follow it.
2924 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002925 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002926 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002927 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002928 ALOGD_IF(DEBUG_GESTURES,
2929 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2930 "bestSpeed=%0.3f",
2931 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002932 }
2933 }
2934
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002935 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002936 // When using spots, the click will occur at the position of the anchor
2937 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002938 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002939 } else {
2940 mPointerVelocityControl.reset();
2941 }
2942
Prabir Pradhan2719e822023-02-28 17:39:36 +00002943 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944
Michael Wright227c5542020-07-02 18:30:52 +01002945 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002946 mPointerGesture.currentGestureIdBits.clear();
2947 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2948 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2949 mPointerGesture.currentGestureProperties[0].clear();
2950 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002951 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002952 mPointerGesture.currentGestureCoords[0].clear();
2953 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2954 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2955 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2956 } else if (currentFingerCount == 0) {
2957 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002958 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002959 *outFinishPreviousGesture = true;
2960 }
2961
2962 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2963 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2964 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002965 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2966 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002967 lastFingerCount == 1) {
2968 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002969 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002970 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2971 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002972 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002973
2974 mPointerGesture.tapUpTime = when;
2975 getContext()->requestTimeoutAtTime(when +
2976 mConfig.pointerGestureTapDragInterval);
2977
2978 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002979 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002980 mPointerGesture.currentGestureIdBits.clear();
2981 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2982 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2983 mPointerGesture.currentGestureProperties[0].clear();
2984 mPointerGesture.currentGestureProperties[0].id =
2985 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002986 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002987 mPointerGesture.currentGestureCoords[0].clear();
2988 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2989 mPointerGesture.tapX);
2990 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2991 mPointerGesture.tapY);
2992 mPointerGesture.currentGestureCoords[0]
2993 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2994
2995 tapped = true;
2996 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002997 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2998 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002999 }
3000 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003001 if (DEBUG_GESTURES) {
3002 if (mPointerGesture.tapDownTime != LLONG_MIN) {
3003 ALOGD("Gestures: Not a TAP, %0.3fms since down",
3004 (when - mPointerGesture.tapDownTime) * 0.000001f);
3005 } else {
3006 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
3007 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003008 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003009 }
3010 }
3011
3012 mPointerVelocityControl.reset();
3013
3014 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00003015 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003016 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01003017 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003018 mPointerGesture.currentGestureIdBits.clear();
3019 }
3020 } else if (currentFingerCount == 1) {
3021 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3022 // The pointer follows the active touch point.
3023 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3024 // When in TAP_DRAG, emit MOVE events at the pointer location.
3025 ALOG_ASSERT(activeTouchId >= 0);
3026
Michael Wright227c5542020-07-02 18:30:52 +01003027 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3028 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003029 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003030 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003031 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3032 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003033 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003034 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003035 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3036 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003037 }
3038 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003039 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3040 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003041 }
Michael Wright227c5542020-07-02 18:30:52 +01003042 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3043 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003044 }
3045
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003046 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003047 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003048 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003049 } else {
3050 mPointerVelocityControl.reset();
3051 }
3052
3053 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003054 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003055 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003056 down = true;
3057 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003058 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003059 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003060 *outFinishPreviousGesture = true;
3061 }
3062 mPointerGesture.activeGestureId = 0;
3063 down = false;
3064 }
3065
Prabir Pradhan2719e822023-02-28 17:39:36 +00003066 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003067
3068 mPointerGesture.currentGestureIdBits.clear();
3069 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3070 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3071 mPointerGesture.currentGestureProperties[0].clear();
3072 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003073 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003074 mPointerGesture.currentGestureCoords[0].clear();
3075 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3076 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3077 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3078 down ? 1.0f : 0.0f);
3079
3080 if (lastFingerCount == 0 && currentFingerCount != 0) {
3081 mPointerGesture.resetTap();
3082 mPointerGesture.tapDownTime = when;
3083 mPointerGesture.tapX = x;
3084 mPointerGesture.tapY = y;
3085 }
3086 } else {
3087 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003088 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003089 }
3090
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003091 if (DEBUG_GESTURES) {
3092 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3093 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3094 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3095 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3096 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3097 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3098 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3099 uint32_t id = idBits.clearFirstMarkedBit();
3100 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3101 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3102 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003103 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003104 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003105 id, index, ftl::enum_string(properties.toolType).c_str(),
3106 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003107 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3108 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3109 }
3110 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3111 uint32_t id = idBits.clearFirstMarkedBit();
3112 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3113 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3114 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003115 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003116 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003117 id, index, ftl::enum_string(properties.toolType).c_str(),
3118 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003119 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3120 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3121 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003122 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003123 return true;
3124}
3125
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003126bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3127 if (mPointerGesture.activeTouchId < 0) {
3128 mPointerGesture.resetQuietTime();
3129 return false;
3130 }
3131
3132 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3133 return true;
3134 }
3135
3136 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3137 bool isQuietTime = false;
3138 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3139 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3140 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3141 currentFingerCount < 2) {
3142 // Enter quiet time when exiting swipe or freeform state.
3143 // This is to prevent accidentally entering the hover state and flinging the
3144 // pointer when finishing a swipe and there is still one pointer left onscreen.
3145 isQuietTime = true;
3146 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3147 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3148 // Enter quiet time when releasing the button and there are still two or more
3149 // fingers down. This may indicate that one finger was used to press the button
3150 // but it has not gone up yet.
3151 isQuietTime = true;
3152 }
3153 if (isQuietTime) {
3154 mPointerGesture.quietTime = when;
3155 }
3156 return isQuietTime;
3157}
3158
3159std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3160 int32_t bestId = -1;
3161 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3162 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3163 uint32_t id = idBits.clearFirstMarkedBit();
3164 std::optional<float> vx =
3165 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3166 std::optional<float> vy =
3167 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3168 if (vx && vy) {
3169 float speed = hypotf(*vx, *vy);
3170 if (speed > bestSpeed) {
3171 bestId = id;
3172 bestSpeed = speed;
3173 }
3174 }
3175 }
3176 return std::make_pair(bestId, bestSpeed);
3177}
3178
3179void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3180 bool* finishPreviousGesture) {
3181 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3182 // to move before deciding what to do.
3183 //
3184 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3185 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3186 // just a press or long-press at the pointer location.
3187 //
3188 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3189 // pointer location.
3190 //
3191 // When the two fingers move enough or when additional fingers are added, we make a decision to
3192 // transition into SWIPE or FREEFORM mode accordingly.
3193 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3194 ALOG_ASSERT(activeTouchId >= 0);
3195
3196 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3197 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3198 bool settled =
3199 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3200 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3201 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3202 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3203 *finishPreviousGesture = true;
3204 } else if (!settled && currentFingerCount > lastFingerCount) {
3205 // Additional pointers have gone down but not yet settled.
3206 // Reset the gesture.
3207 ALOGD_IF(DEBUG_GESTURES,
3208 "Gestures: Resetting gesture since additional pointers went down for "
3209 "MULTITOUCH, settle time remaining %0.3fms",
3210 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3211 when) * 0.000001f);
3212 *cancelPreviousGesture = true;
3213 } else {
3214 // Continue previous gesture.
3215 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3216 }
3217
3218 if (*finishPreviousGesture || *cancelPreviousGesture) {
3219 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3220 mPointerGesture.activeGestureId = 0;
3221 mPointerGesture.referenceIdBits.clear();
3222 mPointerVelocityControl.reset();
3223
3224 // Use the centroid and pointer location as the reference points for the gesture.
3225 ALOGD_IF(DEBUG_GESTURES,
3226 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3227 "%0.3fms",
3228 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3229 when) * 0.000001f);
3230 mCurrentRawState.rawPointerData
3231 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3232 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003233 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3234 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003235 }
3236
3237 // Clear the reference deltas for fingers not yet included in the reference calculation.
3238 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3239 ~mPointerGesture.referenceIdBits.value);
3240 !idBits.isEmpty();) {
3241 uint32_t id = idBits.clearFirstMarkedBit();
3242 mPointerGesture.referenceDeltas[id].dx = 0;
3243 mPointerGesture.referenceDeltas[id].dy = 0;
3244 }
3245 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3246
3247 // Add delta for all fingers and calculate a common movement delta.
3248 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3249 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3250 mCurrentCookedState.fingerIdBits.value);
3251 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3252 bool first = (idBits == commonIdBits);
3253 uint32_t id = idBits.clearFirstMarkedBit();
3254 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3255 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3256 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3257 delta.dx += cpd.x - lpd.x;
3258 delta.dy += cpd.y - lpd.y;
3259
3260 if (first) {
3261 commonDeltaRawX = delta.dx;
3262 commonDeltaRawY = delta.dy;
3263 } else {
3264 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3265 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3266 }
3267 }
3268
3269 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3270 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3271 float dist[MAX_POINTER_ID + 1];
3272 int32_t distOverThreshold = 0;
3273 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3274 uint32_t id = idBits.clearFirstMarkedBit();
3275 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3276 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3277 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3278 distOverThreshold += 1;
3279 }
3280 }
3281
3282 // Only transition when at least two pointers have moved further than
3283 // the minimum distance threshold.
3284 if (distOverThreshold >= 2) {
3285 if (currentFingerCount > 2) {
3286 // There are more than two pointers, switch to FREEFORM.
3287 ALOGD_IF(DEBUG_GESTURES,
3288 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3289 currentFingerCount);
3290 *cancelPreviousGesture = true;
3291 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3292 } else {
3293 // There are exactly two pointers.
3294 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3295 uint32_t id1 = idBits.clearFirstMarkedBit();
3296 uint32_t id2 = idBits.firstMarkedBit();
3297 const RawPointerData::Pointer& p1 =
3298 mCurrentRawState.rawPointerData.pointerForId(id1);
3299 const RawPointerData::Pointer& p2 =
3300 mCurrentRawState.rawPointerData.pointerForId(id2);
3301 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3302 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3303 // There are two pointers but they are too far apart for a SWIPE,
3304 // switch to FREEFORM.
3305 ALOGD_IF(DEBUG_GESTURES,
3306 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3307 mutualDistance, mPointerGestureMaxSwipeWidth);
3308 *cancelPreviousGesture = true;
3309 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3310 } else {
3311 // There are two pointers. Wait for both pointers to start moving
3312 // before deciding whether this is a SWIPE or FREEFORM gesture.
3313 float dist1 = dist[id1];
3314 float dist2 = dist[id2];
3315 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3316 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3317 // Calculate the dot product of the displacement vectors.
3318 // When the vectors are oriented in approximately the same direction,
3319 // the angle betweeen them is near zero and the cosine of the angle
3320 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3321 // mag(v2).
3322 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3323 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3324 float dx1 = delta1.dx * mPointerXZoomScale;
3325 float dy1 = delta1.dy * mPointerYZoomScale;
3326 float dx2 = delta2.dx * mPointerXZoomScale;
3327 float dy2 = delta2.dy * mPointerYZoomScale;
3328 float dot = dx1 * dx2 + dy1 * dy2;
3329 float cosine = dot / (dist1 * dist2); // denominator always > 0
3330 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3331 // Pointers are moving in the same direction. Switch to SWIPE.
3332 ALOGD_IF(DEBUG_GESTURES,
3333 "Gestures: PRESS transitioned to SWIPE, "
3334 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3335 "cosine %0.3f >= %0.3f",
3336 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3337 mConfig.pointerGestureMultitouchMinDistance, cosine,
3338 mConfig.pointerGestureSwipeTransitionAngleCosine);
3339 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3340 } else {
3341 // Pointers are moving in different directions. Switch to FREEFORM.
3342 ALOGD_IF(DEBUG_GESTURES,
3343 "Gestures: PRESS transitioned to FREEFORM, "
3344 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3345 "cosine %0.3f < %0.3f",
3346 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3347 mConfig.pointerGestureMultitouchMinDistance, cosine,
3348 mConfig.pointerGestureSwipeTransitionAngleCosine);
3349 *cancelPreviousGesture = true;
3350 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3351 }
3352 }
3353 }
3354 }
3355 }
3356 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3357 // Switch from SWIPE to FREEFORM if additional pointers go down.
3358 // Cancel previous gesture.
3359 if (currentFingerCount > 2) {
3360 ALOGD_IF(DEBUG_GESTURES,
3361 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3362 currentFingerCount);
3363 *cancelPreviousGesture = true;
3364 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3365 }
3366 }
3367
3368 // Move the reference points based on the overall group motion of the fingers
3369 // except in PRESS mode while waiting for a transition to occur.
3370 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3371 (commonDeltaRawX || commonDeltaRawY)) {
3372 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3373 uint32_t id = idBits.clearFirstMarkedBit();
3374 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3375 delta.dx = 0;
3376 delta.dy = 0;
3377 }
3378
3379 mPointerGesture.referenceTouchX += commonDeltaRawX;
3380 mPointerGesture.referenceTouchY += commonDeltaRawY;
3381
3382 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3383 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3384
3385 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3386 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3387
3388 mPointerGesture.referenceGestureX += commonDeltaX;
3389 mPointerGesture.referenceGestureY += commonDeltaY;
3390 }
3391
3392 // Report gestures.
3393 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3394 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3395 // PRESS or SWIPE mode.
3396 ALOGD_IF(DEBUG_GESTURES,
3397 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3398 "currentTouchPointerCount=%d",
3399 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3400 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3401
3402 mPointerGesture.currentGestureIdBits.clear();
3403 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3404 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3405 mPointerGesture.currentGestureProperties[0].clear();
3406 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003407 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003408 mPointerGesture.currentGestureCoords[0].clear();
3409 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3410 mPointerGesture.referenceGestureX);
3411 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3412 mPointerGesture.referenceGestureY);
3413 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3414 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3415 float xOffset = static_cast<float>(commonDeltaRawX) /
3416 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3417 float yOffset = static_cast<float>(commonDeltaRawY) /
3418 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3419 mPointerGesture.currentGestureCoords[0]
3420 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3421 mPointerGesture.currentGestureCoords[0]
3422 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3423 }
3424 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3425 // FREEFORM mode.
3426 ALOGD_IF(DEBUG_GESTURES,
3427 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3428 "currentTouchPointerCount=%d",
3429 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3430 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3431
3432 mPointerGesture.currentGestureIdBits.clear();
3433
3434 BitSet32 mappedTouchIdBits;
3435 BitSet32 usedGestureIdBits;
3436 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3437 // Initially, assign the active gesture id to the active touch point
3438 // if there is one. No other touch id bits are mapped yet.
3439 if (!*cancelPreviousGesture) {
3440 mappedTouchIdBits.markBit(activeTouchId);
3441 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3442 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3443 mPointerGesture.activeGestureId;
3444 } else {
3445 mPointerGesture.activeGestureId = -1;
3446 }
3447 } else {
3448 // Otherwise, assume we mapped all touches from the previous frame.
3449 // Reuse all mappings that are still applicable.
3450 mappedTouchIdBits.value =
3451 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3452 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3453
3454 // Check whether we need to choose a new active gesture id because the
3455 // current went went up.
3456 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3457 ~mCurrentCookedState.fingerIdBits.value);
3458 !upTouchIdBits.isEmpty();) {
3459 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3460 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3461 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3462 mPointerGesture.activeGestureId = -1;
3463 break;
3464 }
3465 }
3466 }
3467
3468 ALOGD_IF(DEBUG_GESTURES,
3469 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3470 "activeGestureId=%d",
3471 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3472
3473 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3474 for (uint32_t i = 0; i < currentFingerCount; i++) {
3475 uint32_t touchId = idBits.clearFirstMarkedBit();
3476 uint32_t gestureId;
3477 if (!mappedTouchIdBits.hasBit(touchId)) {
3478 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3479 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3480 ALOGD_IF(DEBUG_GESTURES,
3481 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3482 gestureId);
3483 } else {
3484 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3485 ALOGD_IF(DEBUG_GESTURES,
3486 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3487 touchId, gestureId);
3488 }
3489 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3490 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3491
3492 const RawPointerData::Pointer& pointer =
3493 mCurrentRawState.rawPointerData.pointerForId(touchId);
3494 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3495 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3496 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3497
3498 mPointerGesture.currentGestureProperties[i].clear();
3499 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003500 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003501 mPointerGesture.currentGestureCoords[i].clear();
3502 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3503 mPointerGesture.referenceGestureX +
3504 deltaX);
3505 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3506 mPointerGesture.referenceGestureY +
3507 deltaY);
3508 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3509 }
3510
3511 if (mPointerGesture.activeGestureId < 0) {
3512 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3513 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3514 mPointerGesture.activeGestureId);
3515 }
3516 }
3517}
3518
Harry Cutts714d1ad2022-08-24 16:36:43 +00003519void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3520 const RawPointerData::Pointer& currentPointer =
3521 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3522 const RawPointerData::Pointer& lastPointer =
3523 mLastRawState.rawPointerData.pointerForId(pointerId);
3524 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3525 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3526
3527 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3528 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3529
3530 mPointerController->move(deltaX, deltaY);
3531}
3532
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003533std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3534 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003535 mPointerSimple.currentCoords.clear();
3536 mPointerSimple.currentProperties.clear();
3537
3538 bool down, hovering;
3539 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3540 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3541 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003542 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3543 down = !hovering;
3544
Prabir Pradhane71e5702023-03-29 14:51:38 +00003545 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3546 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3547 // Styluses are configured specifically for one display. We only update the
3548 // PointerController for this stylus if the PointerController is configured for
3549 // the same display as this stylus,
3550 if (getAssociatedDisplayId() == mViewport.displayId) {
3551 mPointerController->setPosition(x, y);
3552 std::tie(x, y) = mPointerController->getPosition();
3553 }
3554
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003555 mPointerSimple.currentCoords = mCurrentCookedState.cookedPointerData.pointerCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003556 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3557 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3558 mPointerSimple.currentProperties.id = 0;
3559 mPointerSimple.currentProperties.toolType =
3560 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3561 } else {
3562 down = false;
3563 hovering = false;
3564 }
3565
Prabir Pradhane71e5702023-03-29 14:51:38 +00003566 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003567}
3568
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003569std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3570 uint32_t policyFlags) {
3571 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003572}
3573
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003574std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3575 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003576 mPointerSimple.currentCoords.clear();
3577 mPointerSimple.currentProperties.clear();
3578
3579 bool down, hovering;
3580 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3581 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003582 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003583 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003584 } else {
3585 mPointerVelocityControl.reset();
3586 }
3587
3588 down = isPointerDown(mCurrentRawState.buttonState);
3589 hovering = !down;
3590
Prabir Pradhan2719e822023-02-28 17:39:36 +00003591 const auto [x, y] = mPointerController->getPosition();
3592 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003593 mPointerSimple.currentCoords =
3594 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003595 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3596 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3597 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3598 hovering ? 0.0f : 1.0f);
3599 mPointerSimple.currentProperties.id = 0;
3600 mPointerSimple.currentProperties.toolType =
3601 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3602 } else {
3603 mPointerVelocityControl.reset();
3604
3605 down = false;
3606 hovering = false;
3607 }
3608
Prabir Pradhane71e5702023-03-29 14:51:38 +00003609 const int32_t displayId = mPointerController->getDisplayId();
3610 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003611}
3612
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003613std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3614 uint32_t policyFlags) {
3615 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003616
3617 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003618
3619 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003620}
3621
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003622std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3623 uint32_t policyFlags, bool down,
Prabir Pradhane71e5702023-03-29 14:51:38 +00003624 bool hovering, int32_t displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003625 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3626 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003627 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003628 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003629 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003630
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003631 if (displayId == mPointerController->getDisplayId()) {
3632 std::tie(cursorPosition.x, cursorPosition.y) = mPointerController->getPosition();
3633 if (down || hovering) {
3634 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
3635 mPointerController->clearSpots();
3636 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3637 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
3638 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3639 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003640 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003641
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003642 if (mPointerSimple.down && !down) {
3643 mPointerSimple.down = false;
3644
3645 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003646 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3647 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3648 0, metaState, mLastRawState.buttonState,
3649 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3650 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003651 mOrientedXPrecision, mOrientedYPrecision,
3652 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3653 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003654 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003655 }
3656
3657 if (mPointerSimple.hovering && !hovering) {
3658 mPointerSimple.hovering = false;
3659
3660 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003661 out.push_back(
3662 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3663 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3664 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3665 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3666 &mPointerSimple.lastCoords, mOrientedXPrecision,
3667 mOrientedYPrecision, mPointerSimple.lastCursorX,
3668 mPointerSimple.lastCursorY, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003669 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003670 }
3671
3672 if (down) {
3673 if (!mPointerSimple.down) {
3674 mPointerSimple.down = true;
3675 mPointerSimple.downTime = when;
3676
3677 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003678 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3679 mSource, displayId, policyFlags,
3680 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3681 mCurrentRawState.buttonState, MotionClassification::NONE,
3682 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3683 &mPointerSimple.currentProperties,
3684 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003685 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003686 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003687 }
3688
3689 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003690 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3691 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3692 0, 0, metaState, mCurrentRawState.buttonState,
3693 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3694 &mPointerSimple.currentProperties,
3695 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003696 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003697 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003698 }
3699
3700 if (hovering) {
3701 if (!mPointerSimple.hovering) {
3702 mPointerSimple.hovering = true;
3703
3704 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003705 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3706 mSource, displayId, policyFlags,
3707 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3708 mCurrentRawState.buttonState, MotionClassification::NONE,
3709 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3710 &mPointerSimple.currentProperties,
3711 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003712 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003713 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003714 }
3715
3716 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003717 out.push_back(
3718 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3719 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3720 metaState, mCurrentRawState.buttonState,
3721 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3722 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003723 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003724 cursorPosition.y, mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003725 }
3726
3727 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3728 float vscroll = mCurrentRawState.rawVScroll;
3729 float hscroll = mCurrentRawState.rawHScroll;
3730 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3731 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3732
3733 // Send scroll.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003734 PointerCoords pointerCoords = mPointerSimple.currentCoords;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003735 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3736 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3737
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003738 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3739 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3740 0, 0, metaState, mCurrentRawState.buttonState,
3741 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3742 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003743 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3744 cursorPosition.y, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003745 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003746 }
3747
3748 // Save state.
3749 if (down || hovering) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003750 mPointerSimple.lastCoords = mPointerSimple.currentCoords;
3751 mPointerSimple.lastProperties = mPointerSimple.currentProperties;
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003752 mPointerSimple.displayId = displayId;
3753 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003754 mPointerSimple.lastCursorX = cursorPosition.x;
3755 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003756 } else {
3757 mPointerSimple.reset();
3758 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003759 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003760}
3761
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003762std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3763 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003764 std::list<NotifyArgs> out;
3765 if (mPointerSimple.down || mPointerSimple.hovering) {
3766 int32_t metaState = getContext()->getGlobalMetaState();
3767 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3768 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3769 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3770 metaState, mLastRawState.buttonState,
3771 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3772 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3773 mOrientedXPrecision, mOrientedYPrecision,
3774 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3775 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003776 /*videoFrames=*/{}));
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003777 if (mPointerController != nullptr) {
3778 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3779 }
3780 }
3781 mPointerSimple.reset();
3782 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003783}
3784
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003785NotifyMotionArgs TouchInputMapper::dispatchMotion(
3786 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3787 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003788 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3789 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003790 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003791 std::vector<PointerCoords> pointerCoords;
3792 std::vector<PointerProperties> pointerProperties;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003793 uint32_t pointerCount = 0;
3794 while (!idBits.isEmpty()) {
3795 uint32_t id = idBits.clearFirstMarkedBit();
3796 uint32_t index = idToIndex[id];
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003797 pointerProperties.push_back(properties[index]);
3798 pointerCoords.push_back(coords[index]);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003799
3800 if (changedId >= 0 && id == uint32_t(changedId)) {
3801 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3802 }
3803
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003804 pointerCount++;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003805 }
3806
3807 ALOG_ASSERT(pointerCount != 0);
3808
3809 if (changedId >= 0 && pointerCount == 1) {
3810 // Replace initial down and final up action.
3811 // We can compare the action without masking off the changed pointer index
3812 // because we know the index is 0.
3813 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3814 action = AMOTION_EVENT_ACTION_DOWN;
3815 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003816 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3817 action = AMOTION_EVENT_ACTION_CANCEL;
3818 } else {
3819 action = AMOTION_EVENT_ACTION_UP;
3820 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003821 } else {
3822 // Can't happen.
3823 ALOG_ASSERT(false);
3824 }
3825 }
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00003826 if (mCurrentStreamModifiedByExternalStylus) {
3827 source |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3828 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003829
3830 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3831 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003832 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003833 mPointerController && displayId != ADISPLAY_ID_NONE &&
3834 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003835 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003836 switch (action & AMOTION_EVENT_ACTION_MASK) {
3837 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3838 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3839 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003840 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003841 mPointerController
3842 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3843 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3844 .getY());
3845 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3846 break;
3847 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3848 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3849 break;
3850 }
3851 }
3852
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003853 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3854 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003855 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003856 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003857 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003858 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003859 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003860 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003861 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003862 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3863 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003864 classification, edgeFlags, pointerCount, pointerProperties.data(),
3865 pointerCoords.data(), xPrecision, yPrecision, xCursorPosition,
3866 yCursorPosition, downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003867}
3868
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003869std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3870 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003871 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3872 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003873 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003874}
3875
Prabir Pradhan1728b212021-10-19 16:00:03 -07003876bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003877 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003878 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003879 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003880}
3881
3882const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3883 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003884 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3885 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3886 "left=%d, top=%d, right=%d, bottom=%d",
3887 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3888 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003889
3890 if (virtualKey.isHit(x, y)) {
3891 return &virtualKey;
3892 }
3893 }
3894
3895 return nullptr;
3896}
3897
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003898void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3899 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3900 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003901
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003902 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003903
3904 if (currentPointerCount == 0) {
3905 // No pointers to assign.
3906 return;
3907 }
3908
3909 if (lastPointerCount == 0) {
3910 // All pointers are new.
3911 for (uint32_t i = 0; i < currentPointerCount; i++) {
3912 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003913 current.rawPointerData.pointers[i].id = id;
3914 current.rawPointerData.idToIndex[id] = i;
3915 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003916 }
3917 return;
3918 }
3919
3920 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003921 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003922 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003923 uint32_t id = last.rawPointerData.pointers[0].id;
3924 current.rawPointerData.pointers[0].id = id;
3925 current.rawPointerData.idToIndex[id] = 0;
3926 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003927 return;
3928 }
3929
3930 // General case.
3931 // We build a heap of squared euclidean distances between current and last pointers
3932 // associated with the current and last pointer indices. Then, we find the best
3933 // match (by distance) for each current pointer.
3934 // The pointers must have the same tool type but it is possible for them to
3935 // transition from hovering to touching or vice-versa while retaining the same id.
3936 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3937
3938 uint32_t heapSize = 0;
3939 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3940 currentPointerIndex++) {
3941 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3942 lastPointerIndex++) {
3943 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003944 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003945 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003946 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003947 if (currentPointer.toolType == lastPointer.toolType) {
3948 int64_t deltaX = currentPointer.x - lastPointer.x;
3949 int64_t deltaY = currentPointer.y - lastPointer.y;
3950
3951 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3952
3953 // Insert new element into the heap (sift up).
3954 heap[heapSize].currentPointerIndex = currentPointerIndex;
3955 heap[heapSize].lastPointerIndex = lastPointerIndex;
3956 heap[heapSize].distance = distance;
3957 heapSize += 1;
3958 }
3959 }
3960 }
3961
3962 // Heapify
3963 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3964 startIndex -= 1;
3965 for (uint32_t parentIndex = startIndex;;) {
3966 uint32_t childIndex = parentIndex * 2 + 1;
3967 if (childIndex >= heapSize) {
3968 break;
3969 }
3970
3971 if (childIndex + 1 < heapSize &&
3972 heap[childIndex + 1].distance < heap[childIndex].distance) {
3973 childIndex += 1;
3974 }
3975
3976 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3977 break;
3978 }
3979
3980 swap(heap[parentIndex], heap[childIndex]);
3981 parentIndex = childIndex;
3982 }
3983 }
3984
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003985 if (DEBUG_POINTER_ASSIGNMENT) {
3986 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3987 for (size_t i = 0; i < heapSize; i++) {
3988 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3989 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3990 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003991 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003992
3993 // Pull matches out by increasing order of distance.
3994 // To avoid reassigning pointers that have already been matched, the loop keeps track
3995 // of which last and current pointers have been matched using the matchedXXXBits variables.
3996 // It also tracks the used pointer id bits.
3997 BitSet32 matchedLastBits(0);
3998 BitSet32 matchedCurrentBits(0);
3999 BitSet32 usedIdBits(0);
4000 bool first = true;
4001 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
4002 while (heapSize > 0) {
4003 if (first) {
4004 // The first time through the loop, we just consume the root element of
4005 // the heap (the one with smallest distance).
4006 first = false;
4007 } else {
4008 // Previous iterations consumed the root element of the heap.
4009 // Pop root element off of the heap (sift down).
4010 heap[0] = heap[heapSize];
4011 for (uint32_t parentIndex = 0;;) {
4012 uint32_t childIndex = parentIndex * 2 + 1;
4013 if (childIndex >= heapSize) {
4014 break;
4015 }
4016
4017 if (childIndex + 1 < heapSize &&
4018 heap[childIndex + 1].distance < heap[childIndex].distance) {
4019 childIndex += 1;
4020 }
4021
4022 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4023 break;
4024 }
4025
4026 swap(heap[parentIndex], heap[childIndex]);
4027 parentIndex = childIndex;
4028 }
4029
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004030 if (DEBUG_POINTER_ASSIGNMENT) {
4031 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4032 for (size_t j = 0; j < heapSize; j++) {
4033 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4034 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4035 heap[j].distance);
4036 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004037 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004038 }
4039
4040 heapSize -= 1;
4041
4042 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4043 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4044
4045 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4046 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4047
4048 matchedCurrentBits.markBit(currentPointerIndex);
4049 matchedLastBits.markBit(lastPointerIndex);
4050
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004051 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4052 current.rawPointerData.pointers[currentPointerIndex].id = id;
4053 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4054 current.rawPointerData.markIdBit(id,
4055 current.rawPointerData.isHovering(
4056 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004057 usedIdBits.markBit(id);
4058
Harry Cutts45483602022-08-24 14:36:48 +00004059 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4060 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4061 ", distance=%" PRIu64,
4062 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004063 break;
4064 }
4065 }
4066
4067 // Assign fresh ids to pointers that were not matched in the process.
4068 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4069 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4070 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4071
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004072 current.rawPointerData.pointers[currentPointerIndex].id = id;
4073 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4074 current.rawPointerData.markIdBit(id,
4075 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004076
Harry Cutts45483602022-08-24 14:36:48 +00004077 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4078 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4079 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004080 }
4081}
4082
4083int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4084 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4085 return AKEY_STATE_VIRTUAL;
4086 }
4087
4088 for (const VirtualKey& virtualKey : mVirtualKeys) {
4089 if (virtualKey.keyCode == keyCode) {
4090 return AKEY_STATE_UP;
4091 }
4092 }
4093
4094 return AKEY_STATE_UNKNOWN;
4095}
4096
4097int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4098 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4099 return AKEY_STATE_VIRTUAL;
4100 }
4101
4102 for (const VirtualKey& virtualKey : mVirtualKeys) {
4103 if (virtualKey.scanCode == scanCode) {
4104 return AKEY_STATE_UP;
4105 }
4106 }
4107
4108 return AKEY_STATE_UNKNOWN;
4109}
4110
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004111bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4112 const std::vector<int32_t>& keyCodes,
4113 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004114 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004115 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004116 if (virtualKey.keyCode == keyCodes[i]) {
4117 outFlags[i] = 1;
4118 }
4119 }
4120 }
4121
4122 return true;
4123}
4124
4125std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4126 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004127 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004128 return std::make_optional(mPointerController->getDisplayId());
4129 } else {
4130 return std::make_optional(mViewport.displayId);
4131 }
4132 }
4133 return std::nullopt;
4134}
4135
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004136} // namespace android