blob: 5c90cbb6ce6d718dcfa1ba8d909e6e1e397616f4 [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.
Prabir Pradhan7ff19a12024-07-29 22:40:31 +0000152 return mSource |
153 (mExternalStylusPresence == ExternalStylusPresence::TOUCH_FUSION
154 ? AINPUT_SOURCE_BLUETOOTH_STYLUS
155 : 0);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700156}
157
Harry Cuttsd02ea102023-03-17 18:21:30 +0000158void TouchInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700159 InputMapper::populateDeviceInfo(info);
160
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000161 if (mDeviceMode == DeviceMode::DISABLED) {
162 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700163 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000164
Harry Cuttsd02ea102023-03-17 18:21:30 +0000165 info.addMotionRange(mOrientedRanges.x);
166 info.addMotionRange(mOrientedRanges.y);
167 info.addMotionRange(mOrientedRanges.pressure);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000168
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000169 if (mOrientedRanges.size) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000170 info.addMotionRange(*mOrientedRanges.size);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000171 }
172
173 if (mOrientedRanges.touchMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000174 info.addMotionRange(*mOrientedRanges.touchMajor);
175 info.addMotionRange(*mOrientedRanges.touchMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000176 }
177
178 if (mOrientedRanges.toolMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000179 info.addMotionRange(*mOrientedRanges.toolMajor);
180 info.addMotionRange(*mOrientedRanges.toolMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000181 }
182
183 if (mOrientedRanges.orientation) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000184 info.addMotionRange(*mOrientedRanges.orientation);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000185 }
186
187 if (mOrientedRanges.distance) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000188 info.addMotionRange(*mOrientedRanges.distance);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000189 }
190
191 if (mOrientedRanges.tilt) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000192 info.addMotionRange(*mOrientedRanges.tilt);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000193 }
194
195 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000196 info.addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000197 }
198 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000199 info.addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000200 }
Harry Cuttsd02ea102023-03-17 18:21:30 +0000201 info.setButtonUnderPad(mParameters.hasButtonUnderPad);
202 info.setUsiVersion(mParameters.usiVersion);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700203}
204
205void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700206 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800207 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700208 dumpParameters(dump);
209 dumpVirtualKeys(dump);
210 dumpRawPointerAxes(dump);
211 dumpCalibration(dump);
212 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700213 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700214
215 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000216 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000217 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
218 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
219 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700220 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
221 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
222 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
223 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
224 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
225 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
226 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
227 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
228 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
229 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
230
231 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
232 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
233 mLastRawState.rawPointerData.pointerCount);
234 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
235 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
236 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
237 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
238 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700239 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700240 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
241 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
242 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700243 pointer.distance, ftl::enum_string(pointer.toolType).c_str(),
244 toString(pointer.isHovering));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700245 }
246
247 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
248 mLastCookedState.buttonState);
249 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
250 mLastCookedState.cookedPointerData.pointerCount);
251 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
252 const PointerProperties& pointerProperties =
253 mLastCookedState.cookedPointerData.pointerProperties[i];
254 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000255 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
256 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
257 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700258 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700259 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700260 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000261 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
262 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700263 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
264 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
265 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
266 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
267 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
268 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
269 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
270 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700271 ftl::enum_string(pointerProperties.toolType).c_str(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700272 toString(mLastCookedState.cookedPointerData.isHovering(i)));
273 }
274
275 dump += INDENT3 "Stylus Fusion:\n";
Prabir Pradhan7ff19a12024-07-29 22:40:31 +0000276 dump += StringPrintf(INDENT4 "ExternalStylusPresence: %s\n",
277 ftl::enum_string(mExternalStylusPresence).c_str());
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000278 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
279 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700280 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
281 mExternalStylusFusionTimeout);
Harry Cutts1ee05b62023-06-19 13:49:06 +0000282 dump += StringPrintf(INDENT4 "External Stylus Buttons Applied: 0x%08x\n",
Prabir Pradhan124ea442022-10-28 20:27:44 +0000283 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700284 dump += INDENT3 "External Stylus State:\n";
285 dumpStylusState(dump, mExternalStylusState);
286
Michael Wright227c5542020-07-02 18:30:52 +0100287 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700288 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
289 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
290 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
291 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
292 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
293 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
294 }
295}
296
Arpit Singh4be4eef2023-03-28 14:26:01 +0000297std::list<NotifyArgs> TouchInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000298 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000299 ConfigurationChanges changes) {
Arpit Singh4be4eef2023-03-28 14:26:01 +0000300 std::list<NotifyArgs> out = InputMapper::reconfigure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700301
Arpit Singhed6c3de2023-04-05 19:24:37 +0000302 mConfig = config;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700303
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000304 // Full configuration should happen the first time configure is called and
305 // when the device type is changed. Changing a device type can affect
306 // various other parameters so should result in a reconfiguration.
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000307 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700308 // Configure basic parameters.
Arpit Singh403e53c2023-04-18 11:46:56 +0000309 mParameters = computeParameters(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700310
311 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800312 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000313 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314
315 // Configure absolute axis information.
316 configureRawPointerAxes();
317
318 // Prepare input device calibration.
319 parseCalibration();
320 resolveCalibration();
321 }
322
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000323 if (!changes.any() ||
324 changes.test(InputReaderConfiguration::Change::TOUCH_AFFINE_TRANSFORMATION)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700325 // Update location calibration to reflect current settings
326 updateAffineTransformation();
327 }
328
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000329 if (!changes.any() || changes.test(InputReaderConfiguration::Change::POINTER_SPEED)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700330 // Update pointer speed.
331 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
332 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
333 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
334 }
335
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000336 using namespace ftl::flag_operators;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337 bool resetNeeded = false;
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000338 if (!changes.any() ||
339 changes.any(InputReaderConfiguration::Change::DISPLAY_INFO |
340 InputReaderConfiguration::Change::POINTER_CAPTURE |
341 InputReaderConfiguration::Change::POINTER_GESTURE_ENABLEMENT |
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000342 InputReaderConfiguration::Change::EXTERNAL_STYLUS_PRESENCE |
343 InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700344 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700345 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700346 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700347 }
348
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000349 if (changes.any() && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700350 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000351
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700352 // Send reset, unless this is the first time the device has been configured,
353 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000354 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700355 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700356 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700357}
358
359void TouchInputMapper::resolveExternalStylusPresence() {
360 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 getContext()->getExternalStylusDevices(devices);
Prabir Pradhan7ff19a12024-07-29 22:40:31 +0000362 if (devices.empty()) {
363 mExternalStylusPresence = ExternalStylusPresence::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364 resetExternalStylus();
Prabir Pradhan7ff19a12024-07-29 22:40:31 +0000365 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700366 }
Prabir Pradhan7ff19a12024-07-29 22:40:31 +0000367 mExternalStylusPresence =
368 std::any_of(devices.begin(), devices.end(),
369 [](const auto& info) {
370 return info.getMotionRange(AMOTION_EVENT_AXIS_PRESSURE,
371 AINPUT_SOURCE_STYLUS) != nullptr;
372 })
373 ? ExternalStylusPresence::TOUCH_FUSION
374 : ExternalStylusPresence::BUTTON_FUSION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700375}
376
Arpit Singh403e53c2023-04-18 11:46:56 +0000377TouchInputMapper::Parameters TouchInputMapper::computeParameters(
378 const InputDeviceContext& deviceContext) {
379 Parameters parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700380 // Use the pointer presentation mode for devices that do not support distinct
381 // multitouch. The spot-based presentation relies on being able to accurately
382 // locate two or more fingers on the touch pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000383 parameters.gestureMode = deviceContext.hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100384 ? Parameters::GestureMode::SINGLE_TOUCH
385 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700386
Arpit Singh403e53c2023-04-18 11:46:56 +0000387 const PropertyMap& config = deviceContext.getConfiguration();
Harry Cuttsf13161a2023-03-08 14:15:49 +0000388 std::optional<std::string> gestureModeString = config.getString("touch.gestureMode");
389 if (gestureModeString.has_value()) {
390 if (*gestureModeString == "single-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000391 parameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000392 } else if (*gestureModeString == "multi-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000393 parameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000394 } else if (*gestureModeString != "default") {
395 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700396 }
397 }
398
Arpit Singh403e53c2023-04-18 11:46:56 +0000399 parameters.deviceType = computeDeviceType(deviceContext);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700400
Arpit Singh403e53c2023-04-18 11:46:56 +0000401 parameters.hasButtonUnderPad = deviceContext.hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402
Arpit Singh403e53c2023-04-18 11:46:56 +0000403 parameters.orientationAware =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000404 config.getBool("touch.orientationAware")
Arpit Singh403e53c2023-04-18 11:46:56 +0000405 .value_or(parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700406
Arpit Singh403e53c2023-04-18 11:46:56 +0000407 parameters.orientation = ui::ROTATION_0;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000408 std::optional<std::string> orientationString = config.getString("touch.orientation");
409 if (orientationString.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000410 if (parameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700411 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
Harry Cuttsf13161a2023-03-08 14:15:49 +0000412 } else if (*orientationString == "ORIENTATION_90") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000413 parameters.orientation = ui::ROTATION_90;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000414 } else if (*orientationString == "ORIENTATION_180") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000415 parameters.orientation = ui::ROTATION_180;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000416 } else if (*orientationString == "ORIENTATION_270") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000417 parameters.orientation = ui::ROTATION_270;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000418 } else if (*orientationString != "ORIENTATION_0") {
419 ALOGW("Invalid value for touch.orientation: '%s'", orientationString->c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700420 }
421 }
422
Arpit Singh403e53c2023-04-18 11:46:56 +0000423 parameters.hasAssociatedDisplay = false;
424 parameters.associatedDisplayIsExternal = false;
425 if (parameters.orientationAware ||
426 parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
427 parameters.deviceType == Parameters::DeviceType::POINTER ||
428 (parameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
429 deviceContext.getAssociatedViewport())) {
430 parameters.hasAssociatedDisplay = true;
431 if (parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
432 parameters.associatedDisplayIsExternal = deviceContext.isExternal();
433 parameters.uniqueDisplayId = config.getString("touch.displayId").value_or("").c_str();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700434 }
435 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000436 if (deviceContext.getAssociatedDisplayPort()) {
437 parameters.hasAssociatedDisplay = true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700438 }
439
440 // Initial downs on external touch devices should wake the device.
441 // Normally we don't do this for internal touch screens to prevent them from waking
442 // up in your pocket but you can enable it using the input device configuration.
Arpit Singh403e53c2023-04-18 11:46:56 +0000443 parameters.wake = config.getBool("touch.wake").value_or(deviceContext.isExternal());
Prabir Pradhan167c2702022-09-14 00:37:24 +0000444
Harry Cuttsf13161a2023-03-08 14:15:49 +0000445 std::optional<int32_t> usiVersionMajor = config.getInt("touch.usiVersionMajor");
446 std::optional<int32_t> usiVersionMinor = config.getInt("touch.usiVersionMinor");
447 if (usiVersionMajor.has_value() && usiVersionMinor.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000448 parameters.usiVersion = {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000449 .majorVersion = *usiVersionMajor,
450 .minorVersion = *usiVersionMinor,
451 };
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000452 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700453
Arpit Singh403e53c2023-04-18 11:46:56 +0000454 parameters.enableForInactiveViewport =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000455 config.getBool("touch.enableForInactiveViewport").value_or(false);
Arpit Singh403e53c2023-04-18 11:46:56 +0000456
457 return parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458}
459
Arpit Singh403e53c2023-04-18 11:46:56 +0000460TouchInputMapper::Parameters::DeviceType TouchInputMapper::computeDeviceType(
461 const InputDeviceContext& deviceContext) {
462 Parameters::DeviceType deviceType;
463 if (deviceContext.hasInputProperty(INPUT_PROP_DIRECT)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000464 // The device is a touch screen.
Arpit Singh403e53c2023-04-18 11:46:56 +0000465 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
466 } else if (deviceContext.hasInputProperty(INPUT_PROP_POINTER)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000467 // The device is a pointing device like a track pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000468 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000469 } else {
470 // The device is a touch pad of unknown purpose.
Arpit Singh403e53c2023-04-18 11:46:56 +0000471 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000472 }
473
474 // Type association takes precedence over the device type found in the idc file.
Arpit Singh403e53c2023-04-18 11:46:56 +0000475 std::string deviceTypeString = deviceContext.getDeviceTypeAssociation().value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000476 if (deviceTypeString.empty()) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000477 deviceTypeString =
Arpit Singh403e53c2023-04-18 11:46:56 +0000478 deviceContext.getConfiguration().getString("touch.deviceType").value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000479 }
480 if (deviceTypeString == "touchScreen") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000481 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000482 } else if (deviceTypeString == "touchNavigation") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000483 deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000484 } else if (deviceTypeString == "pointer") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000485 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000486 } else if (deviceTypeString != "default" && deviceTypeString != "") {
487 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
488 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000489 return deviceType;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000490}
491
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700492void TouchInputMapper::dumpParameters(std::string& dump) {
493 dump += INDENT3 "Parameters:\n";
494
Dominik Laskowski75788452021-02-09 18:51:25 -0800495 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496
Dominik Laskowski75788452021-02-09 18:51:25 -0800497 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700498
499 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
500 "displayId='%s'\n",
501 toString(mParameters.hasAssociatedDisplay),
502 toString(mParameters.associatedDisplayIsExternal),
503 mParameters.uniqueDisplayId.c_str());
504 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800505 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000506 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
507 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700508 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
509 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700510}
511
512void TouchInputMapper::configureRawPointerAxes() {
513 mRawPointerAxes.clear();
514}
515
516void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
517 dump += INDENT3 "Raw Touch Axes:\n";
518 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
520 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
521 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
522 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
523 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
524 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
525 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
526 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
527 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
528 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
529 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
530 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
531}
532
533bool TouchInputMapper::hasExternalStylus() const {
Prabir Pradhan7ff19a12024-07-29 22:40:31 +0000534 return mExternalStylusPresence != ExternalStylusPresence::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700535}
536
537/**
538 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000539 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800540 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000541 * 3. Get the matching viewport by either unique id in idc file or by the display type
542 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800543 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700544 */
545std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Harry Cutts8722be92024-04-05 14:46:05 +0000546 if (mParameters.hasAssociatedDisplay) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000547 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800548 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700549 }
550
Michael Wright227c5542020-07-02 18:30:52 +0100551 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800552 std::optional<DisplayViewport> viewport =
553 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
554 if (viewport) {
555 return viewport;
556 } else {
Linnan Li13bf76a2024-05-05 19:18:02 +0800557 ALOGW("Can't find designated display viewport with ID %s for pointers.",
558 mConfig.defaultPointerDisplayId.toString().c_str());
Garfield Tan888a6a42020-01-09 11:39:16 -0800559 }
560 }
561
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700562 // Check if uniqueDisplayId is specified in idc file.
563 if (!mParameters.uniqueDisplayId.empty()) {
564 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
565 }
566
567 ViewportType viewportTypeToUse;
568 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100569 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700570 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100571 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700572 }
573
574 std::optional<DisplayViewport> viewport =
575 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100576 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700577 ALOGW("Input device %s should be associated with external display, "
578 "fallback to internal one for the external viewport is not found.",
579 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100580 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700581 }
582
583 return viewport;
584 }
585
586 // No associated display, return a non-display viewport.
587 DisplayViewport newViewport;
588 // Raw width and height in the natural orientation.
589 int32_t rawWidth = mRawPointerAxes.getRawWidth();
590 int32_t rawHeight = mRawPointerAxes.getRawHeight();
591 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
592 return std::make_optional(newViewport);
593}
594
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800595int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
596 if (resolution < 0) {
597 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
598 getDeviceName().c_str());
599 return 0;
600 }
601 return resolution;
602}
603
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800604void TouchInputMapper::initializeSizeRanges() {
605 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
606 mSizeScale = 0.0f;
607 return;
608 }
609
610 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000611 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800612
613 // Size factors.
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000614 if (mRawPointerAxes.touchMajor && mRawPointerAxes.touchMajor->maxValue != 0) {
615 mSizeScale = 1.0f / mRawPointerAxes.touchMajor->maxValue;
616 } else if (mRawPointerAxes.toolMajor && mRawPointerAxes.toolMajor->maxValue != 0) {
617 mSizeScale = 1.0f / mRawPointerAxes.toolMajor->maxValue;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800618 } else {
619 mSizeScale = 0.0f;
620 }
621
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700622 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
623 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
624 .source = mSource,
625 .min = 0,
626 .max = diagonalSize,
627 .flat = 0,
628 .fuzz = 0,
629 .resolution = 0,
630 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800631
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000632 if (mRawPointerAxes.touchMajor) {
633 mRawPointerAxes.touchMajor->resolution =
634 clampResolution("touchMajor", mRawPointerAxes.touchMajor->resolution);
635 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor->resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800636 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800637
638 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700639 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000640 if (mRawPointerAxes.touchMinor) {
641 mRawPointerAxes.touchMinor->resolution =
642 clampResolution("touchMinor", mRawPointerAxes.touchMinor->resolution);
643 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor->resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800644 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800645
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700646 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
647 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
648 .source = mSource,
649 .min = 0,
650 .max = diagonalSize,
651 .flat = 0,
652 .fuzz = 0,
653 .resolution = 0,
654 };
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000655 if (mRawPointerAxes.toolMajor) {
656 mRawPointerAxes.toolMajor->resolution =
657 clampResolution("toolMajor", mRawPointerAxes.toolMajor->resolution);
658 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor->resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800659 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800660
661 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700662 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000663 if (mRawPointerAxes.toolMinor) {
664 mRawPointerAxes.toolMinor->resolution =
665 clampResolution("toolMinor", mRawPointerAxes.toolMinor->resolution);
666 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor->resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800667 }
668
669 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700670 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
671 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
672 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
673 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800674 } else {
675 // Support for other calibrations can be added here.
676 ALOGW("%s calibration is not supported for size ranges at the moment. "
677 "Using raw resolution instead",
678 ftl::enum_string(mCalibration.sizeCalibration).c_str());
679 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800680
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700681 mOrientedRanges.size = InputDeviceInfo::MotionRange{
682 .axis = AMOTION_EVENT_AXIS_SIZE,
683 .source = mSource,
684 .min = 0,
685 .max = 1.0,
686 .flat = 0,
687 .fuzz = 0,
688 .resolution = 0,
689 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800690}
691
692void TouchInputMapper::initializeOrientedRanges() {
693 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000694 const float orientedScaleX = mRawToDisplay.getScaleX();
695 const float orientedScaleY = mRawToDisplay.getScaleY();
696 mOrientedXPrecision = 1.0f / orientedScaleX;
697 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800698
699 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
700 mOrientedRanges.x.source = mSource;
701 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
702 mOrientedRanges.y.source = mSource;
703
704 // Scale factor for terms that are not oriented in a particular axis.
705 // If the pixels are square then xScale == yScale otherwise we fake it
706 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000707 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800708
709 initializeSizeRanges();
710
711 // Pressure factors.
712 mPressureScale = 0;
713 float pressureMax = 1.0;
714 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
715 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700716 if (mCalibration.pressureScale) {
717 mPressureScale = *mCalibration.pressureScale;
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000718 pressureMax = mPressureScale *
719 (mRawPointerAxes.pressure ? mRawPointerAxes.pressure->maxValue : 0);
720 } else if (mRawPointerAxes.pressure && mRawPointerAxes.pressure->maxValue != 0) {
721 mPressureScale = 1.0f / mRawPointerAxes.pressure->maxValue;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800722 }
723 }
724
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700725 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
726 .axis = AMOTION_EVENT_AXIS_PRESSURE,
727 .source = mSource,
728 .min = 0,
729 .max = pressureMax,
730 .flat = 0,
731 .fuzz = 0,
732 .resolution = 0,
733 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800734
735 // Tilt
736 mTiltXCenter = 0;
737 mTiltXScale = 0;
738 mTiltYCenter = 0;
739 mTiltYScale = 0;
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000740 mHaveTilt = mRawPointerAxes.tiltX && mRawPointerAxes.tiltY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800741 if (mHaveTilt) {
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000742 mTiltXCenter = avg(mRawPointerAxes.tiltX->minValue, mRawPointerAxes.tiltX->maxValue);
743 mTiltYCenter = avg(mRawPointerAxes.tiltY->minValue, mRawPointerAxes.tiltY->maxValue);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800744 mTiltXScale = M_PI / 180;
745 mTiltYScale = M_PI / 180;
746
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000747 if (mRawPointerAxes.tiltX->resolution) {
748 mTiltXScale = 1.0 / mRawPointerAxes.tiltX->resolution;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800749 }
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000750 if (mRawPointerAxes.tiltY->resolution) {
751 mTiltYScale = 1.0 / mRawPointerAxes.tiltY->resolution;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800752 }
753
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700754 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
755 .axis = AMOTION_EVENT_AXIS_TILT,
756 .source = mSource,
757 .min = 0,
758 .max = M_PI_2,
759 .flat = 0,
760 .fuzz = 0,
761 .resolution = 0,
762 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800763 }
764
765 // Orientation
766 mOrientationScale = 0;
767 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700768 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
769 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
770 .source = mSource,
771 .min = -M_PI,
772 .max = M_PI,
773 .flat = 0,
774 .fuzz = 0,
775 .resolution = 0,
776 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800777
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800778 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
779 if (mCalibration.orientationCalibration ==
780 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000781 if (mRawPointerAxes.orientation) {
782 if (mRawPointerAxes.orientation->maxValue > 0) {
783 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation->maxValue;
784 } else if (mRawPointerAxes.orientation->minValue < 0) {
785 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation->minValue;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800786 } else {
787 mOrientationScale = 0;
788 }
789 }
790 }
791
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700792 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
793 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
794 .source = mSource,
795 .min = -M_PI_2,
796 .max = M_PI_2,
797 .flat = 0,
798 .fuzz = 0,
799 .resolution = 0,
800 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800801 }
802
803 // Distance
804 mDistanceScale = 0;
805 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
806 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700807 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800808 }
809
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000810 const bool hasDistance = mRawPointerAxes.distance.has_value();
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700811 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700812 .axis = AMOTION_EVENT_AXIS_DISTANCE,
813 .source = mSource,
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000814 .min = hasDistance ? mRawPointerAxes.distance->minValue * mDistanceScale : 0,
815 .max = hasDistance ? mRawPointerAxes.distance->maxValue * mDistanceScale : 0,
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700816 .flat = 0,
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000817 .fuzz = hasDistance ? mRawPointerAxes.distance->fuzz * mDistanceScale : 0,
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700818 .resolution = 0,
819 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800820 }
821
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000822 // Oriented X/Y range (in the rotated display's orientation)
823 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
824 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
825 .toFloatRect();
826 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
827 mOrientedRanges.x.min = orientedRangeRect.left;
828 mOrientedRanges.y.min = orientedRangeRect.top;
829 mOrientedRanges.x.max = orientedRangeRect.right;
830 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800831
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000832 // Oriented flat (in the rotated display's orientation)
833 const auto orientedFlat =
834 transformWithoutTranslation(mRawToRotatedDisplay,
835 {static_cast<float>(mRawPointerAxes.x.flat),
836 static_cast<float>(mRawPointerAxes.y.flat)});
837 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
838 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800839
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000840 // Oriented fuzz (in the rotated display's orientation)
841 const auto orientedFuzz =
842 transformWithoutTranslation(mRawToRotatedDisplay,
843 {static_cast<float>(mRawPointerAxes.x.fuzz),
844 static_cast<float>(mRawPointerAxes.y.fuzz)});
845 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
846 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800847
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000848 // Oriented resolution (in the rotated display's orientation)
849 const auto orientedRes =
850 transformWithoutTranslation(mRawToRotatedDisplay,
851 {static_cast<float>(mRawPointerAxes.x.resolution),
852 static_cast<float>(mRawPointerAxes.y.resolution)});
853 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
854 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800855}
856
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000857void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000858 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
859 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
860 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000861
Prabir Pradhan3e798762022-12-02 21:02:11 +0000862 // See notes about input coordinates in the inputflinger docs:
863 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000864
865 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000866 ui::Transform undoOffsetInRaw;
867 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000868
Prabir Pradhan3e798762022-12-02 21:02:11 +0000869 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
870 // will now be in the same orientation as the display in ROTATION_0.
871 // Note: Negating an ui::Rotation value will give its inverse rotation.
872 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
873 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
874 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
875 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
876 // When rotating raw values, account for the extra unit added when calculating the raw range.
877 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
878 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000879
Prabir Pradhan3e798762022-12-02 21:02:11 +0000880 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
881 // now be in the same orientation as the rotated display. There is no need to rotate the
882 // coordinates to the display rotation if the device is not orientation-aware.
883 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
884 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
885 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
886 : orientedRawSize;
887 // When rotating raw values, account for the extra unit added when calculating the raw range.
888 const auto rotateInRaw = mParameters.orientationAware
889 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
890 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000891
Prabir Pradhan3e798762022-12-02 21:02:11 +0000892 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000893 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
894 // the surface of the display panel. This is usually true for touchscreens.
895 // - In POINTER mode, we cannot assume that the display and the touch device have the same
896 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
897 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
898 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
899 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000900 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
901 // are in the continuous space of the logical display.
902 ui::Transform scaleRawToDisplay;
903 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
904 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000905 if (mDeviceMode == DeviceMode::DIRECT) {
906 scaleRawToDisplay.set(xScale, 0, 0, yScale);
907 } else if (mDeviceMode == DeviceMode::POINTER) {
908 const float fixedScale = std::max(xScale, yScale);
909 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
910 } else {
911 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
912 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000913
Prabir Pradhan3e798762022-12-02 21:02:11 +0000914 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
915 // that InputReader uses.
916 const auto undoRotateInDisplay =
917 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
918 .inverse();
919
920 // Now put it all together!
921 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
922 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
923 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000924}
925
Prabir Pradhan1728b212021-10-19 16:00:03 -0700926void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000927 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700928
929 resolveExternalStylusPresence();
930
931 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100932 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +0900933 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700934 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100935 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700936 if (hasStylus()) {
937 mSource |= AINPUT_SOURCE_STYLUS;
938 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800939 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700940 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100941 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700942 if (hasStylus()) {
943 mSource |= AINPUT_SOURCE_STYLUS;
944 }
Michael Wright227c5542020-07-02 18:30:52 +0100945 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhan9cf8f322024-06-18 20:22:42 +0000946 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION | AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100947 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700948 } else {
Harry Cutts8722be92024-04-05 14:46:05 +0000949 ALOGW("Touch device '%s' has invalid parameters or configuration. The device will be "
950 "inoperable.",
951 getDeviceName().c_str());
952 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700953 }
954
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000955 const std::optional<DisplayViewport> newViewportOpt = findViewport();
956
957 // Ensure the device is valid and can be used.
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000958 if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700959 ALOGI("Touch device '%s' could not query the properties of its associated "
960 "display. The device will be inoperable until the display size "
961 "becomes available.",
962 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100963 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700964 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000965 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
966 getDeviceName().c_str(), getDeviceId());
967 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000968 }
969
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700970 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000971 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000972 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
973 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
974 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
975 const float rawMeanResolution =
976 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700977
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000978 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
Josh Thielene986aed2023-06-01 14:17:30 +0000979 bool viewportChanged;
980 if (mParameters.enableForInactiveViewport) {
981 // When touch is enabled for an inactive viewport, ignore the
982 // viewport active status when checking whether the viewport has
983 // changed.
984 DisplayViewport tempViewport = mViewport;
985 tempViewport.isActive = newViewport.isActive;
986 viewportChanged = tempViewport != newViewport;
987 } else {
988 viewportChanged = mViewport != newViewport;
989 }
990
Biswarup Pal9ce4d9f2024-06-14 15:05:27 +0000991 const bool deviceModeChanged = mDeviceMode != oldDeviceMode;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700992 bool skipViewportUpdate = false;
Biswarup Pal9ce4d9f2024-06-14 15:05:27 +0000993 if (viewportChanged || deviceModeChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000994 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
995 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
996 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700997
Michael Wright227c5542020-07-02 18:30:52 +0100998 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000999 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001000
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001001 mDisplayBounds = getNaturalDisplaySize(mViewport);
1002 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
1003 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -07001004
Prabir Pradhan3e798762022-12-02 21:02:11 +00001005 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
1006 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
1007 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001008 // InputReader works in the un-rotated display coordinate space, so we don't need to do
1009 // anything if the device is already orientation-aware. If the device is not
1010 // orientation-aware, then we need to apply the inverse rotation of the display so that
1011 // when the display rotation is applied later as a part of the per-window transform, we
1012 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001013 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +00001014 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001015 : getInverseRotation(mViewport.orientation);
1016 // For orientation-aware devices that work in the un-rotated coordinate space, the
1017 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001018 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001019 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001020
1021 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001022 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001023 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001024 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001025 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001026 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001027 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001028 mRawToDisplay.reset();
1029 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001030 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001031 }
1032 }
1033
1034 // If moving between pointer modes, need to reset some state.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001035 if (deviceModeChanged) {
1036 mOrientedRanges.clear();
1037 }
1038
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001039 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001040 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %s, mode %s, "
Linnan Li13bf76a2024-05-05 19:18:02 +08001041 "display id %s",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001042 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001043 ftl::enum_string(mInputDeviceOrientation).c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08001044 ftl::enum_string(mDeviceMode).c_str(), mViewport.displayId.toString().c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001045
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001046 configureVirtualKeys();
1047
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001048 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001049
1050 // Location
1051 updateAffineTransformation();
1052
Michael Wright227c5542020-07-02 18:30:52 +01001053 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001054 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001055 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1056 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057
1058 // Scale movements such that one whole swipe of the touch pad covers a
1059 // given area relative to the diagonal size of the display when no acceleration
1060 // is applied.
1061 // Assume that the touch pad has a square aspect ratio such that movements in
1062 // X and Y of the same number of raw units cover the same physical distance.
1063 mPointerXMovementScale =
1064 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1065 mPointerYMovementScale = mPointerXMovementScale;
1066
1067 // Scale zooms to cover a smaller range of the display than movements do.
1068 // This value determines the area around the pointer that is affected by freeform
1069 // pointer gestures.
1070 mPointerXZoomScale =
1071 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1072 mPointerYZoomScale = mPointerXZoomScale;
1073
HQ Liue6983c72022-04-19 22:14:56 +00001074 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1075 // axis is non positive value.
1076 const float minFreeformGestureWidth =
1077 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1078
1079 mPointerGestureMaxSwipeWidth =
1080 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1081 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001082 }
1083
1084 // Inform the dispatcher about the changes.
1085 *outResetNeeded = true;
1086 bumpGeneration();
1087 }
1088}
1089
Prabir Pradhan1728b212021-10-19 16:00:03 -07001090void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001091 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001092 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001093 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1094 toString(mPhysicalFrameInRotatedDisplay).c_str());
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001095 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %s\n",
1096 ftl::enum_string(mInputDeviceOrientation).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001097}
1098
1099void TouchInputMapper::configureVirtualKeys() {
1100 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001101 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001102
1103 mVirtualKeys.clear();
1104
1105 if (virtualKeyDefinitions.size() == 0) {
1106 return;
1107 }
1108
1109 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1110 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1111 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1112 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1113
1114 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1115 VirtualKey virtualKey;
1116
1117 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1118 int32_t keyCode;
1119 int32_t dummyKeyMetaState;
1120 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001121 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1122 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001123 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1124 continue; // drop the key
1125 }
1126
1127 virtualKey.keyCode = keyCode;
1128 virtualKey.flags = flags;
1129
1130 // convert the key definition's display coordinates into touch coordinates for a hit box
1131 int32_t halfWidth = virtualKeyDefinition.width / 2;
1132 int32_t halfHeight = virtualKeyDefinition.height / 2;
1133
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001134 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1135 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001137 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1138 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001140 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1141 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001143 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1144 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 touchScreenTop;
1146 mVirtualKeys.push_back(virtualKey);
1147 }
1148}
1149
1150void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1151 if (!mVirtualKeys.empty()) {
1152 dump += INDENT3 "Virtual Keys:\n";
1153
1154 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1155 const VirtualKey& virtualKey = mVirtualKeys[i];
1156 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1157 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1158 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1159 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1160 }
1161 }
1162}
1163
1164void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001165 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 Calibration& out = mCalibration;
1167
1168 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001170 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1171 if (sizeCalibrationString.has_value()) {
1172 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001174 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001176 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001177 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001178 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001179 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001180 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001182 } else if (*sizeCalibrationString != "default") {
1183 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 }
1185 }
1186
Harry Cuttsf13161a2023-03-08 14:15:49 +00001187 out.sizeScale = in.getFloat("touch.size.scale");
1188 out.sizeBias = in.getFloat("touch.size.bias");
1189 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190
1191 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001193 std::optional<std::string> pressureCalibrationString =
1194 in.getString("touch.pressure.calibration");
1195 if (pressureCalibrationString.has_value()) {
1196 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001197 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001198 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001200 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001202 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001204 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 }
1206 }
1207
Harry Cuttsf13161a2023-03-08 14:15:49 +00001208 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209
1210 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001211 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001212 std::optional<std::string> orientationCalibrationString =
1213 in.getString("touch.orientation.calibration");
1214 if (orientationCalibrationString.has_value()) {
1215 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001216 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001217 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001218 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001219 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001220 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001221 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001223 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001224 }
1225 }
1226
1227 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001228 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001229 std::optional<std::string> distanceCalibrationString =
1230 in.getString("touch.distance.calibration");
1231 if (distanceCalibrationString.has_value()) {
1232 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001233 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001234 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001235 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001236 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001238 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 }
1240 }
1241
Harry Cuttsf13161a2023-03-08 14:15:49 +00001242 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243}
1244
1245void TouchInputMapper::resolveCalibration() {
1246 // Size
Prabir Pradhan132f21c2024-07-25 16:48:30 +00001247 if (mRawPointerAxes.touchMajor || mRawPointerAxes.toolMajor) {
Michael Wright227c5542020-07-02 18:30:52 +01001248 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1249 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001252 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253 }
1254
1255 // Pressure
Prabir Pradhan132f21c2024-07-25 16:48:30 +00001256 if (mRawPointerAxes.pressure) {
Michael Wright227c5542020-07-02 18:30:52 +01001257 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1258 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001261 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 }
1263
1264 // Orientation
Prabir Pradhan132f21c2024-07-25 16:48:30 +00001265 if (mRawPointerAxes.orientation) {
Michael Wright227c5542020-07-02 18:30:52 +01001266 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1267 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 }
1269 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001270 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 }
1272
1273 // Distance
Prabir Pradhan132f21c2024-07-25 16:48:30 +00001274 if (mRawPointerAxes.distance) {
Michael Wright227c5542020-07-02 18:30:52 +01001275 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1276 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277 }
1278 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001279 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281}
1282
1283void TouchInputMapper::dumpCalibration(std::string& dump) {
1284 dump += INDENT3 "Calibration:\n";
1285
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001286 dump += INDENT4 "touch.size.calibration: ";
1287 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001289 if (mCalibration.sizeScale) {
1290 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291 }
1292
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001293 if (mCalibration.sizeBias) {
1294 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 }
1296
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001297 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001299 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 }
1301
1302 // Pressure
1303 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001304 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001305 dump += INDENT4 "touch.pressure.calibration: none\n";
1306 break;
Michael Wright227c5542020-07-02 18:30:52 +01001307 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 dump += INDENT4 "touch.pressure.calibration: physical\n";
1309 break;
Michael Wright227c5542020-07-02 18:30:52 +01001310 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1312 break;
1313 default:
1314 ALOG_ASSERT(false);
1315 }
1316
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001317 if (mCalibration.pressureScale) {
1318 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 }
1320
1321 // Orientation
1322 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001323 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324 dump += INDENT4 "touch.orientation.calibration: none\n";
1325 break;
Michael Wright227c5542020-07-02 18:30:52 +01001326 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001327 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1328 break;
Michael Wright227c5542020-07-02 18:30:52 +01001329 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 dump += INDENT4 "touch.orientation.calibration: vector\n";
1331 break;
1332 default:
1333 ALOG_ASSERT(false);
1334 }
1335
1336 // Distance
1337 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001338 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001339 dump += INDENT4 "touch.distance.calibration: none\n";
1340 break;
Michael Wright227c5542020-07-02 18:30:52 +01001341 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001342 dump += INDENT4 "touch.distance.calibration: scaled\n";
1343 break;
1344 default:
1345 ALOG_ASSERT(false);
1346 }
1347
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001348 if (mCalibration.distanceScale) {
1349 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001351}
1352
1353void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1354 dump += INDENT3 "Affine Transformation:\n";
1355
1356 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1357 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1358 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1359 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1360 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1361 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1362}
1363
1364void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001365 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001366 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001367}
1368
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001369std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001370 std::list<NotifyArgs> out = cancelTouch(when, when);
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001371
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001372 mCursorButtonAccumulator.reset(getDeviceContext());
1373 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001374 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001375
1376 mPointerVelocityControl.reset();
1377 mWheelXVelocityControl.reset();
1378 mWheelYVelocityControl.reset();
1379
1380 mRawStatesPending.clear();
1381 mCurrentRawState.clear();
1382 mCurrentCookedState.clear();
1383 mLastRawState.clear();
1384 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001385 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001386 mSentHoverEnter = false;
1387 mHavePointerIds = false;
1388 mCurrentMotionAborted = false;
1389 mDownTime = 0;
1390
1391 mCurrentVirtualKey.down = false;
1392
1393 mPointerGesture.reset();
1394 mPointerSimple.reset();
1395 resetExternalStylus();
1396
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001397 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001398}
1399
1400void TouchInputMapper::resetExternalStylus() {
1401 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001402 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001403 mExternalStylusFusionTimeout = LLONG_MAX;
1404 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001405 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001406}
1407
1408void TouchInputMapper::clearStylusDataPendingFlags() {
1409 mExternalStylusDataPending = false;
1410 mExternalStylusFusionTimeout = LLONG_MAX;
1411}
1412
Harry Cuttsa32a1192024-06-04 15:10:31 +00001413std::list<NotifyArgs> TouchInputMapper::process(const RawEvent& rawEvent) {
1414 mCursorButtonAccumulator.process(rawEvent);
1415 mCursorScrollAccumulator.process(rawEvent);
1416 mTouchButtonAccumulator.process(rawEvent);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001417
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001418 std::list<NotifyArgs> out;
Harry Cuttsa32a1192024-06-04 15:10:31 +00001419 if (rawEvent.type == EV_SYN && rawEvent.code == SYN_REPORT) {
1420 out += sync(rawEvent.when, rawEvent.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001421 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001422 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001423}
1424
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001425std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1426 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001427 if (mDeviceMode == DeviceMode::DISABLED) {
1428 // Only save the last pending state when the device is disabled.
1429 mRawStatesPending.clear();
1430 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431 // Push a new state.
1432 mRawStatesPending.emplace_back();
1433
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001434 RawState& next = mRawStatesPending.back();
1435 next.clear();
1436 next.when = when;
1437 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001438
1439 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001440 next.buttonState = filterButtonState(mConfig,
1441 mTouchButtonAccumulator.getButtonState() |
1442 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001443
1444 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001445 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1446 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001447 mCursorScrollAccumulator.finishSync();
1448
1449 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001450 syncTouch(when, &next);
1451
1452 // The last RawState is the actually second to last, since we just added a new state
1453 const RawState& last =
1454 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001456 std::tie(next.when, next.readTime) =
1457 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1458 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001459
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001460 // Assign pointer ids.
1461 if (!mHavePointerIds) {
1462 assignPointerIds(last, next);
1463 }
1464
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001465 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001466 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1467 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1468 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1469 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1470 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1471 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001472
Arthur Hung9ad18942021-06-19 02:04:46 +00001473 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1474 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1475 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1476 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1477 next.rawPointerData.hoveringIdBits.value);
1478 }
1479
Harry Cutts33476232023-01-30 19:57:29 +00001480 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001481 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001482}
1483
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001484std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1485 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001486 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001487 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001488 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001489 }
1490
1491 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1492 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1493 // touching the current state will only observe the events that have been dispatched to the
1494 // rest of the pipeline.
1495 const size_t N = mRawStatesPending.size();
1496 size_t count;
1497 for (count = 0; count < N; count++) {
1498 const RawState& next = mRawStatesPending[count];
1499
1500 // A failure to assign the stylus id means that we're waiting on stylus data
1501 // and so should defer the rest of the pipeline.
1502 if (assignExternalStylusId(next, timeout)) {
1503 break;
1504 }
1505
1506 // All ready to go.
1507 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001508 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001509 if (mCurrentRawState.when < mLastRawState.when) {
1510 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001511 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001512 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001513 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001514 }
1515 if (count != 0) {
1516 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1517 }
1518
1519 if (mExternalStylusDataPending) {
1520 if (timeout) {
1521 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1522 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001523 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001524 ALOGD_IF(DEBUG_STYLUS_FUSION,
1525 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001526 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001527 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001528 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1529 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1530 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1531 }
1532 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001533 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001534}
1535
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001536std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1537 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001538 // Always start with a clean state.
1539 mCurrentCookedState.clear();
1540
1541 // Apply stylus buttons to current raw state.
1542 applyExternalStylusButtonState(when);
1543
1544 // Handle policy on initial down or hover events.
1545 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1546 mCurrentRawState.rawPointerData.pointerCount != 0;
1547
1548 uint32_t policyFlags = 0;
1549 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1550 if (initialDown || buttonsPressed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001551 if (mParameters.wake) {
1552 policyFlags |= POLICY_FLAG_WAKE;
1553 }
1554 }
1555
1556 // Consume raw off-screen touches before cooking pointer data.
1557 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001558 bool consumed;
1559 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1560 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001561 mCurrentRawState.rawPointerData.clear();
1562 }
1563
1564 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1565 // with cooked pointer data that has the same ids and indices as the raw data.
1566 // The following code can use either the raw or cooked data, as needed.
1567 cookPointerData();
1568
1569 // Apply stylus pressure to current cooked state.
1570 applyExternalStylusTouchState(when);
1571
1572 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001573 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1574 mSource, mViewport.displayId, policyFlags,
1575 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001576
1577 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001578 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001579 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1580 uint32_t id = idBits.clearFirstMarkedBit();
1581 const RawPointerData::Pointer& pointer =
1582 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001583 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001584 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001585 } else if (pointer.toolType == ToolType::FINGER ||
1586 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001587 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001588 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001589 mCurrentCookedState.mouseIdBits.markBit(id);
1590 }
1591 }
1592 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1593 uint32_t id = idBits.clearFirstMarkedBit();
1594 const RawPointerData::Pointer& pointer =
1595 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001596 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001597 mCurrentCookedState.stylusIdBits.markBit(id);
1598 }
1599 }
1600
1601 // Stylus takes precedence over all tools, then mouse, then finger.
1602 PointerUsage pointerUsage = mPointerUsage;
1603 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1604 mCurrentCookedState.mouseIdBits.clear();
1605 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001606 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001607 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1608 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001609 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001610 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1611 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001612 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001613 }
1614
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001615 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001616 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617 if (!mCurrentMotionAborted) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001618 out += dispatchButtonRelease(when, readTime, policyFlags);
1619 out += dispatchHoverExit(when, readTime, policyFlags);
1620 out += dispatchTouches(when, readTime, policyFlags);
1621 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1622 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001623 }
1624
1625 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1626 mCurrentMotionAborted = false;
1627 }
1628 }
1629
1630 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001631 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1632 mSource, mViewport.displayId, policyFlags,
1633 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001634
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001635 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1636 mCurrentStreamModifiedByExternalStylus = false;
1637 }
1638
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001639 // Clear some transient state.
1640 mCurrentRawState.rawVScroll = 0;
1641 mCurrentRawState.rawHScroll = 0;
1642
1643 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001644 mLastRawState = mCurrentRawState;
1645 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001646 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001647}
1648
Garfield Tanc734e4f2021-01-15 20:01:39 -08001649bool TouchInputMapper::isTouchScreen() {
1650 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1651 mParameters.hasAssociatedDisplay;
1652}
1653
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001654void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001655 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1656 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001657 const int32_t pressedButtons =
1658 filterButtonState(mConfig,
1659 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001660 const int32_t releasedButtons =
1661 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1662
1663 mCurrentRawState.buttonState |= pressedButtons;
1664 mCurrentRawState.buttonState &= ~releasedButtons;
1665
1666 mExternalStylusButtonsApplied |= pressedButtons;
1667 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001668
1669 if (mExternalStylusButtonsApplied != 0 || releasedButtons != 0) {
1670 mCurrentStreamModifiedByExternalStylus = true;
1671 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001672 }
1673}
1674
1675void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1676 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1677 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001678 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1679 return;
1680 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001681
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001682 mCurrentStreamModifiedByExternalStylus = true;
1683
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001684 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1685 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1686 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1687 : 0.f;
1688 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1689 pressure = *mExternalStylusState.pressure;
1690 }
1691 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1692 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001693
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001694 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001695 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001696 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001697 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001698 }
1699}
1700
1701bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001702 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001703 return false;
1704 }
1705
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001706 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001707 if (mFusedStylusPointerId &&
1708 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001709 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001710 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001711 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001712 }
1713
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001714 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1715 state.rawPointerData.pointerCount != 0;
1716 if (!initialDown) {
1717 return false;
1718 }
1719
1720 if (!mExternalStylusState.pressure) {
1721 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1722 return false;
1723 }
1724
1725 if (*mExternalStylusState.pressure != 0.0f) {
1726 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1727 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1728 return false;
1729 }
1730
1731 if (timeout) {
1732 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1733 mFusedStylusPointerId.reset();
1734 mExternalStylusFusionTimeout = LLONG_MAX;
1735 return false;
1736 }
1737
1738 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1739 // being processed until we either get pressure data or timeout.
1740 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1741 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1742 }
1743 ALOGD_IF(DEBUG_STYLUS_FUSION,
1744 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1745 mExternalStylusFusionTimeout);
1746 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1747 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001748}
1749
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001750std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1751 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001752 if (mDeviceMode == DeviceMode::POINTER) {
1753 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001754 // Since this is a synthetic event, we can consider its latency to be zero
1755 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001756 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001757 }
Michael Wright227c5542020-07-02 18:30:52 +01001758 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001759 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001760 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001761 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1762 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1763 }
1764 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001765 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001766}
1767
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001768std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1769 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001770 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001771 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001772 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001773 // The following three cases are handled here:
1774 // - We're in the middle of a fused stream of data;
1775 // - We're waiting on external stylus data before dispatching the initial down; or
1776 // - Only the button state, which is not reported through a specific pointer, has changed.
1777 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001778 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001779 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001781 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001782}
1783
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001784std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1785 uint32_t policyFlags, bool& outConsumed) {
1786 outConsumed = false;
1787 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001788 // Check for release of a virtual key.
1789 if (mCurrentVirtualKey.down) {
1790 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1791 // Pointer went up while virtual key was down.
1792 mCurrentVirtualKey.down = false;
1793 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001794 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1795 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1796 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001797 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1798 AKEY_EVENT_FLAG_FROM_SYSTEM |
1799 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001800 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001801 outConsumed = true;
1802 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001803 }
1804
1805 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1806 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1807 const RawPointerData::Pointer& pointer =
1808 mCurrentRawState.rawPointerData.pointerForId(id);
1809 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1810 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1811 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001812 outConsumed = true;
1813 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001814 }
1815 }
1816
1817 // Pointer left virtual key area or another pointer also went down.
1818 // Send key cancellation but do not consume the touch yet.
1819 // This is useful when the user swipes through from the virtual key area
1820 // into the main display surface.
1821 mCurrentVirtualKey.down = false;
1822 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001823 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1824 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001825 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1826 AKEY_EVENT_FLAG_FROM_SYSTEM |
1827 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1828 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001829 }
1830 }
1831
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001832 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
Harry Cutts8722be92024-04-05 14:46:05 +00001833 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001834 // We have hovering pointers, and there are no touching pointers.
1835 bool hoveringPointersInFrame = false;
1836 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1837 while (!hoveringIds.isEmpty()) {
1838 uint32_t id = hoveringIds.clearFirstMarkedBit();
1839 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1840 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1841 hoveringPointersInFrame = true;
1842 break;
1843 }
1844 }
1845 if (!hoveringPointersInFrame) {
1846 // All hovering pointers are outside the physical frame.
1847 outConsumed = true;
1848 return out;
1849 }
1850 }
1851
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001852 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1853 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1854 // Pointer just went down. Check for virtual key press or off-screen touches.
1855 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1856 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001857 // Skip checking whether the pointer is inside the physical frame if the device is in
Harry Cutts1db43992023-06-19 17:05:07 +00001858 // unscaled or pointer mode.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001859 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
Harry Cutts8722be92024-04-05 14:46:05 +00001860 mDeviceMode != DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001861 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001862 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001863 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1864 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1865 if (virtualKey) {
1866 mCurrentVirtualKey.down = true;
1867 mCurrentVirtualKey.downTime = when;
1868 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1869 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1870 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001871 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1872 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001873
1874 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001875 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1876 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1877 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001878 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1879 AKEY_EVENT_ACTION_DOWN,
1880 AKEY_EVENT_FLAG_FROM_SYSTEM |
1881 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001882 }
1883 }
1884 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001885 outConsumed = true;
1886 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001887 }
1888 }
1889
1890 // Disable all virtual key touches that happen within a short time interval of the
1891 // most recent touch within the screen area. The idea is to filter out stray
1892 // virtual key presses when interacting with the touch screen.
1893 //
1894 // Problems we're trying to solve:
1895 //
1896 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1897 // virtual key area that is implemented by a separate touch panel and accidentally
1898 // triggers a virtual key.
1899 //
1900 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1901 // area and accidentally triggers a virtual key. This often happens when virtual keys
1902 // are layed out below the screen near to where the on screen keyboard's space bar
1903 // is displayed.
1904 if (mConfig.virtualKeyQuietTime > 0 &&
1905 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001906 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001907 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001908 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001909}
1910
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001911NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1912 uint32_t policyFlags, int32_t keyEventAction,
1913 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001914 int32_t keyCode = mCurrentVirtualKey.keyCode;
1915 int32_t scanCode = mCurrentVirtualKey.scanCode;
1916 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001917 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001918 policyFlags |= POLICY_FLAG_VIRTUAL;
1919
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001920 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1921 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1922 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001923}
1924
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001925std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1926 uint32_t policyFlags) {
1927 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001928 if (mCurrentMotionAborted) {
1929 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001930 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001931 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001932 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1933 if (!currentIdBits.isEmpty()) {
1934 int32_t metaState = getContext()->getGlobalMetaState();
1935 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001936 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001937 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1938 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001939 mCurrentCookedState.cookedPointerData.pointerProperties,
1940 mCurrentCookedState.cookedPointerData.pointerCoords,
1941 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1942 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1943 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001944 mCurrentMotionAborted = true;
1945 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001946 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001947}
1948
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001949// Updates pointer coords and properties for pointers with specified ids that have moved.
1950// Returns true if any of them changed.
1951static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1952 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1953 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1954 BitSet32 idBits) {
1955 bool changed = false;
1956 while (!idBits.isEmpty()) {
1957 uint32_t id = idBits.clearFirstMarkedBit();
1958 uint32_t inIndex = inIdToIndex[id];
1959 uint32_t outIndex = outIdToIndex[id];
1960
1961 const PointerProperties& curInProperties = inProperties[inIndex];
1962 const PointerCoords& curInCoords = inCoords[inIndex];
1963 PointerProperties& curOutProperties = outProperties[outIndex];
1964 PointerCoords& curOutCoords = outCoords[outIndex];
1965
1966 if (curInProperties != curOutProperties) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001967 curOutProperties = curInProperties;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001968 changed = true;
1969 }
1970
1971 if (curInCoords != curOutCoords) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001972 curOutCoords = curInCoords;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001973 changed = true;
1974 }
1975 }
1976 return changed;
1977}
1978
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001979std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1980 uint32_t policyFlags) {
1981 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001982 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1983 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1984 int32_t metaState = getContext()->getGlobalMetaState();
1985 int32_t buttonState = mCurrentCookedState.buttonState;
1986
1987 if (currentIdBits == lastIdBits) {
1988 if (!currentIdBits.isEmpty()) {
1989 // No pointer id changes so this is a move event.
1990 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001991 out.push_back(
1992 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1993 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1994 mCurrentCookedState.cookedPointerData.pointerProperties,
1995 mCurrentCookedState.cookedPointerData.pointerCoords,
1996 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1997 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1998 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001999 }
2000 } else {
2001 // There may be pointers going up and pointers going down and pointers moving
2002 // all at the same time.
2003 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2004 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2005 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2006 BitSet32 dispatchedIdBits(lastIdBits.value);
2007
2008 // Update last coordinates of pointers that have moved so that we observe the new
2009 // pointer positions at the same time as other pointers that have just gone up.
2010 bool moveNeeded =
2011 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2012 mCurrentCookedState.cookedPointerData.pointerCoords,
2013 mCurrentCookedState.cookedPointerData.idToIndex,
2014 mLastCookedState.cookedPointerData.pointerProperties,
2015 mLastCookedState.cookedPointerData.pointerCoords,
2016 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2017 if (buttonState != mLastCookedState.buttonState) {
2018 moveNeeded = true;
2019 }
2020
2021 // Dispatch pointer up events.
2022 while (!upIdBits.isEmpty()) {
2023 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002024 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002025 if (isCanceled) {
2026 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2027 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002028 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2029 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2030 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2031 buttonState, 0,
2032 mLastCookedState.cookedPointerData.pointerProperties,
2033 mLastCookedState.cookedPointerData.pointerCoords,
2034 mLastCookedState.cookedPointerData.idToIndex,
2035 dispatchedIdBits, upId, mOrientedXPrecision,
2036 mOrientedYPrecision, mDownTime,
2037 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002038 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002039 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002040 }
2041
2042 // Dispatch move events if any of the remaining pointers moved from their old locations.
2043 // Although applications receive new locations as part of individual pointer up
2044 // events, they do not generally handle them except when presented in a move event.
2045 if (moveNeeded && !moveIdBits.isEmpty()) {
2046 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002047 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2048 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2049 mCurrentCookedState.cookedPointerData.pointerProperties,
2050 mCurrentCookedState.cookedPointerData.pointerCoords,
2051 mCurrentCookedState.cookedPointerData.idToIndex,
2052 dispatchedIdBits, -1, mOrientedXPrecision,
2053 mOrientedYPrecision, mDownTime,
2054 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002055 }
2056
2057 // Dispatch pointer down events using the new pointer locations.
2058 while (!downIdBits.isEmpty()) {
2059 uint32_t downId = downIdBits.clearFirstMarkedBit();
2060 dispatchedIdBits.markBit(downId);
2061
2062 if (dispatchedIdBits.count() == 1) {
2063 // First pointer is going down. Set down time.
2064 mDownTime = when;
2065 }
2066
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002067 out.push_back(
2068 dispatchMotion(when, readTime, policyFlags, mSource,
2069 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2070 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2071 mCurrentCookedState.cookedPointerData.pointerCoords,
2072 mCurrentCookedState.cookedPointerData.idToIndex,
2073 dispatchedIdBits, downId, mOrientedXPrecision,
2074 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002075 }
2076 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002077 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002078}
2079
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002080std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2081 uint32_t policyFlags) {
2082 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002083 if (mSentHoverEnter &&
2084 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2085 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2086 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002087 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2088 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2089 mLastCookedState.buttonState, 0,
2090 mLastCookedState.cookedPointerData.pointerProperties,
2091 mLastCookedState.cookedPointerData.pointerCoords,
2092 mLastCookedState.cookedPointerData.idToIndex,
2093 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2094 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2095 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002096 mSentHoverEnter = false;
2097 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002098 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002099}
2100
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002101std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2102 uint32_t policyFlags) {
2103 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002104 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2105 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2106 int32_t metaState = getContext()->getGlobalMetaState();
2107 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002108 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2109 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2110 mCurrentRawState.buttonState, 0,
2111 mCurrentCookedState.cookedPointerData.pointerProperties,
2112 mCurrentCookedState.cookedPointerData.pointerCoords,
2113 mCurrentCookedState.cookedPointerData.idToIndex,
2114 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2115 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2116 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002117 mSentHoverEnter = true;
2118 }
2119
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002120 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2121 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2122 mCurrentRawState.buttonState, 0,
2123 mCurrentCookedState.cookedPointerData.pointerProperties,
2124 mCurrentCookedState.cookedPointerData.pointerCoords,
2125 mCurrentCookedState.cookedPointerData.idToIndex,
2126 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2127 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2128 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002129 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002130 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002131}
2132
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002133std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2134 uint32_t policyFlags) {
2135 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002136 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2137 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2138 const int32_t metaState = getContext()->getGlobalMetaState();
2139 int32_t buttonState = mLastCookedState.buttonState;
2140 while (!releasedButtons.isEmpty()) {
2141 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2142 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002143 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2144 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2145 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002146 mLastCookedState.cookedPointerData.pointerProperties,
2147 mLastCookedState.cookedPointerData.pointerCoords,
2148 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002149 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2150 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002151 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002152 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002153}
2154
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002155std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2156 uint32_t policyFlags) {
2157 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002158 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2159 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2160 const int32_t metaState = getContext()->getGlobalMetaState();
2161 int32_t buttonState = mLastCookedState.buttonState;
2162 while (!pressedButtons.isEmpty()) {
2163 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2164 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002165 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2166 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2167 buttonState, 0,
2168 mCurrentCookedState.cookedPointerData.pointerProperties,
2169 mCurrentCookedState.cookedPointerData.pointerCoords,
2170 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2171 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2172 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002173 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002174 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002175}
2176
LiZhihong758eb562022-11-03 15:28:29 +08002177std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2178 uint32_t policyFlags,
2179 BitSet32 idBits,
2180 nsecs_t readTime) {
2181 std::list<NotifyArgs> out;
2182 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2183 const int32_t metaState = getContext()->getGlobalMetaState();
2184 int32_t buttonState = mLastCookedState.buttonState;
2185
2186 while (!releasedButtons.isEmpty()) {
2187 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2188 buttonState &= ~actionButton;
2189 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2190 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2191 metaState, buttonState, 0,
2192 mPointerGesture.lastGestureProperties,
2193 mPointerGesture.lastGestureCoords,
2194 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2195 mOrientedXPrecision, mOrientedYPrecision,
2196 mPointerGesture.downTime, MotionClassification::NONE));
2197 }
2198 return out;
2199}
2200
2201std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2202 uint32_t policyFlags,
2203 BitSet32 idBits,
2204 nsecs_t readTime) {
2205 std::list<NotifyArgs> out;
2206 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2207 const int32_t metaState = getContext()->getGlobalMetaState();
2208 int32_t buttonState = mLastCookedState.buttonState;
2209
2210 while (!pressedButtons.isEmpty()) {
2211 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2212 buttonState |= actionButton;
2213 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2214 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2215 buttonState, 0, mPointerGesture.currentGestureProperties,
2216 mPointerGesture.currentGestureCoords,
2217 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2218 mOrientedXPrecision, mOrientedYPrecision,
2219 mPointerGesture.downTime, MotionClassification::NONE));
2220 }
2221 return out;
2222}
2223
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002224const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2225 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2226 return cookedPointerData.touchingIdBits;
2227 }
2228 return cookedPointerData.hoveringIdBits;
2229}
2230
2231void TouchInputMapper::cookPointerData() {
2232 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2233
2234 mCurrentCookedState.cookedPointerData.clear();
2235 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2236 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2237 mCurrentRawState.rawPointerData.hoveringIdBits;
2238 mCurrentCookedState.cookedPointerData.touchingIdBits =
2239 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002240 mCurrentCookedState.cookedPointerData.canceledIdBits =
2241 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002242
2243 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2244 mCurrentCookedState.buttonState = 0;
2245 } else {
2246 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2247 }
2248
2249 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002250 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002251 for (uint32_t i = 0; i < currentPointerCount; i++) {
2252 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2253
2254 // Size
2255 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2256 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002257 case Calibration::SizeCalibration::GEOMETRIC:
2258 case Calibration::SizeCalibration::DIAMETER:
2259 case Calibration::SizeCalibration::BOX:
2260 case Calibration::SizeCalibration::AREA:
Prabir Pradhan132f21c2024-07-25 16:48:30 +00002261 if (mRawPointerAxes.touchMajor && mRawPointerAxes.toolMajor) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002262 touchMajor = in.touchMajor;
Prabir Pradhan132f21c2024-07-25 16:48:30 +00002263 touchMinor = mRawPointerAxes.touchMinor ? in.touchMinor : in.touchMajor;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002264 toolMajor = in.toolMajor;
Prabir Pradhan132f21c2024-07-25 16:48:30 +00002265 toolMinor = mRawPointerAxes.toolMinor ? in.toolMinor : in.toolMajor;
2266 size = mRawPointerAxes.touchMinor ? avg(in.touchMajor, in.touchMinor)
2267 : in.touchMajor;
2268 } else if (mRawPointerAxes.touchMajor) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002269 toolMajor = touchMajor = in.touchMajor;
2270 toolMinor = touchMinor =
Prabir Pradhan132f21c2024-07-25 16:48:30 +00002271 mRawPointerAxes.touchMinor ? in.touchMinor : in.touchMajor;
2272 size = mRawPointerAxes.touchMinor ? avg(in.touchMajor, in.touchMinor)
2273 : in.touchMajor;
2274 } else if (mRawPointerAxes.toolMajor) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002275 touchMajor = toolMajor = in.toolMajor;
2276 touchMinor = toolMinor =
Prabir Pradhan132f21c2024-07-25 16:48:30 +00002277 mRawPointerAxes.toolMinor ? in.toolMinor : in.toolMajor;
2278 size = mRawPointerAxes.toolMinor ? avg(in.toolMajor, in.toolMinor)
2279 : in.toolMajor;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002280 } else {
2281 ALOG_ASSERT(false,
2282 "No touch or tool axes. "
2283 "Size calibration should have been resolved to NONE.");
2284 touchMajor = 0;
2285 touchMinor = 0;
2286 toolMajor = 0;
2287 toolMinor = 0;
2288 size = 0;
2289 }
2290
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002291 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002292 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2293 if (touchingCount > 1) {
2294 touchMajor /= touchingCount;
2295 touchMinor /= touchingCount;
2296 toolMajor /= touchingCount;
2297 toolMinor /= touchingCount;
2298 size /= touchingCount;
2299 }
2300 }
2301
Michael Wright227c5542020-07-02 18:30:52 +01002302 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002303 touchMajor *= mGeometricScale;
2304 touchMinor *= mGeometricScale;
2305 toolMajor *= mGeometricScale;
2306 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002307 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002308 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2309 touchMinor = touchMajor;
2310 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2311 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002312 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002313 touchMinor = touchMajor;
2314 toolMinor = toolMajor;
2315 }
2316
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002317 mCalibration.applySizeScaleAndBias(touchMajor);
2318 mCalibration.applySizeScaleAndBias(touchMinor);
2319 mCalibration.applySizeScaleAndBias(toolMajor);
2320 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002321 size *= mSizeScale;
2322 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002323 case Calibration::SizeCalibration::DEFAULT:
2324 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2325 break;
2326 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002327 touchMajor = 0;
2328 touchMinor = 0;
2329 toolMajor = 0;
2330 toolMinor = 0;
2331 size = 0;
2332 break;
2333 }
2334
2335 // Pressure
2336 float pressure;
2337 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002338 case Calibration::PressureCalibration::PHYSICAL:
2339 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002340 pressure = in.pressure * mPressureScale;
2341 break;
2342 default:
2343 pressure = in.isHovering ? 0 : 1;
2344 break;
2345 }
2346
2347 // Tilt and Orientation
2348 float tilt;
2349 float orientation;
2350 if (mHaveTilt) {
2351 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2352 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhan9a53b552024-06-04 02:59:40 +00002353 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)),
2354 /*isDirectional=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2356 } else {
2357 tilt = 0;
2358
2359 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002360 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhan9a53b552024-06-04 02:59:40 +00002361 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale,
2362 /*isDirectional=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002363 break;
Michael Wright227c5542020-07-02 18:30:52 +01002364 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002365 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2366 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2367 if (c1 != 0 || c2 != 0) {
Prabir Pradhan9a53b552024-06-04 02:59:40 +00002368 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f,
2369 /*isDirectional=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002370 float confidence = hypotf(c1, c2);
2371 float scale = 1.0f + confidence / 16.0f;
2372 touchMajor *= scale;
2373 touchMinor /= scale;
2374 toolMajor *= scale;
2375 toolMinor /= scale;
2376 } else {
2377 orientation = 0;
2378 }
2379 break;
2380 }
2381 default:
2382 orientation = 0;
2383 }
2384 }
2385
2386 // Distance
2387 float distance;
2388 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002389 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390 distance = in.distance * mDistanceScale;
2391 break;
2392 default:
2393 distance = 0;
2394 }
2395
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002396 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2397 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002398 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2399 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002400
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002401 // Write output coords.
2402 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2403 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002404 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2405 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2407 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2408 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2409 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2410 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2411 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2412 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002413 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2414 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415
Chris Ye364fdb52020-08-05 15:07:56 -07002416 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002417 uint32_t id = in.id;
2418 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2419 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2420 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002421 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2422 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002423 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2424 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2425 }
2426
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 // Write output properties.
2428 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002429 properties.clear();
2430 properties.id = id;
2431 properties.toolType = in.toolType;
2432
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002433 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002435 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 }
2437}
2438
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002439std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2440 uint32_t policyFlags,
2441 PointerUsage pointerUsage) {
2442 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002443 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002444 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 mPointerUsage = pointerUsage;
2446 }
2447
2448 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002449 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002450 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002451 break;
Michael Wright227c5542020-07-02 18:30:52 +01002452 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002453 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002454 break;
Michael Wright227c5542020-07-02 18:30:52 +01002455 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002456 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002457 break;
Michael Wright227c5542020-07-02 18:30:52 +01002458 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002459 break;
2460 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002461 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002462}
2463
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002464std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2465 uint32_t policyFlags) {
2466 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002468 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002469 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470 break;
Michael Wright227c5542020-07-02 18:30:52 +01002471 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002472 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002473 break;
Michael Wright227c5542020-07-02 18:30:52 +01002474 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002475 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002476 break;
Michael Wright227c5542020-07-02 18:30:52 +01002477 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 break;
2479 }
2480
Michael Wright227c5542020-07-02 18:30:52 +01002481 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002482 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002483}
2484
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002485std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2486 uint32_t policyFlags,
2487 bool isTimeout) {
2488 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002489 // Update current gesture coordinates.
2490 bool cancelPreviousGesture, finishPreviousGesture;
2491 bool sendEvents =
2492 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2493 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002494 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002495 }
2496 if (finishPreviousGesture) {
2497 cancelPreviousGesture = false;
2498 }
2499
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002500 // Send events!
2501 int32_t metaState = getContext()->getGlobalMetaState();
2502 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002503 const MotionClassification classification =
2504 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2505 ? MotionClassification::TWO_FINGER_SWIPE
2506 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002507
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002508 uint32_t flags = 0;
2509
2510 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2511 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2512 }
2513
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514 // Update last coordinates of pointers that have moved so that we observe the new
2515 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002516 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2517 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2518 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2519 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2520 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2521 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 bool moveNeeded = false;
2523 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2524 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2525 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2526 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2527 mPointerGesture.lastGestureIdBits.value);
2528 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2529 mPointerGesture.currentGestureCoords,
2530 mPointerGesture.currentGestureIdToIndex,
2531 mPointerGesture.lastGestureProperties,
2532 mPointerGesture.lastGestureCoords,
2533 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2534 if (buttonState != mLastCookedState.buttonState) {
2535 moveNeeded = true;
2536 }
2537 }
2538
2539 // Send motion events for all pointers that went up or were canceled.
2540 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2541 if (!dispatchedGestureIdBits.isEmpty()) {
2542 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002543 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002544 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002545 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002546 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2547 mPointerGesture.lastGestureProperties,
2548 mPointerGesture.lastGestureCoords,
2549 mPointerGesture.lastGestureIdToIndex,
2550 dispatchedGestureIdBits, -1, 0, 0,
2551 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002552
2553 dispatchedGestureIdBits.clear();
2554 } else {
2555 BitSet32 upGestureIdBits;
2556 if (finishPreviousGesture) {
2557 upGestureIdBits = dispatchedGestureIdBits;
2558 } else {
2559 upGestureIdBits.value =
2560 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2561 }
2562 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002563 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2564 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2565 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2566 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2567 readTime);
2568 }
2569 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002570 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2571 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2572 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2573 mPointerGesture.lastGestureProperties,
2574 mPointerGesture.lastGestureCoords,
2575 mPointerGesture.lastGestureIdToIndex,
2576 dispatchedGestureIdBits, id, 0, 0,
2577 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002578
2579 dispatchedGestureIdBits.clearBit(id);
2580 }
2581 }
2582 }
2583
2584 // Send motion events for all pointers that moved.
2585 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002586 out.push_back(
2587 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2588 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2589 mPointerGesture.currentGestureProperties,
2590 mPointerGesture.currentGestureCoords,
2591 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2592 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002593 }
2594
2595 // Send motion events for all pointers that went down.
2596 if (down) {
2597 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2598 ~dispatchedGestureIdBits.value);
2599 while (!downGestureIdBits.isEmpty()) {
2600 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2601 dispatchedGestureIdBits.markBit(id);
2602
2603 if (dispatchedGestureIdBits.count() == 1) {
2604 mPointerGesture.downTime = when;
2605 }
2606
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002607 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2608 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2609 buttonState, 0, mPointerGesture.currentGestureProperties,
2610 mPointerGesture.currentGestureCoords,
2611 mPointerGesture.currentGestureIdToIndex,
2612 dispatchedGestureIdBits, id, 0, 0,
2613 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002614 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2615 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2616 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2617 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2618 readTime);
2619 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002620 }
2621 }
2622
2623 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002624 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002625 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2626 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2627 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2628 mPointerGesture.currentGestureProperties,
2629 mPointerGesture.currentGestureCoords,
2630 mPointerGesture.currentGestureIdToIndex,
2631 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2632 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002633 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2634 // Synthesize a hover move event after all pointers go up to indicate that
2635 // the pointer is hovering again even if the user is not currently touching
2636 // the touch pad. This ensures that a view will receive a fresh hover enter
2637 // event after a tap.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002638
2639 PointerProperties pointerProperties;
2640 pointerProperties.clear();
2641 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002642 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002643
2644 PointerCoords pointerCoords;
2645 pointerCoords.clear();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002646 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002647 mSource, ui::LogicalDisplayId::INVALID, policyFlags,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002648 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2649 buttonState, MotionClassification::NONE,
2650 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002651 &pointerCoords, 0, 0, 0.f, 0.f, mPointerGesture.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00002652 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002653 }
2654
2655 // Update state.
2656 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2657 if (!down) {
2658 mPointerGesture.lastGestureIdBits.clear();
2659 } else {
2660 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2661 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2662 uint32_t id = idBits.clearFirstMarkedBit();
2663 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002664 mPointerGesture.lastGestureProperties[index] =
2665 mPointerGesture.currentGestureProperties[index];
2666 mPointerGesture.lastGestureCoords[index] = mPointerGesture.currentGestureCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002667 mPointerGesture.lastGestureIdToIndex[id] = index;
2668 }
2669 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002670 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002671}
2672
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002673std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2674 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002675 const MotionClassification classification =
2676 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2677 ? MotionClassification::TWO_FINGER_SWIPE
2678 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002679 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002680 // Cancel previously dispatches pointers.
2681 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2682 int32_t metaState = getContext()->getGlobalMetaState();
2683 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002684 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002685 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2686 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002687 mPointerGesture.lastGestureProperties,
2688 mPointerGesture.lastGestureCoords,
2689 mPointerGesture.lastGestureIdToIndex,
2690 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2691 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002692 }
2693
2694 // Reset the current pointer gesture.
2695 mPointerGesture.reset();
2696 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002697 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002698}
2699
2700bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2701 bool* outFinishPreviousGesture, bool isTimeout) {
2702 *outCancelPreviousGesture = false;
2703 *outFinishPreviousGesture = false;
2704
2705 // Handle TAP timeout.
2706 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002707 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002708
Michael Wright227c5542020-07-02 18:30:52 +01002709 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002710 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2711 // The tap/drag timeout has not yet expired.
2712 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2713 mConfig.pointerGestureTapDragInterval);
2714 } else {
2715 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002716 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002717 *outFinishPreviousGesture = true;
2718
2719 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002720 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002721 mPointerGesture.currentGestureIdBits.clear();
2722
2723 mPointerVelocityControl.reset();
2724 return true;
2725 }
2726 }
2727
2728 // We did not handle this timeout.
2729 return false;
2730 }
2731
2732 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2733 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2734
2735 // Update the velocity tracker.
2736 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002737 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002738 uint32_t id = idBits.clearFirstMarkedBit();
2739 const RawPointerData::Pointer& pointer =
2740 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002741 const float x = pointer.x * mPointerXMovementScale;
2742 const float y = pointer.y * mPointerYMovementScale;
2743 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2744 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002745 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002746 }
2747
2748 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2749 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002750 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2751 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2752 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002753 mPointerGesture.resetTap();
2754 }
2755
2756 // Pick a new active touch id if needed.
2757 // Choose an arbitrary pointer that just went down, if there is one.
2758 // Otherwise choose an arbitrary remaining pointer.
2759 // This guarantees we always have an active touch id when there is at least one pointer.
2760 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002761 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002762 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002763 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002764 mPointerGesture.firstTouchTime = when;
2765 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002766 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2767 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2768 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2769 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002770 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002771 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002772
2773 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002774 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002775 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002776 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2777 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2778 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002779 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002780 *outFinishPreviousGesture = true;
2781 }
2782
2783 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002784 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002785 mPointerGesture.currentGestureIdBits.clear();
2786
2787 mPointerVelocityControl.reset();
2788 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2789 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2790 // The pointer follows the active touch point.
2791 // Emit DOWN, MOVE, UP events at the pointer location.
2792 //
2793 // Only the active touch matters; other fingers are ignored. This policy helps
2794 // to handle the case where the user places a second finger on the touch pad
2795 // to apply the necessary force to depress an integrated button below the surface.
2796 // We don't want the second finger to be delivered to applications.
2797 //
2798 // For this to work well, we need to make sure to track the pointer that is really
2799 // active. If the user first puts one finger down to click then adds another
2800 // finger to drag then the active pointer should switch to the finger that is
2801 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002802 ALOGD_IF(DEBUG_GESTURES,
2803 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2804 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002805 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002806 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002807 *outFinishPreviousGesture = true;
2808 mPointerGesture.activeGestureId = 0;
2809 }
2810
2811 // Switch pointers if needed.
2812 // Find the fastest pointer and follow it.
2813 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002814 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002815 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002816 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002817 ALOGD_IF(DEBUG_GESTURES,
2818 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2819 "bestSpeed=%0.3f",
2820 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002821 }
2822 }
2823
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002824 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002825 // When using spots, the click will occur at the position of the anchor
2826 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002827 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002828 } else {
2829 mPointerVelocityControl.reset();
2830 }
2831
Michael Wright227c5542020-07-02 18:30:52 +01002832 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002833 mPointerGesture.currentGestureIdBits.clear();
2834 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2835 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2836 mPointerGesture.currentGestureProperties[0].clear();
2837 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002838 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002839 mPointerGesture.currentGestureCoords[0].clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002840 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2841 } else if (currentFingerCount == 0) {
2842 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002843 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002844 *outFinishPreviousGesture = true;
2845 }
2846
2847 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2848 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2849 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002850 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2851 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002852 lastFingerCount == 1) {
2853 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002854 if (fabs(0.f - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2855 fabs(0.f - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002856 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002857
2858 mPointerGesture.tapUpTime = when;
2859 getContext()->requestTimeoutAtTime(when +
2860 mConfig.pointerGestureTapDragInterval);
2861
2862 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002863 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002864 mPointerGesture.currentGestureIdBits.clear();
2865 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2866 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2867 mPointerGesture.currentGestureProperties[0].clear();
2868 mPointerGesture.currentGestureProperties[0].id =
2869 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002870 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002871 mPointerGesture.currentGestureCoords[0].clear();
2872 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2873 mPointerGesture.tapX);
2874 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2875 mPointerGesture.tapY);
2876 mPointerGesture.currentGestureCoords[0]
2877 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2878
2879 tapped = true;
2880 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002881 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002882 0.f - mPointerGesture.tapX, 0.f - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002883 }
2884 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002885 if (DEBUG_GESTURES) {
2886 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2887 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2888 (when - mPointerGesture.tapDownTime) * 0.000001f);
2889 } else {
2890 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2891 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002893 }
2894 }
2895
2896 mPointerVelocityControl.reset();
2897
2898 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002899 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002900 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002901 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002902 mPointerGesture.currentGestureIdBits.clear();
2903 }
2904 } else if (currentFingerCount == 1) {
2905 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2906 // The pointer follows the active touch point.
2907 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2908 // When in TAP_DRAG, emit MOVE events at the pointer location.
2909 ALOG_ASSERT(activeTouchId >= 0);
2910
Michael Wright227c5542020-07-02 18:30:52 +01002911 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2912 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002913 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002914 if (fabs(0.f - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2915 fabs(0.f - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002916 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002917 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002918 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002919 0.f - mPointerGesture.tapX, 0.f - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002920 }
2921 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002922 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2923 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002924 }
Michael Wright227c5542020-07-02 18:30:52 +01002925 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2926 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002927 }
2928
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002929 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002930 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002931 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002932 } else {
2933 mPointerVelocityControl.reset();
2934 }
2935
2936 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002937 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002938 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002939 down = true;
2940 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002941 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002942 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002943 *outFinishPreviousGesture = true;
2944 }
2945 mPointerGesture.activeGestureId = 0;
2946 down = false;
2947 }
2948
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002949 mPointerGesture.currentGestureIdBits.clear();
2950 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2951 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2952 mPointerGesture.currentGestureProperties[0].clear();
2953 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002954 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002955 mPointerGesture.currentGestureCoords[0].clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002956 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2957 down ? 1.0f : 0.0f);
2958
2959 if (lastFingerCount == 0 && currentFingerCount != 0) {
2960 mPointerGesture.resetTap();
2961 mPointerGesture.tapDownTime = when;
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002962 mPointerGesture.tapX = 0.f;
2963 mPointerGesture.tapY = 0.f;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002964 }
2965 } else {
2966 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002967 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002968 }
2969
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002970 if (DEBUG_GESTURES) {
2971 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00002972 "currentGestureMode=%s, currentGestureIdBits=0x%08x, "
2973 "lastGestureMode=%s, lastGestureIdBits=0x%08x",
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002974 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00002975 ftl::enum_string(mPointerGesture.currentGestureMode).c_str(),
2976 mPointerGesture.currentGestureIdBits.value,
2977 ftl::enum_string(mPointerGesture.lastGestureMode).c_str(),
2978 mPointerGesture.lastGestureIdBits.value);
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002979 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
2980 uint32_t id = idBits.clearFirstMarkedBit();
2981 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2982 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
2983 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002984 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002985 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002986 id, index, ftl::enum_string(properties.toolType).c_str(),
2987 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002988 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
2989 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
2990 }
2991 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
2992 uint32_t id = idBits.clearFirstMarkedBit();
2993 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
2994 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
2995 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002996 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002997 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002998 id, index, ftl::enum_string(properties.toolType).c_str(),
2999 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003000 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3001 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3002 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003004 return true;
3005}
3006
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003007bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3008 if (mPointerGesture.activeTouchId < 0) {
3009 mPointerGesture.resetQuietTime();
3010 return false;
3011 }
3012
3013 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3014 return true;
3015 }
3016
3017 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3018 bool isQuietTime = false;
3019 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3020 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3021 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3022 currentFingerCount < 2) {
3023 // Enter quiet time when exiting swipe or freeform state.
3024 // This is to prevent accidentally entering the hover state and flinging the
3025 // pointer when finishing a swipe and there is still one pointer left onscreen.
3026 isQuietTime = true;
3027 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3028 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3029 // Enter quiet time when releasing the button and there are still two or more
3030 // fingers down. This may indicate that one finger was used to press the button
3031 // but it has not gone up yet.
3032 isQuietTime = true;
3033 }
3034 if (isQuietTime) {
3035 mPointerGesture.quietTime = when;
3036 }
3037 return isQuietTime;
3038}
3039
3040std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3041 int32_t bestId = -1;
3042 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3043 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3044 uint32_t id = idBits.clearFirstMarkedBit();
3045 std::optional<float> vx =
3046 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3047 std::optional<float> vy =
3048 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3049 if (vx && vy) {
3050 float speed = hypotf(*vx, *vy);
3051 if (speed > bestSpeed) {
3052 bestId = id;
3053 bestSpeed = speed;
3054 }
3055 }
3056 }
3057 return std::make_pair(bestId, bestSpeed);
3058}
3059
3060void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3061 bool* finishPreviousGesture) {
3062 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3063 // to move before deciding what to do.
3064 //
3065 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3066 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3067 // just a press or long-press at the pointer location.
3068 //
3069 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3070 // pointer location.
3071 //
3072 // When the two fingers move enough or when additional fingers are added, we make a decision to
3073 // transition into SWIPE or FREEFORM mode accordingly.
3074 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3075 ALOG_ASSERT(activeTouchId >= 0);
3076
3077 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3078 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3079 bool settled =
3080 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3081 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3082 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3083 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3084 *finishPreviousGesture = true;
3085 } else if (!settled && currentFingerCount > lastFingerCount) {
3086 // Additional pointers have gone down but not yet settled.
3087 // Reset the gesture.
3088 ALOGD_IF(DEBUG_GESTURES,
3089 "Gestures: Resetting gesture since additional pointers went down for "
3090 "MULTITOUCH, settle time remaining %0.3fms",
3091 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3092 when) * 0.000001f);
3093 *cancelPreviousGesture = true;
3094 } else {
3095 // Continue previous gesture.
3096 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3097 }
3098
3099 if (*finishPreviousGesture || *cancelPreviousGesture) {
3100 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3101 mPointerGesture.activeGestureId = 0;
3102 mPointerGesture.referenceIdBits.clear();
3103 mPointerVelocityControl.reset();
3104
3105 // Use the centroid and pointer location as the reference points for the gesture.
3106 ALOGD_IF(DEBUG_GESTURES,
3107 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3108 "%0.3fms",
3109 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3110 when) * 0.000001f);
3111 mCurrentRawState.rawPointerData
3112 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3113 &mPointerGesture.referenceTouchY);
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00003114 mPointerGesture.referenceGestureX = 0.f;
3115 mPointerGesture.referenceGestureY = 0.f;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003116 }
3117
3118 // Clear the reference deltas for fingers not yet included in the reference calculation.
3119 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3120 ~mPointerGesture.referenceIdBits.value);
3121 !idBits.isEmpty();) {
3122 uint32_t id = idBits.clearFirstMarkedBit();
3123 mPointerGesture.referenceDeltas[id].dx = 0;
3124 mPointerGesture.referenceDeltas[id].dy = 0;
3125 }
3126 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3127
3128 // Add delta for all fingers and calculate a common movement delta.
3129 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3130 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3131 mCurrentCookedState.fingerIdBits.value);
3132 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3133 bool first = (idBits == commonIdBits);
3134 uint32_t id = idBits.clearFirstMarkedBit();
3135 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3136 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3137 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3138 delta.dx += cpd.x - lpd.x;
3139 delta.dy += cpd.y - lpd.y;
3140
3141 if (first) {
3142 commonDeltaRawX = delta.dx;
3143 commonDeltaRawY = delta.dy;
3144 } else {
3145 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3146 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3147 }
3148 }
3149
3150 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3151 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3152 float dist[MAX_POINTER_ID + 1];
3153 int32_t distOverThreshold = 0;
3154 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3155 uint32_t id = idBits.clearFirstMarkedBit();
3156 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3157 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3158 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3159 distOverThreshold += 1;
3160 }
3161 }
3162
3163 // Only transition when at least two pointers have moved further than
3164 // the minimum distance threshold.
3165 if (distOverThreshold >= 2) {
3166 if (currentFingerCount > 2) {
3167 // There are more than two pointers, switch to FREEFORM.
3168 ALOGD_IF(DEBUG_GESTURES,
3169 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3170 currentFingerCount);
3171 *cancelPreviousGesture = true;
3172 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3173 } else {
3174 // There are exactly two pointers.
3175 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3176 uint32_t id1 = idBits.clearFirstMarkedBit();
3177 uint32_t id2 = idBits.firstMarkedBit();
3178 const RawPointerData::Pointer& p1 =
3179 mCurrentRawState.rawPointerData.pointerForId(id1);
3180 const RawPointerData::Pointer& p2 =
3181 mCurrentRawState.rawPointerData.pointerForId(id2);
3182 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3183 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3184 // There are two pointers but they are too far apart for a SWIPE,
3185 // switch to FREEFORM.
3186 ALOGD_IF(DEBUG_GESTURES,
3187 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3188 mutualDistance, mPointerGestureMaxSwipeWidth);
3189 *cancelPreviousGesture = true;
3190 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3191 } else {
3192 // There are two pointers. Wait for both pointers to start moving
3193 // before deciding whether this is a SWIPE or FREEFORM gesture.
3194 float dist1 = dist[id1];
3195 float dist2 = dist[id2];
3196 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3197 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3198 // Calculate the dot product of the displacement vectors.
3199 // When the vectors are oriented in approximately the same direction,
3200 // the angle betweeen them is near zero and the cosine of the angle
3201 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3202 // mag(v2).
3203 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3204 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3205 float dx1 = delta1.dx * mPointerXZoomScale;
3206 float dy1 = delta1.dy * mPointerYZoomScale;
3207 float dx2 = delta2.dx * mPointerXZoomScale;
3208 float dy2 = delta2.dy * mPointerYZoomScale;
3209 float dot = dx1 * dx2 + dy1 * dy2;
3210 float cosine = dot / (dist1 * dist2); // denominator always > 0
3211 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3212 // Pointers are moving in the same direction. Switch to SWIPE.
3213 ALOGD_IF(DEBUG_GESTURES,
3214 "Gestures: PRESS transitioned to SWIPE, "
3215 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3216 "cosine %0.3f >= %0.3f",
3217 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3218 mConfig.pointerGestureMultitouchMinDistance, cosine,
3219 mConfig.pointerGestureSwipeTransitionAngleCosine);
3220 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3221 } else {
3222 // Pointers are moving in different directions. Switch to FREEFORM.
3223 ALOGD_IF(DEBUG_GESTURES,
3224 "Gestures: PRESS transitioned to FREEFORM, "
3225 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3226 "cosine %0.3f < %0.3f",
3227 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3228 mConfig.pointerGestureMultitouchMinDistance, cosine,
3229 mConfig.pointerGestureSwipeTransitionAngleCosine);
3230 *cancelPreviousGesture = true;
3231 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3232 }
3233 }
3234 }
3235 }
3236 }
3237 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3238 // Switch from SWIPE to FREEFORM if additional pointers go down.
3239 // Cancel previous gesture.
3240 if (currentFingerCount > 2) {
3241 ALOGD_IF(DEBUG_GESTURES,
3242 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3243 currentFingerCount);
3244 *cancelPreviousGesture = true;
3245 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3246 }
3247 }
3248
3249 // Move the reference points based on the overall group motion of the fingers
3250 // except in PRESS mode while waiting for a transition to occur.
3251 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3252 (commonDeltaRawX || commonDeltaRawY)) {
3253 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3254 uint32_t id = idBits.clearFirstMarkedBit();
3255 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3256 delta.dx = 0;
3257 delta.dy = 0;
3258 }
3259
3260 mPointerGesture.referenceTouchX += commonDeltaRawX;
3261 mPointerGesture.referenceTouchY += commonDeltaRawY;
3262
3263 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3264 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3265
3266 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3267 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3268
3269 mPointerGesture.referenceGestureX += commonDeltaX;
3270 mPointerGesture.referenceGestureY += commonDeltaY;
3271 }
3272
3273 // Report gestures.
3274 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3275 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3276 // PRESS or SWIPE mode.
3277 ALOGD_IF(DEBUG_GESTURES,
3278 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3279 "currentTouchPointerCount=%d",
3280 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3281 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3282
3283 mPointerGesture.currentGestureIdBits.clear();
3284 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3285 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3286 mPointerGesture.currentGestureProperties[0].clear();
3287 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003288 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003289 mPointerGesture.currentGestureCoords[0].clear();
3290 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3291 mPointerGesture.referenceGestureX);
3292 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3293 mPointerGesture.referenceGestureY);
3294 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3295 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3296 float xOffset = static_cast<float>(commonDeltaRawX) /
3297 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3298 float yOffset = static_cast<float>(commonDeltaRawY) /
3299 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3300 mPointerGesture.currentGestureCoords[0]
3301 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3302 mPointerGesture.currentGestureCoords[0]
3303 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3304 }
3305 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3306 // FREEFORM mode.
3307 ALOGD_IF(DEBUG_GESTURES,
3308 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3309 "currentTouchPointerCount=%d",
3310 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3311 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3312
3313 mPointerGesture.currentGestureIdBits.clear();
3314
3315 BitSet32 mappedTouchIdBits;
3316 BitSet32 usedGestureIdBits;
3317 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3318 // Initially, assign the active gesture id to the active touch point
3319 // if there is one. No other touch id bits are mapped yet.
3320 if (!*cancelPreviousGesture) {
3321 mappedTouchIdBits.markBit(activeTouchId);
3322 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3323 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3324 mPointerGesture.activeGestureId;
3325 } else {
3326 mPointerGesture.activeGestureId = -1;
3327 }
3328 } else {
3329 // Otherwise, assume we mapped all touches from the previous frame.
3330 // Reuse all mappings that are still applicable.
3331 mappedTouchIdBits.value =
3332 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3333 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3334
3335 // Check whether we need to choose a new active gesture id because the
3336 // current went went up.
3337 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3338 ~mCurrentCookedState.fingerIdBits.value);
3339 !upTouchIdBits.isEmpty();) {
3340 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3341 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3342 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3343 mPointerGesture.activeGestureId = -1;
3344 break;
3345 }
3346 }
3347 }
3348
3349 ALOGD_IF(DEBUG_GESTURES,
3350 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3351 "activeGestureId=%d",
3352 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3353
3354 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3355 for (uint32_t i = 0; i < currentFingerCount; i++) {
3356 uint32_t touchId = idBits.clearFirstMarkedBit();
3357 uint32_t gestureId;
3358 if (!mappedTouchIdBits.hasBit(touchId)) {
3359 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3360 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3361 ALOGD_IF(DEBUG_GESTURES,
3362 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3363 gestureId);
3364 } else {
3365 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3366 ALOGD_IF(DEBUG_GESTURES,
3367 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3368 touchId, gestureId);
3369 }
3370 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3371 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3372
3373 const RawPointerData::Pointer& pointer =
3374 mCurrentRawState.rawPointerData.pointerForId(touchId);
3375 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3376 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3377 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3378
3379 mPointerGesture.currentGestureProperties[i].clear();
3380 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003381 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003382 mPointerGesture.currentGestureCoords[i].clear();
3383 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3384 mPointerGesture.referenceGestureX +
3385 deltaX);
3386 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3387 mPointerGesture.referenceGestureY +
3388 deltaY);
3389 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3390 }
3391
3392 if (mPointerGesture.activeGestureId < 0) {
3393 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3394 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3395 mPointerGesture.activeGestureId);
3396 }
3397 }
3398}
3399
Harry Cutts714d1ad2022-08-24 16:36:43 +00003400void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3401 const RawPointerData::Pointer& currentPointer =
3402 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3403 const RawPointerData::Pointer& lastPointer =
3404 mLastRawState.rawPointerData.pointerForId(pointerId);
3405 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3406 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3407
3408 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3409 mPointerVelocityControl.move(when, &deltaX, &deltaY);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003410}
3411
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003412std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3413 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003414 mPointerSimple.currentCoords.clear();
3415 mPointerSimple.currentProperties.clear();
3416
3417 bool down, hovering;
3418 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3419 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3420 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003421 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3422 down = !hovering;
3423
Prabir Pradhane71e5702023-03-29 14:51:38 +00003424 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3425 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Prabir Pradhane71e5702023-03-29 14:51:38 +00003426
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003427 mPointerSimple.currentCoords = mCurrentCookedState.cookedPointerData.pointerCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003428 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3429 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3430 mPointerSimple.currentProperties.id = 0;
3431 mPointerSimple.currentProperties.toolType =
3432 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3433 } else {
3434 down = false;
3435 hovering = false;
3436 }
3437
Prabir Pradhane71e5702023-03-29 14:51:38 +00003438 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003439}
3440
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003441std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3442 uint32_t policyFlags) {
3443 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003444}
3445
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003446std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3447 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003448 mPointerSimple.currentCoords.clear();
3449 mPointerSimple.currentProperties.clear();
3450
3451 bool down, hovering;
3452 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3453 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003454 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003455 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003456 } else {
3457 mPointerVelocityControl.reset();
3458 }
3459
3460 down = isPointerDown(mCurrentRawState.buttonState);
3461 hovering = !down;
3462
Prabir Pradhan2719e822023-02-28 17:39:36 +00003463 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003464 mPointerSimple.currentCoords =
3465 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003466 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3467 hovering ? 0.0f : 1.0f);
3468 mPointerSimple.currentProperties.id = 0;
3469 mPointerSimple.currentProperties.toolType =
3470 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3471 } else {
3472 mPointerVelocityControl.reset();
3473
3474 down = false;
3475 hovering = false;
3476 }
3477
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07003478 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering,
3479 ui::LogicalDisplayId::INVALID);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003480}
3481
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003482std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3483 uint32_t policyFlags) {
3484 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003485
3486 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003487
3488 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003489}
3490
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003491std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3492 uint32_t policyFlags, bool down,
Linnan Li13bf76a2024-05-05 19:18:02 +08003493 bool hovering,
3494 ui::LogicalDisplayId displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003495 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3496 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003497 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003498 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003499 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003500
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003501 if (mPointerSimple.down && !down) {
3502 mPointerSimple.down = false;
3503
3504 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003505 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3506 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3507 0, metaState, mLastRawState.buttonState,
3508 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3509 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003510 mOrientedXPrecision, mOrientedYPrecision,
3511 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3512 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003513 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003514 }
3515
3516 if (mPointerSimple.hovering && !hovering) {
3517 mPointerSimple.hovering = false;
3518
3519 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003520 out.push_back(
3521 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3522 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3523 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3524 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3525 &mPointerSimple.lastCoords, mOrientedXPrecision,
3526 mOrientedYPrecision, mPointerSimple.lastCursorX,
3527 mPointerSimple.lastCursorY, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003528 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003529 }
3530
3531 if (down) {
3532 if (!mPointerSimple.down) {
3533 mPointerSimple.down = true;
3534 mPointerSimple.downTime = when;
3535
3536 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003537 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3538 mSource, displayId, policyFlags,
3539 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3540 mCurrentRawState.buttonState, MotionClassification::NONE,
3541 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3542 &mPointerSimple.currentProperties,
3543 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003544 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003545 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003546 }
3547
3548 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003549 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3550 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3551 0, 0, metaState, mCurrentRawState.buttonState,
3552 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3553 &mPointerSimple.currentProperties,
3554 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003555 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003556 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003557 }
3558
3559 if (hovering) {
3560 if (!mPointerSimple.hovering) {
3561 mPointerSimple.hovering = true;
3562
3563 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003564 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3565 mSource, displayId, policyFlags,
3566 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3567 mCurrentRawState.buttonState, MotionClassification::NONE,
3568 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3569 &mPointerSimple.currentProperties,
3570 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003571 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003572 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003573 }
3574
3575 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003576 out.push_back(
3577 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3578 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3579 metaState, mCurrentRawState.buttonState,
3580 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3581 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003582 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003583 cursorPosition.y, mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003584 }
3585
3586 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3587 float vscroll = mCurrentRawState.rawVScroll;
3588 float hscroll = mCurrentRawState.rawHScroll;
3589 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3590 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3591
3592 // Send scroll.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003593 PointerCoords pointerCoords = mPointerSimple.currentCoords;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003594 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3595 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3596
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003597 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3598 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3599 0, 0, metaState, mCurrentRawState.buttonState,
3600 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3601 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003602 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3603 cursorPosition.y, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003604 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003605 }
3606
3607 // Save state.
3608 if (down || hovering) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003609 mPointerSimple.lastCoords = mPointerSimple.currentCoords;
3610 mPointerSimple.lastProperties = mPointerSimple.currentProperties;
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003611 mPointerSimple.displayId = displayId;
3612 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003613 mPointerSimple.lastCursorX = cursorPosition.x;
3614 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003615 } else {
3616 mPointerSimple.reset();
3617 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003618 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003619}
3620
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003621std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3622 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003623 std::list<NotifyArgs> out;
3624 if (mPointerSimple.down || mPointerSimple.hovering) {
3625 int32_t metaState = getContext()->getGlobalMetaState();
3626 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3627 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3628 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3629 metaState, mLastRawState.buttonState,
3630 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3631 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3632 mOrientedXPrecision, mOrientedYPrecision,
3633 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3634 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003635 /*videoFrames=*/{}));
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003636 }
3637 mPointerSimple.reset();
3638 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003639}
3640
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003641NotifyMotionArgs TouchInputMapper::dispatchMotion(
3642 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3643 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003644 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3645 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003646 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003647 std::vector<PointerCoords> pointerCoords;
3648 std::vector<PointerProperties> pointerProperties;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003649 uint32_t pointerCount = 0;
3650 while (!idBits.isEmpty()) {
3651 uint32_t id = idBits.clearFirstMarkedBit();
3652 uint32_t index = idToIndex[id];
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003653 pointerProperties.push_back(properties[index]);
3654 pointerCoords.push_back(coords[index]);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003655
3656 if (changedId >= 0 && id == uint32_t(changedId)) {
3657 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3658 }
3659
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003660 pointerCount++;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003661 }
3662
3663 ALOG_ASSERT(pointerCount != 0);
3664
3665 if (changedId >= 0 && pointerCount == 1) {
3666 // Replace initial down and final up action.
3667 // We can compare the action without masking off the changed pointer index
3668 // because we know the index is 0.
3669 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3670 action = AMOTION_EVENT_ACTION_DOWN;
3671 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003672 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3673 action = AMOTION_EVENT_ACTION_CANCEL;
3674 } else {
3675 action = AMOTION_EVENT_ACTION_UP;
3676 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003677 } else {
3678 // Can't happen.
3679 ALOG_ASSERT(false);
3680 }
3681 }
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00003682 if (mCurrentStreamModifiedByExternalStylus) {
3683 source |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3684 }
Prabir Pradhan9a53b552024-06-04 02:59:40 +00003685 if (mOrientedRanges.orientation.has_value()) {
3686 flags |= AMOTION_EVENT_PRIVATE_FLAG_SUPPORTS_ORIENTATION;
3687 if (mOrientedRanges.tilt.has_value()) {
3688 // In the current implementation, only devices that report a value for tilt supports
3689 // directional orientation.
3690 flags |= AMOTION_EVENT_PRIVATE_FLAG_SUPPORTS_DIRECTIONAL_ORIENTATION;
3691 }
3692 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003693
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07003694 const ui::LogicalDisplayId displayId =
3695 getAssociatedDisplayId().value_or(ui::LogicalDisplayId::INVALID);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003696
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003697 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3698 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003699 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00003700 xCursorPosition = yCursorPosition = 0.f;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003701 }
Linnan Li13bf76a2024-05-05 19:18:02 +08003702 const DeviceId deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003703 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003704 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003705 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003706 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3707 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003708 classification, edgeFlags, pointerCount, pointerProperties.data(),
3709 pointerCoords.data(), xPrecision, yPrecision, xCursorPosition,
3710 yCursorPosition, downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003711}
3712
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003713std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3714 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003715 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3716 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003717 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003718}
3719
Prabir Pradhan1728b212021-10-19 16:00:03 -07003720bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003721 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003722 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003723 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003724}
3725
3726const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3727 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003728 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3729 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3730 "left=%d, top=%d, right=%d, bottom=%d",
3731 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3732 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003733
3734 if (virtualKey.isHit(x, y)) {
3735 return &virtualKey;
3736 }
3737 }
3738
3739 return nullptr;
3740}
3741
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003742void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3743 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3744 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003745
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003746 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003747
3748 if (currentPointerCount == 0) {
3749 // No pointers to assign.
3750 return;
3751 }
3752
3753 if (lastPointerCount == 0) {
3754 // All pointers are new.
3755 for (uint32_t i = 0; i < currentPointerCount; i++) {
3756 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003757 current.rawPointerData.pointers[i].id = id;
3758 current.rawPointerData.idToIndex[id] = i;
3759 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003760 }
3761 return;
3762 }
3763
3764 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003765 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003766 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003767 uint32_t id = last.rawPointerData.pointers[0].id;
3768 current.rawPointerData.pointers[0].id = id;
3769 current.rawPointerData.idToIndex[id] = 0;
3770 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003771 return;
3772 }
3773
3774 // General case.
3775 // We build a heap of squared euclidean distances between current and last pointers
3776 // associated with the current and last pointer indices. Then, we find the best
3777 // match (by distance) for each current pointer.
3778 // The pointers must have the same tool type but it is possible for them to
3779 // transition from hovering to touching or vice-versa while retaining the same id.
3780 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3781
3782 uint32_t heapSize = 0;
3783 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3784 currentPointerIndex++) {
3785 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3786 lastPointerIndex++) {
3787 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003788 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003789 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003790 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003791 if (currentPointer.toolType == lastPointer.toolType) {
3792 int64_t deltaX = currentPointer.x - lastPointer.x;
3793 int64_t deltaY = currentPointer.y - lastPointer.y;
3794
3795 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3796
3797 // Insert new element into the heap (sift up).
3798 heap[heapSize].currentPointerIndex = currentPointerIndex;
3799 heap[heapSize].lastPointerIndex = lastPointerIndex;
3800 heap[heapSize].distance = distance;
3801 heapSize += 1;
3802 }
3803 }
3804 }
3805
3806 // Heapify
3807 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3808 startIndex -= 1;
3809 for (uint32_t parentIndex = startIndex;;) {
3810 uint32_t childIndex = parentIndex * 2 + 1;
3811 if (childIndex >= heapSize) {
3812 break;
3813 }
3814
3815 if (childIndex + 1 < heapSize &&
3816 heap[childIndex + 1].distance < heap[childIndex].distance) {
3817 childIndex += 1;
3818 }
3819
3820 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3821 break;
3822 }
3823
3824 swap(heap[parentIndex], heap[childIndex]);
3825 parentIndex = childIndex;
3826 }
3827 }
3828
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003829 if (DEBUG_POINTER_ASSIGNMENT) {
3830 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3831 for (size_t i = 0; i < heapSize; i++) {
3832 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3833 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3834 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003835 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003836
3837 // Pull matches out by increasing order of distance.
3838 // To avoid reassigning pointers that have already been matched, the loop keeps track
3839 // of which last and current pointers have been matched using the matchedXXXBits variables.
3840 // It also tracks the used pointer id bits.
3841 BitSet32 matchedLastBits(0);
3842 BitSet32 matchedCurrentBits(0);
3843 BitSet32 usedIdBits(0);
3844 bool first = true;
3845 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3846 while (heapSize > 0) {
3847 if (first) {
3848 // The first time through the loop, we just consume the root element of
3849 // the heap (the one with smallest distance).
3850 first = false;
3851 } else {
3852 // Previous iterations consumed the root element of the heap.
3853 // Pop root element off of the heap (sift down).
3854 heap[0] = heap[heapSize];
3855 for (uint32_t parentIndex = 0;;) {
3856 uint32_t childIndex = parentIndex * 2 + 1;
3857 if (childIndex >= heapSize) {
3858 break;
3859 }
3860
3861 if (childIndex + 1 < heapSize &&
3862 heap[childIndex + 1].distance < heap[childIndex].distance) {
3863 childIndex += 1;
3864 }
3865
3866 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3867 break;
3868 }
3869
3870 swap(heap[parentIndex], heap[childIndex]);
3871 parentIndex = childIndex;
3872 }
3873
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003874 if (DEBUG_POINTER_ASSIGNMENT) {
3875 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3876 for (size_t j = 0; j < heapSize; j++) {
3877 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3878 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3879 heap[j].distance);
3880 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003881 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003882 }
3883
3884 heapSize -= 1;
3885
3886 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3887 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3888
3889 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3890 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3891
3892 matchedCurrentBits.markBit(currentPointerIndex);
3893 matchedLastBits.markBit(lastPointerIndex);
3894
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003895 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3896 current.rawPointerData.pointers[currentPointerIndex].id = id;
3897 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3898 current.rawPointerData.markIdBit(id,
3899 current.rawPointerData.isHovering(
3900 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003901 usedIdBits.markBit(id);
3902
Harry Cutts45483602022-08-24 14:36:48 +00003903 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3904 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3905 ", distance=%" PRIu64,
3906 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003907 break;
3908 }
3909 }
3910
3911 // Assign fresh ids to pointers that were not matched in the process.
3912 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3913 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3914 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3915
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003916 current.rawPointerData.pointers[currentPointerIndex].id = id;
3917 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3918 current.rawPointerData.markIdBit(id,
3919 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003920
Harry Cutts45483602022-08-24 14:36:48 +00003921 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3922 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
3923 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003924 }
3925}
3926
3927int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3928 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3929 return AKEY_STATE_VIRTUAL;
3930 }
3931
3932 for (const VirtualKey& virtualKey : mVirtualKeys) {
3933 if (virtualKey.keyCode == keyCode) {
3934 return AKEY_STATE_UP;
3935 }
3936 }
3937
3938 return AKEY_STATE_UNKNOWN;
3939}
3940
3941int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3942 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3943 return AKEY_STATE_VIRTUAL;
3944 }
3945
3946 for (const VirtualKey& virtualKey : mVirtualKeys) {
3947 if (virtualKey.scanCode == scanCode) {
3948 return AKEY_STATE_UP;
3949 }
3950 }
3951
3952 return AKEY_STATE_UNKNOWN;
3953}
3954
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003955bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
3956 const std::vector<int32_t>& keyCodes,
3957 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003958 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003959 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003960 if (virtualKey.keyCode == keyCodes[i]) {
3961 outFlags[i] = 1;
3962 }
3963 }
3964 }
3965
3966 return true;
3967}
3968
Linnan Li13bf76a2024-05-05 19:18:02 +08003969std::optional<ui::LogicalDisplayId> TouchInputMapper::getAssociatedDisplayId() {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003970 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003971 if (mDeviceMode == DeviceMode::POINTER) {
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07003972 return ui::LogicalDisplayId::INVALID;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003973 } else {
3974 return std::make_optional(mViewport.displayId);
3975 }
3976 }
3977 return std::nullopt;
3978}
3979
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003980} // namespace android