blob: d8b1d61f6b273c7ce314b78dd64820559171c5a8 [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
Harry Cutts3f570c72024-04-05 16:44:28 +000023#include <algorithm>
24#include <cinttypes>
25#include <cmath>
26#include <cstddef>
27#include <tuple>
28
29#include <math.h>
30
31#include <android-base/stringprintf.h>
32#include <android/input.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080033#include <ftl/enum.h>
Prabir Pradhan8d9ba912022-11-11 22:26:33 +000034#include <input/PrintTools.h>
Harry Cutts3f570c72024-04-05 16:44:28 +000035#include <input/PropertyMap.h>
36#include <input/VirtualKeyMap.h>
37#include <linux/input-event-codes.h>
38#include <log/log_main.h>
39#include <math/vec2.h>
40#include <ui/FloatRect.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080041
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070042#include "CursorButtonAccumulator.h"
43#include "CursorScrollAccumulator.h"
44#include "TouchButtonAccumulator.h"
45#include "TouchCursorInputMapperCommon.h"
Michael Wrighta9cf4192022-12-01 23:46:39 +000046#include "ui/Rotation.h"
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070047
48namespace android {
49
50// --- Constants ---
51
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070052// Artificial latency on synthetic events created from stylus data without corresponding touch
53// data.
54static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
55
HQ Liue6983c72022-04-19 22:14:56 +000056// Minimum width between two pointers to determine a gesture as freeform gesture in mm
57static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070058// --- Static Definitions ---
59
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000060static const DisplayViewport kUninitializedViewport;
61
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000062static std::string toString(const Rect& rect) {
63 return base::StringPrintf("Rect{%d, %d, %d, %d}", rect.left, rect.top, rect.right, rect.bottom);
64}
65
66static std::string toString(const ui::Size& size) {
67 return base::StringPrintf("%dx%d", size.width, size.height);
68}
69
Prabir Pradhan675f25a2022-11-10 22:04:07 +000070static bool isPointInRect(const Rect& rect, vec2 p) {
71 return p.x >= rect.left && p.x < rect.right && p.y >= rect.top && p.y < rect.bottom;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000072}
73
Prabir Pradhane04ffaa2022-12-13 23:04:04 +000074static std::string toString(const InputDeviceUsiVersion& v) {
75 return base::StringPrintf("%d.%d", v.majorVersion, v.minorVersion);
76}
77
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070078template <typename T>
79inline static void swap(T& a, T& b) {
80 T temp = a;
81 a = b;
82 b = temp;
83}
84
85static float calculateCommonVector(float a, float b) {
86 if (a > 0 && b > 0) {
87 return a < b ? a : b;
88 } else if (a < 0 && b < 0) {
89 return a > b ? a : b;
90 } else {
91 return 0;
92 }
93}
94
95inline static float distance(float x1, float y1, float x2, float y2) {
96 return hypotf(x1 - x2, y1 - y2);
97}
98
99inline static int32_t signExtendNybble(int32_t value) {
100 return value >= 8 ? value - 16 : value;
101}
102
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000103static ui::Size getNaturalDisplaySize(const DisplayViewport& viewport) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000104 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000105 if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000106 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
107 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000108 return rotatedDisplaySize;
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000109}
110
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +0000111static int32_t filterButtonState(InputReaderConfiguration& config, int32_t buttonState) {
112 if (!config.stylusButtonMotionEventsEnabled) {
113 buttonState &=
114 ~(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY | AMOTION_EVENT_BUTTON_STYLUS_SECONDARY);
115 }
116 return buttonState;
117}
118
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700119// --- RawPointerData ---
120
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700121void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
122 float x = 0, y = 0;
123 uint32_t count = touchingIdBits.count();
124 if (count) {
125 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
126 uint32_t id = idBits.clearFirstMarkedBit();
127 const Pointer& pointer = pointerForId(id);
128 x += pointer.x;
129 y += pointer.y;
130 }
131 x /= count;
132 y /= count;
133 }
134 *outX = x;
135 *outY = y;
136}
137
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700138// --- TouchInputMapper ---
139
Arpit Singh8e6fb252023-04-06 11:49:17 +0000140TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext,
141 const InputReaderConfiguration& readerConfig)
142 : InputMapper(deviceContext, readerConfig),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000143 mTouchButtonAccumulator(deviceContext),
Arpit Singha8c236b2023-04-25 13:56:05 +0000144 mConfig(readerConfig) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700145
146TouchInputMapper::~TouchInputMapper() {}
147
Philip Junker4af3b3d2021-12-14 10:36:55 +0100148uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanb08a0e82023-09-14 22:28:32 +0000149 // The SOURCE_BLUETOOTH_STYLUS is added to events dynamically if the current stream is modified
150 // by the external stylus state. That's why we don't add it directly to mSource during
151 // configuration.
152 return mSource | (hasExternalStylus() ? AINPUT_SOURCE_BLUETOOTH_STYLUS : 0);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700153}
154
Harry Cuttsd02ea102023-03-17 18:21:30 +0000155void TouchInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700156 InputMapper::populateDeviceInfo(info);
157
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000158 if (mDeviceMode == DeviceMode::DISABLED) {
159 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700160 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000161
Harry Cuttsd02ea102023-03-17 18:21:30 +0000162 info.addMotionRange(mOrientedRanges.x);
163 info.addMotionRange(mOrientedRanges.y);
164 info.addMotionRange(mOrientedRanges.pressure);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000165
166 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
167 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
168 //
169 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
170 // motion, i.e. the hardware dimensions, as the finger could move completely across the
171 // touchpad in one sample cycle.
172 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
173 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
Harry Cuttsd02ea102023-03-17 18:21:30 +0000174 info.addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
175 x.resolution);
176 info.addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
177 y.resolution);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000178 }
179
180 if (mOrientedRanges.size) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000181 info.addMotionRange(*mOrientedRanges.size);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000182 }
183
184 if (mOrientedRanges.touchMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000185 info.addMotionRange(*mOrientedRanges.touchMajor);
186 info.addMotionRange(*mOrientedRanges.touchMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000187 }
188
189 if (mOrientedRanges.toolMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000190 info.addMotionRange(*mOrientedRanges.toolMajor);
191 info.addMotionRange(*mOrientedRanges.toolMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000192 }
193
194 if (mOrientedRanges.orientation) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000195 info.addMotionRange(*mOrientedRanges.orientation);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000196 }
197
198 if (mOrientedRanges.distance) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000199 info.addMotionRange(*mOrientedRanges.distance);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000200 }
201
202 if (mOrientedRanges.tilt) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000203 info.addMotionRange(*mOrientedRanges.tilt);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000204 }
205
206 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000207 info.addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000208 }
209 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000210 info.addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000211 }
Harry Cuttsd02ea102023-03-17 18:21:30 +0000212 info.setButtonUnderPad(mParameters.hasButtonUnderPad);
213 info.setUsiVersion(mParameters.usiVersion);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700214}
215
216void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700217 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800218 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700219 dumpParameters(dump);
220 dumpVirtualKeys(dump);
221 dumpRawPointerAxes(dump);
222 dumpCalibration(dump);
223 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700224 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700225
226 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000227 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000228 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
229 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
230 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700231 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
232 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
233 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
234 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
235 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
236 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
237 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
238 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
239 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
240 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
241
242 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
243 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
244 mLastRawState.rawPointerData.pointerCount);
245 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
246 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
247 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
248 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
249 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700250 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700251 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
252 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
253 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700254 pointer.distance, ftl::enum_string(pointer.toolType).c_str(),
255 toString(pointer.isHovering));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700256 }
257
258 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
259 mLastCookedState.buttonState);
260 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
261 mLastCookedState.cookedPointerData.pointerCount);
262 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
263 const PointerProperties& pointerProperties =
264 mLastCookedState.cookedPointerData.pointerProperties[i];
265 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000266 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
267 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
268 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700269 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700270 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700271 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000272 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
273 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700274 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
275 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
276 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
277 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
278 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
279 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
280 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
281 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700282 ftl::enum_string(pointerProperties.toolType).c_str(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700283 toString(mLastCookedState.cookedPointerData.isHovering(i)));
284 }
285
286 dump += INDENT3 "Stylus Fusion:\n";
287 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
288 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000289 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
290 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700291 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
292 mExternalStylusFusionTimeout);
Harry Cutts1ee05b62023-06-19 13:49:06 +0000293 dump += StringPrintf(INDENT4 "External Stylus Buttons Applied: 0x%08x\n",
Prabir Pradhan124ea442022-10-28 20:27:44 +0000294 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700295 dump += INDENT3 "External Stylus State:\n";
296 dumpStylusState(dump, mExternalStylusState);
297
Michael Wright227c5542020-07-02 18:30:52 +0100298 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700299 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
300 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
301 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
302 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
303 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
304 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
305 }
306}
307
Arpit Singh4be4eef2023-03-28 14:26:01 +0000308std::list<NotifyArgs> TouchInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000309 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000310 ConfigurationChanges changes) {
Arpit Singh4be4eef2023-03-28 14:26:01 +0000311 std::list<NotifyArgs> out = InputMapper::reconfigure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700312
Arpit Singhed6c3de2023-04-05 19:24:37 +0000313 mConfig = config;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000315 // Full configuration should happen the first time configure is called and
316 // when the device type is changed. Changing a device type can affect
317 // various other parameters so should result in a reconfiguration.
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000318 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700319 // Configure basic parameters.
Arpit Singh403e53c2023-04-18 11:46:56 +0000320 mParameters = computeParameters(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700321
322 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800323 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000324 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700325
326 // Configure absolute axis information.
327 configureRawPointerAxes();
328
329 // Prepare input device calibration.
330 parseCalibration();
331 resolveCalibration();
332 }
333
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000334 if (!changes.any() ||
335 changes.test(InputReaderConfiguration::Change::TOUCH_AFFINE_TRANSFORMATION)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700336 // Update location calibration to reflect current settings
337 updateAffineTransformation();
338 }
339
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000340 if (!changes.any() || changes.test(InputReaderConfiguration::Change::POINTER_SPEED)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 // Update pointer speed.
342 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
343 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
344 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
345 }
346
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000347 using namespace ftl::flag_operators;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700348 bool resetNeeded = false;
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000349 if (!changes.any() ||
350 changes.any(InputReaderConfiguration::Change::DISPLAY_INFO |
351 InputReaderConfiguration::Change::POINTER_CAPTURE |
352 InputReaderConfiguration::Change::POINTER_GESTURE_ENABLEMENT |
353 InputReaderConfiguration::Change::SHOW_TOUCHES |
354 InputReaderConfiguration::Change::EXTERNAL_STYLUS_PRESENCE |
355 InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700356 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700357 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700358 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700359 }
360
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000361 if (changes.any() && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700362 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000363
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364 // Send reset, unless this is the first time the device has been configured,
365 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000366 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700367 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700368 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700369}
370
371void TouchInputMapper::resolveExternalStylusPresence() {
372 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800373 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374 mExternalStylusConnected = !devices.empty();
375
376 if (!mExternalStylusConnected) {
377 resetExternalStylus();
378 }
379}
380
Arpit Singh403e53c2023-04-18 11:46:56 +0000381TouchInputMapper::Parameters TouchInputMapper::computeParameters(
382 const InputDeviceContext& deviceContext) {
383 Parameters parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384 // Use the pointer presentation mode for devices that do not support distinct
385 // multitouch. The spot-based presentation relies on being able to accurately
386 // locate two or more fingers on the touch pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000387 parameters.gestureMode = deviceContext.hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100388 ? Parameters::GestureMode::SINGLE_TOUCH
389 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700390
Arpit Singh403e53c2023-04-18 11:46:56 +0000391 const PropertyMap& config = deviceContext.getConfiguration();
Harry Cuttsf13161a2023-03-08 14:15:49 +0000392 std::optional<std::string> gestureModeString = config.getString("touch.gestureMode");
393 if (gestureModeString.has_value()) {
394 if (*gestureModeString == "single-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000395 parameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000396 } else if (*gestureModeString == "multi-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000397 parameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000398 } else if (*gestureModeString != "default") {
399 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700400 }
401 }
402
Arpit Singh403e53c2023-04-18 11:46:56 +0000403 parameters.deviceType = computeDeviceType(deviceContext);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700404
Arpit Singh403e53c2023-04-18 11:46:56 +0000405 parameters.hasButtonUnderPad = deviceContext.hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700406
Arpit Singh403e53c2023-04-18 11:46:56 +0000407 parameters.orientationAware =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000408 config.getBool("touch.orientationAware")
Arpit Singh403e53c2023-04-18 11:46:56 +0000409 .value_or(parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700410
Arpit Singh403e53c2023-04-18 11:46:56 +0000411 parameters.orientation = ui::ROTATION_0;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000412 std::optional<std::string> orientationString = config.getString("touch.orientation");
413 if (orientationString.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000414 if (parameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700415 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
Harry Cuttsf13161a2023-03-08 14:15:49 +0000416 } else if (*orientationString == "ORIENTATION_90") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000417 parameters.orientation = ui::ROTATION_90;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000418 } else if (*orientationString == "ORIENTATION_180") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000419 parameters.orientation = ui::ROTATION_180;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000420 } else if (*orientationString == "ORIENTATION_270") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000421 parameters.orientation = ui::ROTATION_270;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000422 } else if (*orientationString != "ORIENTATION_0") {
423 ALOGW("Invalid value for touch.orientation: '%s'", orientationString->c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700424 }
425 }
426
Arpit Singh403e53c2023-04-18 11:46:56 +0000427 parameters.hasAssociatedDisplay = false;
428 parameters.associatedDisplayIsExternal = false;
429 if (parameters.orientationAware ||
430 parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
431 parameters.deviceType == Parameters::DeviceType::POINTER ||
432 (parameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
433 deviceContext.getAssociatedViewport())) {
434 parameters.hasAssociatedDisplay = true;
435 if (parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
436 parameters.associatedDisplayIsExternal = deviceContext.isExternal();
437 parameters.uniqueDisplayId = config.getString("touch.displayId").value_or("").c_str();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700438 }
439 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000440 if (deviceContext.getAssociatedDisplayPort()) {
441 parameters.hasAssociatedDisplay = true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700442 }
443
444 // Initial downs on external touch devices should wake the device.
445 // Normally we don't do this for internal touch screens to prevent them from waking
446 // up in your pocket but you can enable it using the input device configuration.
Arpit Singh403e53c2023-04-18 11:46:56 +0000447 parameters.wake = config.getBool("touch.wake").value_or(deviceContext.isExternal());
Prabir Pradhan167c2702022-09-14 00:37:24 +0000448
Harry Cuttsf13161a2023-03-08 14:15:49 +0000449 std::optional<int32_t> usiVersionMajor = config.getInt("touch.usiVersionMajor");
450 std::optional<int32_t> usiVersionMinor = config.getInt("touch.usiVersionMinor");
451 if (usiVersionMajor.has_value() && usiVersionMinor.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000452 parameters.usiVersion = {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000453 .majorVersion = *usiVersionMajor,
454 .minorVersion = *usiVersionMinor,
455 };
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000456 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700457
Arpit Singh403e53c2023-04-18 11:46:56 +0000458 parameters.enableForInactiveViewport =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000459 config.getBool("touch.enableForInactiveViewport").value_or(false);
Arpit Singh403e53c2023-04-18 11:46:56 +0000460
461 return parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700462}
463
Arpit Singh403e53c2023-04-18 11:46:56 +0000464TouchInputMapper::Parameters::DeviceType TouchInputMapper::computeDeviceType(
465 const InputDeviceContext& deviceContext) {
466 Parameters::DeviceType deviceType;
467 if (deviceContext.hasInputProperty(INPUT_PROP_DIRECT)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000468 // The device is a touch screen.
Arpit Singh403e53c2023-04-18 11:46:56 +0000469 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
470 } else if (deviceContext.hasInputProperty(INPUT_PROP_POINTER)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000471 // The device is a pointing device like a track pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000472 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000473 } else {
474 // The device is a touch pad of unknown purpose.
Arpit Singh403e53c2023-04-18 11:46:56 +0000475 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000476 }
477
478 // Type association takes precedence over the device type found in the idc file.
Arpit Singh403e53c2023-04-18 11:46:56 +0000479 std::string deviceTypeString = deviceContext.getDeviceTypeAssociation().value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000480 if (deviceTypeString.empty()) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000481 deviceTypeString =
Arpit Singh403e53c2023-04-18 11:46:56 +0000482 deviceContext.getConfiguration().getString("touch.deviceType").value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000483 }
484 if (deviceTypeString == "touchScreen") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000485 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000486 } else if (deviceTypeString == "touchNavigation") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000487 deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000488 } else if (deviceTypeString == "pointer") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000489 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000490 } else if (deviceTypeString != "default" && deviceTypeString != "") {
491 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
492 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000493 return deviceType;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000494}
495
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496void TouchInputMapper::dumpParameters(std::string& dump) {
497 dump += INDENT3 "Parameters:\n";
498
Dominik Laskowski75788452021-02-09 18:51:25 -0800499 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700500
Dominik Laskowski75788452021-02-09 18:51:25 -0800501 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502
503 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
504 "displayId='%s'\n",
505 toString(mParameters.hasAssociatedDisplay),
506 toString(mParameters.associatedDisplayIsExternal),
507 mParameters.uniqueDisplayId.c_str());
508 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800509 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000510 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
511 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700512 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
513 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700514}
515
516void TouchInputMapper::configureRawPointerAxes() {
517 mRawPointerAxes.clear();
518}
519
520void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
521 dump += INDENT3 "Raw Touch Axes:\n";
522 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
523 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
524 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
525 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
526 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
527 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
528 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
529 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
530 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
531 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
532 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
533 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
534 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
535}
536
537bool TouchInputMapper::hasExternalStylus() const {
538 return mExternalStylusConnected;
539}
540
541/**
542 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000543 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800544 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000545 * 3. Get the matching viewport by either unique id in idc file or by the display type
546 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800547 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700548 */
549std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800550 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000551 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800552 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700553 }
554
Christine Franks2a2293c2022-01-18 11:51:16 -0800555 const std::optional<std::string> associatedDisplayUniqueId =
556 getDeviceContext().getAssociatedDisplayUniqueId();
557 if (associatedDisplayUniqueId) {
558 return getDeviceContext().getAssociatedViewport();
559 }
560
Michael Wright227c5542020-07-02 18:30:52 +0100561 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800562 std::optional<DisplayViewport> viewport =
563 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
564 if (viewport) {
565 return viewport;
566 } else {
567 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
568 mConfig.defaultPointerDisplayId);
569 }
570 }
571
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700572 // Check if uniqueDisplayId is specified in idc file.
573 if (!mParameters.uniqueDisplayId.empty()) {
574 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
575 }
576
577 ViewportType viewportTypeToUse;
578 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100579 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700580 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100581 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700582 }
583
584 std::optional<DisplayViewport> viewport =
585 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100586 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700587 ALOGW("Input device %s should be associated with external display, "
588 "fallback to internal one for the external viewport is not found.",
589 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100590 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700591 }
592
593 return viewport;
594 }
595
596 // No associated display, return a non-display viewport.
597 DisplayViewport newViewport;
598 // Raw width and height in the natural orientation.
599 int32_t rawWidth = mRawPointerAxes.getRawWidth();
600 int32_t rawHeight = mRawPointerAxes.getRawHeight();
601 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
602 return std::make_optional(newViewport);
603}
604
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800605int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
606 if (resolution < 0) {
607 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
608 getDeviceName().c_str());
609 return 0;
610 }
611 return resolution;
612}
613
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800614void TouchInputMapper::initializeSizeRanges() {
615 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
616 mSizeScale = 0.0f;
617 return;
618 }
619
620 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000621 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800622
623 // Size factors.
624 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
625 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
626 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
627 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
628 } else {
629 mSizeScale = 0.0f;
630 }
631
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700632 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
633 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
634 .source = mSource,
635 .min = 0,
636 .max = diagonalSize,
637 .flat = 0,
638 .fuzz = 0,
639 .resolution = 0,
640 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800641
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800642 if (mRawPointerAxes.touchMajor.valid) {
643 mRawPointerAxes.touchMajor.resolution =
644 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700645 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800646 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800647
648 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700649 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800650 if (mRawPointerAxes.touchMinor.valid) {
651 mRawPointerAxes.touchMinor.resolution =
652 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700653 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800654 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800655
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700656 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
657 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
658 .source = mSource,
659 .min = 0,
660 .max = diagonalSize,
661 .flat = 0,
662 .fuzz = 0,
663 .resolution = 0,
664 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800665 if (mRawPointerAxes.toolMajor.valid) {
666 mRawPointerAxes.toolMajor.resolution =
667 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700668 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800669 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800670
671 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700672 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800673 if (mRawPointerAxes.toolMinor.valid) {
674 mRawPointerAxes.toolMinor.resolution =
675 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700676 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800677 }
678
679 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700680 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
681 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
682 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
683 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800684 } else {
685 // Support for other calibrations can be added here.
686 ALOGW("%s calibration is not supported for size ranges at the moment. "
687 "Using raw resolution instead",
688 ftl::enum_string(mCalibration.sizeCalibration).c_str());
689 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800690
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700691 mOrientedRanges.size = InputDeviceInfo::MotionRange{
692 .axis = AMOTION_EVENT_AXIS_SIZE,
693 .source = mSource,
694 .min = 0,
695 .max = 1.0,
696 .flat = 0,
697 .fuzz = 0,
698 .resolution = 0,
699 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800700}
701
702void TouchInputMapper::initializeOrientedRanges() {
703 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000704 const float orientedScaleX = mRawToDisplay.getScaleX();
705 const float orientedScaleY = mRawToDisplay.getScaleY();
706 mOrientedXPrecision = 1.0f / orientedScaleX;
707 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800708
709 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
710 mOrientedRanges.x.source = mSource;
711 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
712 mOrientedRanges.y.source = mSource;
713
714 // Scale factor for terms that are not oriented in a particular axis.
715 // If the pixels are square then xScale == yScale otherwise we fake it
716 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000717 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800718
719 initializeSizeRanges();
720
721 // Pressure factors.
722 mPressureScale = 0;
723 float pressureMax = 1.0;
724 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
725 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700726 if (mCalibration.pressureScale) {
727 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800728 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
729 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
730 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
731 }
732 }
733
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700734 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
735 .axis = AMOTION_EVENT_AXIS_PRESSURE,
736 .source = mSource,
737 .min = 0,
738 .max = pressureMax,
739 .flat = 0,
740 .fuzz = 0,
741 .resolution = 0,
742 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800743
744 // Tilt
745 mTiltXCenter = 0;
746 mTiltXScale = 0;
747 mTiltYCenter = 0;
748 mTiltYScale = 0;
749 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
750 if (mHaveTilt) {
751 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
752 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
753 mTiltXScale = M_PI / 180;
754 mTiltYScale = M_PI / 180;
755
756 if (mRawPointerAxes.tiltX.resolution) {
757 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
758 }
759 if (mRawPointerAxes.tiltY.resolution) {
760 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
761 }
762
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700763 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
764 .axis = AMOTION_EVENT_AXIS_TILT,
765 .source = mSource,
766 .min = 0,
767 .max = M_PI_2,
768 .flat = 0,
769 .fuzz = 0,
770 .resolution = 0,
771 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800772 }
773
774 // Orientation
775 mOrientationScale = 0;
776 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700777 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
778 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
779 .source = mSource,
780 .min = -M_PI,
781 .max = M_PI,
782 .flat = 0,
783 .fuzz = 0,
784 .resolution = 0,
785 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800786
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800787 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
788 if (mCalibration.orientationCalibration ==
789 Calibration::OrientationCalibration::INTERPOLATED) {
790 if (mRawPointerAxes.orientation.valid) {
791 if (mRawPointerAxes.orientation.maxValue > 0) {
792 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
793 } else if (mRawPointerAxes.orientation.minValue < 0) {
794 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
795 } else {
796 mOrientationScale = 0;
797 }
798 }
799 }
800
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700801 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
802 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
803 .source = mSource,
804 .min = -M_PI_2,
805 .max = M_PI_2,
806 .flat = 0,
807 .fuzz = 0,
808 .resolution = 0,
809 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800810 }
811
812 // Distance
813 mDistanceScale = 0;
814 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
815 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700816 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800817 }
818
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700819 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800820
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700821 .axis = AMOTION_EVENT_AXIS_DISTANCE,
822 .source = mSource,
823 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
824 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
825 .flat = 0,
826 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
827 .resolution = 0,
828 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800829 }
830
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000831 // Oriented X/Y range (in the rotated display's orientation)
832 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
833 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
834 .toFloatRect();
835 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
836 mOrientedRanges.x.min = orientedRangeRect.left;
837 mOrientedRanges.y.min = orientedRangeRect.top;
838 mOrientedRanges.x.max = orientedRangeRect.right;
839 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800840
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000841 // Oriented flat (in the rotated display's orientation)
842 const auto orientedFlat =
843 transformWithoutTranslation(mRawToRotatedDisplay,
844 {static_cast<float>(mRawPointerAxes.x.flat),
845 static_cast<float>(mRawPointerAxes.y.flat)});
846 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
847 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800848
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000849 // Oriented fuzz (in the rotated display's orientation)
850 const auto orientedFuzz =
851 transformWithoutTranslation(mRawToRotatedDisplay,
852 {static_cast<float>(mRawPointerAxes.x.fuzz),
853 static_cast<float>(mRawPointerAxes.y.fuzz)});
854 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
855 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800856
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000857 // Oriented resolution (in the rotated display's orientation)
858 const auto orientedRes =
859 transformWithoutTranslation(mRawToRotatedDisplay,
860 {static_cast<float>(mRawPointerAxes.x.resolution),
861 static_cast<float>(mRawPointerAxes.y.resolution)});
862 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
863 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800864}
865
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000866void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000867 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
868 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
869 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000870
Prabir Pradhan3e798762022-12-02 21:02:11 +0000871 // See notes about input coordinates in the inputflinger docs:
872 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000873
874 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000875 ui::Transform undoOffsetInRaw;
876 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000877
Prabir Pradhan3e798762022-12-02 21:02:11 +0000878 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
879 // will now be in the same orientation as the display in ROTATION_0.
880 // Note: Negating an ui::Rotation value will give its inverse rotation.
881 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
882 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
883 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
884 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
885 // When rotating raw values, account for the extra unit added when calculating the raw range.
886 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
887 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000888
Prabir Pradhan3e798762022-12-02 21:02:11 +0000889 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
890 // now be in the same orientation as the rotated display. There is no need to rotate the
891 // coordinates to the display rotation if the device is not orientation-aware.
892 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
893 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
894 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
895 : orientedRawSize;
896 // When rotating raw values, account for the extra unit added when calculating the raw range.
897 const auto rotateInRaw = mParameters.orientationAware
898 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
899 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000900
Prabir Pradhan3e798762022-12-02 21:02:11 +0000901 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000902 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
903 // the surface of the display panel. This is usually true for touchscreens.
904 // - In POINTER mode, we cannot assume that the display and the touch device have the same
905 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
906 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
907 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
908 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000909 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
910 // are in the continuous space of the logical display.
911 ui::Transform scaleRawToDisplay;
912 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
913 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000914 if (mDeviceMode == DeviceMode::DIRECT) {
915 scaleRawToDisplay.set(xScale, 0, 0, yScale);
916 } else if (mDeviceMode == DeviceMode::POINTER) {
917 const float fixedScale = std::max(xScale, yScale);
918 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
919 } else {
920 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
921 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000922
Prabir Pradhan3e798762022-12-02 21:02:11 +0000923 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
924 // that InputReader uses.
925 const auto undoRotateInDisplay =
926 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
927 .inverse();
928
929 // Now put it all together!
930 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
931 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
932 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000933}
934
Prabir Pradhan1728b212021-10-19 16:00:03 -0700935void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000936 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700937
938 resolveExternalStylusPresence();
939
940 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100941 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +0900942 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700943 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100944 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700945 if (hasStylus()) {
946 mSource |= AINPUT_SOURCE_STYLUS;
947 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800948 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700949 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100950 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700951 if (hasStylus()) {
952 mSource |= AINPUT_SOURCE_STYLUS;
953 }
Michael Wright227c5542020-07-02 18:30:52 +0100954 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700955 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100956 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700957 } else {
958 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100959 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700960 }
961
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000962 const std::optional<DisplayViewport> newViewportOpt = findViewport();
963
964 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700965 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
966 ALOGW("Touch device '%s' did not report support for X or Y axis! "
967 "The device will be inoperable.",
968 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100969 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000970 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700971 ALOGI("Touch device '%s' could not query the properties of its associated "
972 "display. The device will be inoperable until the display size "
973 "becomes available.",
974 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100975 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700976 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000977 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
978 getDeviceName().c_str(), getDeviceId());
979 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000980 }
981
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700982 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000983 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000984 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
985 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
986 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
987 const float rawMeanResolution =
988 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700989
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000990 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
Josh Thielene986aed2023-06-01 14:17:30 +0000991 bool viewportChanged;
992 if (mParameters.enableForInactiveViewport) {
993 // When touch is enabled for an inactive viewport, ignore the
994 // viewport active status when checking whether the viewport has
995 // changed.
996 DisplayViewport tempViewport = mViewport;
997 tempViewport.isActive = newViewport.isActive;
998 viewportChanged = tempViewport != newViewport;
999 } else {
1000 viewportChanged = mViewport != newViewport;
1001 }
1002
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001003 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001004 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +00001005 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
1006 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
1007 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001008
Michael Wright227c5542020-07-02 18:30:52 +01001009 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +00001010 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001011
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001012 mDisplayBounds = getNaturalDisplaySize(mViewport);
1013 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
1014 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -07001015
Prabir Pradhan3e798762022-12-02 21:02:11 +00001016 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
1017 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
1018 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001019 // InputReader works in the un-rotated display coordinate space, so we don't need to do
1020 // anything if the device is already orientation-aware. If the device is not
1021 // orientation-aware, then we need to apply the inverse rotation of the display so that
1022 // when the display rotation is applied later as a part of the per-window transform, we
1023 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001024 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +00001025 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001026 : getInverseRotation(mViewport.orientation);
1027 // For orientation-aware devices that work in the un-rotated coordinate space, the
1028 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001029 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001030 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001031
1032 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001033 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001034 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001035 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001036 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001037 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001038 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001039 mRawToDisplay.reset();
1040 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001041 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001042 }
1043 }
1044
1045 // If moving between pointer modes, need to reset some state.
1046 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1047 if (deviceModeChanged) {
1048 mOrientedRanges.clear();
1049 }
1050
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001051 // Create and preserve the pointer controller in the following cases:
1052 const bool isPointerControllerNeeded =
1053 // - when the device is in pointer mode, to show the mouse cursor;
1054 (mDeviceMode == DeviceMode::POINTER) ||
1055 // - when pointer capture is enabled, to preserve the mouse cursor position;
1056 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +09001057 mConfig.pointerCaptureRequest.isEnable()) ||
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001058 // - when we should be showing touches;
1059 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1060 // - when we should be showing a pointer icon for direct styluses.
1061 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1062 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001063 if (mPointerController == nullptr) {
1064 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001065 }
Hiroki Sato25040232024-02-22 17:21:22 +09001066 if (mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001067 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1068 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001069 } else {
lilinnandef700b2022-06-17 19:32:01 +08001070 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1071 !mConfig.showTouches) {
1072 mPointerController->clearSpots();
1073 }
Michael Wright17db18e2020-06-26 20:51:44 +01001074 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001075 }
1076
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001077 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001078 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001079 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001080 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001081 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001082
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001083 configureVirtualKeys();
1084
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001085 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086
1087 // Location
1088 updateAffineTransformation();
1089
Michael Wright227c5542020-07-02 18:30:52 +01001090 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001091 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001092 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1093 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001094
1095 // Scale movements such that one whole swipe of the touch pad covers a
1096 // given area relative to the diagonal size of the display when no acceleration
1097 // is applied.
1098 // Assume that the touch pad has a square aspect ratio such that movements in
1099 // X and Y of the same number of raw units cover the same physical distance.
1100 mPointerXMovementScale =
1101 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1102 mPointerYMovementScale = mPointerXMovementScale;
1103
1104 // Scale zooms to cover a smaller range of the display than movements do.
1105 // This value determines the area around the pointer that is affected by freeform
1106 // pointer gestures.
1107 mPointerXZoomScale =
1108 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1109 mPointerYZoomScale = mPointerXZoomScale;
1110
HQ Liue6983c72022-04-19 22:14:56 +00001111 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1112 // axis is non positive value.
1113 const float minFreeformGestureWidth =
1114 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1115
1116 mPointerGestureMaxSwipeWidth =
1117 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1118 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001119 }
1120
1121 // Inform the dispatcher about the changes.
1122 *outResetNeeded = true;
1123 bumpGeneration();
1124 }
1125}
1126
Prabir Pradhan1728b212021-10-19 16:00:03 -07001127void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001128 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001129 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001130 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1131 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001132 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133}
1134
1135void TouchInputMapper::configureVirtualKeys() {
1136 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001137 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001138
1139 mVirtualKeys.clear();
1140
1141 if (virtualKeyDefinitions.size() == 0) {
1142 return;
1143 }
1144
1145 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1146 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1147 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1148 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1149
1150 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1151 VirtualKey virtualKey;
1152
1153 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1154 int32_t keyCode;
1155 int32_t dummyKeyMetaState;
1156 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001157 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1158 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001159 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1160 continue; // drop the key
1161 }
1162
1163 virtualKey.keyCode = keyCode;
1164 virtualKey.flags = flags;
1165
1166 // convert the key definition's display coordinates into touch coordinates for a hit box
1167 int32_t halfWidth = virtualKeyDefinition.width / 2;
1168 int32_t halfHeight = virtualKeyDefinition.height / 2;
1169
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001170 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1171 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001173 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1174 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001176 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1177 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001179 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1180 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181 touchScreenTop;
1182 mVirtualKeys.push_back(virtualKey);
1183 }
1184}
1185
1186void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1187 if (!mVirtualKeys.empty()) {
1188 dump += INDENT3 "Virtual Keys:\n";
1189
1190 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1191 const VirtualKey& virtualKey = mVirtualKeys[i];
1192 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1193 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1194 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1195 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1196 }
1197 }
1198}
1199
1200void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001201 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 Calibration& out = mCalibration;
1203
1204 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001205 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001206 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1207 if (sizeCalibrationString.has_value()) {
1208 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001209 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001210 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001211 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001212 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001213 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001214 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001215 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001216 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001217 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001218 } else if (*sizeCalibrationString != "default") {
1219 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220 }
1221 }
1222
Harry Cuttsf13161a2023-03-08 14:15:49 +00001223 out.sizeScale = in.getFloat("touch.size.scale");
1224 out.sizeBias = in.getFloat("touch.size.bias");
1225 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001226
1227 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001228 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001229 std::optional<std::string> pressureCalibrationString =
1230 in.getString("touch.pressure.calibration");
1231 if (pressureCalibrationString.has_value()) {
1232 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001233 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001234 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001235 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001236 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001237 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001238 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001240 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241 }
1242 }
1243
Harry Cuttsf13161a2023-03-08 14:15:49 +00001244 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245
1246 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001247 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001248 std::optional<std::string> orientationCalibrationString =
1249 in.getString("touch.orientation.calibration");
1250 if (orientationCalibrationString.has_value()) {
1251 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001252 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001253 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001254 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001255 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001256 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001257 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001259 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 }
1261 }
1262
1263 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001264 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001265 std::optional<std::string> distanceCalibrationString =
1266 in.getString("touch.distance.calibration");
1267 if (distanceCalibrationString.has_value()) {
1268 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001269 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001270 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001271 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001272 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001274 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275 }
1276 }
1277
Harry Cuttsf13161a2023-03-08 14:15:49 +00001278 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279}
1280
1281void TouchInputMapper::resolveCalibration() {
1282 // Size
1283 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001284 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1285 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001286 }
1287 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001288 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 }
1290
1291 // Pressure
1292 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001293 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1294 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 }
1296 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001297 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 }
1299
1300 // Orientation
1301 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001302 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1303 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 }
1305 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001306 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 }
1308
1309 // Distance
1310 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001311 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1312 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 }
1314 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001315 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317}
1318
1319void TouchInputMapper::dumpCalibration(std::string& dump) {
1320 dump += INDENT3 "Calibration:\n";
1321
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001322 dump += INDENT4 "touch.size.calibration: ";
1323 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001325 if (mCalibration.sizeScale) {
1326 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001327 }
1328
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001329 if (mCalibration.sizeBias) {
1330 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 }
1332
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001333 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001335 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001336 }
1337
1338 // Pressure
1339 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001340 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.pressure.calibration: none\n";
1342 break;
Michael Wright227c5542020-07-02 18:30:52 +01001343 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.pressure.calibration: physical\n";
1345 break;
Michael Wright227c5542020-07-02 18:30:52 +01001346 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001347 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1348 break;
1349 default:
1350 ALOG_ASSERT(false);
1351 }
1352
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001353 if (mCalibration.pressureScale) {
1354 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001355 }
1356
1357 // Orientation
1358 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001359 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360 dump += INDENT4 "touch.orientation.calibration: none\n";
1361 break;
Michael Wright227c5542020-07-02 18:30:52 +01001362 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001363 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1364 break;
Michael Wright227c5542020-07-02 18:30:52 +01001365 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001366 dump += INDENT4 "touch.orientation.calibration: vector\n";
1367 break;
1368 default:
1369 ALOG_ASSERT(false);
1370 }
1371
1372 // Distance
1373 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001374 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001375 dump += INDENT4 "touch.distance.calibration: none\n";
1376 break;
Michael Wright227c5542020-07-02 18:30:52 +01001377 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001378 dump += INDENT4 "touch.distance.calibration: scaled\n";
1379 break;
1380 default:
1381 ALOG_ASSERT(false);
1382 }
1383
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001384 if (mCalibration.distanceScale) {
1385 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001386 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001387}
1388
1389void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1390 dump += INDENT3 "Affine Transformation:\n";
1391
1392 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1393 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1394 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1395 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1396 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1397 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1398}
1399
1400void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001401 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001402 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001403}
1404
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001405std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001406 std::list<NotifyArgs> out = cancelTouch(when, when);
1407 updateTouchSpots();
1408
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001409 mCursorButtonAccumulator.reset(getDeviceContext());
1410 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001411 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001412
1413 mPointerVelocityControl.reset();
1414 mWheelXVelocityControl.reset();
1415 mWheelYVelocityControl.reset();
1416
1417 mRawStatesPending.clear();
1418 mCurrentRawState.clear();
1419 mCurrentCookedState.clear();
1420 mLastRawState.clear();
1421 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001422 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001423 mSentHoverEnter = false;
1424 mHavePointerIds = false;
1425 mCurrentMotionAborted = false;
1426 mDownTime = 0;
1427
1428 mCurrentVirtualKey.down = false;
1429
1430 mPointerGesture.reset();
1431 mPointerSimple.reset();
1432 resetExternalStylus();
1433
1434 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001435 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436 mPointerController->clearSpots();
1437 }
1438
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001439 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440}
1441
1442void TouchInputMapper::resetExternalStylus() {
1443 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001444 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001445 mExternalStylusFusionTimeout = LLONG_MAX;
1446 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001447 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001448}
1449
1450void TouchInputMapper::clearStylusDataPendingFlags() {
1451 mExternalStylusDataPending = false;
1452 mExternalStylusFusionTimeout = LLONG_MAX;
1453}
1454
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001455std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001456 mCursorButtonAccumulator.process(rawEvent);
1457 mCursorScrollAccumulator.process(rawEvent);
1458 mTouchButtonAccumulator.process(rawEvent);
1459
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001460 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001461 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001462 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001463 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001464 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001465}
1466
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001467std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1468 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001469 if (mDeviceMode == DeviceMode::DISABLED) {
1470 // Only save the last pending state when the device is disabled.
1471 mRawStatesPending.clear();
1472 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001473 // Push a new state.
1474 mRawStatesPending.emplace_back();
1475
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001476 RawState& next = mRawStatesPending.back();
1477 next.clear();
1478 next.when = when;
1479 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001480
1481 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001482 next.buttonState = filterButtonState(mConfig,
1483 mTouchButtonAccumulator.getButtonState() |
1484 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001485
1486 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001487 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1488 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001489 mCursorScrollAccumulator.finishSync();
1490
1491 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001492 syncTouch(when, &next);
1493
1494 // The last RawState is the actually second to last, since we just added a new state
1495 const RawState& last =
1496 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001497
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001498 std::tie(next.when, next.readTime) =
1499 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1500 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001501
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001502 // Assign pointer ids.
1503 if (!mHavePointerIds) {
1504 assignPointerIds(last, next);
1505 }
1506
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001507 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001508 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1509 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1510 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1511 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1512 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1513 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001514
Arthur Hung9ad18942021-06-19 02:04:46 +00001515 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1516 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1517 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1518 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1519 next.rawPointerData.hoveringIdBits.value);
1520 }
1521
Harry Cutts33476232023-01-30 19:57:29 +00001522 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001523 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524}
1525
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001526std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1527 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001528 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001529 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001530 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001531 }
1532
1533 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1534 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1535 // touching the current state will only observe the events that have been dispatched to the
1536 // rest of the pipeline.
1537 const size_t N = mRawStatesPending.size();
1538 size_t count;
1539 for (count = 0; count < N; count++) {
1540 const RawState& next = mRawStatesPending[count];
1541
1542 // A failure to assign the stylus id means that we're waiting on stylus data
1543 // and so should defer the rest of the pipeline.
1544 if (assignExternalStylusId(next, timeout)) {
1545 break;
1546 }
1547
1548 // All ready to go.
1549 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001550 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001551 if (mCurrentRawState.when < mLastRawState.when) {
1552 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001553 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001554 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001555 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001556 }
1557 if (count != 0) {
1558 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1559 }
1560
1561 if (mExternalStylusDataPending) {
1562 if (timeout) {
1563 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1564 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001565 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001566 ALOGD_IF(DEBUG_STYLUS_FUSION,
1567 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001568 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001569 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001570 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1571 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1572 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1573 }
1574 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001575 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001576}
1577
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001578std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1579 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001580 // Always start with a clean state.
1581 mCurrentCookedState.clear();
1582
1583 // Apply stylus buttons to current raw state.
1584 applyExternalStylusButtonState(when);
1585
1586 // Handle policy on initial down or hover events.
1587 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1588 mCurrentRawState.rawPointerData.pointerCount != 0;
1589
1590 uint32_t policyFlags = 0;
1591 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1592 if (initialDown || buttonsPressed) {
1593 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001594 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001595 getContext()->fadePointer();
1596 }
1597
1598 if (mParameters.wake) {
1599 policyFlags |= POLICY_FLAG_WAKE;
1600 }
1601 }
1602
1603 // Consume raw off-screen touches before cooking pointer data.
1604 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001605 bool consumed;
1606 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1607 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001608 mCurrentRawState.rawPointerData.clear();
1609 }
1610
1611 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1612 // with cooked pointer data that has the same ids and indices as the raw data.
1613 // The following code can use either the raw or cooked data, as needed.
1614 cookPointerData();
1615
1616 // Apply stylus pressure to current cooked state.
1617 applyExternalStylusTouchState(when);
1618
1619 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001620 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1621 mSource, mViewport.displayId, policyFlags,
1622 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001623
1624 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001625 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001626 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1627 uint32_t id = idBits.clearFirstMarkedBit();
1628 const RawPointerData::Pointer& pointer =
1629 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001630 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001631 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001632 } else if (pointer.toolType == ToolType::FINGER ||
1633 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001634 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001635 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001636 mCurrentCookedState.mouseIdBits.markBit(id);
1637 }
1638 }
1639 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1640 uint32_t id = idBits.clearFirstMarkedBit();
1641 const RawPointerData::Pointer& pointer =
1642 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001643 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001644 mCurrentCookedState.stylusIdBits.markBit(id);
1645 }
1646 }
1647
1648 // Stylus takes precedence over all tools, then mouse, then finger.
1649 PointerUsage pointerUsage = mPointerUsage;
1650 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1651 mCurrentCookedState.mouseIdBits.clear();
1652 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001653 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001654 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1655 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001656 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001657 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1658 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001659 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001660 }
1661
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001662 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001663 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001664 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001665 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001666 out += dispatchButtonRelease(when, readTime, policyFlags);
1667 out += dispatchHoverExit(when, readTime, policyFlags);
1668 out += dispatchTouches(when, readTime, policyFlags);
1669 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1670 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001671 }
1672
1673 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1674 mCurrentMotionAborted = false;
1675 }
1676 }
1677
1678 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001679 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1680 mSource, mViewport.displayId, policyFlags,
1681 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001682
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001683 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1684 mCurrentStreamModifiedByExternalStylus = false;
1685 }
1686
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001687 // Clear some transient state.
1688 mCurrentRawState.rawVScroll = 0;
1689 mCurrentRawState.rawHScroll = 0;
1690
1691 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001692 mLastRawState = mCurrentRawState;
1693 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001694 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001695}
1696
Garfield Tanc734e4f2021-01-15 20:01:39 -08001697void TouchInputMapper::updateTouchSpots() {
1698 if (!mConfig.showTouches || mPointerController == nullptr) {
1699 return;
1700 }
1701
1702 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1703 // clear touch spots.
1704 if (mDeviceMode != DeviceMode::DIRECT &&
1705 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1706 return;
1707 }
1708
1709 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1710 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1711
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001712 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1713 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001714 mCurrentCookedState.cookedPointerData.touchingIdBits |
1715 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001716 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001717}
1718
1719bool TouchInputMapper::isTouchScreen() {
1720 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1721 mParameters.hasAssociatedDisplay;
1722}
1723
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001724void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001725 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1726 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001727 const int32_t pressedButtons =
1728 filterButtonState(mConfig,
1729 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001730 const int32_t releasedButtons =
1731 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1732
1733 mCurrentRawState.buttonState |= pressedButtons;
1734 mCurrentRawState.buttonState &= ~releasedButtons;
1735
1736 mExternalStylusButtonsApplied |= pressedButtons;
1737 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001738
1739 if (mExternalStylusButtonsApplied != 0 || releasedButtons != 0) {
1740 mCurrentStreamModifiedByExternalStylus = true;
1741 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001742 }
1743}
1744
1745void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1746 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1747 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001748 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1749 return;
1750 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001751
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001752 mCurrentStreamModifiedByExternalStylus = true;
1753
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001754 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1755 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1756 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1757 : 0.f;
1758 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1759 pressure = *mExternalStylusState.pressure;
1760 }
1761 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1762 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001763
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001764 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001765 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001766 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001767 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001768 }
1769}
1770
1771bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001772 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001773 return false;
1774 }
1775
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001776 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001777 if (mFusedStylusPointerId &&
1778 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001779 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001780 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001781 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001782 }
1783
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001784 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1785 state.rawPointerData.pointerCount != 0;
1786 if (!initialDown) {
1787 return false;
1788 }
1789
1790 if (!mExternalStylusState.pressure) {
1791 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1792 return false;
1793 }
1794
1795 if (*mExternalStylusState.pressure != 0.0f) {
1796 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1797 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1798 return false;
1799 }
1800
1801 if (timeout) {
1802 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1803 mFusedStylusPointerId.reset();
1804 mExternalStylusFusionTimeout = LLONG_MAX;
1805 return false;
1806 }
1807
1808 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1809 // being processed until we either get pressure data or timeout.
1810 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1811 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1812 }
1813 ALOGD_IF(DEBUG_STYLUS_FUSION,
1814 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1815 mExternalStylusFusionTimeout);
1816 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1817 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001818}
1819
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001820std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1821 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001822 if (mDeviceMode == DeviceMode::POINTER) {
1823 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001824 // Since this is a synthetic event, we can consider its latency to be zero
1825 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001826 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001827 }
Michael Wright227c5542020-07-02 18:30:52 +01001828 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001829 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001830 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001831 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1832 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1833 }
1834 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001835 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001836}
1837
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001838std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1839 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001840 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001841 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001842 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001843 // The following three cases are handled here:
1844 // - We're in the middle of a fused stream of data;
1845 // - We're waiting on external stylus data before dispatching the initial down; or
1846 // - Only the button state, which is not reported through a specific pointer, has changed.
1847 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001848 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001849 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001850 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001851 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001852}
1853
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001854std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1855 uint32_t policyFlags, bool& outConsumed) {
1856 outConsumed = false;
1857 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001858 // Check for release of a virtual key.
1859 if (mCurrentVirtualKey.down) {
1860 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1861 // Pointer went up while virtual key was down.
1862 mCurrentVirtualKey.down = false;
1863 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001864 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1865 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1866 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001867 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1868 AKEY_EVENT_FLAG_FROM_SYSTEM |
1869 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001870 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001871 outConsumed = true;
1872 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001873 }
1874
1875 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1876 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1877 const RawPointerData::Pointer& pointer =
1878 mCurrentRawState.rawPointerData.pointerForId(id);
1879 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1880 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1881 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001882 outConsumed = true;
1883 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001884 }
1885 }
1886
1887 // Pointer left virtual key area or another pointer also went down.
1888 // Send key cancellation but do not consume the touch yet.
1889 // This is useful when the user swipes through from the virtual key area
1890 // into the main display surface.
1891 mCurrentVirtualKey.down = false;
1892 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001893 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1894 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001895 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1896 AKEY_EVENT_FLAG_FROM_SYSTEM |
1897 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1898 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001899 }
1900 }
1901
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001902 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
1903 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty() &&
1904 mDeviceMode != DeviceMode::UNSCALED) {
1905 // We have hovering pointers, and there are no touching pointers.
1906 bool hoveringPointersInFrame = false;
1907 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1908 while (!hoveringIds.isEmpty()) {
1909 uint32_t id = hoveringIds.clearFirstMarkedBit();
1910 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1911 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1912 hoveringPointersInFrame = true;
1913 break;
1914 }
1915 }
1916 if (!hoveringPointersInFrame) {
1917 // All hovering pointers are outside the physical frame.
1918 outConsumed = true;
1919 return out;
1920 }
1921 }
1922
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001923 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1924 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1925 // Pointer just went down. Check for virtual key press or off-screen touches.
1926 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1927 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001928 // Skip checking whether the pointer is inside the physical frame if the device is in
Harry Cutts1db43992023-06-19 17:05:07 +00001929 // unscaled or pointer mode.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001930 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
Harry Cutts1db43992023-06-19 17:05:07 +00001931 mDeviceMode != DeviceMode::UNSCALED && mDeviceMode != DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001932 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001933 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001934 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1935 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1936 if (virtualKey) {
1937 mCurrentVirtualKey.down = true;
1938 mCurrentVirtualKey.downTime = when;
1939 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1940 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1941 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001942 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1943 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001944
1945 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001946 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1947 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1948 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001949 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1950 AKEY_EVENT_ACTION_DOWN,
1951 AKEY_EVENT_FLAG_FROM_SYSTEM |
1952 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001953 }
1954 }
1955 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001956 outConsumed = true;
1957 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001958 }
1959 }
1960
1961 // Disable all virtual key touches that happen within a short time interval of the
1962 // most recent touch within the screen area. The idea is to filter out stray
1963 // virtual key presses when interacting with the touch screen.
1964 //
1965 // Problems we're trying to solve:
1966 //
1967 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1968 // virtual key area that is implemented by a separate touch panel and accidentally
1969 // triggers a virtual key.
1970 //
1971 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1972 // area and accidentally triggers a virtual key. This often happens when virtual keys
1973 // are layed out below the screen near to where the on screen keyboard's space bar
1974 // is displayed.
1975 if (mConfig.virtualKeyQuietTime > 0 &&
1976 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001977 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001978 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001979 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001980}
1981
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001982NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1983 uint32_t policyFlags, int32_t keyEventAction,
1984 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001985 int32_t keyCode = mCurrentVirtualKey.keyCode;
1986 int32_t scanCode = mCurrentVirtualKey.scanCode;
1987 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001988 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001989 policyFlags |= POLICY_FLAG_VIRTUAL;
1990
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001991 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1992 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1993 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001994}
1995
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001996std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1997 uint32_t policyFlags) {
1998 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001999 if (mCurrentMotionAborted) {
2000 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002001 return out;
lilinnan687e58f2022-07-19 16:00:50 +08002002 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002003 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2004 if (!currentIdBits.isEmpty()) {
2005 int32_t metaState = getContext()->getGlobalMetaState();
2006 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002007 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002008 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2009 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002010 mCurrentCookedState.cookedPointerData.pointerProperties,
2011 mCurrentCookedState.cookedPointerData.pointerCoords,
2012 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2013 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2014 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002015 mCurrentMotionAborted = true;
2016 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002017 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002018}
2019
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002020// Updates pointer coords and properties for pointers with specified ids that have moved.
2021// Returns true if any of them changed.
2022static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
2023 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
2024 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
2025 BitSet32 idBits) {
2026 bool changed = false;
2027 while (!idBits.isEmpty()) {
2028 uint32_t id = idBits.clearFirstMarkedBit();
2029 uint32_t inIndex = inIdToIndex[id];
2030 uint32_t outIndex = outIdToIndex[id];
2031
2032 const PointerProperties& curInProperties = inProperties[inIndex];
2033 const PointerCoords& curInCoords = inCoords[inIndex];
2034 PointerProperties& curOutProperties = outProperties[outIndex];
2035 PointerCoords& curOutCoords = outCoords[outIndex];
2036
2037 if (curInProperties != curOutProperties) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002038 curOutProperties = curInProperties;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002039 changed = true;
2040 }
2041
2042 if (curInCoords != curOutCoords) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002043 curOutCoords = curInCoords;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002044 changed = true;
2045 }
2046 }
2047 return changed;
2048}
2049
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002050std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
2051 uint32_t policyFlags) {
2052 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002053 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2054 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2055 int32_t metaState = getContext()->getGlobalMetaState();
2056 int32_t buttonState = mCurrentCookedState.buttonState;
2057
2058 if (currentIdBits == lastIdBits) {
2059 if (!currentIdBits.isEmpty()) {
2060 // No pointer id changes so this is a move event.
2061 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002062 out.push_back(
2063 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2064 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2065 mCurrentCookedState.cookedPointerData.pointerProperties,
2066 mCurrentCookedState.cookedPointerData.pointerCoords,
2067 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2068 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2069 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002070 }
2071 } else {
2072 // There may be pointers going up and pointers going down and pointers moving
2073 // all at the same time.
2074 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2075 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2076 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2077 BitSet32 dispatchedIdBits(lastIdBits.value);
2078
2079 // Update last coordinates of pointers that have moved so that we observe the new
2080 // pointer positions at the same time as other pointers that have just gone up.
2081 bool moveNeeded =
2082 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2083 mCurrentCookedState.cookedPointerData.pointerCoords,
2084 mCurrentCookedState.cookedPointerData.idToIndex,
2085 mLastCookedState.cookedPointerData.pointerProperties,
2086 mLastCookedState.cookedPointerData.pointerCoords,
2087 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2088 if (buttonState != mLastCookedState.buttonState) {
2089 moveNeeded = true;
2090 }
2091
2092 // Dispatch pointer up events.
2093 while (!upIdBits.isEmpty()) {
2094 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002095 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002096 if (isCanceled) {
2097 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2098 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002099 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2100 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2101 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2102 buttonState, 0,
2103 mLastCookedState.cookedPointerData.pointerProperties,
2104 mLastCookedState.cookedPointerData.pointerCoords,
2105 mLastCookedState.cookedPointerData.idToIndex,
2106 dispatchedIdBits, upId, mOrientedXPrecision,
2107 mOrientedYPrecision, mDownTime,
2108 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002109 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002110 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002111 }
2112
2113 // Dispatch move events if any of the remaining pointers moved from their old locations.
2114 // Although applications receive new locations as part of individual pointer up
2115 // events, they do not generally handle them except when presented in a move event.
2116 if (moveNeeded && !moveIdBits.isEmpty()) {
2117 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002118 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2119 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2120 mCurrentCookedState.cookedPointerData.pointerProperties,
2121 mCurrentCookedState.cookedPointerData.pointerCoords,
2122 mCurrentCookedState.cookedPointerData.idToIndex,
2123 dispatchedIdBits, -1, mOrientedXPrecision,
2124 mOrientedYPrecision, mDownTime,
2125 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002126 }
2127
2128 // Dispatch pointer down events using the new pointer locations.
2129 while (!downIdBits.isEmpty()) {
2130 uint32_t downId = downIdBits.clearFirstMarkedBit();
2131 dispatchedIdBits.markBit(downId);
2132
2133 if (dispatchedIdBits.count() == 1) {
2134 // First pointer is going down. Set down time.
2135 mDownTime = when;
2136 }
2137
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002138 out.push_back(
2139 dispatchMotion(when, readTime, policyFlags, mSource,
2140 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2141 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2142 mCurrentCookedState.cookedPointerData.pointerCoords,
2143 mCurrentCookedState.cookedPointerData.idToIndex,
2144 dispatchedIdBits, downId, mOrientedXPrecision,
2145 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002146 }
2147 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002148 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002149}
2150
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002151std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2152 uint32_t policyFlags) {
2153 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002154 if (mSentHoverEnter &&
2155 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2156 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2157 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002158 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2159 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2160 mLastCookedState.buttonState, 0,
2161 mLastCookedState.cookedPointerData.pointerProperties,
2162 mLastCookedState.cookedPointerData.pointerCoords,
2163 mLastCookedState.cookedPointerData.idToIndex,
2164 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2165 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2166 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002167 mSentHoverEnter = false;
2168 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002169 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002170}
2171
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002172std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2173 uint32_t policyFlags) {
2174 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002175 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2176 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2177 int32_t metaState = getContext()->getGlobalMetaState();
2178 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002179 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2180 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2181 mCurrentRawState.buttonState, 0,
2182 mCurrentCookedState.cookedPointerData.pointerProperties,
2183 mCurrentCookedState.cookedPointerData.pointerCoords,
2184 mCurrentCookedState.cookedPointerData.idToIndex,
2185 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2186 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2187 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002188 mSentHoverEnter = true;
2189 }
2190
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002191 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2192 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2193 mCurrentRawState.buttonState, 0,
2194 mCurrentCookedState.cookedPointerData.pointerProperties,
2195 mCurrentCookedState.cookedPointerData.pointerCoords,
2196 mCurrentCookedState.cookedPointerData.idToIndex,
2197 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2198 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2199 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002200 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002201 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002202}
2203
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002204std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2205 uint32_t policyFlags) {
2206 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002207 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2208 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2209 const int32_t metaState = getContext()->getGlobalMetaState();
2210 int32_t buttonState = mLastCookedState.buttonState;
2211 while (!releasedButtons.isEmpty()) {
2212 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2213 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002214 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2215 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2216 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002217 mLastCookedState.cookedPointerData.pointerProperties,
2218 mLastCookedState.cookedPointerData.pointerCoords,
2219 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002220 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2221 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002222 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002223 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002224}
2225
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002226std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2227 uint32_t policyFlags) {
2228 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002229 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2230 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2231 const int32_t metaState = getContext()->getGlobalMetaState();
2232 int32_t buttonState = mLastCookedState.buttonState;
2233 while (!pressedButtons.isEmpty()) {
2234 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2235 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002236 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2237 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2238 buttonState, 0,
2239 mCurrentCookedState.cookedPointerData.pointerProperties,
2240 mCurrentCookedState.cookedPointerData.pointerCoords,
2241 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2242 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2243 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002244 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002245 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002246}
2247
LiZhihong758eb562022-11-03 15:28:29 +08002248std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2249 uint32_t policyFlags,
2250 BitSet32 idBits,
2251 nsecs_t readTime) {
2252 std::list<NotifyArgs> out;
2253 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2254 const int32_t metaState = getContext()->getGlobalMetaState();
2255 int32_t buttonState = mLastCookedState.buttonState;
2256
2257 while (!releasedButtons.isEmpty()) {
2258 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2259 buttonState &= ~actionButton;
2260 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2261 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2262 metaState, buttonState, 0,
2263 mPointerGesture.lastGestureProperties,
2264 mPointerGesture.lastGestureCoords,
2265 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2266 mOrientedXPrecision, mOrientedYPrecision,
2267 mPointerGesture.downTime, MotionClassification::NONE));
2268 }
2269 return out;
2270}
2271
2272std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2273 uint32_t policyFlags,
2274 BitSet32 idBits,
2275 nsecs_t readTime) {
2276 std::list<NotifyArgs> out;
2277 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2278 const int32_t metaState = getContext()->getGlobalMetaState();
2279 int32_t buttonState = mLastCookedState.buttonState;
2280
2281 while (!pressedButtons.isEmpty()) {
2282 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2283 buttonState |= actionButton;
2284 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2285 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2286 buttonState, 0, mPointerGesture.currentGestureProperties,
2287 mPointerGesture.currentGestureCoords,
2288 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2289 mOrientedXPrecision, mOrientedYPrecision,
2290 mPointerGesture.downTime, MotionClassification::NONE));
2291 }
2292 return out;
2293}
2294
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002295const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2296 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2297 return cookedPointerData.touchingIdBits;
2298 }
2299 return cookedPointerData.hoveringIdBits;
2300}
2301
2302void TouchInputMapper::cookPointerData() {
2303 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2304
2305 mCurrentCookedState.cookedPointerData.clear();
2306 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2307 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2308 mCurrentRawState.rawPointerData.hoveringIdBits;
2309 mCurrentCookedState.cookedPointerData.touchingIdBits =
2310 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002311 mCurrentCookedState.cookedPointerData.canceledIdBits =
2312 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002313
2314 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2315 mCurrentCookedState.buttonState = 0;
2316 } else {
2317 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2318 }
2319
2320 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002321 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002322 for (uint32_t i = 0; i < currentPointerCount; i++) {
2323 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2324
2325 // Size
2326 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2327 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002328 case Calibration::SizeCalibration::GEOMETRIC:
2329 case Calibration::SizeCalibration::DIAMETER:
2330 case Calibration::SizeCalibration::BOX:
2331 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002332 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2333 touchMajor = in.touchMajor;
2334 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2335 toolMajor = in.toolMajor;
2336 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2337 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2338 : in.touchMajor;
2339 } else if (mRawPointerAxes.touchMajor.valid) {
2340 toolMajor = touchMajor = in.touchMajor;
2341 toolMinor = touchMinor =
2342 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2343 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2344 : in.touchMajor;
2345 } else if (mRawPointerAxes.toolMajor.valid) {
2346 touchMajor = toolMajor = in.toolMajor;
2347 touchMinor = toolMinor =
2348 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2349 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2350 : in.toolMajor;
2351 } else {
2352 ALOG_ASSERT(false,
2353 "No touch or tool axes. "
2354 "Size calibration should have been resolved to NONE.");
2355 touchMajor = 0;
2356 touchMinor = 0;
2357 toolMajor = 0;
2358 toolMinor = 0;
2359 size = 0;
2360 }
2361
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002362 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002363 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2364 if (touchingCount > 1) {
2365 touchMajor /= touchingCount;
2366 touchMinor /= touchingCount;
2367 toolMajor /= touchingCount;
2368 toolMinor /= touchingCount;
2369 size /= touchingCount;
2370 }
2371 }
2372
Michael Wright227c5542020-07-02 18:30:52 +01002373 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 touchMajor *= mGeometricScale;
2375 touchMinor *= mGeometricScale;
2376 toolMajor *= mGeometricScale;
2377 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002378 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2380 touchMinor = touchMajor;
2381 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2382 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002383 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002384 touchMinor = touchMajor;
2385 toolMinor = toolMajor;
2386 }
2387
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002388 mCalibration.applySizeScaleAndBias(touchMajor);
2389 mCalibration.applySizeScaleAndBias(touchMinor);
2390 mCalibration.applySizeScaleAndBias(toolMajor);
2391 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002392 size *= mSizeScale;
2393 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002394 case Calibration::SizeCalibration::DEFAULT:
2395 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2396 break;
2397 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 touchMajor = 0;
2399 touchMinor = 0;
2400 toolMajor = 0;
2401 toolMinor = 0;
2402 size = 0;
2403 break;
2404 }
2405
2406 // Pressure
2407 float pressure;
2408 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002409 case Calibration::PressureCalibration::PHYSICAL:
2410 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 pressure = in.pressure * mPressureScale;
2412 break;
2413 default:
2414 pressure = in.isHovering ? 0 : 1;
2415 break;
2416 }
2417
2418 // Tilt and Orientation
2419 float tilt;
2420 float orientation;
2421 if (mHaveTilt) {
2422 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2423 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002424 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2426 } else {
2427 tilt = 0;
2428
2429 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002430 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002431 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002432 break;
Michael Wright227c5542020-07-02 18:30:52 +01002433 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2435 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2436 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002437 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002438 float confidence = hypotf(c1, c2);
2439 float scale = 1.0f + confidence / 16.0f;
2440 touchMajor *= scale;
2441 touchMinor /= scale;
2442 toolMajor *= scale;
2443 toolMinor /= scale;
2444 } else {
2445 orientation = 0;
2446 }
2447 break;
2448 }
2449 default:
2450 orientation = 0;
2451 }
2452 }
2453
2454 // Distance
2455 float distance;
2456 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002457 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 distance = in.distance * mDistanceScale;
2459 break;
2460 default:
2461 distance = 0;
2462 }
2463
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002464 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2465 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002466 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2467 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 // Write output coords.
2470 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2471 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002472 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2473 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2475 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2476 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2477 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2478 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2479 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2480 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002481 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2482 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002483
Chris Ye364fdb52020-08-05 15:07:56 -07002484 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002485 uint32_t id = in.id;
2486 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2487 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2488 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002489 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2490 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002491 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2492 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2493 }
2494
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002495 // Write output properties.
2496 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002497 properties.clear();
2498 properties.id = id;
2499 properties.toolType = in.toolType;
2500
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002501 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002502 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002503 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504 }
2505}
2506
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002507std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2508 uint32_t policyFlags,
2509 PointerUsage pointerUsage) {
2510 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002511 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002512 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002513 mPointerUsage = pointerUsage;
2514 }
2515
2516 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002517 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002518 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002519 break;
Michael Wright227c5542020-07-02 18:30:52 +01002520 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002521 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 break;
Michael Wright227c5542020-07-02 18:30:52 +01002523 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002524 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002525 break;
Michael Wright227c5542020-07-02 18:30:52 +01002526 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002527 break;
2528 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002529 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002530}
2531
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002532std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2533 uint32_t policyFlags) {
2534 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002535 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002536 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002537 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002538 break;
Michael Wright227c5542020-07-02 18:30:52 +01002539 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002540 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002541 break;
Michael Wright227c5542020-07-02 18:30:52 +01002542 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002543 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544 break;
Michael Wright227c5542020-07-02 18:30:52 +01002545 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002546 break;
2547 }
2548
Michael Wright227c5542020-07-02 18:30:52 +01002549 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002550 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002551}
2552
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002553std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2554 uint32_t policyFlags,
2555 bool isTimeout) {
2556 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002557 // Update current gesture coordinates.
2558 bool cancelPreviousGesture, finishPreviousGesture;
2559 bool sendEvents =
2560 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2561 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002562 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002563 }
2564 if (finishPreviousGesture) {
2565 cancelPreviousGesture = false;
2566 }
2567
2568 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002569 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002570 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002571 if (finishPreviousGesture || cancelPreviousGesture) {
2572 mPointerController->clearSpots();
2573 }
2574
Michael Wright227c5542020-07-02 18:30:52 +01002575 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002576 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2577 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002578 mPointerGesture.currentGestureIdBits,
2579 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002580 }
2581 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002582 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002583 }
2584
2585 // Show or hide the pointer if needed.
2586 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002587 case PointerGesture::Mode::NEUTRAL:
2588 case PointerGesture::Mode::QUIET:
2589 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2590 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002591 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002592 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002593 }
2594 break;
Michael Wright227c5542020-07-02 18:30:52 +01002595 case PointerGesture::Mode::TAP:
2596 case PointerGesture::Mode::TAP_DRAG:
2597 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2598 case PointerGesture::Mode::HOVER:
2599 case PointerGesture::Mode::PRESS:
2600 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002601 // Unfade the pointer when the current gesture manipulates the
2602 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002603 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002604 break;
Michael Wright227c5542020-07-02 18:30:52 +01002605 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002606 // Fade the pointer when the current gesture manipulates a different
2607 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002608 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002609 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002610 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002611 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002612 }
2613 break;
2614 }
2615
2616 // Send events!
2617 int32_t metaState = getContext()->getGlobalMetaState();
2618 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002619 const MotionClassification classification =
2620 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2621 ? MotionClassification::TWO_FINGER_SWIPE
2622 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002623
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002624 uint32_t flags = 0;
2625
2626 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2627 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2628 }
2629
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002630 // Update last coordinates of pointers that have moved so that we observe the new
2631 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002632 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2633 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2634 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2635 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2636 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2637 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002638 bool moveNeeded = false;
2639 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2640 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2641 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2642 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2643 mPointerGesture.lastGestureIdBits.value);
2644 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2645 mPointerGesture.currentGestureCoords,
2646 mPointerGesture.currentGestureIdToIndex,
2647 mPointerGesture.lastGestureProperties,
2648 mPointerGesture.lastGestureCoords,
2649 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2650 if (buttonState != mLastCookedState.buttonState) {
2651 moveNeeded = true;
2652 }
2653 }
2654
2655 // Send motion events for all pointers that went up or were canceled.
2656 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2657 if (!dispatchedGestureIdBits.isEmpty()) {
2658 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002659 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002660 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002661 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002662 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2663 mPointerGesture.lastGestureProperties,
2664 mPointerGesture.lastGestureCoords,
2665 mPointerGesture.lastGestureIdToIndex,
2666 dispatchedGestureIdBits, -1, 0, 0,
2667 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002668
2669 dispatchedGestureIdBits.clear();
2670 } else {
2671 BitSet32 upGestureIdBits;
2672 if (finishPreviousGesture) {
2673 upGestureIdBits = dispatchedGestureIdBits;
2674 } else {
2675 upGestureIdBits.value =
2676 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2677 }
2678 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002679 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2680 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2681 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2682 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2683 readTime);
2684 }
2685 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002686 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2687 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2688 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2689 mPointerGesture.lastGestureProperties,
2690 mPointerGesture.lastGestureCoords,
2691 mPointerGesture.lastGestureIdToIndex,
2692 dispatchedGestureIdBits, id, 0, 0,
2693 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002694
2695 dispatchedGestureIdBits.clearBit(id);
2696 }
2697 }
2698 }
2699
2700 // Send motion events for all pointers that moved.
2701 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002702 out.push_back(
2703 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2704 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2705 mPointerGesture.currentGestureProperties,
2706 mPointerGesture.currentGestureCoords,
2707 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2708 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002709 }
2710
2711 // Send motion events for all pointers that went down.
2712 if (down) {
2713 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2714 ~dispatchedGestureIdBits.value);
2715 while (!downGestureIdBits.isEmpty()) {
2716 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2717 dispatchedGestureIdBits.markBit(id);
2718
2719 if (dispatchedGestureIdBits.count() == 1) {
2720 mPointerGesture.downTime = when;
2721 }
2722
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002723 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2724 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2725 buttonState, 0, mPointerGesture.currentGestureProperties,
2726 mPointerGesture.currentGestureCoords,
2727 mPointerGesture.currentGestureIdToIndex,
2728 dispatchedGestureIdBits, id, 0, 0,
2729 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002730 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2731 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2732 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2733 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2734 readTime);
2735 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002736 }
2737 }
2738
2739 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002740 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002741 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2742 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2743 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2744 mPointerGesture.currentGestureProperties,
2745 mPointerGesture.currentGestureCoords,
2746 mPointerGesture.currentGestureIdToIndex,
2747 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2748 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002749 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2750 // Synthesize a hover move event after all pointers go up to indicate that
2751 // the pointer is hovering again even if the user is not currently touching
2752 // the touch pad. This ensures that a view will receive a fresh hover enter
2753 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002754 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002755
2756 PointerProperties pointerProperties;
2757 pointerProperties.clear();
2758 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002759 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002760
2761 PointerCoords pointerCoords;
2762 pointerCoords.clear();
2763 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2764 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2765
2766 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002767 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2768 mSource, displayId, policyFlags,
2769 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2770 buttonState, MotionClassification::NONE,
2771 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2772 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00002773 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002774 }
2775
2776 // Update state.
2777 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2778 if (!down) {
2779 mPointerGesture.lastGestureIdBits.clear();
2780 } else {
2781 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2782 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2783 uint32_t id = idBits.clearFirstMarkedBit();
2784 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002785 mPointerGesture.lastGestureProperties[index] =
2786 mPointerGesture.currentGestureProperties[index];
2787 mPointerGesture.lastGestureCoords[index] = mPointerGesture.currentGestureCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002788 mPointerGesture.lastGestureIdToIndex[id] = index;
2789 }
2790 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002791 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002792}
2793
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002794std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2795 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002796 const MotionClassification classification =
2797 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2798 ? MotionClassification::TWO_FINGER_SWIPE
2799 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002800 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002801 // Cancel previously dispatches pointers.
2802 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2803 int32_t metaState = getContext()->getGlobalMetaState();
2804 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002805 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002806 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2807 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002808 mPointerGesture.lastGestureProperties,
2809 mPointerGesture.lastGestureCoords,
2810 mPointerGesture.lastGestureIdToIndex,
2811 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2812 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002813 }
2814
2815 // Reset the current pointer gesture.
2816 mPointerGesture.reset();
2817 mPointerVelocityControl.reset();
2818
2819 // Remove any current spots.
2820 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002821 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002822 mPointerController->clearSpots();
2823 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002824 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002825}
2826
2827bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2828 bool* outFinishPreviousGesture, bool isTimeout) {
2829 *outCancelPreviousGesture = false;
2830 *outFinishPreviousGesture = false;
2831
2832 // Handle TAP timeout.
2833 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002834 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002835
Michael Wright227c5542020-07-02 18:30:52 +01002836 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002837 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2838 // The tap/drag timeout has not yet expired.
2839 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2840 mConfig.pointerGestureTapDragInterval);
2841 } else {
2842 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002843 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002844 *outFinishPreviousGesture = true;
2845
2846 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002847 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002848 mPointerGesture.currentGestureIdBits.clear();
2849
2850 mPointerVelocityControl.reset();
2851 return true;
2852 }
2853 }
2854
2855 // We did not handle this timeout.
2856 return false;
2857 }
2858
2859 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2860 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2861
2862 // Update the velocity tracker.
2863 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002864 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002865 uint32_t id = idBits.clearFirstMarkedBit();
2866 const RawPointerData::Pointer& pointer =
2867 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002868 const float x = pointer.x * mPointerXMovementScale;
2869 const float y = pointer.y * mPointerYMovementScale;
2870 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2871 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002873 }
2874
2875 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2876 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002877 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2878 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2879 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002880 mPointerGesture.resetTap();
2881 }
2882
2883 // Pick a new active touch id if needed.
2884 // Choose an arbitrary pointer that just went down, if there is one.
2885 // Otherwise choose an arbitrary remaining pointer.
2886 // This guarantees we always have an active touch id when there is at least one pointer.
2887 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002888 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002889 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002890 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891 mPointerGesture.firstTouchTime = when;
2892 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002893 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2894 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2895 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2896 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002897 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002898 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002899
2900 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002901 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002902 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002903 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2904 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2905 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002906 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907 *outFinishPreviousGesture = true;
2908 }
2909
2910 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002911 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002912 mPointerGesture.currentGestureIdBits.clear();
2913
2914 mPointerVelocityControl.reset();
2915 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2916 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2917 // The pointer follows the active touch point.
2918 // Emit DOWN, MOVE, UP events at the pointer location.
2919 //
2920 // Only the active touch matters; other fingers are ignored. This policy helps
2921 // to handle the case where the user places a second finger on the touch pad
2922 // to apply the necessary force to depress an integrated button below the surface.
2923 // We don't want the second finger to be delivered to applications.
2924 //
2925 // For this to work well, we need to make sure to track the pointer that is really
2926 // active. If the user first puts one finger down to click then adds another
2927 // finger to drag then the active pointer should switch to the finger that is
2928 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002929 ALOGD_IF(DEBUG_GESTURES,
2930 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2931 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002932 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002933 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002934 *outFinishPreviousGesture = true;
2935 mPointerGesture.activeGestureId = 0;
2936 }
2937
2938 // Switch pointers if needed.
2939 // Find the fastest pointer and follow it.
2940 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002941 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002942 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002943 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002944 ALOGD_IF(DEBUG_GESTURES,
2945 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2946 "bestSpeed=%0.3f",
2947 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002948 }
2949 }
2950
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002951 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002952 // When using spots, the click will occur at the position of the anchor
2953 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002954 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002955 } else {
2956 mPointerVelocityControl.reset();
2957 }
2958
Prabir Pradhan2719e822023-02-28 17:39:36 +00002959 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002960
Michael Wright227c5542020-07-02 18:30:52 +01002961 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002962 mPointerGesture.currentGestureIdBits.clear();
2963 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2964 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2965 mPointerGesture.currentGestureProperties[0].clear();
2966 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002967 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002968 mPointerGesture.currentGestureCoords[0].clear();
2969 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2970 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2971 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2972 } else if (currentFingerCount == 0) {
2973 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002974 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002975 *outFinishPreviousGesture = true;
2976 }
2977
2978 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2979 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2980 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002981 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2982 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002983 lastFingerCount == 1) {
2984 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002985 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002986 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2987 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002988 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002989
2990 mPointerGesture.tapUpTime = when;
2991 getContext()->requestTimeoutAtTime(when +
2992 mConfig.pointerGestureTapDragInterval);
2993
2994 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002995 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002996 mPointerGesture.currentGestureIdBits.clear();
2997 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2998 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2999 mPointerGesture.currentGestureProperties[0].clear();
3000 mPointerGesture.currentGestureProperties[0].id =
3001 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003002 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003 mPointerGesture.currentGestureCoords[0].clear();
3004 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3005 mPointerGesture.tapX);
3006 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3007 mPointerGesture.tapY);
3008 mPointerGesture.currentGestureCoords[0]
3009 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3010
3011 tapped = true;
3012 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003013 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
3014 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003015 }
3016 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003017 if (DEBUG_GESTURES) {
3018 if (mPointerGesture.tapDownTime != LLONG_MIN) {
3019 ALOGD("Gestures: Not a TAP, %0.3fms since down",
3020 (when - mPointerGesture.tapDownTime) * 0.000001f);
3021 } else {
3022 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
3023 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003024 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003025 }
3026 }
3027
3028 mPointerVelocityControl.reset();
3029
3030 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00003031 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003032 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01003033 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003034 mPointerGesture.currentGestureIdBits.clear();
3035 }
3036 } else if (currentFingerCount == 1) {
3037 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3038 // The pointer follows the active touch point.
3039 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3040 // When in TAP_DRAG, emit MOVE events at the pointer location.
3041 ALOG_ASSERT(activeTouchId >= 0);
3042
Michael Wright227c5542020-07-02 18:30:52 +01003043 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3044 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003045 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003046 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003047 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3048 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003049 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003050 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003051 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3052 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003053 }
3054 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003055 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3056 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003057 }
Michael Wright227c5542020-07-02 18:30:52 +01003058 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3059 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003060 }
3061
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003062 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003063 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003064 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003065 } else {
3066 mPointerVelocityControl.reset();
3067 }
3068
3069 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003070 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003071 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003072 down = true;
3073 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003074 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003075 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003076 *outFinishPreviousGesture = true;
3077 }
3078 mPointerGesture.activeGestureId = 0;
3079 down = false;
3080 }
3081
Prabir Pradhan2719e822023-02-28 17:39:36 +00003082 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003083
3084 mPointerGesture.currentGestureIdBits.clear();
3085 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3086 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3087 mPointerGesture.currentGestureProperties[0].clear();
3088 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003089 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003090 mPointerGesture.currentGestureCoords[0].clear();
3091 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3092 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3093 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3094 down ? 1.0f : 0.0f);
3095
3096 if (lastFingerCount == 0 && currentFingerCount != 0) {
3097 mPointerGesture.resetTap();
3098 mPointerGesture.tapDownTime = when;
3099 mPointerGesture.tapX = x;
3100 mPointerGesture.tapY = y;
3101 }
3102 } else {
3103 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003104 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003105 }
3106
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003107 if (DEBUG_GESTURES) {
3108 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3109 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3110 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3111 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3112 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3113 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3114 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3115 uint32_t id = idBits.clearFirstMarkedBit();
3116 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3117 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3118 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003119 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003120 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003121 id, index, ftl::enum_string(properties.toolType).c_str(),
3122 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003123 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3124 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3125 }
3126 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3127 uint32_t id = idBits.clearFirstMarkedBit();
3128 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3129 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3130 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003131 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003132 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003133 id, index, ftl::enum_string(properties.toolType).c_str(),
3134 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003135 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3136 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3137 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003138 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003139 return true;
3140}
3141
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003142bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3143 if (mPointerGesture.activeTouchId < 0) {
3144 mPointerGesture.resetQuietTime();
3145 return false;
3146 }
3147
3148 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3149 return true;
3150 }
3151
3152 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3153 bool isQuietTime = false;
3154 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3155 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3156 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3157 currentFingerCount < 2) {
3158 // Enter quiet time when exiting swipe or freeform state.
3159 // This is to prevent accidentally entering the hover state and flinging the
3160 // pointer when finishing a swipe and there is still one pointer left onscreen.
3161 isQuietTime = true;
3162 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3163 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3164 // Enter quiet time when releasing the button and there are still two or more
3165 // fingers down. This may indicate that one finger was used to press the button
3166 // but it has not gone up yet.
3167 isQuietTime = true;
3168 }
3169 if (isQuietTime) {
3170 mPointerGesture.quietTime = when;
3171 }
3172 return isQuietTime;
3173}
3174
3175std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3176 int32_t bestId = -1;
3177 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3178 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3179 uint32_t id = idBits.clearFirstMarkedBit();
3180 std::optional<float> vx =
3181 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3182 std::optional<float> vy =
3183 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3184 if (vx && vy) {
3185 float speed = hypotf(*vx, *vy);
3186 if (speed > bestSpeed) {
3187 bestId = id;
3188 bestSpeed = speed;
3189 }
3190 }
3191 }
3192 return std::make_pair(bestId, bestSpeed);
3193}
3194
3195void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3196 bool* finishPreviousGesture) {
3197 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3198 // to move before deciding what to do.
3199 //
3200 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3201 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3202 // just a press or long-press at the pointer location.
3203 //
3204 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3205 // pointer location.
3206 //
3207 // When the two fingers move enough or when additional fingers are added, we make a decision to
3208 // transition into SWIPE or FREEFORM mode accordingly.
3209 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3210 ALOG_ASSERT(activeTouchId >= 0);
3211
3212 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3213 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3214 bool settled =
3215 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3216 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3217 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3218 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3219 *finishPreviousGesture = true;
3220 } else if (!settled && currentFingerCount > lastFingerCount) {
3221 // Additional pointers have gone down but not yet settled.
3222 // Reset the gesture.
3223 ALOGD_IF(DEBUG_GESTURES,
3224 "Gestures: Resetting gesture since additional pointers went down for "
3225 "MULTITOUCH, settle time remaining %0.3fms",
3226 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3227 when) * 0.000001f);
3228 *cancelPreviousGesture = true;
3229 } else {
3230 // Continue previous gesture.
3231 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3232 }
3233
3234 if (*finishPreviousGesture || *cancelPreviousGesture) {
3235 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3236 mPointerGesture.activeGestureId = 0;
3237 mPointerGesture.referenceIdBits.clear();
3238 mPointerVelocityControl.reset();
3239
3240 // Use the centroid and pointer location as the reference points for the gesture.
3241 ALOGD_IF(DEBUG_GESTURES,
3242 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3243 "%0.3fms",
3244 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3245 when) * 0.000001f);
3246 mCurrentRawState.rawPointerData
3247 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3248 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003249 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3250 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003251 }
3252
3253 // Clear the reference deltas for fingers not yet included in the reference calculation.
3254 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3255 ~mPointerGesture.referenceIdBits.value);
3256 !idBits.isEmpty();) {
3257 uint32_t id = idBits.clearFirstMarkedBit();
3258 mPointerGesture.referenceDeltas[id].dx = 0;
3259 mPointerGesture.referenceDeltas[id].dy = 0;
3260 }
3261 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3262
3263 // Add delta for all fingers and calculate a common movement delta.
3264 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3265 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3266 mCurrentCookedState.fingerIdBits.value);
3267 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3268 bool first = (idBits == commonIdBits);
3269 uint32_t id = idBits.clearFirstMarkedBit();
3270 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3271 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3272 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3273 delta.dx += cpd.x - lpd.x;
3274 delta.dy += cpd.y - lpd.y;
3275
3276 if (first) {
3277 commonDeltaRawX = delta.dx;
3278 commonDeltaRawY = delta.dy;
3279 } else {
3280 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3281 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3282 }
3283 }
3284
3285 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3286 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3287 float dist[MAX_POINTER_ID + 1];
3288 int32_t distOverThreshold = 0;
3289 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3290 uint32_t id = idBits.clearFirstMarkedBit();
3291 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3292 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3293 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3294 distOverThreshold += 1;
3295 }
3296 }
3297
3298 // Only transition when at least two pointers have moved further than
3299 // the minimum distance threshold.
3300 if (distOverThreshold >= 2) {
3301 if (currentFingerCount > 2) {
3302 // There are more than two pointers, switch to FREEFORM.
3303 ALOGD_IF(DEBUG_GESTURES,
3304 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3305 currentFingerCount);
3306 *cancelPreviousGesture = true;
3307 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3308 } else {
3309 // There are exactly two pointers.
3310 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3311 uint32_t id1 = idBits.clearFirstMarkedBit();
3312 uint32_t id2 = idBits.firstMarkedBit();
3313 const RawPointerData::Pointer& p1 =
3314 mCurrentRawState.rawPointerData.pointerForId(id1);
3315 const RawPointerData::Pointer& p2 =
3316 mCurrentRawState.rawPointerData.pointerForId(id2);
3317 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3318 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3319 // There are two pointers but they are too far apart for a SWIPE,
3320 // switch to FREEFORM.
3321 ALOGD_IF(DEBUG_GESTURES,
3322 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3323 mutualDistance, mPointerGestureMaxSwipeWidth);
3324 *cancelPreviousGesture = true;
3325 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3326 } else {
3327 // There are two pointers. Wait for both pointers to start moving
3328 // before deciding whether this is a SWIPE or FREEFORM gesture.
3329 float dist1 = dist[id1];
3330 float dist2 = dist[id2];
3331 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3332 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3333 // Calculate the dot product of the displacement vectors.
3334 // When the vectors are oriented in approximately the same direction,
3335 // the angle betweeen them is near zero and the cosine of the angle
3336 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3337 // mag(v2).
3338 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3339 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3340 float dx1 = delta1.dx * mPointerXZoomScale;
3341 float dy1 = delta1.dy * mPointerYZoomScale;
3342 float dx2 = delta2.dx * mPointerXZoomScale;
3343 float dy2 = delta2.dy * mPointerYZoomScale;
3344 float dot = dx1 * dx2 + dy1 * dy2;
3345 float cosine = dot / (dist1 * dist2); // denominator always > 0
3346 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3347 // Pointers are moving in the same direction. Switch to SWIPE.
3348 ALOGD_IF(DEBUG_GESTURES,
3349 "Gestures: PRESS transitioned to SWIPE, "
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 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3356 } else {
3357 // Pointers are moving in different directions. Switch to FREEFORM.
3358 ALOGD_IF(DEBUG_GESTURES,
3359 "Gestures: PRESS transitioned to FREEFORM, "
3360 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3361 "cosine %0.3f < %0.3f",
3362 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3363 mConfig.pointerGestureMultitouchMinDistance, cosine,
3364 mConfig.pointerGestureSwipeTransitionAngleCosine);
3365 *cancelPreviousGesture = true;
3366 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3367 }
3368 }
3369 }
3370 }
3371 }
3372 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3373 // Switch from SWIPE to FREEFORM if additional pointers go down.
3374 // Cancel previous gesture.
3375 if (currentFingerCount > 2) {
3376 ALOGD_IF(DEBUG_GESTURES,
3377 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3378 currentFingerCount);
3379 *cancelPreviousGesture = true;
3380 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3381 }
3382 }
3383
3384 // Move the reference points based on the overall group motion of the fingers
3385 // except in PRESS mode while waiting for a transition to occur.
3386 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3387 (commonDeltaRawX || commonDeltaRawY)) {
3388 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3389 uint32_t id = idBits.clearFirstMarkedBit();
3390 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3391 delta.dx = 0;
3392 delta.dy = 0;
3393 }
3394
3395 mPointerGesture.referenceTouchX += commonDeltaRawX;
3396 mPointerGesture.referenceTouchY += commonDeltaRawY;
3397
3398 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3399 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3400
3401 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3402 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3403
3404 mPointerGesture.referenceGestureX += commonDeltaX;
3405 mPointerGesture.referenceGestureY += commonDeltaY;
3406 }
3407
3408 // Report gestures.
3409 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3410 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3411 // PRESS or SWIPE mode.
3412 ALOGD_IF(DEBUG_GESTURES,
3413 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3414 "currentTouchPointerCount=%d",
3415 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3416 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3417
3418 mPointerGesture.currentGestureIdBits.clear();
3419 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3420 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3421 mPointerGesture.currentGestureProperties[0].clear();
3422 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003423 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003424 mPointerGesture.currentGestureCoords[0].clear();
3425 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3426 mPointerGesture.referenceGestureX);
3427 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3428 mPointerGesture.referenceGestureY);
3429 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3430 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3431 float xOffset = static_cast<float>(commonDeltaRawX) /
3432 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3433 float yOffset = static_cast<float>(commonDeltaRawY) /
3434 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3435 mPointerGesture.currentGestureCoords[0]
3436 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3437 mPointerGesture.currentGestureCoords[0]
3438 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3439 }
3440 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3441 // FREEFORM mode.
3442 ALOGD_IF(DEBUG_GESTURES,
3443 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3444 "currentTouchPointerCount=%d",
3445 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3446 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3447
3448 mPointerGesture.currentGestureIdBits.clear();
3449
3450 BitSet32 mappedTouchIdBits;
3451 BitSet32 usedGestureIdBits;
3452 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3453 // Initially, assign the active gesture id to the active touch point
3454 // if there is one. No other touch id bits are mapped yet.
3455 if (!*cancelPreviousGesture) {
3456 mappedTouchIdBits.markBit(activeTouchId);
3457 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3458 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3459 mPointerGesture.activeGestureId;
3460 } else {
3461 mPointerGesture.activeGestureId = -1;
3462 }
3463 } else {
3464 // Otherwise, assume we mapped all touches from the previous frame.
3465 // Reuse all mappings that are still applicable.
3466 mappedTouchIdBits.value =
3467 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3468 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3469
3470 // Check whether we need to choose a new active gesture id because the
3471 // current went went up.
3472 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3473 ~mCurrentCookedState.fingerIdBits.value);
3474 !upTouchIdBits.isEmpty();) {
3475 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3476 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3477 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3478 mPointerGesture.activeGestureId = -1;
3479 break;
3480 }
3481 }
3482 }
3483
3484 ALOGD_IF(DEBUG_GESTURES,
3485 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3486 "activeGestureId=%d",
3487 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3488
3489 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3490 for (uint32_t i = 0; i < currentFingerCount; i++) {
3491 uint32_t touchId = idBits.clearFirstMarkedBit();
3492 uint32_t gestureId;
3493 if (!mappedTouchIdBits.hasBit(touchId)) {
3494 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3495 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3496 ALOGD_IF(DEBUG_GESTURES,
3497 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3498 gestureId);
3499 } else {
3500 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3501 ALOGD_IF(DEBUG_GESTURES,
3502 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3503 touchId, gestureId);
3504 }
3505 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3506 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3507
3508 const RawPointerData::Pointer& pointer =
3509 mCurrentRawState.rawPointerData.pointerForId(touchId);
3510 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3511 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3512 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3513
3514 mPointerGesture.currentGestureProperties[i].clear();
3515 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003516 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003517 mPointerGesture.currentGestureCoords[i].clear();
3518 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3519 mPointerGesture.referenceGestureX +
3520 deltaX);
3521 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3522 mPointerGesture.referenceGestureY +
3523 deltaY);
3524 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3525 }
3526
3527 if (mPointerGesture.activeGestureId < 0) {
3528 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3529 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3530 mPointerGesture.activeGestureId);
3531 }
3532 }
3533}
3534
Harry Cutts714d1ad2022-08-24 16:36:43 +00003535void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3536 const RawPointerData::Pointer& currentPointer =
3537 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3538 const RawPointerData::Pointer& lastPointer =
3539 mLastRawState.rawPointerData.pointerForId(pointerId);
3540 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3541 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3542
3543 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3544 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3545
3546 mPointerController->move(deltaX, deltaY);
3547}
3548
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003549std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3550 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003551 mPointerSimple.currentCoords.clear();
3552 mPointerSimple.currentProperties.clear();
3553
3554 bool down, hovering;
3555 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3556 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3557 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003558 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3559 down = !hovering;
3560
Prabir Pradhane71e5702023-03-29 14:51:38 +00003561 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3562 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3563 // Styluses are configured specifically for one display. We only update the
3564 // PointerController for this stylus if the PointerController is configured for
3565 // the same display as this stylus,
3566 if (getAssociatedDisplayId() == mViewport.displayId) {
3567 mPointerController->setPosition(x, y);
3568 std::tie(x, y) = mPointerController->getPosition();
3569 }
3570
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003571 mPointerSimple.currentCoords = mCurrentCookedState.cookedPointerData.pointerCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003572 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3573 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3574 mPointerSimple.currentProperties.id = 0;
3575 mPointerSimple.currentProperties.toolType =
3576 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3577 } else {
3578 down = false;
3579 hovering = false;
3580 }
3581
Prabir Pradhane71e5702023-03-29 14:51:38 +00003582 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003583}
3584
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003585std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3586 uint32_t policyFlags) {
3587 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003588}
3589
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003590std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3591 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003592 mPointerSimple.currentCoords.clear();
3593 mPointerSimple.currentProperties.clear();
3594
3595 bool down, hovering;
3596 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3597 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003599 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003600 } else {
3601 mPointerVelocityControl.reset();
3602 }
3603
3604 down = isPointerDown(mCurrentRawState.buttonState);
3605 hovering = !down;
3606
Prabir Pradhan2719e822023-02-28 17:39:36 +00003607 const auto [x, y] = mPointerController->getPosition();
3608 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003609 mPointerSimple.currentCoords =
3610 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003611 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3612 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3613 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3614 hovering ? 0.0f : 1.0f);
3615 mPointerSimple.currentProperties.id = 0;
3616 mPointerSimple.currentProperties.toolType =
3617 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3618 } else {
3619 mPointerVelocityControl.reset();
3620
3621 down = false;
3622 hovering = false;
3623 }
3624
Prabir Pradhane71e5702023-03-29 14:51:38 +00003625 const int32_t displayId = mPointerController->getDisplayId();
3626 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003627}
3628
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003629std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3630 uint32_t policyFlags) {
3631 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003632
3633 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003634
3635 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003636}
3637
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003638std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3639 uint32_t policyFlags, bool down,
Prabir Pradhane71e5702023-03-29 14:51:38 +00003640 bool hovering, int32_t displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003641 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3642 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003643 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003644 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003645 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003646
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003647 if (displayId == mPointerController->getDisplayId()) {
3648 std::tie(cursorPosition.x, cursorPosition.y) = mPointerController->getPosition();
3649 if (down || hovering) {
3650 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
3651 mPointerController->clearSpots();
3652 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3653 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
3654 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3655 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003656 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003657
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003658 if (mPointerSimple.down && !down) {
3659 mPointerSimple.down = false;
3660
3661 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003662 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3663 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3664 0, metaState, mLastRawState.buttonState,
3665 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3666 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003667 mOrientedXPrecision, mOrientedYPrecision,
3668 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3669 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003670 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003671 }
3672
3673 if (mPointerSimple.hovering && !hovering) {
3674 mPointerSimple.hovering = false;
3675
3676 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003677 out.push_back(
3678 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3679 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3680 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3681 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3682 &mPointerSimple.lastCoords, mOrientedXPrecision,
3683 mOrientedYPrecision, mPointerSimple.lastCursorX,
3684 mPointerSimple.lastCursorY, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003685 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003686 }
3687
3688 if (down) {
3689 if (!mPointerSimple.down) {
3690 mPointerSimple.down = true;
3691 mPointerSimple.downTime = when;
3692
3693 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003694 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3695 mSource, displayId, policyFlags,
3696 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3697 mCurrentRawState.buttonState, MotionClassification::NONE,
3698 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3699 &mPointerSimple.currentProperties,
3700 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003701 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003702 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003703 }
3704
3705 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003706 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3707 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3708 0, 0, metaState, mCurrentRawState.buttonState,
3709 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3710 &mPointerSimple.currentProperties,
3711 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003712 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003713 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003714 }
3715
3716 if (hovering) {
3717 if (!mPointerSimple.hovering) {
3718 mPointerSimple.hovering = true;
3719
3720 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003721 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3722 mSource, displayId, policyFlags,
3723 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3724 mCurrentRawState.buttonState, MotionClassification::NONE,
3725 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3726 &mPointerSimple.currentProperties,
3727 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003728 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003729 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003730 }
3731
3732 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003733 out.push_back(
3734 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3735 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3736 metaState, mCurrentRawState.buttonState,
3737 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3738 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003739 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003740 cursorPosition.y, mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003741 }
3742
3743 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3744 float vscroll = mCurrentRawState.rawVScroll;
3745 float hscroll = mCurrentRawState.rawHScroll;
3746 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3747 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3748
3749 // Send scroll.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003750 PointerCoords pointerCoords = mPointerSimple.currentCoords;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003751 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3752 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3753
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003754 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3755 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3756 0, 0, metaState, mCurrentRawState.buttonState,
3757 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3758 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003759 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3760 cursorPosition.y, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003761 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003762 }
3763
3764 // Save state.
3765 if (down || hovering) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003766 mPointerSimple.lastCoords = mPointerSimple.currentCoords;
3767 mPointerSimple.lastProperties = mPointerSimple.currentProperties;
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003768 mPointerSimple.displayId = displayId;
3769 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003770 mPointerSimple.lastCursorX = cursorPosition.x;
3771 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003772 } else {
3773 mPointerSimple.reset();
3774 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003775 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003776}
3777
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003778std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3779 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003780 std::list<NotifyArgs> out;
3781 if (mPointerSimple.down || mPointerSimple.hovering) {
3782 int32_t metaState = getContext()->getGlobalMetaState();
3783 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3784 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3785 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3786 metaState, mLastRawState.buttonState,
3787 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3788 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3789 mOrientedXPrecision, mOrientedYPrecision,
3790 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3791 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003792 /*videoFrames=*/{}));
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003793 if (mPointerController != nullptr) {
3794 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3795 }
3796 }
3797 mPointerSimple.reset();
3798 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003799}
3800
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003801NotifyMotionArgs TouchInputMapper::dispatchMotion(
3802 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3803 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003804 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3805 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003806 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003807 std::vector<PointerCoords> pointerCoords;
3808 std::vector<PointerProperties> pointerProperties;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003809 uint32_t pointerCount = 0;
3810 while (!idBits.isEmpty()) {
3811 uint32_t id = idBits.clearFirstMarkedBit();
3812 uint32_t index = idToIndex[id];
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003813 pointerProperties.push_back(properties[index]);
3814 pointerCoords.push_back(coords[index]);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003815
3816 if (changedId >= 0 && id == uint32_t(changedId)) {
3817 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3818 }
3819
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003820 pointerCount++;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003821 }
3822
3823 ALOG_ASSERT(pointerCount != 0);
3824
3825 if (changedId >= 0 && pointerCount == 1) {
3826 // Replace initial down and final up action.
3827 // We can compare the action without masking off the changed pointer index
3828 // because we know the index is 0.
3829 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3830 action = AMOTION_EVENT_ACTION_DOWN;
3831 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003832 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3833 action = AMOTION_EVENT_ACTION_CANCEL;
3834 } else {
3835 action = AMOTION_EVENT_ACTION_UP;
3836 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003837 } else {
3838 // Can't happen.
3839 ALOG_ASSERT(false);
3840 }
3841 }
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00003842 if (mCurrentStreamModifiedByExternalStylus) {
3843 source |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3844 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003845
3846 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3847 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003848 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003849 mPointerController && displayId != ADISPLAY_ID_NONE &&
3850 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003851 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003852 switch (action & AMOTION_EVENT_ACTION_MASK) {
3853 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3854 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3855 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003856 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003857 mPointerController
3858 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3859 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3860 .getY());
3861 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3862 break;
3863 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3864 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3865 break;
3866 }
3867 }
3868
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003869 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3870 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003871 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003872 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003873 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003874 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003875 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003876 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003877 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003878 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3879 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003880 classification, edgeFlags, pointerCount, pointerProperties.data(),
3881 pointerCoords.data(), xPrecision, yPrecision, xCursorPosition,
3882 yCursorPosition, downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003883}
3884
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003885std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3886 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003887 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3888 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003889 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003890}
3891
Prabir Pradhan1728b212021-10-19 16:00:03 -07003892bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003893 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003894 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003895 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003896}
3897
3898const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3899 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003900 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3901 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3902 "left=%d, top=%d, right=%d, bottom=%d",
3903 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3904 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003905
3906 if (virtualKey.isHit(x, y)) {
3907 return &virtualKey;
3908 }
3909 }
3910
3911 return nullptr;
3912}
3913
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003914void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3915 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3916 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003917
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003918 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003919
3920 if (currentPointerCount == 0) {
3921 // No pointers to assign.
3922 return;
3923 }
3924
3925 if (lastPointerCount == 0) {
3926 // All pointers are new.
3927 for (uint32_t i = 0; i < currentPointerCount; i++) {
3928 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003929 current.rawPointerData.pointers[i].id = id;
3930 current.rawPointerData.idToIndex[id] = i;
3931 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003932 }
3933 return;
3934 }
3935
3936 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003937 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003938 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003939 uint32_t id = last.rawPointerData.pointers[0].id;
3940 current.rawPointerData.pointers[0].id = id;
3941 current.rawPointerData.idToIndex[id] = 0;
3942 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003943 return;
3944 }
3945
3946 // General case.
3947 // We build a heap of squared euclidean distances between current and last pointers
3948 // associated with the current and last pointer indices. Then, we find the best
3949 // match (by distance) for each current pointer.
3950 // The pointers must have the same tool type but it is possible for them to
3951 // transition from hovering to touching or vice-versa while retaining the same id.
3952 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3953
3954 uint32_t heapSize = 0;
3955 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3956 currentPointerIndex++) {
3957 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3958 lastPointerIndex++) {
3959 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003960 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003961 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003962 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003963 if (currentPointer.toolType == lastPointer.toolType) {
3964 int64_t deltaX = currentPointer.x - lastPointer.x;
3965 int64_t deltaY = currentPointer.y - lastPointer.y;
3966
3967 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3968
3969 // Insert new element into the heap (sift up).
3970 heap[heapSize].currentPointerIndex = currentPointerIndex;
3971 heap[heapSize].lastPointerIndex = lastPointerIndex;
3972 heap[heapSize].distance = distance;
3973 heapSize += 1;
3974 }
3975 }
3976 }
3977
3978 // Heapify
3979 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3980 startIndex -= 1;
3981 for (uint32_t parentIndex = startIndex;;) {
3982 uint32_t childIndex = parentIndex * 2 + 1;
3983 if (childIndex >= heapSize) {
3984 break;
3985 }
3986
3987 if (childIndex + 1 < heapSize &&
3988 heap[childIndex + 1].distance < heap[childIndex].distance) {
3989 childIndex += 1;
3990 }
3991
3992 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3993 break;
3994 }
3995
3996 swap(heap[parentIndex], heap[childIndex]);
3997 parentIndex = childIndex;
3998 }
3999 }
4000
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004001 if (DEBUG_POINTER_ASSIGNMENT) {
4002 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
4003 for (size_t i = 0; i < heapSize; i++) {
4004 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
4005 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
4006 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004007 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004008
4009 // Pull matches out by increasing order of distance.
4010 // To avoid reassigning pointers that have already been matched, the loop keeps track
4011 // of which last and current pointers have been matched using the matchedXXXBits variables.
4012 // It also tracks the used pointer id bits.
4013 BitSet32 matchedLastBits(0);
4014 BitSet32 matchedCurrentBits(0);
4015 BitSet32 usedIdBits(0);
4016 bool first = true;
4017 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
4018 while (heapSize > 0) {
4019 if (first) {
4020 // The first time through the loop, we just consume the root element of
4021 // the heap (the one with smallest distance).
4022 first = false;
4023 } else {
4024 // Previous iterations consumed the root element of the heap.
4025 // Pop root element off of the heap (sift down).
4026 heap[0] = heap[heapSize];
4027 for (uint32_t parentIndex = 0;;) {
4028 uint32_t childIndex = parentIndex * 2 + 1;
4029 if (childIndex >= heapSize) {
4030 break;
4031 }
4032
4033 if (childIndex + 1 < heapSize &&
4034 heap[childIndex + 1].distance < heap[childIndex].distance) {
4035 childIndex += 1;
4036 }
4037
4038 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4039 break;
4040 }
4041
4042 swap(heap[parentIndex], heap[childIndex]);
4043 parentIndex = childIndex;
4044 }
4045
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004046 if (DEBUG_POINTER_ASSIGNMENT) {
4047 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4048 for (size_t j = 0; j < heapSize; j++) {
4049 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4050 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4051 heap[j].distance);
4052 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004053 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004054 }
4055
4056 heapSize -= 1;
4057
4058 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4059 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4060
4061 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4062 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4063
4064 matchedCurrentBits.markBit(currentPointerIndex);
4065 matchedLastBits.markBit(lastPointerIndex);
4066
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004067 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4068 current.rawPointerData.pointers[currentPointerIndex].id = id;
4069 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4070 current.rawPointerData.markIdBit(id,
4071 current.rawPointerData.isHovering(
4072 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004073 usedIdBits.markBit(id);
4074
Harry Cutts45483602022-08-24 14:36:48 +00004075 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4076 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4077 ", distance=%" PRIu64,
4078 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004079 break;
4080 }
4081 }
4082
4083 // Assign fresh ids to pointers that were not matched in the process.
4084 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4085 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4086 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4087
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004088 current.rawPointerData.pointers[currentPointerIndex].id = id;
4089 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4090 current.rawPointerData.markIdBit(id,
4091 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004092
Harry Cutts45483602022-08-24 14:36:48 +00004093 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4094 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4095 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004096 }
4097}
4098
4099int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4100 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4101 return AKEY_STATE_VIRTUAL;
4102 }
4103
4104 for (const VirtualKey& virtualKey : mVirtualKeys) {
4105 if (virtualKey.keyCode == keyCode) {
4106 return AKEY_STATE_UP;
4107 }
4108 }
4109
4110 return AKEY_STATE_UNKNOWN;
4111}
4112
4113int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4114 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4115 return AKEY_STATE_VIRTUAL;
4116 }
4117
4118 for (const VirtualKey& virtualKey : mVirtualKeys) {
4119 if (virtualKey.scanCode == scanCode) {
4120 return AKEY_STATE_UP;
4121 }
4122 }
4123
4124 return AKEY_STATE_UNKNOWN;
4125}
4126
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004127bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4128 const std::vector<int32_t>& keyCodes,
4129 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004130 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004131 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004132 if (virtualKey.keyCode == keyCodes[i]) {
4133 outFlags[i] = 1;
4134 }
4135 }
4136 }
4137
4138 return true;
4139}
4140
4141std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4142 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004143 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004144 return std::make_optional(mPointerController->getDisplayId());
4145 } else {
4146 return std::make_optional(mViewport.displayId);
4147 }
4148 }
4149 return std::nullopt;
4150}
4151
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004152} // namespace android