blob: 489bea89595d561226e534bed07d70ad47beb82c [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
Harry Cutts3f570c72024-04-05 16:44:28 +000023#include <algorithm>
24#include <cinttypes>
25#include <cmath>
26#include <cstddef>
27#include <tuple>
28
29#include <math.h>
30
31#include <android-base/stringprintf.h>
32#include <android/input.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080033#include <ftl/enum.h>
Prabir Pradhan8d9ba912022-11-11 22:26:33 +000034#include <input/PrintTools.h>
Harry Cutts3f570c72024-04-05 16:44:28 +000035#include <input/PropertyMap.h>
36#include <input/VirtualKeyMap.h>
37#include <linux/input-event-codes.h>
38#include <log/log_main.h>
39#include <math/vec2.h>
40#include <ui/FloatRect.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080041
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070042#include "CursorButtonAccumulator.h"
43#include "CursorScrollAccumulator.h"
44#include "TouchButtonAccumulator.h"
45#include "TouchCursorInputMapperCommon.h"
Michael Wrighta9cf4192022-12-01 23:46:39 +000046#include "ui/Rotation.h"
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070047
48namespace android {
49
50// --- Constants ---
51
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070052// Artificial latency on synthetic events created from stylus data without corresponding touch
53// data.
54static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
55
HQ Liue6983c72022-04-19 22:14:56 +000056// Minimum width between two pointers to determine a gesture as freeform gesture in mm
57static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070058// --- Static Definitions ---
59
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000060static const DisplayViewport kUninitializedViewport;
61
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000062static std::string toString(const Rect& rect) {
63 return base::StringPrintf("Rect{%d, %d, %d, %d}", rect.left, rect.top, rect.right, rect.bottom);
64}
65
66static std::string toString(const ui::Size& size) {
67 return base::StringPrintf("%dx%d", size.width, size.height);
68}
69
Prabir Pradhan675f25a2022-11-10 22:04:07 +000070static bool isPointInRect(const Rect& rect, vec2 p) {
71 return p.x >= rect.left && p.x < rect.right && p.y >= rect.top && p.y < rect.bottom;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000072}
73
Prabir Pradhane04ffaa2022-12-13 23:04:04 +000074static std::string toString(const InputDeviceUsiVersion& v) {
75 return base::StringPrintf("%d.%d", v.majorVersion, v.minorVersion);
76}
77
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070078template <typename T>
79inline static void swap(T& a, T& b) {
80 T temp = a;
81 a = b;
82 b = temp;
83}
84
85static float calculateCommonVector(float a, float b) {
86 if (a > 0 && b > 0) {
87 return a < b ? a : b;
88 } else if (a < 0 && b < 0) {
89 return a > b ? a : b;
90 } else {
91 return 0;
92 }
93}
94
95inline static float distance(float x1, float y1, float x2, float y2) {
96 return hypotf(x1 - x2, y1 - y2);
97}
98
99inline static int32_t signExtendNybble(int32_t value) {
100 return value >= 8 ? value - 16 : value;
101}
102
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000103static ui::Size getNaturalDisplaySize(const DisplayViewport& viewport) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000104 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000105 if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000106 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
107 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000108 return rotatedDisplaySize;
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000109}
110
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +0000111static int32_t filterButtonState(InputReaderConfiguration& config, int32_t buttonState) {
112 if (!config.stylusButtonMotionEventsEnabled) {
113 buttonState &=
114 ~(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY | AMOTION_EVENT_BUTTON_STYLUS_SECONDARY);
115 }
116 return buttonState;
117}
118
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700119// --- RawPointerData ---
120
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700121void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
122 float x = 0, y = 0;
123 uint32_t count = touchingIdBits.count();
124 if (count) {
125 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
126 uint32_t id = idBits.clearFirstMarkedBit();
127 const Pointer& pointer = pointerForId(id);
128 x += pointer.x;
129 y += pointer.y;
130 }
131 x /= count;
132 y /= count;
133 }
134 *outX = x;
135 *outY = y;
136}
137
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700138// --- TouchInputMapper ---
139
Arpit Singh8e6fb252023-04-06 11:49:17 +0000140TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext,
141 const InputReaderConfiguration& readerConfig)
142 : InputMapper(deviceContext, readerConfig),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000143 mTouchButtonAccumulator(deviceContext),
Arpit Singha8c236b2023-04-25 13:56:05 +0000144 mConfig(readerConfig) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700145
146TouchInputMapper::~TouchInputMapper() {}
147
Philip Junker4af3b3d2021-12-14 10:36:55 +0100148uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanb08a0e82023-09-14 22:28:32 +0000149 // The SOURCE_BLUETOOTH_STYLUS is added to events dynamically if the current stream is modified
150 // by the external stylus state. That's why we don't add it directly to mSource during
151 // configuration.
152 return mSource | (hasExternalStylus() ? AINPUT_SOURCE_BLUETOOTH_STYLUS : 0);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700153}
154
Harry Cuttsd02ea102023-03-17 18:21:30 +0000155void TouchInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700156 InputMapper::populateDeviceInfo(info);
157
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000158 if (mDeviceMode == DeviceMode::DISABLED) {
159 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700160 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000161
Harry Cuttsd02ea102023-03-17 18:21:30 +0000162 info.addMotionRange(mOrientedRanges.x);
163 info.addMotionRange(mOrientedRanges.y);
164 info.addMotionRange(mOrientedRanges.pressure);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000165
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000166 if (mOrientedRanges.size) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000167 info.addMotionRange(*mOrientedRanges.size);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000168 }
169
170 if (mOrientedRanges.touchMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000171 info.addMotionRange(*mOrientedRanges.touchMajor);
172 info.addMotionRange(*mOrientedRanges.touchMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000173 }
174
175 if (mOrientedRanges.toolMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000176 info.addMotionRange(*mOrientedRanges.toolMajor);
177 info.addMotionRange(*mOrientedRanges.toolMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000178 }
179
180 if (mOrientedRanges.orientation) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000181 info.addMotionRange(*mOrientedRanges.orientation);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000182 }
183
184 if (mOrientedRanges.distance) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000185 info.addMotionRange(*mOrientedRanges.distance);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000186 }
187
188 if (mOrientedRanges.tilt) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000189 info.addMotionRange(*mOrientedRanges.tilt);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000190 }
191
192 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000193 info.addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000194 }
195 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000196 info.addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000197 }
Harry Cuttsd02ea102023-03-17 18:21:30 +0000198 info.setButtonUnderPad(mParameters.hasButtonUnderPad);
199 info.setUsiVersion(mParameters.usiVersion);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700200}
201
202void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700203 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800204 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700205 dumpParameters(dump);
206 dumpVirtualKeys(dump);
207 dumpRawPointerAxes(dump);
208 dumpCalibration(dump);
209 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700210 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700211
212 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000213 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000214 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
215 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
216 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700217 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
218 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
219 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
220 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
221 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
222 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
223 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
224 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
225 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
226 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
227
228 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
229 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
230 mLastRawState.rawPointerData.pointerCount);
231 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
232 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
233 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
234 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
235 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700236 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700237 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
238 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
239 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700240 pointer.distance, ftl::enum_string(pointer.toolType).c_str(),
241 toString(pointer.isHovering));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700242 }
243
244 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
245 mLastCookedState.buttonState);
246 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
247 mLastCookedState.cookedPointerData.pointerCount);
248 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
249 const PointerProperties& pointerProperties =
250 mLastCookedState.cookedPointerData.pointerProperties[i];
251 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000252 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
253 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
254 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700255 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700256 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700257 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000258 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
259 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700260 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
261 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
262 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
263 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
264 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
265 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
266 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
267 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700268 ftl::enum_string(pointerProperties.toolType).c_str(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700269 toString(mLastCookedState.cookedPointerData.isHovering(i)));
270 }
271
272 dump += INDENT3 "Stylus Fusion:\n";
273 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
274 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000275 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
276 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700277 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
278 mExternalStylusFusionTimeout);
Harry Cutts1ee05b62023-06-19 13:49:06 +0000279 dump += StringPrintf(INDENT4 "External Stylus Buttons Applied: 0x%08x\n",
Prabir Pradhan124ea442022-10-28 20:27:44 +0000280 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700281 dump += INDENT3 "External Stylus State:\n";
282 dumpStylusState(dump, mExternalStylusState);
283
Michael Wright227c5542020-07-02 18:30:52 +0100284 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700285 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
286 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
287 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
288 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
289 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
290 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
291 }
292}
293
Arpit Singh4be4eef2023-03-28 14:26:01 +0000294std::list<NotifyArgs> TouchInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000295 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000296 ConfigurationChanges changes) {
Arpit Singh4be4eef2023-03-28 14:26:01 +0000297 std::list<NotifyArgs> out = InputMapper::reconfigure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700298
Arpit Singhed6c3de2023-04-05 19:24:37 +0000299 mConfig = config;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700300
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000301 // Full configuration should happen the first time configure is called and
302 // when the device type is changed. Changing a device type can affect
303 // various other parameters so should result in a reconfiguration.
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000304 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700305 // Configure basic parameters.
Arpit Singh403e53c2023-04-18 11:46:56 +0000306 mParameters = computeParameters(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700307
308 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800309 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000310 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700311
312 // Configure absolute axis information.
313 configureRawPointerAxes();
314
315 // Prepare input device calibration.
316 parseCalibration();
317 resolveCalibration();
318 }
319
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000320 if (!changes.any() ||
321 changes.test(InputReaderConfiguration::Change::TOUCH_AFFINE_TRANSFORMATION)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700322 // Update location calibration to reflect current settings
323 updateAffineTransformation();
324 }
325
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000326 if (!changes.any() || changes.test(InputReaderConfiguration::Change::POINTER_SPEED)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700327 // Update pointer speed.
328 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
329 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
330 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
331 }
332
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000333 using namespace ftl::flag_operators;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700334 bool resetNeeded = false;
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000335 if (!changes.any() ||
336 changes.any(InputReaderConfiguration::Change::DISPLAY_INFO |
337 InputReaderConfiguration::Change::POINTER_CAPTURE |
338 InputReaderConfiguration::Change::POINTER_GESTURE_ENABLEMENT |
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000339 InputReaderConfiguration::Change::EXTERNAL_STYLUS_PRESENCE |
340 InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700341 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700342 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700343 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700344 }
345
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000346 if (changes.any() && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700347 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000348
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700349 // Send reset, unless this is the first time the device has been configured,
350 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000351 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700352 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700353 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700354}
355
356void TouchInputMapper::resolveExternalStylusPresence() {
357 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800358 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700359 mExternalStylusConnected = !devices.empty();
360
361 if (!mExternalStylusConnected) {
362 resetExternalStylus();
363 }
364}
365
Arpit Singh403e53c2023-04-18 11:46:56 +0000366TouchInputMapper::Parameters TouchInputMapper::computeParameters(
367 const InputDeviceContext& deviceContext) {
368 Parameters parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700369 // Use the pointer presentation mode for devices that do not support distinct
370 // multitouch. The spot-based presentation relies on being able to accurately
371 // locate two or more fingers on the touch pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000372 parameters.gestureMode = deviceContext.hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100373 ? Parameters::GestureMode::SINGLE_TOUCH
374 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700375
Arpit Singh403e53c2023-04-18 11:46:56 +0000376 const PropertyMap& config = deviceContext.getConfiguration();
Harry Cuttsf13161a2023-03-08 14:15:49 +0000377 std::optional<std::string> gestureModeString = config.getString("touch.gestureMode");
378 if (gestureModeString.has_value()) {
379 if (*gestureModeString == "single-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000380 parameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000381 } else if (*gestureModeString == "multi-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000382 parameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000383 } else if (*gestureModeString != "default") {
384 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700385 }
386 }
387
Arpit Singh403e53c2023-04-18 11:46:56 +0000388 parameters.deviceType = computeDeviceType(deviceContext);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389
Arpit Singh403e53c2023-04-18 11:46:56 +0000390 parameters.hasButtonUnderPad = deviceContext.hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700391
Arpit Singh403e53c2023-04-18 11:46:56 +0000392 parameters.orientationAware =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000393 config.getBool("touch.orientationAware")
Arpit Singh403e53c2023-04-18 11:46:56 +0000394 .value_or(parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700395
Arpit Singh403e53c2023-04-18 11:46:56 +0000396 parameters.orientation = ui::ROTATION_0;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000397 std::optional<std::string> orientationString = config.getString("touch.orientation");
398 if (orientationString.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000399 if (parameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700400 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
Harry Cuttsf13161a2023-03-08 14:15:49 +0000401 } else if (*orientationString == "ORIENTATION_90") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000402 parameters.orientation = ui::ROTATION_90;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000403 } else if (*orientationString == "ORIENTATION_180") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000404 parameters.orientation = ui::ROTATION_180;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000405 } else if (*orientationString == "ORIENTATION_270") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000406 parameters.orientation = ui::ROTATION_270;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000407 } else if (*orientationString != "ORIENTATION_0") {
408 ALOGW("Invalid value for touch.orientation: '%s'", orientationString->c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700409 }
410 }
411
Arpit Singh403e53c2023-04-18 11:46:56 +0000412 parameters.hasAssociatedDisplay = false;
413 parameters.associatedDisplayIsExternal = false;
414 if (parameters.orientationAware ||
415 parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
416 parameters.deviceType == Parameters::DeviceType::POINTER ||
417 (parameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
418 deviceContext.getAssociatedViewport())) {
419 parameters.hasAssociatedDisplay = true;
420 if (parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
421 parameters.associatedDisplayIsExternal = deviceContext.isExternal();
422 parameters.uniqueDisplayId = config.getString("touch.displayId").value_or("").c_str();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700423 }
424 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000425 if (deviceContext.getAssociatedDisplayPort()) {
426 parameters.hasAssociatedDisplay = true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700427 }
428
429 // Initial downs on external touch devices should wake the device.
430 // Normally we don't do this for internal touch screens to prevent them from waking
431 // up in your pocket but you can enable it using the input device configuration.
Arpit Singh403e53c2023-04-18 11:46:56 +0000432 parameters.wake = config.getBool("touch.wake").value_or(deviceContext.isExternal());
Prabir Pradhan167c2702022-09-14 00:37:24 +0000433
Harry Cuttsf13161a2023-03-08 14:15:49 +0000434 std::optional<int32_t> usiVersionMajor = config.getInt("touch.usiVersionMajor");
435 std::optional<int32_t> usiVersionMinor = config.getInt("touch.usiVersionMinor");
436 if (usiVersionMajor.has_value() && usiVersionMinor.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000437 parameters.usiVersion = {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000438 .majorVersion = *usiVersionMajor,
439 .minorVersion = *usiVersionMinor,
440 };
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000441 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700442
Arpit Singh403e53c2023-04-18 11:46:56 +0000443 parameters.enableForInactiveViewport =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000444 config.getBool("touch.enableForInactiveViewport").value_or(false);
Arpit Singh403e53c2023-04-18 11:46:56 +0000445
446 return parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700447}
448
Arpit Singh403e53c2023-04-18 11:46:56 +0000449TouchInputMapper::Parameters::DeviceType TouchInputMapper::computeDeviceType(
450 const InputDeviceContext& deviceContext) {
451 Parameters::DeviceType deviceType;
452 if (deviceContext.hasInputProperty(INPUT_PROP_DIRECT)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000453 // The device is a touch screen.
Arpit Singh403e53c2023-04-18 11:46:56 +0000454 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
455 } else if (deviceContext.hasInputProperty(INPUT_PROP_POINTER)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000456 // The device is a pointing device like a track pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000457 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000458 } else {
459 // The device is a touch pad of unknown purpose.
Arpit Singh403e53c2023-04-18 11:46:56 +0000460 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000461 }
462
463 // Type association takes precedence over the device type found in the idc file.
Arpit Singh403e53c2023-04-18 11:46:56 +0000464 std::string deviceTypeString = deviceContext.getDeviceTypeAssociation().value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000465 if (deviceTypeString.empty()) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000466 deviceTypeString =
Arpit Singh403e53c2023-04-18 11:46:56 +0000467 deviceContext.getConfiguration().getString("touch.deviceType").value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000468 }
469 if (deviceTypeString == "touchScreen") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000470 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000471 } else if (deviceTypeString == "touchNavigation") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000472 deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000473 } else if (deviceTypeString == "pointer") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000474 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000475 } else if (deviceTypeString != "default" && deviceTypeString != "") {
476 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
477 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000478 return deviceType;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000479}
480
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700481void TouchInputMapper::dumpParameters(std::string& dump) {
482 dump += INDENT3 "Parameters:\n";
483
Dominik Laskowski75788452021-02-09 18:51:25 -0800484 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700485
Dominik Laskowski75788452021-02-09 18:51:25 -0800486 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700487
488 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
489 "displayId='%s'\n",
490 toString(mParameters.hasAssociatedDisplay),
491 toString(mParameters.associatedDisplayIsExternal),
492 mParameters.uniqueDisplayId.c_str());
493 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800494 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000495 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
496 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700497 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
498 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700499}
500
501void TouchInputMapper::configureRawPointerAxes() {
502 mRawPointerAxes.clear();
503}
504
505void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
506 dump += INDENT3 "Raw Touch Axes:\n";
507 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
508 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
509 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
510 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
511 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
512 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
513 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
514 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
515 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
516 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
517 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
518 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
520}
521
522bool TouchInputMapper::hasExternalStylus() const {
523 return mExternalStylusConnected;
524}
525
526/**
527 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000528 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800529 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000530 * 3. Get the matching viewport by either unique id in idc file or by the display type
531 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800532 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700533 */
534std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Harry Cutts8722be92024-04-05 14:46:05 +0000535 if (mParameters.hasAssociatedDisplay) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000536 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800537 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700538 }
539
Antonio Kantek0ac5e092024-04-22 17:10:27 +0000540 const std::optional<std::string> associatedDisplayUniqueIdByDescriptor =
541 getDeviceContext().getAssociatedDisplayUniqueIdByDescriptor();
542 if (associatedDisplayUniqueIdByDescriptor) {
543 return getDeviceContext().getAssociatedViewport();
544 }
545
546 const std::optional<std::string> associatedDisplayUniqueIdByPort =
547 getDeviceContext().getAssociatedDisplayUniqueIdByPort();
548 if (associatedDisplayUniqueIdByPort) {
Christine Franks2a2293c2022-01-18 11:51:16 -0800549 return getDeviceContext().getAssociatedViewport();
550 }
551
Michael Wright227c5542020-07-02 18:30:52 +0100552 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800553 std::optional<DisplayViewport> viewport =
554 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
555 if (viewport) {
556 return viewport;
557 } else {
Linnan Li13bf76a2024-05-05 19:18:02 +0800558 ALOGW("Can't find designated display viewport with ID %s for pointers.",
559 mConfig.defaultPointerDisplayId.toString().c_str());
Garfield Tan888a6a42020-01-09 11:39:16 -0800560 }
561 }
562
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700563 // Check if uniqueDisplayId is specified in idc file.
564 if (!mParameters.uniqueDisplayId.empty()) {
565 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
566 }
567
568 ViewportType viewportTypeToUse;
569 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100570 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700571 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100572 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700573 }
574
575 std::optional<DisplayViewport> viewport =
576 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100577 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700578 ALOGW("Input device %s should be associated with external display, "
579 "fallback to internal one for the external viewport is not found.",
580 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100581 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700582 }
583
584 return viewport;
585 }
586
587 // No associated display, return a non-display viewport.
588 DisplayViewport newViewport;
589 // Raw width and height in the natural orientation.
590 int32_t rawWidth = mRawPointerAxes.getRawWidth();
591 int32_t rawHeight = mRawPointerAxes.getRawHeight();
592 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
593 return std::make_optional(newViewport);
594}
595
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800596int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
597 if (resolution < 0) {
598 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
599 getDeviceName().c_str());
600 return 0;
601 }
602 return resolution;
603}
604
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800605void TouchInputMapper::initializeSizeRanges() {
606 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
607 mSizeScale = 0.0f;
608 return;
609 }
610
611 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000612 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800613
614 // Size factors.
615 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
616 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
617 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
618 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
619 } else {
620 mSizeScale = 0.0f;
621 }
622
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700623 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
624 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
625 .source = mSource,
626 .min = 0,
627 .max = diagonalSize,
628 .flat = 0,
629 .fuzz = 0,
630 .resolution = 0,
631 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800632
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800633 if (mRawPointerAxes.touchMajor.valid) {
634 mRawPointerAxes.touchMajor.resolution =
635 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700636 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800637 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800638
639 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700640 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800641 if (mRawPointerAxes.touchMinor.valid) {
642 mRawPointerAxes.touchMinor.resolution =
643 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700644 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800645 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800646
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700647 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
648 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
649 .source = mSource,
650 .min = 0,
651 .max = diagonalSize,
652 .flat = 0,
653 .fuzz = 0,
654 .resolution = 0,
655 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800656 if (mRawPointerAxes.toolMajor.valid) {
657 mRawPointerAxes.toolMajor.resolution =
658 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700659 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800660 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800661
662 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700663 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800664 if (mRawPointerAxes.toolMinor.valid) {
665 mRawPointerAxes.toolMinor.resolution =
666 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700667 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800668 }
669
670 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700671 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
672 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
673 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
674 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800675 } else {
676 // Support for other calibrations can be added here.
677 ALOGW("%s calibration is not supported for size ranges at the moment. "
678 "Using raw resolution instead",
679 ftl::enum_string(mCalibration.sizeCalibration).c_str());
680 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800681
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700682 mOrientedRanges.size = InputDeviceInfo::MotionRange{
683 .axis = AMOTION_EVENT_AXIS_SIZE,
684 .source = mSource,
685 .min = 0,
686 .max = 1.0,
687 .flat = 0,
688 .fuzz = 0,
689 .resolution = 0,
690 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800691}
692
693void TouchInputMapper::initializeOrientedRanges() {
694 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000695 const float orientedScaleX = mRawToDisplay.getScaleX();
696 const float orientedScaleY = mRawToDisplay.getScaleY();
697 mOrientedXPrecision = 1.0f / orientedScaleX;
698 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800699
700 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
701 mOrientedRanges.x.source = mSource;
702 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
703 mOrientedRanges.y.source = mSource;
704
705 // Scale factor for terms that are not oriented in a particular axis.
706 // If the pixels are square then xScale == yScale otherwise we fake it
707 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000708 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800709
710 initializeSizeRanges();
711
712 // Pressure factors.
713 mPressureScale = 0;
714 float pressureMax = 1.0;
715 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
716 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700717 if (mCalibration.pressureScale) {
718 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800719 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
720 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
721 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
722 }
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;
740 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
741 if (mHaveTilt) {
742 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
743 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
744 mTiltXScale = M_PI / 180;
745 mTiltYScale = M_PI / 180;
746
747 if (mRawPointerAxes.tiltX.resolution) {
748 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
749 }
750 if (mRawPointerAxes.tiltY.resolution) {
751 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
752 }
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) {
781 if (mRawPointerAxes.orientation.valid) {
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;
786 } 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
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700810 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800811
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700812 .axis = AMOTION_EVENT_AXIS_DISTANCE,
813 .source = mSource,
814 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
815 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
816 .flat = 0,
817 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
818 .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 Pradhanbaa5c822019-08-30 15:27:05 -0700946 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
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 Pradhanbaa5c822019-08-30 15:27:05 -0700958 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
959 ALOGW("Touch device '%s' did not report support for X or Y axis! "
960 "The device will be inoperable.",
961 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100962 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000963 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700964 ALOGI("Touch device '%s' could not query the properties of its associated "
965 "display. The device will be inoperable until the display size "
966 "becomes available.",
967 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100968 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700969 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000970 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
971 getDeviceName().c_str(), getDeviceId());
972 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000973 }
974
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700975 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000976 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000977 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
978 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
979 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
980 const float rawMeanResolution =
981 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700982
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000983 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
Josh Thielene986aed2023-06-01 14:17:30 +0000984 bool viewportChanged;
985 if (mParameters.enableForInactiveViewport) {
986 // When touch is enabled for an inactive viewport, ignore the
987 // viewport active status when checking whether the viewport has
988 // changed.
989 DisplayViewport tempViewport = mViewport;
990 tempViewport.isActive = newViewport.isActive;
991 viewportChanged = tempViewport != newViewport;
992 } else {
993 viewportChanged = mViewport != newViewport;
994 }
995
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700996 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700997 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000998 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
999 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
1000 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001001
Michael Wright227c5542020-07-02 18:30:52 +01001002 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +00001003 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001004
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001005 mDisplayBounds = getNaturalDisplaySize(mViewport);
1006 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
1007 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -07001008
Prabir Pradhan3e798762022-12-02 21:02:11 +00001009 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
1010 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
1011 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001012 // InputReader works in the un-rotated display coordinate space, so we don't need to do
1013 // anything if the device is already orientation-aware. If the device is not
1014 // orientation-aware, then we need to apply the inverse rotation of the display so that
1015 // when the display rotation is applied later as a part of the per-window transform, we
1016 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001017 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +00001018 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001019 : getInverseRotation(mViewport.orientation);
1020 // For orientation-aware devices that work in the un-rotated coordinate space, the
1021 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001022 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001023 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001024
1025 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001026 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001027 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001028 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001029 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001030 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001031 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001032 mRawToDisplay.reset();
1033 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001034 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001035 }
1036 }
1037
1038 // If moving between pointer modes, need to reset some state.
1039 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1040 if (deviceModeChanged) {
1041 mOrientedRanges.clear();
1042 }
1043
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001044 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001045 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %s, mode %s, "
Linnan Li13bf76a2024-05-05 19:18:02 +08001046 "display id %s",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001047 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001048 ftl::enum_string(mInputDeviceOrientation).c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08001049 ftl::enum_string(mDeviceMode).c_str(), mViewport.displayId.toString().c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001050
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001051 configureVirtualKeys();
1052
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001053 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001054
1055 // Location
1056 updateAffineTransformation();
1057
Michael Wright227c5542020-07-02 18:30:52 +01001058 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001059 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001060 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1061 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001062
1063 // Scale movements such that one whole swipe of the touch pad covers a
1064 // given area relative to the diagonal size of the display when no acceleration
1065 // is applied.
1066 // Assume that the touch pad has a square aspect ratio such that movements in
1067 // X and Y of the same number of raw units cover the same physical distance.
1068 mPointerXMovementScale =
1069 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1070 mPointerYMovementScale = mPointerXMovementScale;
1071
1072 // Scale zooms to cover a smaller range of the display than movements do.
1073 // This value determines the area around the pointer that is affected by freeform
1074 // pointer gestures.
1075 mPointerXZoomScale =
1076 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1077 mPointerYZoomScale = mPointerXZoomScale;
1078
HQ Liue6983c72022-04-19 22:14:56 +00001079 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1080 // axis is non positive value.
1081 const float minFreeformGestureWidth =
1082 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1083
1084 mPointerGestureMaxSwipeWidth =
1085 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1086 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001087 }
1088
1089 // Inform the dispatcher about the changes.
1090 *outResetNeeded = true;
1091 bumpGeneration();
1092 }
1093}
1094
Prabir Pradhan1728b212021-10-19 16:00:03 -07001095void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001096 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001097 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001098 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1099 toString(mPhysicalFrameInRotatedDisplay).c_str());
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001100 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %s\n",
1101 ftl::enum_string(mInputDeviceOrientation).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001102}
1103
1104void TouchInputMapper::configureVirtualKeys() {
1105 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001106 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001107
1108 mVirtualKeys.clear();
1109
1110 if (virtualKeyDefinitions.size() == 0) {
1111 return;
1112 }
1113
1114 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1115 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1116 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1117 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1118
1119 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1120 VirtualKey virtualKey;
1121
1122 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1123 int32_t keyCode;
1124 int32_t dummyKeyMetaState;
1125 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001126 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1127 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001128 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1129 continue; // drop the key
1130 }
1131
1132 virtualKey.keyCode = keyCode;
1133 virtualKey.flags = flags;
1134
1135 // convert the key definition's display coordinates into touch coordinates for a hit box
1136 int32_t halfWidth = virtualKeyDefinition.width / 2;
1137 int32_t halfHeight = virtualKeyDefinition.height / 2;
1138
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001139 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1140 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001142 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1143 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001145 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1146 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001148 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1149 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 touchScreenTop;
1151 mVirtualKeys.push_back(virtualKey);
1152 }
1153}
1154
1155void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1156 if (!mVirtualKeys.empty()) {
1157 dump += INDENT3 "Virtual Keys:\n";
1158
1159 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1160 const VirtualKey& virtualKey = mVirtualKeys[i];
1161 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1162 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1163 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1164 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1165 }
1166 }
1167}
1168
1169void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001170 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 Calibration& out = mCalibration;
1172
1173 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001174 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001175 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1176 if (sizeCalibrationString.has_value()) {
1177 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001178 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001179 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001180 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001181 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001182 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001183 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001185 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001186 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001187 } else if (*sizeCalibrationString != "default") {
1188 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001189 }
1190 }
1191
Harry Cuttsf13161a2023-03-08 14:15:49 +00001192 out.sizeScale = in.getFloat("touch.size.scale");
1193 out.sizeBias = in.getFloat("touch.size.bias");
1194 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195
1196 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001197 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001198 std::optional<std::string> pressureCalibrationString =
1199 in.getString("touch.pressure.calibration");
1200 if (pressureCalibrationString.has_value()) {
1201 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001202 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001203 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001205 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001207 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001208 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001209 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210 }
1211 }
1212
Harry Cuttsf13161a2023-03-08 14:15:49 +00001213 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214
1215 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001216 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001217 std::optional<std::string> orientationCalibrationString =
1218 in.getString("touch.orientation.calibration");
1219 if (orientationCalibrationString.has_value()) {
1220 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001221 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001222 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001223 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001224 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001225 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001226 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001228 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 }
1230 }
1231
1232 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001233 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001234 std::optional<std::string> distanceCalibrationString =
1235 in.getString("touch.distance.calibration");
1236 if (distanceCalibrationString.has_value()) {
1237 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001238 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001239 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001240 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001241 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001243 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 }
1245 }
1246
Harry Cuttsf13161a2023-03-08 14:15:49 +00001247 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248}
1249
1250void TouchInputMapper::resolveCalibration() {
1251 // Size
1252 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001253 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1254 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001257 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 }
1259
1260 // Pressure
1261 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001262 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1263 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001266 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 }
1268
1269 // Orientation
1270 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001271 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1272 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 }
1274 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001275 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 }
1277
1278 // Distance
1279 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001280 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1281 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 }
1283 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001284 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001286}
1287
1288void TouchInputMapper::dumpCalibration(std::string& dump) {
1289 dump += INDENT3 "Calibration:\n";
1290
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001291 dump += INDENT4 "touch.size.calibration: ";
1292 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001294 if (mCalibration.sizeScale) {
1295 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001296 }
1297
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001298 if (mCalibration.sizeBias) {
1299 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 }
1301
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001302 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001304 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001305 }
1306
1307 // Pressure
1308 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001309 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.pressure.calibration: none\n";
1311 break;
Michael Wright227c5542020-07-02 18:30:52 +01001312 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.pressure.calibration: physical\n";
1314 break;
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1317 break;
1318 default:
1319 ALOG_ASSERT(false);
1320 }
1321
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001322 if (mCalibration.pressureScale) {
1323 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324 }
1325
1326 // Orientation
1327 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001328 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329 dump += INDENT4 "touch.orientation.calibration: none\n";
1330 break;
Michael Wright227c5542020-07-02 18:30:52 +01001331 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1333 break;
Michael Wright227c5542020-07-02 18:30:52 +01001334 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001335 dump += INDENT4 "touch.orientation.calibration: vector\n";
1336 break;
1337 default:
1338 ALOG_ASSERT(false);
1339 }
1340
1341 // Distance
1342 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001343 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.distance.calibration: none\n";
1345 break;
Michael Wright227c5542020-07-02 18:30:52 +01001346 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001347 dump += INDENT4 "touch.distance.calibration: scaled\n";
1348 break;
1349 default:
1350 ALOG_ASSERT(false);
1351 }
1352
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001353 if (mCalibration.distanceScale) {
1354 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001355 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356}
1357
1358void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1359 dump += INDENT3 "Affine Transformation:\n";
1360
1361 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1362 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1363 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1364 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1365 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1366 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1367}
1368
1369void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001370 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001371 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001372}
1373
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001374std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001375 std::list<NotifyArgs> out = cancelTouch(when, when);
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001376
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001377 mCursorButtonAccumulator.reset(getDeviceContext());
1378 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001379 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001380
1381 mPointerVelocityControl.reset();
1382 mWheelXVelocityControl.reset();
1383 mWheelYVelocityControl.reset();
1384
1385 mRawStatesPending.clear();
1386 mCurrentRawState.clear();
1387 mCurrentCookedState.clear();
1388 mLastRawState.clear();
1389 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001390 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001391 mSentHoverEnter = false;
1392 mHavePointerIds = false;
1393 mCurrentMotionAborted = false;
1394 mDownTime = 0;
1395
1396 mCurrentVirtualKey.down = false;
1397
1398 mPointerGesture.reset();
1399 mPointerSimple.reset();
1400 resetExternalStylus();
1401
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001402 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001403}
1404
1405void TouchInputMapper::resetExternalStylus() {
1406 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001407 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001408 mExternalStylusFusionTimeout = LLONG_MAX;
1409 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001410 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411}
1412
1413void TouchInputMapper::clearStylusDataPendingFlags() {
1414 mExternalStylusDataPending = false;
1415 mExternalStylusFusionTimeout = LLONG_MAX;
1416}
1417
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001418std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001419 mCursorButtonAccumulator.process(rawEvent);
1420 mCursorScrollAccumulator.process(rawEvent);
1421 mTouchButtonAccumulator.process(rawEvent);
1422
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001423 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001424 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001425 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001426 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001427 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001428}
1429
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001430std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1431 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001432 if (mDeviceMode == DeviceMode::DISABLED) {
1433 // Only save the last pending state when the device is disabled.
1434 mRawStatesPending.clear();
1435 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436 // Push a new state.
1437 mRawStatesPending.emplace_back();
1438
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001439 RawState& next = mRawStatesPending.back();
1440 next.clear();
1441 next.when = when;
1442 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001443
1444 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001445 next.buttonState = filterButtonState(mConfig,
1446 mTouchButtonAccumulator.getButtonState() |
1447 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001448
1449 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001450 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1451 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001452 mCursorScrollAccumulator.finishSync();
1453
1454 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001455 syncTouch(when, &next);
1456
1457 // The last RawState is the actually second to last, since we just added a new state
1458 const RawState& last =
1459 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001460
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001461 std::tie(next.when, next.readTime) =
1462 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1463 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001464
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001465 // Assign pointer ids.
1466 if (!mHavePointerIds) {
1467 assignPointerIds(last, next);
1468 }
1469
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001470 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001471 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1472 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1473 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1474 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1475 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1476 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001477
Arthur Hung9ad18942021-06-19 02:04:46 +00001478 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1479 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1480 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1481 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1482 next.rawPointerData.hoveringIdBits.value);
1483 }
1484
Harry Cutts33476232023-01-30 19:57:29 +00001485 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001486 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001487}
1488
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001489std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1490 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001491 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001492 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001493 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001494 }
1495
1496 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1497 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1498 // touching the current state will only observe the events that have been dispatched to the
1499 // rest of the pipeline.
1500 const size_t N = mRawStatesPending.size();
1501 size_t count;
1502 for (count = 0; count < N; count++) {
1503 const RawState& next = mRawStatesPending[count];
1504
1505 // A failure to assign the stylus id means that we're waiting on stylus data
1506 // and so should defer the rest of the pipeline.
1507 if (assignExternalStylusId(next, timeout)) {
1508 break;
1509 }
1510
1511 // All ready to go.
1512 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001513 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001514 if (mCurrentRawState.when < mLastRawState.when) {
1515 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001516 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001517 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001518 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001519 }
1520 if (count != 0) {
1521 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1522 }
1523
1524 if (mExternalStylusDataPending) {
1525 if (timeout) {
1526 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1527 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001528 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001529 ALOGD_IF(DEBUG_STYLUS_FUSION,
1530 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001531 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001532 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001533 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1534 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1535 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1536 }
1537 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001538 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001539}
1540
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001541std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1542 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001543 // Always start with a clean state.
1544 mCurrentCookedState.clear();
1545
1546 // Apply stylus buttons to current raw state.
1547 applyExternalStylusButtonState(when);
1548
1549 // Handle policy on initial down or hover events.
1550 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1551 mCurrentRawState.rawPointerData.pointerCount != 0;
1552
1553 uint32_t policyFlags = 0;
1554 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1555 if (initialDown || buttonsPressed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001556 if (mParameters.wake) {
1557 policyFlags |= POLICY_FLAG_WAKE;
1558 }
1559 }
1560
1561 // Consume raw off-screen touches before cooking pointer data.
1562 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001563 bool consumed;
1564 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1565 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001566 mCurrentRawState.rawPointerData.clear();
1567 }
1568
1569 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1570 // with cooked pointer data that has the same ids and indices as the raw data.
1571 // The following code can use either the raw or cooked data, as needed.
1572 cookPointerData();
1573
1574 // Apply stylus pressure to current cooked state.
1575 applyExternalStylusTouchState(when);
1576
1577 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001578 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1579 mSource, mViewport.displayId, policyFlags,
1580 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001581
1582 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001583 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001584 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1585 uint32_t id = idBits.clearFirstMarkedBit();
1586 const RawPointerData::Pointer& pointer =
1587 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001588 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001589 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001590 } else if (pointer.toolType == ToolType::FINGER ||
1591 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001592 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001593 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001594 mCurrentCookedState.mouseIdBits.markBit(id);
1595 }
1596 }
1597 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1598 uint32_t id = idBits.clearFirstMarkedBit();
1599 const RawPointerData::Pointer& pointer =
1600 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001601 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001602 mCurrentCookedState.stylusIdBits.markBit(id);
1603 }
1604 }
1605
1606 // Stylus takes precedence over all tools, then mouse, then finger.
1607 PointerUsage pointerUsage = mPointerUsage;
1608 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1609 mCurrentCookedState.mouseIdBits.clear();
1610 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001611 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001612 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1613 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001614 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001615 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1616 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001617 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001618 }
1619
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001620 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001621 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001622 if (!mCurrentMotionAborted) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001623 out += dispatchButtonRelease(when, readTime, policyFlags);
1624 out += dispatchHoverExit(when, readTime, policyFlags);
1625 out += dispatchTouches(when, readTime, policyFlags);
1626 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1627 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001628 }
1629
1630 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1631 mCurrentMotionAborted = false;
1632 }
1633 }
1634
1635 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001636 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1637 mSource, mViewport.displayId, policyFlags,
1638 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001639
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001640 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1641 mCurrentStreamModifiedByExternalStylus = false;
1642 }
1643
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001644 // Clear some transient state.
1645 mCurrentRawState.rawVScroll = 0;
1646 mCurrentRawState.rawHScroll = 0;
1647
1648 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001649 mLastRawState = mCurrentRawState;
1650 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001651 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001652}
1653
Garfield Tanc734e4f2021-01-15 20:01:39 -08001654bool TouchInputMapper::isTouchScreen() {
1655 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1656 mParameters.hasAssociatedDisplay;
1657}
1658
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001659void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001660 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1661 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001662 const int32_t pressedButtons =
1663 filterButtonState(mConfig,
1664 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001665 const int32_t releasedButtons =
1666 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1667
1668 mCurrentRawState.buttonState |= pressedButtons;
1669 mCurrentRawState.buttonState &= ~releasedButtons;
1670
1671 mExternalStylusButtonsApplied |= pressedButtons;
1672 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001673
1674 if (mExternalStylusButtonsApplied != 0 || releasedButtons != 0) {
1675 mCurrentStreamModifiedByExternalStylus = true;
1676 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001677 }
1678}
1679
1680void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1681 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1682 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001683 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1684 return;
1685 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001686
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001687 mCurrentStreamModifiedByExternalStylus = true;
1688
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001689 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1690 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1691 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1692 : 0.f;
1693 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1694 pressure = *mExternalStylusState.pressure;
1695 }
1696 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1697 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001698
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001699 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001700 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001701 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001702 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001703 }
1704}
1705
1706bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001707 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001708 return false;
1709 }
1710
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001711 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001712 if (mFusedStylusPointerId &&
1713 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001714 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001715 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001716 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001717 }
1718
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001719 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1720 state.rawPointerData.pointerCount != 0;
1721 if (!initialDown) {
1722 return false;
1723 }
1724
1725 if (!mExternalStylusState.pressure) {
1726 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1727 return false;
1728 }
1729
1730 if (*mExternalStylusState.pressure != 0.0f) {
1731 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1732 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1733 return false;
1734 }
1735
1736 if (timeout) {
1737 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1738 mFusedStylusPointerId.reset();
1739 mExternalStylusFusionTimeout = LLONG_MAX;
1740 return false;
1741 }
1742
1743 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1744 // being processed until we either get pressure data or timeout.
1745 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1746 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1747 }
1748 ALOGD_IF(DEBUG_STYLUS_FUSION,
1749 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1750 mExternalStylusFusionTimeout);
1751 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1752 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001753}
1754
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001755std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1756 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001757 if (mDeviceMode == DeviceMode::POINTER) {
1758 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001759 // Since this is a synthetic event, we can consider its latency to be zero
1760 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001761 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001762 }
Michael Wright227c5542020-07-02 18:30:52 +01001763 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001764 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001765 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001766 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1767 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1768 }
1769 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001770 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001771}
1772
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001773std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1774 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001775 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001776 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001777 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001778 // The following three cases are handled here:
1779 // - We're in the middle of a fused stream of data;
1780 // - We're waiting on external stylus data before dispatching the initial down; or
1781 // - Only the button state, which is not reported through a specific pointer, has changed.
1782 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001783 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001784 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001785 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001786 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001787}
1788
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001789std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1790 uint32_t policyFlags, bool& outConsumed) {
1791 outConsumed = false;
1792 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001793 // Check for release of a virtual key.
1794 if (mCurrentVirtualKey.down) {
1795 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1796 // Pointer went up while virtual key was down.
1797 mCurrentVirtualKey.down = false;
1798 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001799 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1800 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1801 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001802 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1803 AKEY_EVENT_FLAG_FROM_SYSTEM |
1804 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001805 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001806 outConsumed = true;
1807 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001808 }
1809
1810 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1811 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1812 const RawPointerData::Pointer& pointer =
1813 mCurrentRawState.rawPointerData.pointerForId(id);
1814 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1815 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1816 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001817 outConsumed = true;
1818 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001819 }
1820 }
1821
1822 // Pointer left virtual key area or another pointer also went down.
1823 // Send key cancellation but do not consume the touch yet.
1824 // This is useful when the user swipes through from the virtual key area
1825 // into the main display surface.
1826 mCurrentVirtualKey.down = false;
1827 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001828 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1829 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001830 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1831 AKEY_EVENT_FLAG_FROM_SYSTEM |
1832 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1833 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001834 }
1835 }
1836
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001837 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
Harry Cutts8722be92024-04-05 14:46:05 +00001838 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001839 // We have hovering pointers, and there are no touching pointers.
1840 bool hoveringPointersInFrame = false;
1841 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1842 while (!hoveringIds.isEmpty()) {
1843 uint32_t id = hoveringIds.clearFirstMarkedBit();
1844 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1845 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1846 hoveringPointersInFrame = true;
1847 break;
1848 }
1849 }
1850 if (!hoveringPointersInFrame) {
1851 // All hovering pointers are outside the physical frame.
1852 outConsumed = true;
1853 return out;
1854 }
1855 }
1856
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001857 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1858 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1859 // Pointer just went down. Check for virtual key press or off-screen touches.
1860 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1861 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001862 // Skip checking whether the pointer is inside the physical frame if the device is in
Harry Cutts1db43992023-06-19 17:05:07 +00001863 // unscaled or pointer mode.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001864 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
Harry Cutts8722be92024-04-05 14:46:05 +00001865 mDeviceMode != DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001866 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001867 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001868 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1869 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1870 if (virtualKey) {
1871 mCurrentVirtualKey.down = true;
1872 mCurrentVirtualKey.downTime = when;
1873 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1874 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1875 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001876 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1877 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001878
1879 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001880 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1881 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1882 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001883 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1884 AKEY_EVENT_ACTION_DOWN,
1885 AKEY_EVENT_FLAG_FROM_SYSTEM |
1886 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001887 }
1888 }
1889 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001890 outConsumed = true;
1891 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001892 }
1893 }
1894
1895 // Disable all virtual key touches that happen within a short time interval of the
1896 // most recent touch within the screen area. The idea is to filter out stray
1897 // virtual key presses when interacting with the touch screen.
1898 //
1899 // Problems we're trying to solve:
1900 //
1901 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1902 // virtual key area that is implemented by a separate touch panel and accidentally
1903 // triggers a virtual key.
1904 //
1905 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1906 // area and accidentally triggers a virtual key. This often happens when virtual keys
1907 // are layed out below the screen near to where the on screen keyboard's space bar
1908 // is displayed.
1909 if (mConfig.virtualKeyQuietTime > 0 &&
1910 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001911 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001912 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001913 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001914}
1915
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001916NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1917 uint32_t policyFlags, int32_t keyEventAction,
1918 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001919 int32_t keyCode = mCurrentVirtualKey.keyCode;
1920 int32_t scanCode = mCurrentVirtualKey.scanCode;
1921 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001922 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001923 policyFlags |= POLICY_FLAG_VIRTUAL;
1924
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001925 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1926 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1927 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001928}
1929
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001930std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1931 uint32_t policyFlags) {
1932 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001933 if (mCurrentMotionAborted) {
1934 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001935 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001936 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001937 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1938 if (!currentIdBits.isEmpty()) {
1939 int32_t metaState = getContext()->getGlobalMetaState();
1940 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001941 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001942 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1943 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001944 mCurrentCookedState.cookedPointerData.pointerProperties,
1945 mCurrentCookedState.cookedPointerData.pointerCoords,
1946 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1947 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1948 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001949 mCurrentMotionAborted = true;
1950 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001951 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001952}
1953
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001954// Updates pointer coords and properties for pointers with specified ids that have moved.
1955// Returns true if any of them changed.
1956static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1957 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1958 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1959 BitSet32 idBits) {
1960 bool changed = false;
1961 while (!idBits.isEmpty()) {
1962 uint32_t id = idBits.clearFirstMarkedBit();
1963 uint32_t inIndex = inIdToIndex[id];
1964 uint32_t outIndex = outIdToIndex[id];
1965
1966 const PointerProperties& curInProperties = inProperties[inIndex];
1967 const PointerCoords& curInCoords = inCoords[inIndex];
1968 PointerProperties& curOutProperties = outProperties[outIndex];
1969 PointerCoords& curOutCoords = outCoords[outIndex];
1970
1971 if (curInProperties != curOutProperties) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001972 curOutProperties = curInProperties;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001973 changed = true;
1974 }
1975
1976 if (curInCoords != curOutCoords) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001977 curOutCoords = curInCoords;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001978 changed = true;
1979 }
1980 }
1981 return changed;
1982}
1983
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001984std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1985 uint32_t policyFlags) {
1986 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001987 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1988 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1989 int32_t metaState = getContext()->getGlobalMetaState();
1990 int32_t buttonState = mCurrentCookedState.buttonState;
1991
1992 if (currentIdBits == lastIdBits) {
1993 if (!currentIdBits.isEmpty()) {
1994 // No pointer id changes so this is a move event.
1995 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001996 out.push_back(
1997 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1998 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1999 mCurrentCookedState.cookedPointerData.pointerProperties,
2000 mCurrentCookedState.cookedPointerData.pointerCoords,
2001 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2002 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2003 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002004 }
2005 } else {
2006 // There may be pointers going up and pointers going down and pointers moving
2007 // all at the same time.
2008 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2009 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2010 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2011 BitSet32 dispatchedIdBits(lastIdBits.value);
2012
2013 // Update last coordinates of pointers that have moved so that we observe the new
2014 // pointer positions at the same time as other pointers that have just gone up.
2015 bool moveNeeded =
2016 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2017 mCurrentCookedState.cookedPointerData.pointerCoords,
2018 mCurrentCookedState.cookedPointerData.idToIndex,
2019 mLastCookedState.cookedPointerData.pointerProperties,
2020 mLastCookedState.cookedPointerData.pointerCoords,
2021 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2022 if (buttonState != mLastCookedState.buttonState) {
2023 moveNeeded = true;
2024 }
2025
2026 // Dispatch pointer up events.
2027 while (!upIdBits.isEmpty()) {
2028 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002029 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002030 if (isCanceled) {
2031 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2032 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002033 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2034 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2035 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2036 buttonState, 0,
2037 mLastCookedState.cookedPointerData.pointerProperties,
2038 mLastCookedState.cookedPointerData.pointerCoords,
2039 mLastCookedState.cookedPointerData.idToIndex,
2040 dispatchedIdBits, upId, mOrientedXPrecision,
2041 mOrientedYPrecision, mDownTime,
2042 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002043 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002044 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002045 }
2046
2047 // Dispatch move events if any of the remaining pointers moved from their old locations.
2048 // Although applications receive new locations as part of individual pointer up
2049 // events, they do not generally handle them except when presented in a move event.
2050 if (moveNeeded && !moveIdBits.isEmpty()) {
2051 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002052 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2053 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2054 mCurrentCookedState.cookedPointerData.pointerProperties,
2055 mCurrentCookedState.cookedPointerData.pointerCoords,
2056 mCurrentCookedState.cookedPointerData.idToIndex,
2057 dispatchedIdBits, -1, mOrientedXPrecision,
2058 mOrientedYPrecision, mDownTime,
2059 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002060 }
2061
2062 // Dispatch pointer down events using the new pointer locations.
2063 while (!downIdBits.isEmpty()) {
2064 uint32_t downId = downIdBits.clearFirstMarkedBit();
2065 dispatchedIdBits.markBit(downId);
2066
2067 if (dispatchedIdBits.count() == 1) {
2068 // First pointer is going down. Set down time.
2069 mDownTime = when;
2070 }
2071
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002072 out.push_back(
2073 dispatchMotion(when, readTime, policyFlags, mSource,
2074 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2075 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2076 mCurrentCookedState.cookedPointerData.pointerCoords,
2077 mCurrentCookedState.cookedPointerData.idToIndex,
2078 dispatchedIdBits, downId, mOrientedXPrecision,
2079 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002080 }
2081 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002082 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002083}
2084
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002085std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2086 uint32_t policyFlags) {
2087 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002088 if (mSentHoverEnter &&
2089 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2090 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2091 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002092 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2093 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2094 mLastCookedState.buttonState, 0,
2095 mLastCookedState.cookedPointerData.pointerProperties,
2096 mLastCookedState.cookedPointerData.pointerCoords,
2097 mLastCookedState.cookedPointerData.idToIndex,
2098 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2099 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2100 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002101 mSentHoverEnter = false;
2102 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002103 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002104}
2105
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002106std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2107 uint32_t policyFlags) {
2108 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002109 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2110 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2111 int32_t metaState = getContext()->getGlobalMetaState();
2112 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002113 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2114 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2115 mCurrentRawState.buttonState, 0,
2116 mCurrentCookedState.cookedPointerData.pointerProperties,
2117 mCurrentCookedState.cookedPointerData.pointerCoords,
2118 mCurrentCookedState.cookedPointerData.idToIndex,
2119 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2120 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2121 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002122 mSentHoverEnter = true;
2123 }
2124
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002125 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2126 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2127 mCurrentRawState.buttonState, 0,
2128 mCurrentCookedState.cookedPointerData.pointerProperties,
2129 mCurrentCookedState.cookedPointerData.pointerCoords,
2130 mCurrentCookedState.cookedPointerData.idToIndex,
2131 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2132 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2133 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002134 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002135 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002136}
2137
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002138std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2139 uint32_t policyFlags) {
2140 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002141 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2142 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2143 const int32_t metaState = getContext()->getGlobalMetaState();
2144 int32_t buttonState = mLastCookedState.buttonState;
2145 while (!releasedButtons.isEmpty()) {
2146 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2147 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002148 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2149 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2150 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002151 mLastCookedState.cookedPointerData.pointerProperties,
2152 mLastCookedState.cookedPointerData.pointerCoords,
2153 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002154 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2155 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002156 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002157 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002158}
2159
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002160std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2161 uint32_t policyFlags) {
2162 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002163 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2164 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2165 const int32_t metaState = getContext()->getGlobalMetaState();
2166 int32_t buttonState = mLastCookedState.buttonState;
2167 while (!pressedButtons.isEmpty()) {
2168 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2169 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002170 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2171 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2172 buttonState, 0,
2173 mCurrentCookedState.cookedPointerData.pointerProperties,
2174 mCurrentCookedState.cookedPointerData.pointerCoords,
2175 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2176 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2177 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002178 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002179 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002180}
2181
LiZhihong758eb562022-11-03 15:28:29 +08002182std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2183 uint32_t policyFlags,
2184 BitSet32 idBits,
2185 nsecs_t readTime) {
2186 std::list<NotifyArgs> out;
2187 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2188 const int32_t metaState = getContext()->getGlobalMetaState();
2189 int32_t buttonState = mLastCookedState.buttonState;
2190
2191 while (!releasedButtons.isEmpty()) {
2192 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2193 buttonState &= ~actionButton;
2194 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2195 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2196 metaState, buttonState, 0,
2197 mPointerGesture.lastGestureProperties,
2198 mPointerGesture.lastGestureCoords,
2199 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2200 mOrientedXPrecision, mOrientedYPrecision,
2201 mPointerGesture.downTime, MotionClassification::NONE));
2202 }
2203 return out;
2204}
2205
2206std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2207 uint32_t policyFlags,
2208 BitSet32 idBits,
2209 nsecs_t readTime) {
2210 std::list<NotifyArgs> out;
2211 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2212 const int32_t metaState = getContext()->getGlobalMetaState();
2213 int32_t buttonState = mLastCookedState.buttonState;
2214
2215 while (!pressedButtons.isEmpty()) {
2216 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2217 buttonState |= actionButton;
2218 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2219 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2220 buttonState, 0, mPointerGesture.currentGestureProperties,
2221 mPointerGesture.currentGestureCoords,
2222 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2223 mOrientedXPrecision, mOrientedYPrecision,
2224 mPointerGesture.downTime, MotionClassification::NONE));
2225 }
2226 return out;
2227}
2228
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002229const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2230 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2231 return cookedPointerData.touchingIdBits;
2232 }
2233 return cookedPointerData.hoveringIdBits;
2234}
2235
2236void TouchInputMapper::cookPointerData() {
2237 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2238
2239 mCurrentCookedState.cookedPointerData.clear();
2240 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2241 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2242 mCurrentRawState.rawPointerData.hoveringIdBits;
2243 mCurrentCookedState.cookedPointerData.touchingIdBits =
2244 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002245 mCurrentCookedState.cookedPointerData.canceledIdBits =
2246 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002247
2248 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2249 mCurrentCookedState.buttonState = 0;
2250 } else {
2251 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2252 }
2253
2254 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002255 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002256 for (uint32_t i = 0; i < currentPointerCount; i++) {
2257 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2258
2259 // Size
2260 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2261 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002262 case Calibration::SizeCalibration::GEOMETRIC:
2263 case Calibration::SizeCalibration::DIAMETER:
2264 case Calibration::SizeCalibration::BOX:
2265 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002266 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2267 touchMajor = in.touchMajor;
2268 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2269 toolMajor = in.toolMajor;
2270 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2271 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2272 : in.touchMajor;
2273 } else if (mRawPointerAxes.touchMajor.valid) {
2274 toolMajor = touchMajor = in.touchMajor;
2275 toolMinor = touchMinor =
2276 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2277 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2278 : in.touchMajor;
2279 } else if (mRawPointerAxes.toolMajor.valid) {
2280 touchMajor = toolMajor = in.toolMajor;
2281 touchMinor = toolMinor =
2282 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2283 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2284 : in.toolMajor;
2285 } else {
2286 ALOG_ASSERT(false,
2287 "No touch or tool axes. "
2288 "Size calibration should have been resolved to NONE.");
2289 touchMajor = 0;
2290 touchMinor = 0;
2291 toolMajor = 0;
2292 toolMinor = 0;
2293 size = 0;
2294 }
2295
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002296 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2298 if (touchingCount > 1) {
2299 touchMajor /= touchingCount;
2300 touchMinor /= touchingCount;
2301 toolMajor /= touchingCount;
2302 toolMinor /= touchingCount;
2303 size /= touchingCount;
2304 }
2305 }
2306
Michael Wright227c5542020-07-02 18:30:52 +01002307 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002308 touchMajor *= mGeometricScale;
2309 touchMinor *= mGeometricScale;
2310 toolMajor *= mGeometricScale;
2311 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002312 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002313 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2314 touchMinor = touchMajor;
2315 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2316 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002317 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002318 touchMinor = touchMajor;
2319 toolMinor = toolMajor;
2320 }
2321
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002322 mCalibration.applySizeScaleAndBias(touchMajor);
2323 mCalibration.applySizeScaleAndBias(touchMinor);
2324 mCalibration.applySizeScaleAndBias(toolMajor);
2325 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002326 size *= mSizeScale;
2327 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002328 case Calibration::SizeCalibration::DEFAULT:
2329 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2330 break;
2331 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002332 touchMajor = 0;
2333 touchMinor = 0;
2334 toolMajor = 0;
2335 toolMinor = 0;
2336 size = 0;
2337 break;
2338 }
2339
2340 // Pressure
2341 float pressure;
2342 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002343 case Calibration::PressureCalibration::PHYSICAL:
2344 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002345 pressure = in.pressure * mPressureScale;
2346 break;
2347 default:
2348 pressure = in.isHovering ? 0 : 1;
2349 break;
2350 }
2351
2352 // Tilt and Orientation
2353 float tilt;
2354 float orientation;
2355 if (mHaveTilt) {
2356 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2357 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002358 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2360 } else {
2361 tilt = 0;
2362
2363 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002364 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002365 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 break;
Michael Wright227c5542020-07-02 18:30:52 +01002367 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2369 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2370 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002371 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 float confidence = hypotf(c1, c2);
2373 float scale = 1.0f + confidence / 16.0f;
2374 touchMajor *= scale;
2375 touchMinor /= scale;
2376 toolMajor *= scale;
2377 toolMinor /= scale;
2378 } else {
2379 orientation = 0;
2380 }
2381 break;
2382 }
2383 default:
2384 orientation = 0;
2385 }
2386 }
2387
2388 // Distance
2389 float distance;
2390 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002391 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002392 distance = in.distance * mDistanceScale;
2393 break;
2394 default:
2395 distance = 0;
2396 }
2397
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002398 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2399 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002400 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2401 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002403 // Write output coords.
2404 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2405 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002406 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2407 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002408 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2409 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2410 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2411 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2412 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2413 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2414 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002415 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2416 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002417
Chris Ye364fdb52020-08-05 15:07:56 -07002418 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002419 uint32_t id = in.id;
2420 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2421 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2422 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002423 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2424 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002425 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2426 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2427 }
2428
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002429 // Write output properties.
2430 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002431 properties.clear();
2432 properties.id = id;
2433 properties.toolType = in.toolType;
2434
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002435 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002437 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002438 }
2439}
2440
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002441std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2442 uint32_t policyFlags,
2443 PointerUsage pointerUsage) {
2444 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002446 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002447 mPointerUsage = pointerUsage;
2448 }
2449
2450 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002451 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002452 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002453 break;
Michael Wright227c5542020-07-02 18:30:52 +01002454 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002455 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 break;
Michael Wright227c5542020-07-02 18:30:52 +01002457 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002458 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002459 break;
Michael Wright227c5542020-07-02 18:30:52 +01002460 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 break;
2462 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002463 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464}
2465
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002466std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2467 uint32_t policyFlags) {
2468 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002470 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002471 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472 break;
Michael Wright227c5542020-07-02 18:30:52 +01002473 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002474 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002475 break;
Michael Wright227c5542020-07-02 18:30:52 +01002476 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002477 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 break;
Michael Wright227c5542020-07-02 18:30:52 +01002479 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002480 break;
2481 }
2482
Michael Wright227c5542020-07-02 18:30:52 +01002483 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002484 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002485}
2486
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002487std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2488 uint32_t policyFlags,
2489 bool isTimeout) {
2490 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002491 // Update current gesture coordinates.
2492 bool cancelPreviousGesture, finishPreviousGesture;
2493 bool sendEvents =
2494 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2495 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002496 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002497 }
2498 if (finishPreviousGesture) {
2499 cancelPreviousGesture = false;
2500 }
2501
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002502 // Send events!
2503 int32_t metaState = getContext()->getGlobalMetaState();
2504 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002505 const MotionClassification classification =
2506 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2507 ? MotionClassification::TWO_FINGER_SWIPE
2508 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002510 uint32_t flags = 0;
2511
2512 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2513 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2514 }
2515
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002516 // Update last coordinates of pointers that have moved so that we observe the new
2517 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002518 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2519 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2520 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2521 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2522 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2523 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 bool moveNeeded = false;
2525 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2526 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2527 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2528 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2529 mPointerGesture.lastGestureIdBits.value);
2530 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2531 mPointerGesture.currentGestureCoords,
2532 mPointerGesture.currentGestureIdToIndex,
2533 mPointerGesture.lastGestureProperties,
2534 mPointerGesture.lastGestureCoords,
2535 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2536 if (buttonState != mLastCookedState.buttonState) {
2537 moveNeeded = true;
2538 }
2539 }
2540
2541 // Send motion events for all pointers that went up or were canceled.
2542 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2543 if (!dispatchedGestureIdBits.isEmpty()) {
2544 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002545 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002546 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002547 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002548 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2549 mPointerGesture.lastGestureProperties,
2550 mPointerGesture.lastGestureCoords,
2551 mPointerGesture.lastGestureIdToIndex,
2552 dispatchedGestureIdBits, -1, 0, 0,
2553 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002554
2555 dispatchedGestureIdBits.clear();
2556 } else {
2557 BitSet32 upGestureIdBits;
2558 if (finishPreviousGesture) {
2559 upGestureIdBits = dispatchedGestureIdBits;
2560 } else {
2561 upGestureIdBits.value =
2562 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2563 }
2564 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002565 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2566 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2567 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2568 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2569 readTime);
2570 }
2571 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002572 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2573 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2574 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2575 mPointerGesture.lastGestureProperties,
2576 mPointerGesture.lastGestureCoords,
2577 mPointerGesture.lastGestureIdToIndex,
2578 dispatchedGestureIdBits, id, 0, 0,
2579 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002580
2581 dispatchedGestureIdBits.clearBit(id);
2582 }
2583 }
2584 }
2585
2586 // Send motion events for all pointers that moved.
2587 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002588 out.push_back(
2589 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2590 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2591 mPointerGesture.currentGestureProperties,
2592 mPointerGesture.currentGestureCoords,
2593 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2594 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002595 }
2596
2597 // Send motion events for all pointers that went down.
2598 if (down) {
2599 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2600 ~dispatchedGestureIdBits.value);
2601 while (!downGestureIdBits.isEmpty()) {
2602 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2603 dispatchedGestureIdBits.markBit(id);
2604
2605 if (dispatchedGestureIdBits.count() == 1) {
2606 mPointerGesture.downTime = when;
2607 }
2608
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002609 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2610 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2611 buttonState, 0, mPointerGesture.currentGestureProperties,
2612 mPointerGesture.currentGestureCoords,
2613 mPointerGesture.currentGestureIdToIndex,
2614 dispatchedGestureIdBits, id, 0, 0,
2615 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002616 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2617 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2618 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2619 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2620 readTime);
2621 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002622 }
2623 }
2624
2625 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002626 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002627 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2628 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2629 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2630 mPointerGesture.currentGestureProperties,
2631 mPointerGesture.currentGestureCoords,
2632 mPointerGesture.currentGestureIdToIndex,
2633 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2634 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002635 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2636 // Synthesize a hover move event after all pointers go up to indicate that
2637 // the pointer is hovering again even if the user is not currently touching
2638 // the touch pad. This ensures that a view will receive a fresh hover enter
2639 // event after a tap.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002640
2641 PointerProperties pointerProperties;
2642 pointerProperties.clear();
2643 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002644 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002645
2646 PointerCoords pointerCoords;
2647 pointerCoords.clear();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002648 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
Linnan Li13bf76a2024-05-05 19:18:02 +08002649 mSource, ui::ADISPLAY_ID_NONE, policyFlags,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002650 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2651 buttonState, MotionClassification::NONE,
2652 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002653 &pointerCoords, 0, 0, 0.f, 0.f, mPointerGesture.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00002654 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002655 }
2656
2657 // Update state.
2658 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2659 if (!down) {
2660 mPointerGesture.lastGestureIdBits.clear();
2661 } else {
2662 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2663 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2664 uint32_t id = idBits.clearFirstMarkedBit();
2665 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002666 mPointerGesture.lastGestureProperties[index] =
2667 mPointerGesture.currentGestureProperties[index];
2668 mPointerGesture.lastGestureCoords[index] = mPointerGesture.currentGestureCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002669 mPointerGesture.lastGestureIdToIndex[id] = index;
2670 }
2671 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002672 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002673}
2674
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002675std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2676 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002677 const MotionClassification classification =
2678 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2679 ? MotionClassification::TWO_FINGER_SWIPE
2680 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002681 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002682 // Cancel previously dispatches pointers.
2683 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2684 int32_t metaState = getContext()->getGlobalMetaState();
2685 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002686 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002687 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2688 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002689 mPointerGesture.lastGestureProperties,
2690 mPointerGesture.lastGestureCoords,
2691 mPointerGesture.lastGestureIdToIndex,
2692 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2693 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002694 }
2695
2696 // Reset the current pointer gesture.
2697 mPointerGesture.reset();
2698 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002699 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002700}
2701
2702bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2703 bool* outFinishPreviousGesture, bool isTimeout) {
2704 *outCancelPreviousGesture = false;
2705 *outFinishPreviousGesture = false;
2706
2707 // Handle TAP timeout.
2708 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002709 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002710
Michael Wright227c5542020-07-02 18:30:52 +01002711 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002712 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2713 // The tap/drag timeout has not yet expired.
2714 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2715 mConfig.pointerGestureTapDragInterval);
2716 } else {
2717 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002718 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002719 *outFinishPreviousGesture = true;
2720
2721 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002722 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002723 mPointerGesture.currentGestureIdBits.clear();
2724
2725 mPointerVelocityControl.reset();
2726 return true;
2727 }
2728 }
2729
2730 // We did not handle this timeout.
2731 return false;
2732 }
2733
2734 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2735 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2736
2737 // Update the velocity tracker.
2738 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002739 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002740 uint32_t id = idBits.clearFirstMarkedBit();
2741 const RawPointerData::Pointer& pointer =
2742 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002743 const float x = pointer.x * mPointerXMovementScale;
2744 const float y = pointer.y * mPointerYMovementScale;
2745 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2746 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002747 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002748 }
2749
2750 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2751 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002752 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2753 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2754 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002755 mPointerGesture.resetTap();
2756 }
2757
2758 // Pick a new active touch id if needed.
2759 // Choose an arbitrary pointer that just went down, if there is one.
2760 // Otherwise choose an arbitrary remaining pointer.
2761 // This guarantees we always have an active touch id when there is at least one pointer.
2762 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002763 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002764 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002765 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002766 mPointerGesture.firstTouchTime = when;
2767 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002768 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2769 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2770 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2771 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002772 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002773 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002774
2775 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002776 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002777 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002778 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2779 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2780 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002781 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002782 *outFinishPreviousGesture = true;
2783 }
2784
2785 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002786 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002787 mPointerGesture.currentGestureIdBits.clear();
2788
2789 mPointerVelocityControl.reset();
2790 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2791 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2792 // The pointer follows the active touch point.
2793 // Emit DOWN, MOVE, UP events at the pointer location.
2794 //
2795 // Only the active touch matters; other fingers are ignored. This policy helps
2796 // to handle the case where the user places a second finger on the touch pad
2797 // to apply the necessary force to depress an integrated button below the surface.
2798 // We don't want the second finger to be delivered to applications.
2799 //
2800 // For this to work well, we need to make sure to track the pointer that is really
2801 // active. If the user first puts one finger down to click then adds another
2802 // finger to drag then the active pointer should switch to the finger that is
2803 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002804 ALOGD_IF(DEBUG_GESTURES,
2805 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2806 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002807 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002808 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002809 *outFinishPreviousGesture = true;
2810 mPointerGesture.activeGestureId = 0;
2811 }
2812
2813 // Switch pointers if needed.
2814 // Find the fastest pointer and follow it.
2815 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002816 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002817 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002818 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002819 ALOGD_IF(DEBUG_GESTURES,
2820 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2821 "bestSpeed=%0.3f",
2822 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002823 }
2824 }
2825
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002826 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002827 // When using spots, the click will occur at the position of the anchor
2828 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002829 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 } else {
2831 mPointerVelocityControl.reset();
2832 }
2833
Michael Wright227c5542020-07-02 18:30:52 +01002834 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002835 mPointerGesture.currentGestureIdBits.clear();
2836 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2837 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2838 mPointerGesture.currentGestureProperties[0].clear();
2839 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002840 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002841 mPointerGesture.currentGestureCoords[0].clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002842 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2843 } else if (currentFingerCount == 0) {
2844 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002845 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002846 *outFinishPreviousGesture = true;
2847 }
2848
2849 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2850 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2851 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002852 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2853 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 lastFingerCount == 1) {
2855 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002856 if (fabs(0.f - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2857 fabs(0.f - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002858 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002859
2860 mPointerGesture.tapUpTime = when;
2861 getContext()->requestTimeoutAtTime(when +
2862 mConfig.pointerGestureTapDragInterval);
2863
2864 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002865 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002866 mPointerGesture.currentGestureIdBits.clear();
2867 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2868 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2869 mPointerGesture.currentGestureProperties[0].clear();
2870 mPointerGesture.currentGestureProperties[0].id =
2871 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002872 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002873 mPointerGesture.currentGestureCoords[0].clear();
2874 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2875 mPointerGesture.tapX);
2876 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2877 mPointerGesture.tapY);
2878 mPointerGesture.currentGestureCoords[0]
2879 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2880
2881 tapped = true;
2882 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002883 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002884 0.f - mPointerGesture.tapX, 0.f - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002885 }
2886 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002887 if (DEBUG_GESTURES) {
2888 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2889 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2890 (when - mPointerGesture.tapDownTime) * 0.000001f);
2891 } else {
2892 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2893 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002894 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895 }
2896 }
2897
2898 mPointerVelocityControl.reset();
2899
2900 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002901 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002902 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002903 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002904 mPointerGesture.currentGestureIdBits.clear();
2905 }
2906 } else if (currentFingerCount == 1) {
2907 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2908 // The pointer follows the active touch point.
2909 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2910 // When in TAP_DRAG, emit MOVE events at the pointer location.
2911 ALOG_ASSERT(activeTouchId >= 0);
2912
Michael Wright227c5542020-07-02 18:30:52 +01002913 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2914 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002915 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002916 if (fabs(0.f - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2917 fabs(0.f - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002918 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002920 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002921 0.f - mPointerGesture.tapX, 0.f - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 }
2923 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002924 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2925 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002926 }
Michael Wright227c5542020-07-02 18:30:52 +01002927 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2928 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002929 }
2930
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002931 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002932 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002933 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002934 } else {
2935 mPointerVelocityControl.reset();
2936 }
2937
2938 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002939 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002940 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002941 down = true;
2942 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002943 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002944 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002945 *outFinishPreviousGesture = true;
2946 }
2947 mPointerGesture.activeGestureId = 0;
2948 down = false;
2949 }
2950
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002951 mPointerGesture.currentGestureIdBits.clear();
2952 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2953 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2954 mPointerGesture.currentGestureProperties[0].clear();
2955 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002956 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002957 mPointerGesture.currentGestureCoords[0].clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002958 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2959 down ? 1.0f : 0.0f);
2960
2961 if (lastFingerCount == 0 && currentFingerCount != 0) {
2962 mPointerGesture.resetTap();
2963 mPointerGesture.tapDownTime = when;
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002964 mPointerGesture.tapX = 0.f;
2965 mPointerGesture.tapY = 0.f;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002966 }
2967 } else {
2968 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002969 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002970 }
2971
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002972 if (DEBUG_GESTURES) {
2973 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00002974 "currentGestureMode=%s, currentGestureIdBits=0x%08x, "
2975 "lastGestureMode=%s, lastGestureIdBits=0x%08x",
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002976 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00002977 ftl::enum_string(mPointerGesture.currentGestureMode).c_str(),
2978 mPointerGesture.currentGestureIdBits.value,
2979 ftl::enum_string(mPointerGesture.lastGestureMode).c_str(),
2980 mPointerGesture.lastGestureIdBits.value);
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002981 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
2982 uint32_t id = idBits.clearFirstMarkedBit();
2983 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2984 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
2985 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002986 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002987 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002988 id, index, ftl::enum_string(properties.toolType).c_str(),
2989 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002990 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
2991 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
2992 }
2993 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
2994 uint32_t id = idBits.clearFirstMarkedBit();
2995 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
2996 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
2997 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002998 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002999 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003000 id, index, ftl::enum_string(properties.toolType).c_str(),
3001 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003002 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3003 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3004 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003005 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003006 return true;
3007}
3008
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003009bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3010 if (mPointerGesture.activeTouchId < 0) {
3011 mPointerGesture.resetQuietTime();
3012 return false;
3013 }
3014
3015 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3016 return true;
3017 }
3018
3019 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3020 bool isQuietTime = false;
3021 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3022 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3023 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3024 currentFingerCount < 2) {
3025 // Enter quiet time when exiting swipe or freeform state.
3026 // This is to prevent accidentally entering the hover state and flinging the
3027 // pointer when finishing a swipe and there is still one pointer left onscreen.
3028 isQuietTime = true;
3029 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3030 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3031 // Enter quiet time when releasing the button and there are still two or more
3032 // fingers down. This may indicate that one finger was used to press the button
3033 // but it has not gone up yet.
3034 isQuietTime = true;
3035 }
3036 if (isQuietTime) {
3037 mPointerGesture.quietTime = when;
3038 }
3039 return isQuietTime;
3040}
3041
3042std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3043 int32_t bestId = -1;
3044 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3045 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3046 uint32_t id = idBits.clearFirstMarkedBit();
3047 std::optional<float> vx =
3048 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3049 std::optional<float> vy =
3050 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3051 if (vx && vy) {
3052 float speed = hypotf(*vx, *vy);
3053 if (speed > bestSpeed) {
3054 bestId = id;
3055 bestSpeed = speed;
3056 }
3057 }
3058 }
3059 return std::make_pair(bestId, bestSpeed);
3060}
3061
3062void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3063 bool* finishPreviousGesture) {
3064 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3065 // to move before deciding what to do.
3066 //
3067 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3068 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3069 // just a press or long-press at the pointer location.
3070 //
3071 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3072 // pointer location.
3073 //
3074 // When the two fingers move enough or when additional fingers are added, we make a decision to
3075 // transition into SWIPE or FREEFORM mode accordingly.
3076 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3077 ALOG_ASSERT(activeTouchId >= 0);
3078
3079 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3080 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3081 bool settled =
3082 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3083 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3084 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3085 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3086 *finishPreviousGesture = true;
3087 } else if (!settled && currentFingerCount > lastFingerCount) {
3088 // Additional pointers have gone down but not yet settled.
3089 // Reset the gesture.
3090 ALOGD_IF(DEBUG_GESTURES,
3091 "Gestures: Resetting gesture since additional pointers went down for "
3092 "MULTITOUCH, settle time remaining %0.3fms",
3093 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3094 when) * 0.000001f);
3095 *cancelPreviousGesture = true;
3096 } else {
3097 // Continue previous gesture.
3098 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3099 }
3100
3101 if (*finishPreviousGesture || *cancelPreviousGesture) {
3102 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3103 mPointerGesture.activeGestureId = 0;
3104 mPointerGesture.referenceIdBits.clear();
3105 mPointerVelocityControl.reset();
3106
3107 // Use the centroid and pointer location as the reference points for the gesture.
3108 ALOGD_IF(DEBUG_GESTURES,
3109 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3110 "%0.3fms",
3111 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3112 when) * 0.000001f);
3113 mCurrentRawState.rawPointerData
3114 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3115 &mPointerGesture.referenceTouchY);
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00003116 mPointerGesture.referenceGestureX = 0.f;
3117 mPointerGesture.referenceGestureY = 0.f;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003118 }
3119
3120 // Clear the reference deltas for fingers not yet included in the reference calculation.
3121 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3122 ~mPointerGesture.referenceIdBits.value);
3123 !idBits.isEmpty();) {
3124 uint32_t id = idBits.clearFirstMarkedBit();
3125 mPointerGesture.referenceDeltas[id].dx = 0;
3126 mPointerGesture.referenceDeltas[id].dy = 0;
3127 }
3128 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3129
3130 // Add delta for all fingers and calculate a common movement delta.
3131 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3132 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3133 mCurrentCookedState.fingerIdBits.value);
3134 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3135 bool first = (idBits == commonIdBits);
3136 uint32_t id = idBits.clearFirstMarkedBit();
3137 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3138 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3139 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3140 delta.dx += cpd.x - lpd.x;
3141 delta.dy += cpd.y - lpd.y;
3142
3143 if (first) {
3144 commonDeltaRawX = delta.dx;
3145 commonDeltaRawY = delta.dy;
3146 } else {
3147 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3148 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3149 }
3150 }
3151
3152 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3153 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3154 float dist[MAX_POINTER_ID + 1];
3155 int32_t distOverThreshold = 0;
3156 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3157 uint32_t id = idBits.clearFirstMarkedBit();
3158 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3159 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3160 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3161 distOverThreshold += 1;
3162 }
3163 }
3164
3165 // Only transition when at least two pointers have moved further than
3166 // the minimum distance threshold.
3167 if (distOverThreshold >= 2) {
3168 if (currentFingerCount > 2) {
3169 // There are more than two pointers, switch to FREEFORM.
3170 ALOGD_IF(DEBUG_GESTURES,
3171 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3172 currentFingerCount);
3173 *cancelPreviousGesture = true;
3174 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3175 } else {
3176 // There are exactly two pointers.
3177 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3178 uint32_t id1 = idBits.clearFirstMarkedBit();
3179 uint32_t id2 = idBits.firstMarkedBit();
3180 const RawPointerData::Pointer& p1 =
3181 mCurrentRawState.rawPointerData.pointerForId(id1);
3182 const RawPointerData::Pointer& p2 =
3183 mCurrentRawState.rawPointerData.pointerForId(id2);
3184 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3185 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3186 // There are two pointers but they are too far apart for a SWIPE,
3187 // switch to FREEFORM.
3188 ALOGD_IF(DEBUG_GESTURES,
3189 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3190 mutualDistance, mPointerGestureMaxSwipeWidth);
3191 *cancelPreviousGesture = true;
3192 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3193 } else {
3194 // There are two pointers. Wait for both pointers to start moving
3195 // before deciding whether this is a SWIPE or FREEFORM gesture.
3196 float dist1 = dist[id1];
3197 float dist2 = dist[id2];
3198 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3199 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3200 // Calculate the dot product of the displacement vectors.
3201 // When the vectors are oriented in approximately the same direction,
3202 // the angle betweeen them is near zero and the cosine of the angle
3203 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3204 // mag(v2).
3205 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3206 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3207 float dx1 = delta1.dx * mPointerXZoomScale;
3208 float dy1 = delta1.dy * mPointerYZoomScale;
3209 float dx2 = delta2.dx * mPointerXZoomScale;
3210 float dy2 = delta2.dy * mPointerYZoomScale;
3211 float dot = dx1 * dx2 + dy1 * dy2;
3212 float cosine = dot / (dist1 * dist2); // denominator always > 0
3213 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3214 // Pointers are moving in the same direction. Switch to SWIPE.
3215 ALOGD_IF(DEBUG_GESTURES,
3216 "Gestures: PRESS transitioned to SWIPE, "
3217 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3218 "cosine %0.3f >= %0.3f",
3219 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3220 mConfig.pointerGestureMultitouchMinDistance, cosine,
3221 mConfig.pointerGestureSwipeTransitionAngleCosine);
3222 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3223 } else {
3224 // Pointers are moving in different directions. Switch to FREEFORM.
3225 ALOGD_IF(DEBUG_GESTURES,
3226 "Gestures: PRESS transitioned to FREEFORM, "
3227 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3228 "cosine %0.3f < %0.3f",
3229 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3230 mConfig.pointerGestureMultitouchMinDistance, cosine,
3231 mConfig.pointerGestureSwipeTransitionAngleCosine);
3232 *cancelPreviousGesture = true;
3233 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3234 }
3235 }
3236 }
3237 }
3238 }
3239 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3240 // Switch from SWIPE to FREEFORM if additional pointers go down.
3241 // Cancel previous gesture.
3242 if (currentFingerCount > 2) {
3243 ALOGD_IF(DEBUG_GESTURES,
3244 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3245 currentFingerCount);
3246 *cancelPreviousGesture = true;
3247 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3248 }
3249 }
3250
3251 // Move the reference points based on the overall group motion of the fingers
3252 // except in PRESS mode while waiting for a transition to occur.
3253 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3254 (commonDeltaRawX || commonDeltaRawY)) {
3255 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3256 uint32_t id = idBits.clearFirstMarkedBit();
3257 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3258 delta.dx = 0;
3259 delta.dy = 0;
3260 }
3261
3262 mPointerGesture.referenceTouchX += commonDeltaRawX;
3263 mPointerGesture.referenceTouchY += commonDeltaRawY;
3264
3265 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3266 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3267
3268 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3269 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3270
3271 mPointerGesture.referenceGestureX += commonDeltaX;
3272 mPointerGesture.referenceGestureY += commonDeltaY;
3273 }
3274
3275 // Report gestures.
3276 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3277 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3278 // PRESS or SWIPE mode.
3279 ALOGD_IF(DEBUG_GESTURES,
3280 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3281 "currentTouchPointerCount=%d",
3282 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3283 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3284
3285 mPointerGesture.currentGestureIdBits.clear();
3286 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3287 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3288 mPointerGesture.currentGestureProperties[0].clear();
3289 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003290 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003291 mPointerGesture.currentGestureCoords[0].clear();
3292 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3293 mPointerGesture.referenceGestureX);
3294 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3295 mPointerGesture.referenceGestureY);
3296 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3297 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3298 float xOffset = static_cast<float>(commonDeltaRawX) /
3299 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3300 float yOffset = static_cast<float>(commonDeltaRawY) /
3301 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3302 mPointerGesture.currentGestureCoords[0]
3303 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3304 mPointerGesture.currentGestureCoords[0]
3305 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3306 }
3307 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3308 // FREEFORM mode.
3309 ALOGD_IF(DEBUG_GESTURES,
3310 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3311 "currentTouchPointerCount=%d",
3312 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3313 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3314
3315 mPointerGesture.currentGestureIdBits.clear();
3316
3317 BitSet32 mappedTouchIdBits;
3318 BitSet32 usedGestureIdBits;
3319 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3320 // Initially, assign the active gesture id to the active touch point
3321 // if there is one. No other touch id bits are mapped yet.
3322 if (!*cancelPreviousGesture) {
3323 mappedTouchIdBits.markBit(activeTouchId);
3324 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3325 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3326 mPointerGesture.activeGestureId;
3327 } else {
3328 mPointerGesture.activeGestureId = -1;
3329 }
3330 } else {
3331 // Otherwise, assume we mapped all touches from the previous frame.
3332 // Reuse all mappings that are still applicable.
3333 mappedTouchIdBits.value =
3334 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3335 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3336
3337 // Check whether we need to choose a new active gesture id because the
3338 // current went went up.
3339 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3340 ~mCurrentCookedState.fingerIdBits.value);
3341 !upTouchIdBits.isEmpty();) {
3342 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3343 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3344 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3345 mPointerGesture.activeGestureId = -1;
3346 break;
3347 }
3348 }
3349 }
3350
3351 ALOGD_IF(DEBUG_GESTURES,
3352 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3353 "activeGestureId=%d",
3354 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3355
3356 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3357 for (uint32_t i = 0; i < currentFingerCount; i++) {
3358 uint32_t touchId = idBits.clearFirstMarkedBit();
3359 uint32_t gestureId;
3360 if (!mappedTouchIdBits.hasBit(touchId)) {
3361 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3362 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3363 ALOGD_IF(DEBUG_GESTURES,
3364 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3365 gestureId);
3366 } else {
3367 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3368 ALOGD_IF(DEBUG_GESTURES,
3369 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3370 touchId, gestureId);
3371 }
3372 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3373 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3374
3375 const RawPointerData::Pointer& pointer =
3376 mCurrentRawState.rawPointerData.pointerForId(touchId);
3377 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3378 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3379 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3380
3381 mPointerGesture.currentGestureProperties[i].clear();
3382 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003383 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003384 mPointerGesture.currentGestureCoords[i].clear();
3385 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3386 mPointerGesture.referenceGestureX +
3387 deltaX);
3388 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3389 mPointerGesture.referenceGestureY +
3390 deltaY);
3391 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3392 }
3393
3394 if (mPointerGesture.activeGestureId < 0) {
3395 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3396 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3397 mPointerGesture.activeGestureId);
3398 }
3399 }
3400}
3401
Harry Cutts714d1ad2022-08-24 16:36:43 +00003402void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3403 const RawPointerData::Pointer& currentPointer =
3404 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3405 const RawPointerData::Pointer& lastPointer =
3406 mLastRawState.rawPointerData.pointerForId(pointerId);
3407 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3408 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3409
3410 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3411 mPointerVelocityControl.move(when, &deltaX, &deltaY);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003412}
3413
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003414std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3415 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003416 mPointerSimple.currentCoords.clear();
3417 mPointerSimple.currentProperties.clear();
3418
3419 bool down, hovering;
3420 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3421 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3422 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003423 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3424 down = !hovering;
3425
Prabir Pradhane71e5702023-03-29 14:51:38 +00003426 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3427 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Prabir Pradhane71e5702023-03-29 14:51:38 +00003428
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003429 mPointerSimple.currentCoords = mCurrentCookedState.cookedPointerData.pointerCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003430 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3431 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3432 mPointerSimple.currentProperties.id = 0;
3433 mPointerSimple.currentProperties.toolType =
3434 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3435 } else {
3436 down = false;
3437 hovering = false;
3438 }
3439
Prabir Pradhane71e5702023-03-29 14:51:38 +00003440 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003441}
3442
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003443std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3444 uint32_t policyFlags) {
3445 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003446}
3447
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003448std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3449 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003450 mPointerSimple.currentCoords.clear();
3451 mPointerSimple.currentProperties.clear();
3452
3453 bool down, hovering;
3454 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3455 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003456 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003457 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003458 } else {
3459 mPointerVelocityControl.reset();
3460 }
3461
3462 down = isPointerDown(mCurrentRawState.buttonState);
3463 hovering = !down;
3464
Prabir Pradhan2719e822023-02-28 17:39:36 +00003465 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003466 mPointerSimple.currentCoords =
3467 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003468 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3469 hovering ? 0.0f : 1.0f);
3470 mPointerSimple.currentProperties.id = 0;
3471 mPointerSimple.currentProperties.toolType =
3472 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3473 } else {
3474 mPointerVelocityControl.reset();
3475
3476 down = false;
3477 hovering = false;
3478 }
3479
Linnan Li13bf76a2024-05-05 19:18:02 +08003480 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, ui::ADISPLAY_ID_NONE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003481}
3482
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003483std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3484 uint32_t policyFlags) {
3485 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003486
3487 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003488
3489 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003490}
3491
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003492std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3493 uint32_t policyFlags, bool down,
Linnan Li13bf76a2024-05-05 19:18:02 +08003494 bool hovering,
3495 ui::LogicalDisplayId displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003496 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3497 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003498 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003499 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003500 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003501
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003502 if (mPointerSimple.down && !down) {
3503 mPointerSimple.down = false;
3504
3505 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003506 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3507 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3508 0, metaState, mLastRawState.buttonState,
3509 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3510 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003511 mOrientedXPrecision, mOrientedYPrecision,
3512 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3513 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003514 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515 }
3516
3517 if (mPointerSimple.hovering && !hovering) {
3518 mPointerSimple.hovering = false;
3519
3520 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003521 out.push_back(
3522 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3523 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3524 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3525 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3526 &mPointerSimple.lastCoords, mOrientedXPrecision,
3527 mOrientedYPrecision, mPointerSimple.lastCursorX,
3528 mPointerSimple.lastCursorY, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003529 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003530 }
3531
3532 if (down) {
3533 if (!mPointerSimple.down) {
3534 mPointerSimple.down = true;
3535 mPointerSimple.downTime = when;
3536
3537 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003538 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3539 mSource, displayId, policyFlags,
3540 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3541 mCurrentRawState.buttonState, MotionClassification::NONE,
3542 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3543 &mPointerSimple.currentProperties,
3544 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003545 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003546 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003547 }
3548
3549 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003550 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3551 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3552 0, 0, metaState, mCurrentRawState.buttonState,
3553 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3554 &mPointerSimple.currentProperties,
3555 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003556 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003557 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003558 }
3559
3560 if (hovering) {
3561 if (!mPointerSimple.hovering) {
3562 mPointerSimple.hovering = true;
3563
3564 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003565 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3566 mSource, displayId, policyFlags,
3567 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3568 mCurrentRawState.buttonState, MotionClassification::NONE,
3569 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3570 &mPointerSimple.currentProperties,
3571 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003572 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003573 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003574 }
3575
3576 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003577 out.push_back(
3578 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3579 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3580 metaState, mCurrentRawState.buttonState,
3581 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3582 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003583 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003584 cursorPosition.y, mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003585 }
3586
3587 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3588 float vscroll = mCurrentRawState.rawVScroll;
3589 float hscroll = mCurrentRawState.rawHScroll;
3590 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3591 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3592
3593 // Send scroll.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003594 PointerCoords pointerCoords = mPointerSimple.currentCoords;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003595 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3596 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3597
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003598 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3599 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3600 0, 0, metaState, mCurrentRawState.buttonState,
3601 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3602 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003603 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3604 cursorPosition.y, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003605 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003606 }
3607
3608 // Save state.
3609 if (down || hovering) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003610 mPointerSimple.lastCoords = mPointerSimple.currentCoords;
3611 mPointerSimple.lastProperties = mPointerSimple.currentProperties;
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003612 mPointerSimple.displayId = displayId;
3613 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003614 mPointerSimple.lastCursorX = cursorPosition.x;
3615 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003616 } else {
3617 mPointerSimple.reset();
3618 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003619 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003620}
3621
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003622std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3623 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003624 std::list<NotifyArgs> out;
3625 if (mPointerSimple.down || mPointerSimple.hovering) {
3626 int32_t metaState = getContext()->getGlobalMetaState();
3627 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3628 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3629 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3630 metaState, mLastRawState.buttonState,
3631 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3632 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3633 mOrientedXPrecision, mOrientedYPrecision,
3634 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3635 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003636 /*videoFrames=*/{}));
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003637 }
3638 mPointerSimple.reset();
3639 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003640}
3641
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003642NotifyMotionArgs TouchInputMapper::dispatchMotion(
3643 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3644 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003645 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3646 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003647 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003648 std::vector<PointerCoords> pointerCoords;
3649 std::vector<PointerProperties> pointerProperties;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003650 uint32_t pointerCount = 0;
3651 while (!idBits.isEmpty()) {
3652 uint32_t id = idBits.clearFirstMarkedBit();
3653 uint32_t index = idToIndex[id];
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003654 pointerProperties.push_back(properties[index]);
3655 pointerCoords.push_back(coords[index]);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003656
3657 if (changedId >= 0 && id == uint32_t(changedId)) {
3658 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3659 }
3660
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003661 pointerCount++;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003662 }
3663
3664 ALOG_ASSERT(pointerCount != 0);
3665
3666 if (changedId >= 0 && pointerCount == 1) {
3667 // Replace initial down and final up action.
3668 // We can compare the action without masking off the changed pointer index
3669 // because we know the index is 0.
3670 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3671 action = AMOTION_EVENT_ACTION_DOWN;
3672 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003673 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3674 action = AMOTION_EVENT_ACTION_CANCEL;
3675 } else {
3676 action = AMOTION_EVENT_ACTION_UP;
3677 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003678 } else {
3679 // Can't happen.
3680 ALOG_ASSERT(false);
3681 }
3682 }
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00003683 if (mCurrentStreamModifiedByExternalStylus) {
3684 source |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3685 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003686
Linnan Li13bf76a2024-05-05 19:18:02 +08003687 const ui::LogicalDisplayId displayId = getAssociatedDisplayId().value_or(ui::ADISPLAY_ID_NONE);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003688
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003689 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3690 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003691 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00003692 xCursorPosition = yCursorPosition = 0.f;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003693 }
Linnan Li13bf76a2024-05-05 19:18:02 +08003694 const DeviceId deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003695 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003696 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003697 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003698 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3699 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003700 classification, edgeFlags, pointerCount, pointerProperties.data(),
3701 pointerCoords.data(), xPrecision, yPrecision, xCursorPosition,
3702 yCursorPosition, downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003703}
3704
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003705std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3706 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003707 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3708 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003709 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003710}
3711
Prabir Pradhan1728b212021-10-19 16:00:03 -07003712bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003713 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003714 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003715 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003716}
3717
3718const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3719 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003720 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3721 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3722 "left=%d, top=%d, right=%d, bottom=%d",
3723 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3724 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003725
3726 if (virtualKey.isHit(x, y)) {
3727 return &virtualKey;
3728 }
3729 }
3730
3731 return nullptr;
3732}
3733
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003734void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3735 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3736 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003737
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003738 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003739
3740 if (currentPointerCount == 0) {
3741 // No pointers to assign.
3742 return;
3743 }
3744
3745 if (lastPointerCount == 0) {
3746 // All pointers are new.
3747 for (uint32_t i = 0; i < currentPointerCount; i++) {
3748 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003749 current.rawPointerData.pointers[i].id = id;
3750 current.rawPointerData.idToIndex[id] = i;
3751 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003752 }
3753 return;
3754 }
3755
3756 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003757 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003758 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003759 uint32_t id = last.rawPointerData.pointers[0].id;
3760 current.rawPointerData.pointers[0].id = id;
3761 current.rawPointerData.idToIndex[id] = 0;
3762 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003763 return;
3764 }
3765
3766 // General case.
3767 // We build a heap of squared euclidean distances between current and last pointers
3768 // associated with the current and last pointer indices. Then, we find the best
3769 // match (by distance) for each current pointer.
3770 // The pointers must have the same tool type but it is possible for them to
3771 // transition from hovering to touching or vice-versa while retaining the same id.
3772 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3773
3774 uint32_t heapSize = 0;
3775 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3776 currentPointerIndex++) {
3777 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3778 lastPointerIndex++) {
3779 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003780 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003781 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003782 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003783 if (currentPointer.toolType == lastPointer.toolType) {
3784 int64_t deltaX = currentPointer.x - lastPointer.x;
3785 int64_t deltaY = currentPointer.y - lastPointer.y;
3786
3787 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3788
3789 // Insert new element into the heap (sift up).
3790 heap[heapSize].currentPointerIndex = currentPointerIndex;
3791 heap[heapSize].lastPointerIndex = lastPointerIndex;
3792 heap[heapSize].distance = distance;
3793 heapSize += 1;
3794 }
3795 }
3796 }
3797
3798 // Heapify
3799 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3800 startIndex -= 1;
3801 for (uint32_t parentIndex = startIndex;;) {
3802 uint32_t childIndex = parentIndex * 2 + 1;
3803 if (childIndex >= heapSize) {
3804 break;
3805 }
3806
3807 if (childIndex + 1 < heapSize &&
3808 heap[childIndex + 1].distance < heap[childIndex].distance) {
3809 childIndex += 1;
3810 }
3811
3812 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3813 break;
3814 }
3815
3816 swap(heap[parentIndex], heap[childIndex]);
3817 parentIndex = childIndex;
3818 }
3819 }
3820
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003821 if (DEBUG_POINTER_ASSIGNMENT) {
3822 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3823 for (size_t i = 0; i < heapSize; i++) {
3824 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3825 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3826 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003827 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003828
3829 // Pull matches out by increasing order of distance.
3830 // To avoid reassigning pointers that have already been matched, the loop keeps track
3831 // of which last and current pointers have been matched using the matchedXXXBits variables.
3832 // It also tracks the used pointer id bits.
3833 BitSet32 matchedLastBits(0);
3834 BitSet32 matchedCurrentBits(0);
3835 BitSet32 usedIdBits(0);
3836 bool first = true;
3837 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3838 while (heapSize > 0) {
3839 if (first) {
3840 // The first time through the loop, we just consume the root element of
3841 // the heap (the one with smallest distance).
3842 first = false;
3843 } else {
3844 // Previous iterations consumed the root element of the heap.
3845 // Pop root element off of the heap (sift down).
3846 heap[0] = heap[heapSize];
3847 for (uint32_t parentIndex = 0;;) {
3848 uint32_t childIndex = parentIndex * 2 + 1;
3849 if (childIndex >= heapSize) {
3850 break;
3851 }
3852
3853 if (childIndex + 1 < heapSize &&
3854 heap[childIndex + 1].distance < heap[childIndex].distance) {
3855 childIndex += 1;
3856 }
3857
3858 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3859 break;
3860 }
3861
3862 swap(heap[parentIndex], heap[childIndex]);
3863 parentIndex = childIndex;
3864 }
3865
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003866 if (DEBUG_POINTER_ASSIGNMENT) {
3867 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3868 for (size_t j = 0; j < heapSize; j++) {
3869 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3870 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3871 heap[j].distance);
3872 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003873 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003874 }
3875
3876 heapSize -= 1;
3877
3878 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3879 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3880
3881 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3882 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3883
3884 matchedCurrentBits.markBit(currentPointerIndex);
3885 matchedLastBits.markBit(lastPointerIndex);
3886
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003887 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3888 current.rawPointerData.pointers[currentPointerIndex].id = id;
3889 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3890 current.rawPointerData.markIdBit(id,
3891 current.rawPointerData.isHovering(
3892 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003893 usedIdBits.markBit(id);
3894
Harry Cutts45483602022-08-24 14:36:48 +00003895 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3896 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3897 ", distance=%" PRIu64,
3898 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003899 break;
3900 }
3901 }
3902
3903 // Assign fresh ids to pointers that were not matched in the process.
3904 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3905 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3906 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3907
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003908 current.rawPointerData.pointers[currentPointerIndex].id = id;
3909 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3910 current.rawPointerData.markIdBit(id,
3911 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003912
Harry Cutts45483602022-08-24 14:36:48 +00003913 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3914 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
3915 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003916 }
3917}
3918
3919int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3920 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3921 return AKEY_STATE_VIRTUAL;
3922 }
3923
3924 for (const VirtualKey& virtualKey : mVirtualKeys) {
3925 if (virtualKey.keyCode == keyCode) {
3926 return AKEY_STATE_UP;
3927 }
3928 }
3929
3930 return AKEY_STATE_UNKNOWN;
3931}
3932
3933int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3934 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3935 return AKEY_STATE_VIRTUAL;
3936 }
3937
3938 for (const VirtualKey& virtualKey : mVirtualKeys) {
3939 if (virtualKey.scanCode == scanCode) {
3940 return AKEY_STATE_UP;
3941 }
3942 }
3943
3944 return AKEY_STATE_UNKNOWN;
3945}
3946
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003947bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
3948 const std::vector<int32_t>& keyCodes,
3949 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003950 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003951 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003952 if (virtualKey.keyCode == keyCodes[i]) {
3953 outFlags[i] = 1;
3954 }
3955 }
3956 }
3957
3958 return true;
3959}
3960
Linnan Li13bf76a2024-05-05 19:18:02 +08003961std::optional<ui::LogicalDisplayId> TouchInputMapper::getAssociatedDisplayId() {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003962 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003963 if (mDeviceMode == DeviceMode::POINTER) {
Linnan Li13bf76a2024-05-05 19:18:02 +08003964 return ui::ADISPLAY_ID_NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003965 } else {
3966 return std::make_optional(mViewport.displayId);
3967 }
3968 }
3969 return std::nullopt;
3970}
3971
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003972} // namespace android