blob: 82d816c30ba1566b42f9137060b1423f6db195ad [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
Michael Crimandob12a7492023-05-22 11:01:17 -0400539 const std::optional<std::string> associatedDisplayUniqueIdByDescriptor =
540 getDeviceContext().getAssociatedDisplayUniqueIdByDescriptor();
541 if (associatedDisplayUniqueIdByDescriptor) {
542 return getDeviceContext().getAssociatedViewport();
543 }
544
545 const std::optional<std::string> associatedDisplayUniqueIdByPort =
546 getDeviceContext().getAssociatedDisplayUniqueIdByPort();
547 if (associatedDisplayUniqueIdByPort) {
Christine Franks2a2293c2022-01-18 11:51:16 -0800548 return getDeviceContext().getAssociatedViewport();
549 }
550
Michael Wright227c5542020-07-02 18:30:52 +0100551 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800552 std::optional<DisplayViewport> viewport =
553 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
554 if (viewport) {
555 return viewport;
556 } else {
557 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
558 mConfig.defaultPointerDisplayId);
559 }
560 }
561
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700562 // Check if uniqueDisplayId is specified in idc file.
563 if (!mParameters.uniqueDisplayId.empty()) {
564 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
565 }
566
567 ViewportType viewportTypeToUse;
568 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100569 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700570 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100571 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700572 }
573
574 std::optional<DisplayViewport> viewport =
575 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100576 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700577 ALOGW("Input device %s should be associated with external display, "
578 "fallback to internal one for the external viewport is not found.",
579 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100580 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700581 }
582
583 return viewport;
584 }
585
586 // No associated display, return a non-display viewport.
587 DisplayViewport newViewport;
588 // Raw width and height in the natural orientation.
589 int32_t rawWidth = mRawPointerAxes.getRawWidth();
590 int32_t rawHeight = mRawPointerAxes.getRawHeight();
591 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
592 return std::make_optional(newViewport);
593}
594
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800595int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
596 if (resolution < 0) {
597 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
598 getDeviceName().c_str());
599 return 0;
600 }
601 return resolution;
602}
603
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800604void TouchInputMapper::initializeSizeRanges() {
605 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
606 mSizeScale = 0.0f;
607 return;
608 }
609
610 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000611 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800612
613 // Size factors.
614 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
615 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
616 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
617 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
618 } else {
619 mSizeScale = 0.0f;
620 }
621
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700622 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
623 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
624 .source = mSource,
625 .min = 0,
626 .max = diagonalSize,
627 .flat = 0,
628 .fuzz = 0,
629 .resolution = 0,
630 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800631
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800632 if (mRawPointerAxes.touchMajor.valid) {
633 mRawPointerAxes.touchMajor.resolution =
634 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700635 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800636 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800637
638 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700639 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800640 if (mRawPointerAxes.touchMinor.valid) {
641 mRawPointerAxes.touchMinor.resolution =
642 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700643 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800644 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800645
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700646 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
647 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
648 .source = mSource,
649 .min = 0,
650 .max = diagonalSize,
651 .flat = 0,
652 .fuzz = 0,
653 .resolution = 0,
654 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800655 if (mRawPointerAxes.toolMajor.valid) {
656 mRawPointerAxes.toolMajor.resolution =
657 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700658 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800659 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800660
661 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700662 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800663 if (mRawPointerAxes.toolMinor.valid) {
664 mRawPointerAxes.toolMinor.resolution =
665 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700666 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800667 }
668
669 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700670 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
671 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
672 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
673 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800674 } else {
675 // Support for other calibrations can be added here.
676 ALOGW("%s calibration is not supported for size ranges at the moment. "
677 "Using raw resolution instead",
678 ftl::enum_string(mCalibration.sizeCalibration).c_str());
679 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800680
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700681 mOrientedRanges.size = InputDeviceInfo::MotionRange{
682 .axis = AMOTION_EVENT_AXIS_SIZE,
683 .source = mSource,
684 .min = 0,
685 .max = 1.0,
686 .flat = 0,
687 .fuzz = 0,
688 .resolution = 0,
689 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800690}
691
692void TouchInputMapper::initializeOrientedRanges() {
693 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000694 const float orientedScaleX = mRawToDisplay.getScaleX();
695 const float orientedScaleY = mRawToDisplay.getScaleY();
696 mOrientedXPrecision = 1.0f / orientedScaleX;
697 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800698
699 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
700 mOrientedRanges.x.source = mSource;
701 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
702 mOrientedRanges.y.source = mSource;
703
704 // Scale factor for terms that are not oriented in a particular axis.
705 // If the pixels are square then xScale == yScale otherwise we fake it
706 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000707 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800708
709 initializeSizeRanges();
710
711 // Pressure factors.
712 mPressureScale = 0;
713 float pressureMax = 1.0;
714 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
715 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700716 if (mCalibration.pressureScale) {
717 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800718 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
719 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
720 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
721 }
722 }
723
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700724 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
725 .axis = AMOTION_EVENT_AXIS_PRESSURE,
726 .source = mSource,
727 .min = 0,
728 .max = pressureMax,
729 .flat = 0,
730 .fuzz = 0,
731 .resolution = 0,
732 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800733
734 // Tilt
735 mTiltXCenter = 0;
736 mTiltXScale = 0;
737 mTiltYCenter = 0;
738 mTiltYScale = 0;
739 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
740 if (mHaveTilt) {
741 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
742 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
743 mTiltXScale = M_PI / 180;
744 mTiltYScale = M_PI / 180;
745
746 if (mRawPointerAxes.tiltX.resolution) {
747 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
748 }
749 if (mRawPointerAxes.tiltY.resolution) {
750 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
751 }
752
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700753 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
754 .axis = AMOTION_EVENT_AXIS_TILT,
755 .source = mSource,
756 .min = 0,
757 .max = M_PI_2,
758 .flat = 0,
759 .fuzz = 0,
760 .resolution = 0,
761 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800762 }
763
764 // Orientation
765 mOrientationScale = 0;
766 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700767 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
768 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
769 .source = mSource,
770 .min = -M_PI,
771 .max = M_PI,
772 .flat = 0,
773 .fuzz = 0,
774 .resolution = 0,
775 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800776
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800777 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
778 if (mCalibration.orientationCalibration ==
779 Calibration::OrientationCalibration::INTERPOLATED) {
780 if (mRawPointerAxes.orientation.valid) {
781 if (mRawPointerAxes.orientation.maxValue > 0) {
782 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
783 } else if (mRawPointerAxes.orientation.minValue < 0) {
784 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
785 } else {
786 mOrientationScale = 0;
787 }
788 }
789 }
790
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700791 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
792 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
793 .source = mSource,
794 .min = -M_PI_2,
795 .max = M_PI_2,
796 .flat = 0,
797 .fuzz = 0,
798 .resolution = 0,
799 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800800 }
801
802 // Distance
803 mDistanceScale = 0;
804 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
805 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700806 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800807 }
808
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700809 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800810
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700811 .axis = AMOTION_EVENT_AXIS_DISTANCE,
812 .source = mSource,
813 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
814 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
815 .flat = 0,
816 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
817 .resolution = 0,
818 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800819 }
820
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000821 // Oriented X/Y range (in the rotated display's orientation)
822 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
823 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
824 .toFloatRect();
825 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
826 mOrientedRanges.x.min = orientedRangeRect.left;
827 mOrientedRanges.y.min = orientedRangeRect.top;
828 mOrientedRanges.x.max = orientedRangeRect.right;
829 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800830
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000831 // Oriented flat (in the rotated display's orientation)
832 const auto orientedFlat =
833 transformWithoutTranslation(mRawToRotatedDisplay,
834 {static_cast<float>(mRawPointerAxes.x.flat),
835 static_cast<float>(mRawPointerAxes.y.flat)});
836 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
837 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800838
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000839 // Oriented fuzz (in the rotated display's orientation)
840 const auto orientedFuzz =
841 transformWithoutTranslation(mRawToRotatedDisplay,
842 {static_cast<float>(mRawPointerAxes.x.fuzz),
843 static_cast<float>(mRawPointerAxes.y.fuzz)});
844 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
845 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800846
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000847 // Oriented resolution (in the rotated display's orientation)
848 const auto orientedRes =
849 transformWithoutTranslation(mRawToRotatedDisplay,
850 {static_cast<float>(mRawPointerAxes.x.resolution),
851 static_cast<float>(mRawPointerAxes.y.resolution)});
852 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
853 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800854}
855
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000856void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000857 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
858 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
859 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000860
Prabir Pradhan3e798762022-12-02 21:02:11 +0000861 // See notes about input coordinates in the inputflinger docs:
862 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000863
864 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000865 ui::Transform undoOffsetInRaw;
866 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000867
Prabir Pradhan3e798762022-12-02 21:02:11 +0000868 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
869 // will now be in the same orientation as the display in ROTATION_0.
870 // Note: Negating an ui::Rotation value will give its inverse rotation.
871 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
872 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
873 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
874 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
875 // When rotating raw values, account for the extra unit added when calculating the raw range.
876 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
877 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000878
Prabir Pradhan3e798762022-12-02 21:02:11 +0000879 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
880 // now be in the same orientation as the rotated display. There is no need to rotate the
881 // coordinates to the display rotation if the device is not orientation-aware.
882 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
883 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
884 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
885 : orientedRawSize;
886 // When rotating raw values, account for the extra unit added when calculating the raw range.
887 const auto rotateInRaw = mParameters.orientationAware
888 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
889 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000890
Prabir Pradhan3e798762022-12-02 21:02:11 +0000891 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000892 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
893 // the surface of the display panel. This is usually true for touchscreens.
894 // - In POINTER mode, we cannot assume that the display and the touch device have the same
895 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
896 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
897 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
898 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000899 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
900 // are in the continuous space of the logical display.
901 ui::Transform scaleRawToDisplay;
902 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
903 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000904 if (mDeviceMode == DeviceMode::DIRECT) {
905 scaleRawToDisplay.set(xScale, 0, 0, yScale);
906 } else if (mDeviceMode == DeviceMode::POINTER) {
907 const float fixedScale = std::max(xScale, yScale);
908 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
909 } else {
910 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
911 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000912
Prabir Pradhan3e798762022-12-02 21:02:11 +0000913 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
914 // that InputReader uses.
915 const auto undoRotateInDisplay =
916 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
917 .inverse();
918
919 // Now put it all together!
920 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
921 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
922 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000923}
924
Prabir Pradhan1728b212021-10-19 16:00:03 -0700925void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000926 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700927
928 resolveExternalStylusPresence();
929
930 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100931 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +0900932 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700933 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100934 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700935 if (hasStylus()) {
936 mSource |= AINPUT_SOURCE_STYLUS;
937 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800938 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700939 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100940 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700941 if (hasStylus()) {
942 mSource |= AINPUT_SOURCE_STYLUS;
943 }
Michael Wright227c5542020-07-02 18:30:52 +0100944 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700945 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100946 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700947 } else {
948 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100949 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700950 }
951
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000952 const std::optional<DisplayViewport> newViewportOpt = findViewport();
953
954 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700955 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
956 ALOGW("Touch device '%s' did not report support for X or Y axis! "
957 "The device will be inoperable.",
958 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100959 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000960 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700961 ALOGI("Touch device '%s' could not query the properties of its associated "
962 "display. The device will be inoperable until the display size "
963 "becomes available.",
964 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100965 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700966 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000967 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
968 getDeviceName().c_str(), getDeviceId());
969 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000970 }
971
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700972 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000973 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000974 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
975 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
976 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
977 const float rawMeanResolution =
978 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700979
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000980 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
Josh Thielene986aed2023-06-01 14:17:30 +0000981 bool viewportChanged;
982 if (mParameters.enableForInactiveViewport) {
983 // When touch is enabled for an inactive viewport, ignore the
984 // viewport active status when checking whether the viewport has
985 // changed.
986 DisplayViewport tempViewport = mViewport;
987 tempViewport.isActive = newViewport.isActive;
988 viewportChanged = tempViewport != newViewport;
989 } else {
990 viewportChanged = mViewport != newViewport;
991 }
992
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700993 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700994 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000995 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
996 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
997 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700998
Michael Wright227c5542020-07-02 18:30:52 +0100999 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +00001000 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001001
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001002 mDisplayBounds = getNaturalDisplaySize(mViewport);
1003 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
1004 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -07001005
Prabir Pradhan3e798762022-12-02 21:02:11 +00001006 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
1007 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
1008 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001009 // InputReader works in the un-rotated display coordinate space, so we don't need to do
1010 // anything if the device is already orientation-aware. If the device is not
1011 // orientation-aware, then we need to apply the inverse rotation of the display so that
1012 // when the display rotation is applied later as a part of the per-window transform, we
1013 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001014 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +00001015 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001016 : getInverseRotation(mViewport.orientation);
1017 // For orientation-aware devices that work in the un-rotated coordinate space, the
1018 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001019 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001020 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001021
1022 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001023 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001024 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001025 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001026 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001027 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001028 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001029 mRawToDisplay.reset();
1030 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001031 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001032 }
1033 }
1034
1035 // If moving between pointer modes, need to reset some state.
1036 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1037 if (deviceModeChanged) {
1038 mOrientedRanges.clear();
1039 }
1040
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001041 // Create and preserve the pointer controller in the following cases:
1042 const bool isPointerControllerNeeded =
1043 // - when the device is in pointer mode, to show the mouse cursor;
1044 (mDeviceMode == DeviceMode::POINTER) ||
1045 // - when pointer capture is enabled, to preserve the mouse cursor position;
1046 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +09001047 mConfig.pointerCaptureRequest.isEnable()) ||
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001048 // - when we should be showing touches;
1049 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1050 // - when we should be showing a pointer icon for direct styluses.
1051 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1052 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001053 if (mPointerController == nullptr) {
1054 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001055 }
Hiroki Sato25040232024-02-22 17:21:22 +09001056 if (mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001057 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1058 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001059 } else {
lilinnandef700b2022-06-17 19:32:01 +08001060 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1061 !mConfig.showTouches) {
1062 mPointerController->clearSpots();
1063 }
Michael Wright17db18e2020-06-26 20:51:44 +01001064 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001065 }
1066
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001067 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001068 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001069 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001070 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001071 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001072
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001073 configureVirtualKeys();
1074
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001075 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001076
1077 // Location
1078 updateAffineTransformation();
1079
Michael Wright227c5542020-07-02 18:30:52 +01001080 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001081 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001082 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1083 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001084
1085 // Scale movements such that one whole swipe of the touch pad covers a
1086 // given area relative to the diagonal size of the display when no acceleration
1087 // is applied.
1088 // Assume that the touch pad has a square aspect ratio such that movements in
1089 // X and Y of the same number of raw units cover the same physical distance.
1090 mPointerXMovementScale =
1091 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1092 mPointerYMovementScale = mPointerXMovementScale;
1093
1094 // Scale zooms to cover a smaller range of the display than movements do.
1095 // This value determines the area around the pointer that is affected by freeform
1096 // pointer gestures.
1097 mPointerXZoomScale =
1098 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1099 mPointerYZoomScale = mPointerXZoomScale;
1100
HQ Liue6983c72022-04-19 22:14:56 +00001101 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1102 // axis is non positive value.
1103 const float minFreeformGestureWidth =
1104 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1105
1106 mPointerGestureMaxSwipeWidth =
1107 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1108 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001109 }
1110
1111 // Inform the dispatcher about the changes.
1112 *outResetNeeded = true;
1113 bumpGeneration();
1114 }
1115}
1116
Prabir Pradhan1728b212021-10-19 16:00:03 -07001117void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001118 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001119 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001120 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1121 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001122 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001123}
1124
1125void TouchInputMapper::configureVirtualKeys() {
1126 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001127 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001128
1129 mVirtualKeys.clear();
1130
1131 if (virtualKeyDefinitions.size() == 0) {
1132 return;
1133 }
1134
1135 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1136 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1137 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1138 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1139
1140 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1141 VirtualKey virtualKey;
1142
1143 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1144 int32_t keyCode;
1145 int32_t dummyKeyMetaState;
1146 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001147 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1148 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1150 continue; // drop the key
1151 }
1152
1153 virtualKey.keyCode = keyCode;
1154 virtualKey.flags = flags;
1155
1156 // convert the key definition's display coordinates into touch coordinates for a hit box
1157 int32_t halfWidth = virtualKeyDefinition.width / 2;
1158 int32_t halfHeight = virtualKeyDefinition.height / 2;
1159
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001160 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1161 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001162 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001163 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1164 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001166 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1167 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001169 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1170 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 touchScreenTop;
1172 mVirtualKeys.push_back(virtualKey);
1173 }
1174}
1175
1176void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1177 if (!mVirtualKeys.empty()) {
1178 dump += INDENT3 "Virtual Keys:\n";
1179
1180 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1181 const VirtualKey& virtualKey = mVirtualKeys[i];
1182 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1183 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1184 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1185 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1186 }
1187 }
1188}
1189
1190void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001191 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 Calibration& out = mCalibration;
1193
1194 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001195 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001196 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1197 if (sizeCalibrationString.has_value()) {
1198 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001200 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001202 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001203 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001204 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001205 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001206 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001207 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001208 } else if (*sizeCalibrationString != "default") {
1209 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210 }
1211 }
1212
Harry Cuttsf13161a2023-03-08 14:15:49 +00001213 out.sizeScale = in.getFloat("touch.size.scale");
1214 out.sizeBias = in.getFloat("touch.size.bias");
1215 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216
1217 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001218 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001219 std::optional<std::string> pressureCalibrationString =
1220 in.getString("touch.pressure.calibration");
1221 if (pressureCalibrationString.has_value()) {
1222 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001223 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001224 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001225 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001226 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001227 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001228 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001230 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 }
1232 }
1233
Harry Cuttsf13161a2023-03-08 14:15:49 +00001234 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001235
1236 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001237 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001238 std::optional<std::string> orientationCalibrationString =
1239 in.getString("touch.orientation.calibration");
1240 if (orientationCalibrationString.has_value()) {
1241 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001242 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001243 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001244 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001245 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001246 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001247 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001249 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251 }
1252
1253 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001254 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001255 std::optional<std::string> distanceCalibrationString =
1256 in.getString("touch.distance.calibration");
1257 if (distanceCalibrationString.has_value()) {
1258 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001259 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001260 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001261 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001262 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001264 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 }
1266 }
1267
Harry Cuttsf13161a2023-03-08 14:15:49 +00001268 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269}
1270
1271void TouchInputMapper::resolveCalibration() {
1272 // Size
1273 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001274 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1275 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 }
1277 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001278 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 }
1280
1281 // Pressure
1282 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001283 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1284 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 }
1286 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001287 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288 }
1289
1290 // Orientation
1291 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001292 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1293 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 }
1295 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001296 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 }
1298
1299 // Distance
1300 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001301 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1302 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 }
1304 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001305 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307}
1308
1309void TouchInputMapper::dumpCalibration(std::string& dump) {
1310 dump += INDENT3 "Calibration:\n";
1311
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001312 dump += INDENT4 "touch.size.calibration: ";
1313 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001314
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001315 if (mCalibration.sizeScale) {
1316 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317 }
1318
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001319 if (mCalibration.sizeBias) {
1320 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001321 }
1322
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001323 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001325 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001326 }
1327
1328 // Pressure
1329 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.pressure.calibration: none\n";
1332 break;
Michael Wright227c5542020-07-02 18:30:52 +01001333 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.pressure.calibration: physical\n";
1335 break;
Michael Wright227c5542020-07-02 18:30:52 +01001336 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001337 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1338 break;
1339 default:
1340 ALOG_ASSERT(false);
1341 }
1342
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001343 if (mCalibration.pressureScale) {
1344 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001345 }
1346
1347 // Orientation
1348 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001349 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350 dump += INDENT4 "touch.orientation.calibration: none\n";
1351 break;
Michael Wright227c5542020-07-02 18:30:52 +01001352 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1354 break;
Michael Wright227c5542020-07-02 18:30:52 +01001355 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356 dump += INDENT4 "touch.orientation.calibration: vector\n";
1357 break;
1358 default:
1359 ALOG_ASSERT(false);
1360 }
1361
1362 // Distance
1363 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001364 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001365 dump += INDENT4 "touch.distance.calibration: none\n";
1366 break;
Michael Wright227c5542020-07-02 18:30:52 +01001367 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001368 dump += INDENT4 "touch.distance.calibration: scaled\n";
1369 break;
1370 default:
1371 ALOG_ASSERT(false);
1372 }
1373
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001374 if (mCalibration.distanceScale) {
1375 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001376 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001377}
1378
1379void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1380 dump += INDENT3 "Affine Transformation:\n";
1381
1382 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1383 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1384 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1385 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1386 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1387 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1388}
1389
1390void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001391 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001392 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001393}
1394
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001395std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001396 std::list<NotifyArgs> out = cancelTouch(when, when);
1397 updateTouchSpots();
1398
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001399 mCursorButtonAccumulator.reset(getDeviceContext());
1400 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001401 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001402
1403 mPointerVelocityControl.reset();
1404 mWheelXVelocityControl.reset();
1405 mWheelYVelocityControl.reset();
1406
1407 mRawStatesPending.clear();
1408 mCurrentRawState.clear();
1409 mCurrentCookedState.clear();
1410 mLastRawState.clear();
1411 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001412 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001413 mSentHoverEnter = false;
1414 mHavePointerIds = false;
1415 mCurrentMotionAborted = false;
1416 mDownTime = 0;
1417
1418 mCurrentVirtualKey.down = false;
1419
1420 mPointerGesture.reset();
1421 mPointerSimple.reset();
1422 resetExternalStylus();
1423
1424 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001425 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001426 mPointerController->clearSpots();
1427 }
1428
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001429 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001430}
1431
1432void TouchInputMapper::resetExternalStylus() {
1433 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001434 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001435 mExternalStylusFusionTimeout = LLONG_MAX;
1436 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001437 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001438}
1439
1440void TouchInputMapper::clearStylusDataPendingFlags() {
1441 mExternalStylusDataPending = false;
1442 mExternalStylusFusionTimeout = LLONG_MAX;
1443}
1444
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001445std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001446 mCursorButtonAccumulator.process(rawEvent);
1447 mCursorScrollAccumulator.process(rawEvent);
1448 mTouchButtonAccumulator.process(rawEvent);
1449
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001450 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001452 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001453 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001454 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455}
1456
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001457std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1458 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001459 if (mDeviceMode == DeviceMode::DISABLED) {
1460 // Only save the last pending state when the device is disabled.
1461 mRawStatesPending.clear();
1462 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001463 // Push a new state.
1464 mRawStatesPending.emplace_back();
1465
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001466 RawState& next = mRawStatesPending.back();
1467 next.clear();
1468 next.when = when;
1469 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001470
1471 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001472 next.buttonState = filterButtonState(mConfig,
1473 mTouchButtonAccumulator.getButtonState() |
1474 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001475
1476 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001477 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1478 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001479 mCursorScrollAccumulator.finishSync();
1480
1481 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001482 syncTouch(when, &next);
1483
1484 // The last RawState is the actually second to last, since we just added a new state
1485 const RawState& last =
1486 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001487
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001488 std::tie(next.when, next.readTime) =
1489 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1490 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001491
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001492 // Assign pointer ids.
1493 if (!mHavePointerIds) {
1494 assignPointerIds(last, next);
1495 }
1496
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001497 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001498 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1499 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1500 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1501 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1502 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1503 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001504
Arthur Hung9ad18942021-06-19 02:04:46 +00001505 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1506 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1507 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1508 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1509 next.rawPointerData.hoveringIdBits.value);
1510 }
1511
Harry Cutts33476232023-01-30 19:57:29 +00001512 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001513 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001514}
1515
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001516std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1517 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001518 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001519 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001520 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001521 }
1522
1523 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1524 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1525 // touching the current state will only observe the events that have been dispatched to the
1526 // rest of the pipeline.
1527 const size_t N = mRawStatesPending.size();
1528 size_t count;
1529 for (count = 0; count < N; count++) {
1530 const RawState& next = mRawStatesPending[count];
1531
1532 // A failure to assign the stylus id means that we're waiting on stylus data
1533 // and so should defer the rest of the pipeline.
1534 if (assignExternalStylusId(next, timeout)) {
1535 break;
1536 }
1537
1538 // All ready to go.
1539 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001540 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001541 if (mCurrentRawState.when < mLastRawState.when) {
1542 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001543 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001544 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001545 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001546 }
1547 if (count != 0) {
1548 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1549 }
1550
1551 if (mExternalStylusDataPending) {
1552 if (timeout) {
1553 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1554 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001555 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001556 ALOGD_IF(DEBUG_STYLUS_FUSION,
1557 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001558 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001559 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001560 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1561 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1562 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1563 }
1564 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001565 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001566}
1567
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001568std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1569 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001570 // Always start with a clean state.
1571 mCurrentCookedState.clear();
1572
1573 // Apply stylus buttons to current raw state.
1574 applyExternalStylusButtonState(when);
1575
1576 // Handle policy on initial down or hover events.
1577 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1578 mCurrentRawState.rawPointerData.pointerCount != 0;
1579
1580 uint32_t policyFlags = 0;
1581 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1582 if (initialDown || buttonsPressed) {
1583 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001584 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001585 getContext()->fadePointer();
1586 }
1587
1588 if (mParameters.wake) {
1589 policyFlags |= POLICY_FLAG_WAKE;
1590 }
1591 }
1592
1593 // Consume raw off-screen touches before cooking pointer data.
1594 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001595 bool consumed;
1596 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1597 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001598 mCurrentRawState.rawPointerData.clear();
1599 }
1600
1601 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1602 // with cooked pointer data that has the same ids and indices as the raw data.
1603 // The following code can use either the raw or cooked data, as needed.
1604 cookPointerData();
1605
1606 // Apply stylus pressure to current cooked state.
1607 applyExternalStylusTouchState(when);
1608
1609 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001610 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1611 mSource, mViewport.displayId, policyFlags,
1612 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001613
1614 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001615 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001616 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1617 uint32_t id = idBits.clearFirstMarkedBit();
1618 const RawPointerData::Pointer& pointer =
1619 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001620 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001621 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001622 } else if (pointer.toolType == ToolType::FINGER ||
1623 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001625 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001626 mCurrentCookedState.mouseIdBits.markBit(id);
1627 }
1628 }
1629 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1630 uint32_t id = idBits.clearFirstMarkedBit();
1631 const RawPointerData::Pointer& pointer =
1632 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001633 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001634 mCurrentCookedState.stylusIdBits.markBit(id);
1635 }
1636 }
1637
1638 // Stylus takes precedence over all tools, then mouse, then finger.
1639 PointerUsage pointerUsage = mPointerUsage;
1640 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1641 mCurrentCookedState.mouseIdBits.clear();
1642 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001643 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001644 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1645 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001646 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001647 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1648 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001649 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001650 }
1651
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001652 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001653 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001654 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001655 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001656 out += dispatchButtonRelease(when, readTime, policyFlags);
1657 out += dispatchHoverExit(when, readTime, policyFlags);
1658 out += dispatchTouches(when, readTime, policyFlags);
1659 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1660 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001661 }
1662
1663 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1664 mCurrentMotionAborted = false;
1665 }
1666 }
1667
1668 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001669 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1670 mSource, mViewport.displayId, policyFlags,
1671 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001672
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001673 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1674 mCurrentStreamModifiedByExternalStylus = false;
1675 }
1676
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001677 // Clear some transient state.
1678 mCurrentRawState.rawVScroll = 0;
1679 mCurrentRawState.rawHScroll = 0;
1680
1681 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001682 mLastRawState = mCurrentRawState;
1683 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001684 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001685}
1686
Garfield Tanc734e4f2021-01-15 20:01:39 -08001687void TouchInputMapper::updateTouchSpots() {
1688 if (!mConfig.showTouches || mPointerController == nullptr) {
1689 return;
1690 }
1691
1692 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1693 // clear touch spots.
1694 if (mDeviceMode != DeviceMode::DIRECT &&
1695 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1696 return;
1697 }
1698
1699 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1700 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1701
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001702 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1703 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001704 mCurrentCookedState.cookedPointerData.touchingIdBits |
1705 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001706 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001707}
1708
1709bool TouchInputMapper::isTouchScreen() {
1710 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1711 mParameters.hasAssociatedDisplay;
1712}
1713
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001714void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001715 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1716 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001717 const int32_t pressedButtons =
1718 filterButtonState(mConfig,
1719 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001720 const int32_t releasedButtons =
1721 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1722
1723 mCurrentRawState.buttonState |= pressedButtons;
1724 mCurrentRawState.buttonState &= ~releasedButtons;
1725
1726 mExternalStylusButtonsApplied |= pressedButtons;
1727 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001728
1729 if (mExternalStylusButtonsApplied != 0 || releasedButtons != 0) {
1730 mCurrentStreamModifiedByExternalStylus = true;
1731 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001732 }
1733}
1734
1735void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1736 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1737 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001738 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1739 return;
1740 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001741
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001742 mCurrentStreamModifiedByExternalStylus = true;
1743
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001744 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1745 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1746 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1747 : 0.f;
1748 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1749 pressure = *mExternalStylusState.pressure;
1750 }
1751 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1752 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001753
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001754 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001755 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001756 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001757 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001758 }
1759}
1760
1761bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001762 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001763 return false;
1764 }
1765
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001766 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001767 if (mFusedStylusPointerId &&
1768 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001769 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001770 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001771 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001772 }
1773
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001774 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1775 state.rawPointerData.pointerCount != 0;
1776 if (!initialDown) {
1777 return false;
1778 }
1779
1780 if (!mExternalStylusState.pressure) {
1781 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1782 return false;
1783 }
1784
1785 if (*mExternalStylusState.pressure != 0.0f) {
1786 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1787 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1788 return false;
1789 }
1790
1791 if (timeout) {
1792 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1793 mFusedStylusPointerId.reset();
1794 mExternalStylusFusionTimeout = LLONG_MAX;
1795 return false;
1796 }
1797
1798 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1799 // being processed until we either get pressure data or timeout.
1800 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1801 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1802 }
1803 ALOGD_IF(DEBUG_STYLUS_FUSION,
1804 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1805 mExternalStylusFusionTimeout);
1806 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1807 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001808}
1809
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001810std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1811 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001812 if (mDeviceMode == DeviceMode::POINTER) {
1813 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001814 // Since this is a synthetic event, we can consider its latency to be zero
1815 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001816 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001817 }
Michael Wright227c5542020-07-02 18:30:52 +01001818 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001819 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001820 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001821 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1822 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1823 }
1824 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001825 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001826}
1827
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001828std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1829 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001830 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001831 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001832 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001833 // The following three cases are handled here:
1834 // - We're in the middle of a fused stream of data;
1835 // - We're waiting on external stylus data before dispatching the initial down; or
1836 // - Only the button state, which is not reported through a specific pointer, has changed.
1837 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001838 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001839 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001840 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001841 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001842}
1843
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001844std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1845 uint32_t policyFlags, bool& outConsumed) {
1846 outConsumed = false;
1847 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001848 // Check for release of a virtual key.
1849 if (mCurrentVirtualKey.down) {
1850 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1851 // Pointer went up while virtual key was down.
1852 mCurrentVirtualKey.down = false;
1853 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001854 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1855 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1856 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001857 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1858 AKEY_EVENT_FLAG_FROM_SYSTEM |
1859 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001860 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001861 outConsumed = true;
1862 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001863 }
1864
1865 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1866 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1867 const RawPointerData::Pointer& pointer =
1868 mCurrentRawState.rawPointerData.pointerForId(id);
1869 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1870 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1871 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001872 outConsumed = true;
1873 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001874 }
1875 }
1876
1877 // Pointer left virtual key area or another pointer also went down.
1878 // Send key cancellation but do not consume the touch yet.
1879 // This is useful when the user swipes through from the virtual key area
1880 // into the main display surface.
1881 mCurrentVirtualKey.down = false;
1882 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001883 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1884 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001885 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1886 AKEY_EVENT_FLAG_FROM_SYSTEM |
1887 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1888 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001889 }
1890 }
1891
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001892 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
1893 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty() &&
1894 mDeviceMode != DeviceMode::UNSCALED) {
1895 // We have hovering pointers, and there are no touching pointers.
1896 bool hoveringPointersInFrame = false;
1897 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1898 while (!hoveringIds.isEmpty()) {
1899 uint32_t id = hoveringIds.clearFirstMarkedBit();
1900 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1901 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1902 hoveringPointersInFrame = true;
1903 break;
1904 }
1905 }
1906 if (!hoveringPointersInFrame) {
1907 // All hovering pointers are outside the physical frame.
1908 outConsumed = true;
1909 return out;
1910 }
1911 }
1912
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001913 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1914 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1915 // Pointer just went down. Check for virtual key press or off-screen touches.
1916 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1917 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001918 // Skip checking whether the pointer is inside the physical frame if the device is in
Harry Cutts1db43992023-06-19 17:05:07 +00001919 // unscaled or pointer mode.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001920 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
Harry Cutts1db43992023-06-19 17:05:07 +00001921 mDeviceMode != DeviceMode::UNSCALED && mDeviceMode != DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001922 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001923 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001924 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1925 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1926 if (virtualKey) {
1927 mCurrentVirtualKey.down = true;
1928 mCurrentVirtualKey.downTime = when;
1929 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1930 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1931 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001932 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1933 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001934
1935 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001936 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1937 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1938 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001939 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1940 AKEY_EVENT_ACTION_DOWN,
1941 AKEY_EVENT_FLAG_FROM_SYSTEM |
1942 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001943 }
1944 }
1945 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001946 outConsumed = true;
1947 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001948 }
1949 }
1950
1951 // Disable all virtual key touches that happen within a short time interval of the
1952 // most recent touch within the screen area. The idea is to filter out stray
1953 // virtual key presses when interacting with the touch screen.
1954 //
1955 // Problems we're trying to solve:
1956 //
1957 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1958 // virtual key area that is implemented by a separate touch panel and accidentally
1959 // triggers a virtual key.
1960 //
1961 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1962 // area and accidentally triggers a virtual key. This often happens when virtual keys
1963 // are layed out below the screen near to where the on screen keyboard's space bar
1964 // is displayed.
1965 if (mConfig.virtualKeyQuietTime > 0 &&
1966 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001967 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001968 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001969 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001970}
1971
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001972NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1973 uint32_t policyFlags, int32_t keyEventAction,
1974 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001975 int32_t keyCode = mCurrentVirtualKey.keyCode;
1976 int32_t scanCode = mCurrentVirtualKey.scanCode;
1977 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001978 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001979 policyFlags |= POLICY_FLAG_VIRTUAL;
1980
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001981 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1982 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1983 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001984}
1985
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001986std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1987 uint32_t policyFlags) {
1988 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001989 if (mCurrentMotionAborted) {
1990 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001991 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001992 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001993 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1994 if (!currentIdBits.isEmpty()) {
1995 int32_t metaState = getContext()->getGlobalMetaState();
1996 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001997 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001998 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1999 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002000 mCurrentCookedState.cookedPointerData.pointerProperties,
2001 mCurrentCookedState.cookedPointerData.pointerCoords,
2002 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2003 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2004 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002005 mCurrentMotionAborted = true;
2006 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002007 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002008}
2009
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002010// Updates pointer coords and properties for pointers with specified ids that have moved.
2011// Returns true if any of them changed.
2012static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
2013 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
2014 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
2015 BitSet32 idBits) {
2016 bool changed = false;
2017 while (!idBits.isEmpty()) {
2018 uint32_t id = idBits.clearFirstMarkedBit();
2019 uint32_t inIndex = inIdToIndex[id];
2020 uint32_t outIndex = outIdToIndex[id];
2021
2022 const PointerProperties& curInProperties = inProperties[inIndex];
2023 const PointerCoords& curInCoords = inCoords[inIndex];
2024 PointerProperties& curOutProperties = outProperties[outIndex];
2025 PointerCoords& curOutCoords = outCoords[outIndex];
2026
2027 if (curInProperties != curOutProperties) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002028 curOutProperties = curInProperties;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002029 changed = true;
2030 }
2031
2032 if (curInCoords != curOutCoords) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002033 curOutCoords = curInCoords;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002034 changed = true;
2035 }
2036 }
2037 return changed;
2038}
2039
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002040std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
2041 uint32_t policyFlags) {
2042 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002043 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2044 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2045 int32_t metaState = getContext()->getGlobalMetaState();
2046 int32_t buttonState = mCurrentCookedState.buttonState;
2047
2048 if (currentIdBits == lastIdBits) {
2049 if (!currentIdBits.isEmpty()) {
2050 // No pointer id changes so this is a move event.
2051 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002052 out.push_back(
2053 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2054 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2055 mCurrentCookedState.cookedPointerData.pointerProperties,
2056 mCurrentCookedState.cookedPointerData.pointerCoords,
2057 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2058 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2059 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002060 }
2061 } else {
2062 // There may be pointers going up and pointers going down and pointers moving
2063 // all at the same time.
2064 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2065 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2066 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2067 BitSet32 dispatchedIdBits(lastIdBits.value);
2068
2069 // Update last coordinates of pointers that have moved so that we observe the new
2070 // pointer positions at the same time as other pointers that have just gone up.
2071 bool moveNeeded =
2072 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2073 mCurrentCookedState.cookedPointerData.pointerCoords,
2074 mCurrentCookedState.cookedPointerData.idToIndex,
2075 mLastCookedState.cookedPointerData.pointerProperties,
2076 mLastCookedState.cookedPointerData.pointerCoords,
2077 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2078 if (buttonState != mLastCookedState.buttonState) {
2079 moveNeeded = true;
2080 }
2081
2082 // Dispatch pointer up events.
2083 while (!upIdBits.isEmpty()) {
2084 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002085 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002086 if (isCanceled) {
2087 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2088 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002089 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2090 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2091 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2092 buttonState, 0,
2093 mLastCookedState.cookedPointerData.pointerProperties,
2094 mLastCookedState.cookedPointerData.pointerCoords,
2095 mLastCookedState.cookedPointerData.idToIndex,
2096 dispatchedIdBits, upId, mOrientedXPrecision,
2097 mOrientedYPrecision, mDownTime,
2098 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002099 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002100 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002101 }
2102
2103 // Dispatch move events if any of the remaining pointers moved from their old locations.
2104 // Although applications receive new locations as part of individual pointer up
2105 // events, they do not generally handle them except when presented in a move event.
2106 if (moveNeeded && !moveIdBits.isEmpty()) {
2107 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002108 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2109 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2110 mCurrentCookedState.cookedPointerData.pointerProperties,
2111 mCurrentCookedState.cookedPointerData.pointerCoords,
2112 mCurrentCookedState.cookedPointerData.idToIndex,
2113 dispatchedIdBits, -1, mOrientedXPrecision,
2114 mOrientedYPrecision, mDownTime,
2115 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002116 }
2117
2118 // Dispatch pointer down events using the new pointer locations.
2119 while (!downIdBits.isEmpty()) {
2120 uint32_t downId = downIdBits.clearFirstMarkedBit();
2121 dispatchedIdBits.markBit(downId);
2122
2123 if (dispatchedIdBits.count() == 1) {
2124 // First pointer is going down. Set down time.
2125 mDownTime = when;
2126 }
2127
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002128 out.push_back(
2129 dispatchMotion(when, readTime, policyFlags, mSource,
2130 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2131 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2132 mCurrentCookedState.cookedPointerData.pointerCoords,
2133 mCurrentCookedState.cookedPointerData.idToIndex,
2134 dispatchedIdBits, downId, mOrientedXPrecision,
2135 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002136 }
2137 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002138 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002139}
2140
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002141std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2142 uint32_t policyFlags) {
2143 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002144 if (mSentHoverEnter &&
2145 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2146 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2147 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002148 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2149 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2150 mLastCookedState.buttonState, 0,
2151 mLastCookedState.cookedPointerData.pointerProperties,
2152 mLastCookedState.cookedPointerData.pointerCoords,
2153 mLastCookedState.cookedPointerData.idToIndex,
2154 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2155 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2156 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002157 mSentHoverEnter = false;
2158 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002159 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002160}
2161
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002162std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2163 uint32_t policyFlags) {
2164 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002165 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2166 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2167 int32_t metaState = getContext()->getGlobalMetaState();
2168 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002169 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2170 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2171 mCurrentRawState.buttonState, 0,
2172 mCurrentCookedState.cookedPointerData.pointerProperties,
2173 mCurrentCookedState.cookedPointerData.pointerCoords,
2174 mCurrentCookedState.cookedPointerData.idToIndex,
2175 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2176 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2177 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002178 mSentHoverEnter = true;
2179 }
2180
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002181 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2182 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2183 mCurrentRawState.buttonState, 0,
2184 mCurrentCookedState.cookedPointerData.pointerProperties,
2185 mCurrentCookedState.cookedPointerData.pointerCoords,
2186 mCurrentCookedState.cookedPointerData.idToIndex,
2187 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2188 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2189 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002190 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002191 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002192}
2193
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002194std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2195 uint32_t policyFlags) {
2196 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002197 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2198 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2199 const int32_t metaState = getContext()->getGlobalMetaState();
2200 int32_t buttonState = mLastCookedState.buttonState;
2201 while (!releasedButtons.isEmpty()) {
2202 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2203 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002204 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2205 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2206 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002207 mLastCookedState.cookedPointerData.pointerProperties,
2208 mLastCookedState.cookedPointerData.pointerCoords,
2209 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002210 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2211 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002212 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002213 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002214}
2215
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002216std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2217 uint32_t policyFlags) {
2218 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002219 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2220 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2221 const int32_t metaState = getContext()->getGlobalMetaState();
2222 int32_t buttonState = mLastCookedState.buttonState;
2223 while (!pressedButtons.isEmpty()) {
2224 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2225 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002226 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2227 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2228 buttonState, 0,
2229 mCurrentCookedState.cookedPointerData.pointerProperties,
2230 mCurrentCookedState.cookedPointerData.pointerCoords,
2231 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2232 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2233 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002234 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002235 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002236}
2237
LiZhihong758eb562022-11-03 15:28:29 +08002238std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2239 uint32_t policyFlags,
2240 BitSet32 idBits,
2241 nsecs_t readTime) {
2242 std::list<NotifyArgs> out;
2243 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2244 const int32_t metaState = getContext()->getGlobalMetaState();
2245 int32_t buttonState = mLastCookedState.buttonState;
2246
2247 while (!releasedButtons.isEmpty()) {
2248 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2249 buttonState &= ~actionButton;
2250 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2251 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2252 metaState, buttonState, 0,
2253 mPointerGesture.lastGestureProperties,
2254 mPointerGesture.lastGestureCoords,
2255 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2256 mOrientedXPrecision, mOrientedYPrecision,
2257 mPointerGesture.downTime, MotionClassification::NONE));
2258 }
2259 return out;
2260}
2261
2262std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2263 uint32_t policyFlags,
2264 BitSet32 idBits,
2265 nsecs_t readTime) {
2266 std::list<NotifyArgs> out;
2267 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2268 const int32_t metaState = getContext()->getGlobalMetaState();
2269 int32_t buttonState = mLastCookedState.buttonState;
2270
2271 while (!pressedButtons.isEmpty()) {
2272 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2273 buttonState |= actionButton;
2274 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2275 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2276 buttonState, 0, mPointerGesture.currentGestureProperties,
2277 mPointerGesture.currentGestureCoords,
2278 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2279 mOrientedXPrecision, mOrientedYPrecision,
2280 mPointerGesture.downTime, MotionClassification::NONE));
2281 }
2282 return out;
2283}
2284
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002285const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2286 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2287 return cookedPointerData.touchingIdBits;
2288 }
2289 return cookedPointerData.hoveringIdBits;
2290}
2291
2292void TouchInputMapper::cookPointerData() {
2293 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2294
2295 mCurrentCookedState.cookedPointerData.clear();
2296 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2297 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2298 mCurrentRawState.rawPointerData.hoveringIdBits;
2299 mCurrentCookedState.cookedPointerData.touchingIdBits =
2300 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002301 mCurrentCookedState.cookedPointerData.canceledIdBits =
2302 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002303
2304 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2305 mCurrentCookedState.buttonState = 0;
2306 } else {
2307 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2308 }
2309
2310 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002311 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002312 for (uint32_t i = 0; i < currentPointerCount; i++) {
2313 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2314
2315 // Size
2316 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2317 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002318 case Calibration::SizeCalibration::GEOMETRIC:
2319 case Calibration::SizeCalibration::DIAMETER:
2320 case Calibration::SizeCalibration::BOX:
2321 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002322 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2323 touchMajor = in.touchMajor;
2324 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2325 toolMajor = in.toolMajor;
2326 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2327 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2328 : in.touchMajor;
2329 } else if (mRawPointerAxes.touchMajor.valid) {
2330 toolMajor = touchMajor = in.touchMajor;
2331 toolMinor = touchMinor =
2332 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2333 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2334 : in.touchMajor;
2335 } else if (mRawPointerAxes.toolMajor.valid) {
2336 touchMajor = toolMajor = in.toolMajor;
2337 touchMinor = toolMinor =
2338 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2339 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2340 : in.toolMajor;
2341 } else {
2342 ALOG_ASSERT(false,
2343 "No touch or tool axes. "
2344 "Size calibration should have been resolved to NONE.");
2345 touchMajor = 0;
2346 touchMinor = 0;
2347 toolMajor = 0;
2348 toolMinor = 0;
2349 size = 0;
2350 }
2351
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002352 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002353 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2354 if (touchingCount > 1) {
2355 touchMajor /= touchingCount;
2356 touchMinor /= touchingCount;
2357 toolMajor /= touchingCount;
2358 toolMinor /= touchingCount;
2359 size /= touchingCount;
2360 }
2361 }
2362
Michael Wright227c5542020-07-02 18:30:52 +01002363 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002364 touchMajor *= mGeometricScale;
2365 touchMinor *= mGeometricScale;
2366 toolMajor *= mGeometricScale;
2367 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002368 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2370 touchMinor = touchMajor;
2371 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2372 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002373 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 touchMinor = touchMajor;
2375 toolMinor = toolMajor;
2376 }
2377
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002378 mCalibration.applySizeScaleAndBias(touchMajor);
2379 mCalibration.applySizeScaleAndBias(touchMinor);
2380 mCalibration.applySizeScaleAndBias(toolMajor);
2381 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 size *= mSizeScale;
2383 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002384 case Calibration::SizeCalibration::DEFAULT:
2385 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2386 break;
2387 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 touchMajor = 0;
2389 touchMinor = 0;
2390 toolMajor = 0;
2391 toolMinor = 0;
2392 size = 0;
2393 break;
2394 }
2395
2396 // Pressure
2397 float pressure;
2398 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002399 case Calibration::PressureCalibration::PHYSICAL:
2400 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002401 pressure = in.pressure * mPressureScale;
2402 break;
2403 default:
2404 pressure = in.isHovering ? 0 : 1;
2405 break;
2406 }
2407
2408 // Tilt and Orientation
2409 float tilt;
2410 float orientation;
2411 if (mHaveTilt) {
2412 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2413 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002414 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2416 } else {
2417 tilt = 0;
2418
2419 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002420 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002421 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002422 break;
Michael Wright227c5542020-07-02 18:30:52 +01002423 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002424 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2425 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2426 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002427 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002428 float confidence = hypotf(c1, c2);
2429 float scale = 1.0f + confidence / 16.0f;
2430 touchMajor *= scale;
2431 touchMinor /= scale;
2432 toolMajor *= scale;
2433 toolMinor /= scale;
2434 } else {
2435 orientation = 0;
2436 }
2437 break;
2438 }
2439 default:
2440 orientation = 0;
2441 }
2442 }
2443
2444 // Distance
2445 float distance;
2446 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002447 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002448 distance = in.distance * mDistanceScale;
2449 break;
2450 default:
2451 distance = 0;
2452 }
2453
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002454 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2455 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002456 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2457 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002459 // Write output coords.
2460 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2461 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002462 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2463 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2465 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2466 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2467 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2468 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2469 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2470 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002471 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2472 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002473
Chris Ye364fdb52020-08-05 15:07:56 -07002474 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002475 uint32_t id = in.id;
2476 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2477 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2478 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002479 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2480 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002481 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2482 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2483 }
2484
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002485 // Write output properties.
2486 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002487 properties.clear();
2488 properties.id = id;
2489 properties.toolType = in.toolType;
2490
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002491 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002492 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002493 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002494 }
2495}
2496
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002497std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2498 uint32_t policyFlags,
2499 PointerUsage pointerUsage) {
2500 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002501 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002502 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 mPointerUsage = pointerUsage;
2504 }
2505
2506 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002507 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002508 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 break;
Michael Wright227c5542020-07-02 18:30:52 +01002510 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002511 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512 break;
Michael Wright227c5542020-07-02 18:30:52 +01002513 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002514 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002515 break;
Michael Wright227c5542020-07-02 18:30:52 +01002516 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002517 break;
2518 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002519 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002520}
2521
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002522std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2523 uint32_t policyFlags) {
2524 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002525 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002526 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002527 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002528 break;
Michael Wright227c5542020-07-02 18:30:52 +01002529 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002530 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002531 break;
Michael Wright227c5542020-07-02 18:30:52 +01002532 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002533 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 break;
Michael Wright227c5542020-07-02 18:30:52 +01002535 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002536 break;
2537 }
2538
Michael Wright227c5542020-07-02 18:30:52 +01002539 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002540 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002541}
2542
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002543std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2544 uint32_t policyFlags,
2545 bool isTimeout) {
2546 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002547 // Update current gesture coordinates.
2548 bool cancelPreviousGesture, finishPreviousGesture;
2549 bool sendEvents =
2550 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2551 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002552 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553 }
2554 if (finishPreviousGesture) {
2555 cancelPreviousGesture = false;
2556 }
2557
2558 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002559 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002560 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002561 if (finishPreviousGesture || cancelPreviousGesture) {
2562 mPointerController->clearSpots();
2563 }
2564
Michael Wright227c5542020-07-02 18:30:52 +01002565 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002566 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2567 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002568 mPointerGesture.currentGestureIdBits,
2569 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002570 }
2571 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002572 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002573 }
2574
2575 // Show or hide the pointer if needed.
2576 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002577 case PointerGesture::Mode::NEUTRAL:
2578 case PointerGesture::Mode::QUIET:
2579 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2580 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002581 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002582 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002583 }
2584 break;
Michael Wright227c5542020-07-02 18:30:52 +01002585 case PointerGesture::Mode::TAP:
2586 case PointerGesture::Mode::TAP_DRAG:
2587 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2588 case PointerGesture::Mode::HOVER:
2589 case PointerGesture::Mode::PRESS:
2590 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002591 // Unfade the pointer when the current gesture manipulates the
2592 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002593 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002594 break;
Michael Wright227c5542020-07-02 18:30:52 +01002595 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002596 // Fade the pointer when the current gesture manipulates a different
2597 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002598 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002599 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002600 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002601 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002602 }
2603 break;
2604 }
2605
2606 // Send events!
2607 int32_t metaState = getContext()->getGlobalMetaState();
2608 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002609 const MotionClassification classification =
2610 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2611 ? MotionClassification::TWO_FINGER_SWIPE
2612 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002613
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002614 uint32_t flags = 0;
2615
2616 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2617 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2618 }
2619
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002620 // Update last coordinates of pointers that have moved so that we observe the new
2621 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002622 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2623 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2624 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2625 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2626 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2627 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002628 bool moveNeeded = false;
2629 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2630 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2631 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2632 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2633 mPointerGesture.lastGestureIdBits.value);
2634 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2635 mPointerGesture.currentGestureCoords,
2636 mPointerGesture.currentGestureIdToIndex,
2637 mPointerGesture.lastGestureProperties,
2638 mPointerGesture.lastGestureCoords,
2639 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2640 if (buttonState != mLastCookedState.buttonState) {
2641 moveNeeded = true;
2642 }
2643 }
2644
2645 // Send motion events for all pointers that went up or were canceled.
2646 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2647 if (!dispatchedGestureIdBits.isEmpty()) {
2648 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002649 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002650 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002651 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002652 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2653 mPointerGesture.lastGestureProperties,
2654 mPointerGesture.lastGestureCoords,
2655 mPointerGesture.lastGestureIdToIndex,
2656 dispatchedGestureIdBits, -1, 0, 0,
2657 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002658
2659 dispatchedGestureIdBits.clear();
2660 } else {
2661 BitSet32 upGestureIdBits;
2662 if (finishPreviousGesture) {
2663 upGestureIdBits = dispatchedGestureIdBits;
2664 } else {
2665 upGestureIdBits.value =
2666 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2667 }
2668 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002669 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2670 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2671 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2672 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2673 readTime);
2674 }
2675 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002676 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2677 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2678 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2679 mPointerGesture.lastGestureProperties,
2680 mPointerGesture.lastGestureCoords,
2681 mPointerGesture.lastGestureIdToIndex,
2682 dispatchedGestureIdBits, id, 0, 0,
2683 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002684
2685 dispatchedGestureIdBits.clearBit(id);
2686 }
2687 }
2688 }
2689
2690 // Send motion events for all pointers that moved.
2691 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002692 out.push_back(
2693 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2694 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2695 mPointerGesture.currentGestureProperties,
2696 mPointerGesture.currentGestureCoords,
2697 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2698 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002699 }
2700
2701 // Send motion events for all pointers that went down.
2702 if (down) {
2703 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2704 ~dispatchedGestureIdBits.value);
2705 while (!downGestureIdBits.isEmpty()) {
2706 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2707 dispatchedGestureIdBits.markBit(id);
2708
2709 if (dispatchedGestureIdBits.count() == 1) {
2710 mPointerGesture.downTime = when;
2711 }
2712
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002713 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2714 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2715 buttonState, 0, mPointerGesture.currentGestureProperties,
2716 mPointerGesture.currentGestureCoords,
2717 mPointerGesture.currentGestureIdToIndex,
2718 dispatchedGestureIdBits, id, 0, 0,
2719 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002720 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2721 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2722 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2723 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2724 readTime);
2725 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002726 }
2727 }
2728
2729 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002730 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002731 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2732 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2733 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2734 mPointerGesture.currentGestureProperties,
2735 mPointerGesture.currentGestureCoords,
2736 mPointerGesture.currentGestureIdToIndex,
2737 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2738 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002739 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2740 // Synthesize a hover move event after all pointers go up to indicate that
2741 // the pointer is hovering again even if the user is not currently touching
2742 // the touch pad. This ensures that a view will receive a fresh hover enter
2743 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002744 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002745
2746 PointerProperties pointerProperties;
2747 pointerProperties.clear();
2748 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002749 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002750
2751 PointerCoords pointerCoords;
2752 pointerCoords.clear();
2753 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2754 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2755
2756 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002757 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2758 mSource, displayId, policyFlags,
2759 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2760 buttonState, MotionClassification::NONE,
2761 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2762 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00002763 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002764 }
2765
2766 // Update state.
2767 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2768 if (!down) {
2769 mPointerGesture.lastGestureIdBits.clear();
2770 } else {
2771 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2772 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2773 uint32_t id = idBits.clearFirstMarkedBit();
2774 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002775 mPointerGesture.lastGestureProperties[index] =
2776 mPointerGesture.currentGestureProperties[index];
2777 mPointerGesture.lastGestureCoords[index] = mPointerGesture.currentGestureCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002778 mPointerGesture.lastGestureIdToIndex[id] = index;
2779 }
2780 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002781 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002782}
2783
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002784std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2785 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002786 const MotionClassification classification =
2787 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2788 ? MotionClassification::TWO_FINGER_SWIPE
2789 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002790 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002791 // Cancel previously dispatches pointers.
2792 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2793 int32_t metaState = getContext()->getGlobalMetaState();
2794 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002795 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002796 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2797 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002798 mPointerGesture.lastGestureProperties,
2799 mPointerGesture.lastGestureCoords,
2800 mPointerGesture.lastGestureIdToIndex,
2801 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2802 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002803 }
2804
2805 // Reset the current pointer gesture.
2806 mPointerGesture.reset();
2807 mPointerVelocityControl.reset();
2808
2809 // Remove any current spots.
2810 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002811 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002812 mPointerController->clearSpots();
2813 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002814 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002815}
2816
2817bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2818 bool* outFinishPreviousGesture, bool isTimeout) {
2819 *outCancelPreviousGesture = false;
2820 *outFinishPreviousGesture = false;
2821
2822 // Handle TAP timeout.
2823 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002824 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002825
Michael Wright227c5542020-07-02 18:30:52 +01002826 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002827 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2828 // The tap/drag timeout has not yet expired.
2829 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2830 mConfig.pointerGestureTapDragInterval);
2831 } else {
2832 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002833 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002834 *outFinishPreviousGesture = true;
2835
2836 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002837 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002838 mPointerGesture.currentGestureIdBits.clear();
2839
2840 mPointerVelocityControl.reset();
2841 return true;
2842 }
2843 }
2844
2845 // We did not handle this timeout.
2846 return false;
2847 }
2848
2849 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2850 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2851
2852 // Update the velocity tracker.
2853 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002854 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002855 uint32_t id = idBits.clearFirstMarkedBit();
2856 const RawPointerData::Pointer& pointer =
2857 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002858 const float x = pointer.x * mPointerXMovementScale;
2859 const float y = pointer.y * mPointerYMovementScale;
2860 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2861 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002862 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002863 }
2864
2865 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2866 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002867 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2868 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2869 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002870 mPointerGesture.resetTap();
2871 }
2872
2873 // Pick a new active touch id if needed.
2874 // Choose an arbitrary pointer that just went down, if there is one.
2875 // Otherwise choose an arbitrary remaining pointer.
2876 // This guarantees we always have an active touch id when there is at least one pointer.
2877 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002878 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002879 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002880 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002881 mPointerGesture.firstTouchTime = when;
2882 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002883 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2884 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2885 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2886 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002887 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002888 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002889
2890 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002891 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002893 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2894 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2895 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002896 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002897 *outFinishPreviousGesture = true;
2898 }
2899
2900 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002901 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002902 mPointerGesture.currentGestureIdBits.clear();
2903
2904 mPointerVelocityControl.reset();
2905 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2906 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2907 // The pointer follows the active touch point.
2908 // Emit DOWN, MOVE, UP events at the pointer location.
2909 //
2910 // Only the active touch matters; other fingers are ignored. This policy helps
2911 // to handle the case where the user places a second finger on the touch pad
2912 // to apply the necessary force to depress an integrated button below the surface.
2913 // We don't want the second finger to be delivered to applications.
2914 //
2915 // For this to work well, we need to make sure to track the pointer that is really
2916 // active. If the user first puts one finger down to click then adds another
2917 // finger to drag then the active pointer should switch to the finger that is
2918 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002919 ALOGD_IF(DEBUG_GESTURES,
2920 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2921 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002923 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002924 *outFinishPreviousGesture = true;
2925 mPointerGesture.activeGestureId = 0;
2926 }
2927
2928 // Switch pointers if needed.
2929 // Find the fastest pointer and follow it.
2930 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002931 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002932 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002933 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002934 ALOGD_IF(DEBUG_GESTURES,
2935 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2936 "bestSpeed=%0.3f",
2937 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002938 }
2939 }
2940
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002941 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002942 // When using spots, the click will occur at the position of the anchor
2943 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002944 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002945 } else {
2946 mPointerVelocityControl.reset();
2947 }
2948
Prabir Pradhan2719e822023-02-28 17:39:36 +00002949 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002950
Michael Wright227c5542020-07-02 18:30:52 +01002951 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002952 mPointerGesture.currentGestureIdBits.clear();
2953 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2954 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2955 mPointerGesture.currentGestureProperties[0].clear();
2956 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002957 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002958 mPointerGesture.currentGestureCoords[0].clear();
2959 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2960 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2961 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2962 } else if (currentFingerCount == 0) {
2963 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002964 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002965 *outFinishPreviousGesture = true;
2966 }
2967
2968 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2969 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2970 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002971 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2972 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002973 lastFingerCount == 1) {
2974 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002975 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002976 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2977 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002978 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002979
2980 mPointerGesture.tapUpTime = when;
2981 getContext()->requestTimeoutAtTime(when +
2982 mConfig.pointerGestureTapDragInterval);
2983
2984 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002985 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002986 mPointerGesture.currentGestureIdBits.clear();
2987 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2988 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2989 mPointerGesture.currentGestureProperties[0].clear();
2990 mPointerGesture.currentGestureProperties[0].id =
2991 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002992 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002993 mPointerGesture.currentGestureCoords[0].clear();
2994 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2995 mPointerGesture.tapX);
2996 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2997 mPointerGesture.tapY);
2998 mPointerGesture.currentGestureCoords[0]
2999 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3000
3001 tapped = true;
3002 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003003 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
3004 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003005 }
3006 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003007 if (DEBUG_GESTURES) {
3008 if (mPointerGesture.tapDownTime != LLONG_MIN) {
3009 ALOGD("Gestures: Not a TAP, %0.3fms since down",
3010 (when - mPointerGesture.tapDownTime) * 0.000001f);
3011 } else {
3012 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
3013 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003014 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003015 }
3016 }
3017
3018 mPointerVelocityControl.reset();
3019
3020 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00003021 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003022 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01003023 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003024 mPointerGesture.currentGestureIdBits.clear();
3025 }
3026 } else if (currentFingerCount == 1) {
3027 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3028 // The pointer follows the active touch point.
3029 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3030 // When in TAP_DRAG, emit MOVE events at the pointer location.
3031 ALOG_ASSERT(activeTouchId >= 0);
3032
Michael Wright227c5542020-07-02 18:30:52 +01003033 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3034 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003035 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003036 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003037 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3038 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003039 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003040 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003041 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3042 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003043 }
3044 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003045 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3046 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003047 }
Michael Wright227c5542020-07-02 18:30:52 +01003048 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3049 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003050 }
3051
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003052 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003053 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003054 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003055 } else {
3056 mPointerVelocityControl.reset();
3057 }
3058
3059 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003060 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003061 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003062 down = true;
3063 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003064 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003065 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003066 *outFinishPreviousGesture = true;
3067 }
3068 mPointerGesture.activeGestureId = 0;
3069 down = false;
3070 }
3071
Prabir Pradhan2719e822023-02-28 17:39:36 +00003072 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003073
3074 mPointerGesture.currentGestureIdBits.clear();
3075 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3076 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3077 mPointerGesture.currentGestureProperties[0].clear();
3078 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003079 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003080 mPointerGesture.currentGestureCoords[0].clear();
3081 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3082 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3083 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3084 down ? 1.0f : 0.0f);
3085
3086 if (lastFingerCount == 0 && currentFingerCount != 0) {
3087 mPointerGesture.resetTap();
3088 mPointerGesture.tapDownTime = when;
3089 mPointerGesture.tapX = x;
3090 mPointerGesture.tapY = y;
3091 }
3092 } else {
3093 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003094 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003095 }
3096
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003097 if (DEBUG_GESTURES) {
3098 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3099 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3100 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3101 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3102 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3103 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3104 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3105 uint32_t id = idBits.clearFirstMarkedBit();
3106 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3107 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3108 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003109 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003110 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003111 id, index, ftl::enum_string(properties.toolType).c_str(),
3112 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003113 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3114 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3115 }
3116 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3117 uint32_t id = idBits.clearFirstMarkedBit();
3118 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3119 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3120 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003121 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003122 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003123 id, index, ftl::enum_string(properties.toolType).c_str(),
3124 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003125 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3126 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3127 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003128 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003129 return true;
3130}
3131
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003132bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3133 if (mPointerGesture.activeTouchId < 0) {
3134 mPointerGesture.resetQuietTime();
3135 return false;
3136 }
3137
3138 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3139 return true;
3140 }
3141
3142 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3143 bool isQuietTime = false;
3144 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3145 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3146 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3147 currentFingerCount < 2) {
3148 // Enter quiet time when exiting swipe or freeform state.
3149 // This is to prevent accidentally entering the hover state and flinging the
3150 // pointer when finishing a swipe and there is still one pointer left onscreen.
3151 isQuietTime = true;
3152 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3153 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3154 // Enter quiet time when releasing the button and there are still two or more
3155 // fingers down. This may indicate that one finger was used to press the button
3156 // but it has not gone up yet.
3157 isQuietTime = true;
3158 }
3159 if (isQuietTime) {
3160 mPointerGesture.quietTime = when;
3161 }
3162 return isQuietTime;
3163}
3164
3165std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3166 int32_t bestId = -1;
3167 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3168 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3169 uint32_t id = idBits.clearFirstMarkedBit();
3170 std::optional<float> vx =
3171 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3172 std::optional<float> vy =
3173 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3174 if (vx && vy) {
3175 float speed = hypotf(*vx, *vy);
3176 if (speed > bestSpeed) {
3177 bestId = id;
3178 bestSpeed = speed;
3179 }
3180 }
3181 }
3182 return std::make_pair(bestId, bestSpeed);
3183}
3184
3185void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3186 bool* finishPreviousGesture) {
3187 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3188 // to move before deciding what to do.
3189 //
3190 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3191 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3192 // just a press or long-press at the pointer location.
3193 //
3194 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3195 // pointer location.
3196 //
3197 // When the two fingers move enough or when additional fingers are added, we make a decision to
3198 // transition into SWIPE or FREEFORM mode accordingly.
3199 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3200 ALOG_ASSERT(activeTouchId >= 0);
3201
3202 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3203 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3204 bool settled =
3205 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3206 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3207 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3208 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3209 *finishPreviousGesture = true;
3210 } else if (!settled && currentFingerCount > lastFingerCount) {
3211 // Additional pointers have gone down but not yet settled.
3212 // Reset the gesture.
3213 ALOGD_IF(DEBUG_GESTURES,
3214 "Gestures: Resetting gesture since additional pointers went down for "
3215 "MULTITOUCH, settle time remaining %0.3fms",
3216 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3217 when) * 0.000001f);
3218 *cancelPreviousGesture = true;
3219 } else {
3220 // Continue previous gesture.
3221 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3222 }
3223
3224 if (*finishPreviousGesture || *cancelPreviousGesture) {
3225 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3226 mPointerGesture.activeGestureId = 0;
3227 mPointerGesture.referenceIdBits.clear();
3228 mPointerVelocityControl.reset();
3229
3230 // Use the centroid and pointer location as the reference points for the gesture.
3231 ALOGD_IF(DEBUG_GESTURES,
3232 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3233 "%0.3fms",
3234 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3235 when) * 0.000001f);
3236 mCurrentRawState.rawPointerData
3237 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3238 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003239 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3240 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003241 }
3242
3243 // Clear the reference deltas for fingers not yet included in the reference calculation.
3244 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3245 ~mPointerGesture.referenceIdBits.value);
3246 !idBits.isEmpty();) {
3247 uint32_t id = idBits.clearFirstMarkedBit();
3248 mPointerGesture.referenceDeltas[id].dx = 0;
3249 mPointerGesture.referenceDeltas[id].dy = 0;
3250 }
3251 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3252
3253 // Add delta for all fingers and calculate a common movement delta.
3254 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3255 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3256 mCurrentCookedState.fingerIdBits.value);
3257 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3258 bool first = (idBits == commonIdBits);
3259 uint32_t id = idBits.clearFirstMarkedBit();
3260 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3261 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3262 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3263 delta.dx += cpd.x - lpd.x;
3264 delta.dy += cpd.y - lpd.y;
3265
3266 if (first) {
3267 commonDeltaRawX = delta.dx;
3268 commonDeltaRawY = delta.dy;
3269 } else {
3270 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3271 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3272 }
3273 }
3274
3275 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3276 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3277 float dist[MAX_POINTER_ID + 1];
3278 int32_t distOverThreshold = 0;
3279 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3280 uint32_t id = idBits.clearFirstMarkedBit();
3281 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3282 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3283 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3284 distOverThreshold += 1;
3285 }
3286 }
3287
3288 // Only transition when at least two pointers have moved further than
3289 // the minimum distance threshold.
3290 if (distOverThreshold >= 2) {
3291 if (currentFingerCount > 2) {
3292 // There are more than two pointers, switch to FREEFORM.
3293 ALOGD_IF(DEBUG_GESTURES,
3294 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3295 currentFingerCount);
3296 *cancelPreviousGesture = true;
3297 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3298 } else {
3299 // There are exactly two pointers.
3300 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3301 uint32_t id1 = idBits.clearFirstMarkedBit();
3302 uint32_t id2 = idBits.firstMarkedBit();
3303 const RawPointerData::Pointer& p1 =
3304 mCurrentRawState.rawPointerData.pointerForId(id1);
3305 const RawPointerData::Pointer& p2 =
3306 mCurrentRawState.rawPointerData.pointerForId(id2);
3307 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3308 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3309 // There are two pointers but they are too far apart for a SWIPE,
3310 // switch to FREEFORM.
3311 ALOGD_IF(DEBUG_GESTURES,
3312 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3313 mutualDistance, mPointerGestureMaxSwipeWidth);
3314 *cancelPreviousGesture = true;
3315 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3316 } else {
3317 // There are two pointers. Wait for both pointers to start moving
3318 // before deciding whether this is a SWIPE or FREEFORM gesture.
3319 float dist1 = dist[id1];
3320 float dist2 = dist[id2];
3321 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3322 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3323 // Calculate the dot product of the displacement vectors.
3324 // When the vectors are oriented in approximately the same direction,
3325 // the angle betweeen them is near zero and the cosine of the angle
3326 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3327 // mag(v2).
3328 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3329 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3330 float dx1 = delta1.dx * mPointerXZoomScale;
3331 float dy1 = delta1.dy * mPointerYZoomScale;
3332 float dx2 = delta2.dx * mPointerXZoomScale;
3333 float dy2 = delta2.dy * mPointerYZoomScale;
3334 float dot = dx1 * dx2 + dy1 * dy2;
3335 float cosine = dot / (dist1 * dist2); // denominator always > 0
3336 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3337 // Pointers are moving in the same direction. Switch to SWIPE.
3338 ALOGD_IF(DEBUG_GESTURES,
3339 "Gestures: PRESS transitioned to SWIPE, "
3340 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3341 "cosine %0.3f >= %0.3f",
3342 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3343 mConfig.pointerGestureMultitouchMinDistance, cosine,
3344 mConfig.pointerGestureSwipeTransitionAngleCosine);
3345 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3346 } else {
3347 // Pointers are moving in different directions. Switch to FREEFORM.
3348 ALOGD_IF(DEBUG_GESTURES,
3349 "Gestures: PRESS transitioned to FREEFORM, "
3350 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3351 "cosine %0.3f < %0.3f",
3352 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3353 mConfig.pointerGestureMultitouchMinDistance, cosine,
3354 mConfig.pointerGestureSwipeTransitionAngleCosine);
3355 *cancelPreviousGesture = true;
3356 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3357 }
3358 }
3359 }
3360 }
3361 }
3362 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3363 // Switch from SWIPE to FREEFORM if additional pointers go down.
3364 // Cancel previous gesture.
3365 if (currentFingerCount > 2) {
3366 ALOGD_IF(DEBUG_GESTURES,
3367 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3368 currentFingerCount);
3369 *cancelPreviousGesture = true;
3370 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3371 }
3372 }
3373
3374 // Move the reference points based on the overall group motion of the fingers
3375 // except in PRESS mode while waiting for a transition to occur.
3376 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3377 (commonDeltaRawX || commonDeltaRawY)) {
3378 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3379 uint32_t id = idBits.clearFirstMarkedBit();
3380 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3381 delta.dx = 0;
3382 delta.dy = 0;
3383 }
3384
3385 mPointerGesture.referenceTouchX += commonDeltaRawX;
3386 mPointerGesture.referenceTouchY += commonDeltaRawY;
3387
3388 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3389 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3390
3391 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3392 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3393
3394 mPointerGesture.referenceGestureX += commonDeltaX;
3395 mPointerGesture.referenceGestureY += commonDeltaY;
3396 }
3397
3398 // Report gestures.
3399 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3400 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3401 // PRESS or SWIPE mode.
3402 ALOGD_IF(DEBUG_GESTURES,
3403 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3404 "currentTouchPointerCount=%d",
3405 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3406 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3407
3408 mPointerGesture.currentGestureIdBits.clear();
3409 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3410 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3411 mPointerGesture.currentGestureProperties[0].clear();
3412 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003413 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003414 mPointerGesture.currentGestureCoords[0].clear();
3415 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3416 mPointerGesture.referenceGestureX);
3417 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3418 mPointerGesture.referenceGestureY);
3419 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3420 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3421 float xOffset = static_cast<float>(commonDeltaRawX) /
3422 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3423 float yOffset = static_cast<float>(commonDeltaRawY) /
3424 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3425 mPointerGesture.currentGestureCoords[0]
3426 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3427 mPointerGesture.currentGestureCoords[0]
3428 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3429 }
3430 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3431 // FREEFORM mode.
3432 ALOGD_IF(DEBUG_GESTURES,
3433 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3434 "currentTouchPointerCount=%d",
3435 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3436 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3437
3438 mPointerGesture.currentGestureIdBits.clear();
3439
3440 BitSet32 mappedTouchIdBits;
3441 BitSet32 usedGestureIdBits;
3442 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3443 // Initially, assign the active gesture id to the active touch point
3444 // if there is one. No other touch id bits are mapped yet.
3445 if (!*cancelPreviousGesture) {
3446 mappedTouchIdBits.markBit(activeTouchId);
3447 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3448 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3449 mPointerGesture.activeGestureId;
3450 } else {
3451 mPointerGesture.activeGestureId = -1;
3452 }
3453 } else {
3454 // Otherwise, assume we mapped all touches from the previous frame.
3455 // Reuse all mappings that are still applicable.
3456 mappedTouchIdBits.value =
3457 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3458 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3459
3460 // Check whether we need to choose a new active gesture id because the
3461 // current went went up.
3462 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3463 ~mCurrentCookedState.fingerIdBits.value);
3464 !upTouchIdBits.isEmpty();) {
3465 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3466 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3467 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3468 mPointerGesture.activeGestureId = -1;
3469 break;
3470 }
3471 }
3472 }
3473
3474 ALOGD_IF(DEBUG_GESTURES,
3475 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3476 "activeGestureId=%d",
3477 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3478
3479 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3480 for (uint32_t i = 0; i < currentFingerCount; i++) {
3481 uint32_t touchId = idBits.clearFirstMarkedBit();
3482 uint32_t gestureId;
3483 if (!mappedTouchIdBits.hasBit(touchId)) {
3484 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3485 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3486 ALOGD_IF(DEBUG_GESTURES,
3487 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3488 gestureId);
3489 } else {
3490 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3491 ALOGD_IF(DEBUG_GESTURES,
3492 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3493 touchId, gestureId);
3494 }
3495 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3496 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3497
3498 const RawPointerData::Pointer& pointer =
3499 mCurrentRawState.rawPointerData.pointerForId(touchId);
3500 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3501 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3502 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3503
3504 mPointerGesture.currentGestureProperties[i].clear();
3505 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003506 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003507 mPointerGesture.currentGestureCoords[i].clear();
3508 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3509 mPointerGesture.referenceGestureX +
3510 deltaX);
3511 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3512 mPointerGesture.referenceGestureY +
3513 deltaY);
3514 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3515 }
3516
3517 if (mPointerGesture.activeGestureId < 0) {
3518 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3519 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3520 mPointerGesture.activeGestureId);
3521 }
3522 }
3523}
3524
Harry Cutts714d1ad2022-08-24 16:36:43 +00003525void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3526 const RawPointerData::Pointer& currentPointer =
3527 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3528 const RawPointerData::Pointer& lastPointer =
3529 mLastRawState.rawPointerData.pointerForId(pointerId);
3530 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3531 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3532
3533 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3534 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3535
3536 mPointerController->move(deltaX, deltaY);
3537}
3538
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003539std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3540 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003541 mPointerSimple.currentCoords.clear();
3542 mPointerSimple.currentProperties.clear();
3543
3544 bool down, hovering;
3545 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3546 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3547 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003548 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3549 down = !hovering;
3550
Prabir Pradhane71e5702023-03-29 14:51:38 +00003551 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3552 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3553 // Styluses are configured specifically for one display. We only update the
3554 // PointerController for this stylus if the PointerController is configured for
3555 // the same display as this stylus,
3556 if (getAssociatedDisplayId() == mViewport.displayId) {
3557 mPointerController->setPosition(x, y);
3558 std::tie(x, y) = mPointerController->getPosition();
3559 }
3560
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003561 mPointerSimple.currentCoords = mCurrentCookedState.cookedPointerData.pointerCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003562 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3563 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3564 mPointerSimple.currentProperties.id = 0;
3565 mPointerSimple.currentProperties.toolType =
3566 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3567 } else {
3568 down = false;
3569 hovering = false;
3570 }
3571
Prabir Pradhane71e5702023-03-29 14:51:38 +00003572 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003573}
3574
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003575std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3576 uint32_t policyFlags) {
3577 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003578}
3579
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003580std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3581 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003582 mPointerSimple.currentCoords.clear();
3583 mPointerSimple.currentProperties.clear();
3584
3585 bool down, hovering;
3586 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3587 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003588 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003589 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003590 } else {
3591 mPointerVelocityControl.reset();
3592 }
3593
3594 down = isPointerDown(mCurrentRawState.buttonState);
3595 hovering = !down;
3596
Prabir Pradhan2719e822023-02-28 17:39:36 +00003597 const auto [x, y] = mPointerController->getPosition();
3598 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003599 mPointerSimple.currentCoords =
3600 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003601 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3602 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3603 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3604 hovering ? 0.0f : 1.0f);
3605 mPointerSimple.currentProperties.id = 0;
3606 mPointerSimple.currentProperties.toolType =
3607 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3608 } else {
3609 mPointerVelocityControl.reset();
3610
3611 down = false;
3612 hovering = false;
3613 }
3614
Prabir Pradhane71e5702023-03-29 14:51:38 +00003615 const int32_t displayId = mPointerController->getDisplayId();
3616 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003617}
3618
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003619std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3620 uint32_t policyFlags) {
3621 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003622
3623 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003624
3625 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003626}
3627
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003628std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3629 uint32_t policyFlags, bool down,
Prabir Pradhane71e5702023-03-29 14:51:38 +00003630 bool hovering, int32_t displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003631 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3632 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003633 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003634 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003635 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003636
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003637 if (displayId == mPointerController->getDisplayId()) {
3638 std::tie(cursorPosition.x, cursorPosition.y) = mPointerController->getPosition();
3639 if (down || hovering) {
3640 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
3641 mPointerController->clearSpots();
3642 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3643 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
3644 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3645 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003646 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003647
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003648 if (mPointerSimple.down && !down) {
3649 mPointerSimple.down = false;
3650
3651 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003652 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3653 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3654 0, metaState, mLastRawState.buttonState,
3655 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3656 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003657 mOrientedXPrecision, mOrientedYPrecision,
3658 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3659 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003660 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003661 }
3662
3663 if (mPointerSimple.hovering && !hovering) {
3664 mPointerSimple.hovering = false;
3665
3666 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003667 out.push_back(
3668 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3669 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3670 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3671 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3672 &mPointerSimple.lastCoords, mOrientedXPrecision,
3673 mOrientedYPrecision, mPointerSimple.lastCursorX,
3674 mPointerSimple.lastCursorY, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003675 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003676 }
3677
3678 if (down) {
3679 if (!mPointerSimple.down) {
3680 mPointerSimple.down = true;
3681 mPointerSimple.downTime = when;
3682
3683 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003684 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3685 mSource, displayId, policyFlags,
3686 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3687 mCurrentRawState.buttonState, MotionClassification::NONE,
3688 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3689 &mPointerSimple.currentProperties,
3690 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003691 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003692 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003693 }
3694
3695 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003696 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3697 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3698 0, 0, metaState, mCurrentRawState.buttonState,
3699 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3700 &mPointerSimple.currentProperties,
3701 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003702 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003703 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003704 }
3705
3706 if (hovering) {
3707 if (!mPointerSimple.hovering) {
3708 mPointerSimple.hovering = true;
3709
3710 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003711 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3712 mSource, displayId, policyFlags,
3713 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3714 mCurrentRawState.buttonState, MotionClassification::NONE,
3715 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3716 &mPointerSimple.currentProperties,
3717 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003718 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003719 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003720 }
3721
3722 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003723 out.push_back(
3724 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3725 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3726 metaState, mCurrentRawState.buttonState,
3727 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3728 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003729 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003730 cursorPosition.y, mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003731 }
3732
3733 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3734 float vscroll = mCurrentRawState.rawVScroll;
3735 float hscroll = mCurrentRawState.rawHScroll;
3736 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3737 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3738
3739 // Send scroll.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003740 PointerCoords pointerCoords = mPointerSimple.currentCoords;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003741 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3742 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3743
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003744 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3745 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3746 0, 0, metaState, mCurrentRawState.buttonState,
3747 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3748 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003749 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3750 cursorPosition.y, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003751 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003752 }
3753
3754 // Save state.
3755 if (down || hovering) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003756 mPointerSimple.lastCoords = mPointerSimple.currentCoords;
3757 mPointerSimple.lastProperties = mPointerSimple.currentProperties;
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003758 mPointerSimple.displayId = displayId;
3759 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003760 mPointerSimple.lastCursorX = cursorPosition.x;
3761 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003762 } else {
3763 mPointerSimple.reset();
3764 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003765 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003766}
3767
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003768std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3769 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003770 std::list<NotifyArgs> out;
3771 if (mPointerSimple.down || mPointerSimple.hovering) {
3772 int32_t metaState = getContext()->getGlobalMetaState();
3773 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3774 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3775 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3776 metaState, mLastRawState.buttonState,
3777 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3778 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3779 mOrientedXPrecision, mOrientedYPrecision,
3780 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3781 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003782 /*videoFrames=*/{}));
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003783 if (mPointerController != nullptr) {
3784 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3785 }
3786 }
3787 mPointerSimple.reset();
3788 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003789}
3790
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003791NotifyMotionArgs TouchInputMapper::dispatchMotion(
3792 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3793 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003794 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3795 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003796 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003797 std::vector<PointerCoords> pointerCoords;
3798 std::vector<PointerProperties> pointerProperties;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003799 uint32_t pointerCount = 0;
3800 while (!idBits.isEmpty()) {
3801 uint32_t id = idBits.clearFirstMarkedBit();
3802 uint32_t index = idToIndex[id];
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003803 pointerProperties.push_back(properties[index]);
3804 pointerCoords.push_back(coords[index]);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003805
3806 if (changedId >= 0 && id == uint32_t(changedId)) {
3807 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3808 }
3809
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003810 pointerCount++;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003811 }
3812
3813 ALOG_ASSERT(pointerCount != 0);
3814
3815 if (changedId >= 0 && pointerCount == 1) {
3816 // Replace initial down and final up action.
3817 // We can compare the action without masking off the changed pointer index
3818 // because we know the index is 0.
3819 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3820 action = AMOTION_EVENT_ACTION_DOWN;
3821 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003822 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3823 action = AMOTION_EVENT_ACTION_CANCEL;
3824 } else {
3825 action = AMOTION_EVENT_ACTION_UP;
3826 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003827 } else {
3828 // Can't happen.
3829 ALOG_ASSERT(false);
3830 }
3831 }
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00003832 if (mCurrentStreamModifiedByExternalStylus) {
3833 source |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3834 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003835
3836 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3837 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003838 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003839 mPointerController && displayId != ADISPLAY_ID_NONE &&
3840 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003841 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003842 switch (action & AMOTION_EVENT_ACTION_MASK) {
3843 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3844 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3845 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003846 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003847 mPointerController
3848 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3849 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3850 .getY());
3851 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3852 break;
3853 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3854 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3855 break;
3856 }
3857 }
3858
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003859 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3860 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003861 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003862 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003863 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003864 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003865 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003866 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003867 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003868 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3869 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003870 classification, edgeFlags, pointerCount, pointerProperties.data(),
3871 pointerCoords.data(), xPrecision, yPrecision, xCursorPosition,
3872 yCursorPosition, downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003873}
3874
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003875std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3876 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003877 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3878 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003879 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003880}
3881
Prabir Pradhan1728b212021-10-19 16:00:03 -07003882bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003883 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003884 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003885 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003886}
3887
3888const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3889 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003890 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3891 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3892 "left=%d, top=%d, right=%d, bottom=%d",
3893 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3894 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003895
3896 if (virtualKey.isHit(x, y)) {
3897 return &virtualKey;
3898 }
3899 }
3900
3901 return nullptr;
3902}
3903
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003904void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3905 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3906 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003907
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003908 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003909
3910 if (currentPointerCount == 0) {
3911 // No pointers to assign.
3912 return;
3913 }
3914
3915 if (lastPointerCount == 0) {
3916 // All pointers are new.
3917 for (uint32_t i = 0; i < currentPointerCount; i++) {
3918 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003919 current.rawPointerData.pointers[i].id = id;
3920 current.rawPointerData.idToIndex[id] = i;
3921 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003922 }
3923 return;
3924 }
3925
3926 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003927 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003928 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003929 uint32_t id = last.rawPointerData.pointers[0].id;
3930 current.rawPointerData.pointers[0].id = id;
3931 current.rawPointerData.idToIndex[id] = 0;
3932 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003933 return;
3934 }
3935
3936 // General case.
3937 // We build a heap of squared euclidean distances between current and last pointers
3938 // associated with the current and last pointer indices. Then, we find the best
3939 // match (by distance) for each current pointer.
3940 // The pointers must have the same tool type but it is possible for them to
3941 // transition from hovering to touching or vice-versa while retaining the same id.
3942 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3943
3944 uint32_t heapSize = 0;
3945 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3946 currentPointerIndex++) {
3947 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3948 lastPointerIndex++) {
3949 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003950 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003951 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003952 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003953 if (currentPointer.toolType == lastPointer.toolType) {
3954 int64_t deltaX = currentPointer.x - lastPointer.x;
3955 int64_t deltaY = currentPointer.y - lastPointer.y;
3956
3957 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3958
3959 // Insert new element into the heap (sift up).
3960 heap[heapSize].currentPointerIndex = currentPointerIndex;
3961 heap[heapSize].lastPointerIndex = lastPointerIndex;
3962 heap[heapSize].distance = distance;
3963 heapSize += 1;
3964 }
3965 }
3966 }
3967
3968 // Heapify
3969 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3970 startIndex -= 1;
3971 for (uint32_t parentIndex = startIndex;;) {
3972 uint32_t childIndex = parentIndex * 2 + 1;
3973 if (childIndex >= heapSize) {
3974 break;
3975 }
3976
3977 if (childIndex + 1 < heapSize &&
3978 heap[childIndex + 1].distance < heap[childIndex].distance) {
3979 childIndex += 1;
3980 }
3981
3982 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3983 break;
3984 }
3985
3986 swap(heap[parentIndex], heap[childIndex]);
3987 parentIndex = childIndex;
3988 }
3989 }
3990
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003991 if (DEBUG_POINTER_ASSIGNMENT) {
3992 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3993 for (size_t i = 0; i < heapSize; i++) {
3994 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3995 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3996 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003997 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003998
3999 // Pull matches out by increasing order of distance.
4000 // To avoid reassigning pointers that have already been matched, the loop keeps track
4001 // of which last and current pointers have been matched using the matchedXXXBits variables.
4002 // It also tracks the used pointer id bits.
4003 BitSet32 matchedLastBits(0);
4004 BitSet32 matchedCurrentBits(0);
4005 BitSet32 usedIdBits(0);
4006 bool first = true;
4007 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
4008 while (heapSize > 0) {
4009 if (first) {
4010 // The first time through the loop, we just consume the root element of
4011 // the heap (the one with smallest distance).
4012 first = false;
4013 } else {
4014 // Previous iterations consumed the root element of the heap.
4015 // Pop root element off of the heap (sift down).
4016 heap[0] = heap[heapSize];
4017 for (uint32_t parentIndex = 0;;) {
4018 uint32_t childIndex = parentIndex * 2 + 1;
4019 if (childIndex >= heapSize) {
4020 break;
4021 }
4022
4023 if (childIndex + 1 < heapSize &&
4024 heap[childIndex + 1].distance < heap[childIndex].distance) {
4025 childIndex += 1;
4026 }
4027
4028 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4029 break;
4030 }
4031
4032 swap(heap[parentIndex], heap[childIndex]);
4033 parentIndex = childIndex;
4034 }
4035
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004036 if (DEBUG_POINTER_ASSIGNMENT) {
4037 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4038 for (size_t j = 0; j < heapSize; j++) {
4039 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4040 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4041 heap[j].distance);
4042 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004043 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004044 }
4045
4046 heapSize -= 1;
4047
4048 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4049 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4050
4051 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4052 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4053
4054 matchedCurrentBits.markBit(currentPointerIndex);
4055 matchedLastBits.markBit(lastPointerIndex);
4056
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004057 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4058 current.rawPointerData.pointers[currentPointerIndex].id = id;
4059 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4060 current.rawPointerData.markIdBit(id,
4061 current.rawPointerData.isHovering(
4062 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004063 usedIdBits.markBit(id);
4064
Harry Cutts45483602022-08-24 14:36:48 +00004065 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4066 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4067 ", distance=%" PRIu64,
4068 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004069 break;
4070 }
4071 }
4072
4073 // Assign fresh ids to pointers that were not matched in the process.
4074 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4075 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4076 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4077
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004078 current.rawPointerData.pointers[currentPointerIndex].id = id;
4079 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4080 current.rawPointerData.markIdBit(id,
4081 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004082
Harry Cutts45483602022-08-24 14:36:48 +00004083 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4084 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4085 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004086 }
4087}
4088
4089int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4090 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4091 return AKEY_STATE_VIRTUAL;
4092 }
4093
4094 for (const VirtualKey& virtualKey : mVirtualKeys) {
4095 if (virtualKey.keyCode == keyCode) {
4096 return AKEY_STATE_UP;
4097 }
4098 }
4099
4100 return AKEY_STATE_UNKNOWN;
4101}
4102
4103int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4104 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4105 return AKEY_STATE_VIRTUAL;
4106 }
4107
4108 for (const VirtualKey& virtualKey : mVirtualKeys) {
4109 if (virtualKey.scanCode == scanCode) {
4110 return AKEY_STATE_UP;
4111 }
4112 }
4113
4114 return AKEY_STATE_UNKNOWN;
4115}
4116
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004117bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4118 const std::vector<int32_t>& keyCodes,
4119 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004120 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004121 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004122 if (virtualKey.keyCode == keyCodes[i]) {
4123 outFlags[i] = 1;
4124 }
4125 }
4126 }
4127
4128 return true;
4129}
4130
4131std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4132 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004133 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004134 return std::make_optional(mPointerController->getDisplayId());
4135 } else {
4136 return std::make_optional(mViewport.displayId);
4137 }
4138 }
4139 return std::nullopt;
4140}
4141
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004142} // namespace android