blob: 9d049ae78081f86fb5b7c63425b7b3eb578e2c6f [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
Michael Wright227c5542020-07-02 18:30:52 +0100540 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800541 std::optional<DisplayViewport> viewport =
542 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
543 if (viewport) {
544 return viewport;
545 } else {
Linnan Li13bf76a2024-05-05 19:18:02 +0800546 ALOGW("Can't find designated display viewport with ID %s for pointers.",
547 mConfig.defaultPointerDisplayId.toString().c_str());
Garfield Tan888a6a42020-01-09 11:39:16 -0800548 }
549 }
550
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700551 // Check if uniqueDisplayId is specified in idc file.
552 if (!mParameters.uniqueDisplayId.empty()) {
553 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
554 }
555
556 ViewportType viewportTypeToUse;
557 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100558 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700559 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100560 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700561 }
562
563 std::optional<DisplayViewport> viewport =
564 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100565 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 ALOGW("Input device %s should be associated with external display, "
567 "fallback to internal one for the external viewport is not found.",
568 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100569 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700570 }
571
572 return viewport;
573 }
574
575 // No associated display, return a non-display viewport.
576 DisplayViewport newViewport;
577 // Raw width and height in the natural orientation.
578 int32_t rawWidth = mRawPointerAxes.getRawWidth();
579 int32_t rawHeight = mRawPointerAxes.getRawHeight();
580 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
581 return std::make_optional(newViewport);
582}
583
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800584int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
585 if (resolution < 0) {
586 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
587 getDeviceName().c_str());
588 return 0;
589 }
590 return resolution;
591}
592
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800593void TouchInputMapper::initializeSizeRanges() {
594 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
595 mSizeScale = 0.0f;
596 return;
597 }
598
599 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000600 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800601
602 // Size factors.
603 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
604 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
605 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
606 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
607 } else {
608 mSizeScale = 0.0f;
609 }
610
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700611 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
612 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
613 .source = mSource,
614 .min = 0,
615 .max = diagonalSize,
616 .flat = 0,
617 .fuzz = 0,
618 .resolution = 0,
619 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800620
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800621 if (mRawPointerAxes.touchMajor.valid) {
622 mRawPointerAxes.touchMajor.resolution =
623 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700624 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800625 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800626
627 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700628 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800629 if (mRawPointerAxes.touchMinor.valid) {
630 mRawPointerAxes.touchMinor.resolution =
631 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700632 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800633 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800634
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700635 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
636 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
637 .source = mSource,
638 .min = 0,
639 .max = diagonalSize,
640 .flat = 0,
641 .fuzz = 0,
642 .resolution = 0,
643 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800644 if (mRawPointerAxes.toolMajor.valid) {
645 mRawPointerAxes.toolMajor.resolution =
646 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700647 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800648 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800649
650 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700651 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800652 if (mRawPointerAxes.toolMinor.valid) {
653 mRawPointerAxes.toolMinor.resolution =
654 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700655 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800656 }
657
658 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700659 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
660 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
661 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
662 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800663 } else {
664 // Support for other calibrations can be added here.
665 ALOGW("%s calibration is not supported for size ranges at the moment. "
666 "Using raw resolution instead",
667 ftl::enum_string(mCalibration.sizeCalibration).c_str());
668 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800669
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700670 mOrientedRanges.size = InputDeviceInfo::MotionRange{
671 .axis = AMOTION_EVENT_AXIS_SIZE,
672 .source = mSource,
673 .min = 0,
674 .max = 1.0,
675 .flat = 0,
676 .fuzz = 0,
677 .resolution = 0,
678 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800679}
680
681void TouchInputMapper::initializeOrientedRanges() {
682 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000683 const float orientedScaleX = mRawToDisplay.getScaleX();
684 const float orientedScaleY = mRawToDisplay.getScaleY();
685 mOrientedXPrecision = 1.0f / orientedScaleX;
686 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800687
688 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
689 mOrientedRanges.x.source = mSource;
690 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
691 mOrientedRanges.y.source = mSource;
692
693 // Scale factor for terms that are not oriented in a particular axis.
694 // If the pixels are square then xScale == yScale otherwise we fake it
695 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000696 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800697
698 initializeSizeRanges();
699
700 // Pressure factors.
701 mPressureScale = 0;
702 float pressureMax = 1.0;
703 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
704 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700705 if (mCalibration.pressureScale) {
706 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800707 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
708 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
709 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
710 }
711 }
712
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700713 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
714 .axis = AMOTION_EVENT_AXIS_PRESSURE,
715 .source = mSource,
716 .min = 0,
717 .max = pressureMax,
718 .flat = 0,
719 .fuzz = 0,
720 .resolution = 0,
721 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800722
723 // Tilt
724 mTiltXCenter = 0;
725 mTiltXScale = 0;
726 mTiltYCenter = 0;
727 mTiltYScale = 0;
728 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
729 if (mHaveTilt) {
730 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
731 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
732 mTiltXScale = M_PI / 180;
733 mTiltYScale = M_PI / 180;
734
735 if (mRawPointerAxes.tiltX.resolution) {
736 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
737 }
738 if (mRawPointerAxes.tiltY.resolution) {
739 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
740 }
741
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700742 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
743 .axis = AMOTION_EVENT_AXIS_TILT,
744 .source = mSource,
745 .min = 0,
746 .max = M_PI_2,
747 .flat = 0,
748 .fuzz = 0,
749 .resolution = 0,
750 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800751 }
752
753 // Orientation
754 mOrientationScale = 0;
755 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700756 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
757 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
758 .source = mSource,
759 .min = -M_PI,
760 .max = M_PI,
761 .flat = 0,
762 .fuzz = 0,
763 .resolution = 0,
764 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800765
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800766 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
767 if (mCalibration.orientationCalibration ==
768 Calibration::OrientationCalibration::INTERPOLATED) {
769 if (mRawPointerAxes.orientation.valid) {
770 if (mRawPointerAxes.orientation.maxValue > 0) {
771 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
772 } else if (mRawPointerAxes.orientation.minValue < 0) {
773 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
774 } else {
775 mOrientationScale = 0;
776 }
777 }
778 }
779
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700780 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
781 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
782 .source = mSource,
783 .min = -M_PI_2,
784 .max = M_PI_2,
785 .flat = 0,
786 .fuzz = 0,
787 .resolution = 0,
788 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800789 }
790
791 // Distance
792 mDistanceScale = 0;
793 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
794 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700795 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800796 }
797
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700798 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800799
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700800 .axis = AMOTION_EVENT_AXIS_DISTANCE,
801 .source = mSource,
802 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
803 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
804 .flat = 0,
805 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
806 .resolution = 0,
807 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800808 }
809
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000810 // Oriented X/Y range (in the rotated display's orientation)
811 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
812 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
813 .toFloatRect();
814 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
815 mOrientedRanges.x.min = orientedRangeRect.left;
816 mOrientedRanges.y.min = orientedRangeRect.top;
817 mOrientedRanges.x.max = orientedRangeRect.right;
818 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800819
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000820 // Oriented flat (in the rotated display's orientation)
821 const auto orientedFlat =
822 transformWithoutTranslation(mRawToRotatedDisplay,
823 {static_cast<float>(mRawPointerAxes.x.flat),
824 static_cast<float>(mRawPointerAxes.y.flat)});
825 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
826 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800827
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000828 // Oriented fuzz (in the rotated display's orientation)
829 const auto orientedFuzz =
830 transformWithoutTranslation(mRawToRotatedDisplay,
831 {static_cast<float>(mRawPointerAxes.x.fuzz),
832 static_cast<float>(mRawPointerAxes.y.fuzz)});
833 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
834 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800835
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000836 // Oriented resolution (in the rotated display's orientation)
837 const auto orientedRes =
838 transformWithoutTranslation(mRawToRotatedDisplay,
839 {static_cast<float>(mRawPointerAxes.x.resolution),
840 static_cast<float>(mRawPointerAxes.y.resolution)});
841 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
842 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800843}
844
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000845void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000846 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
847 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
848 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000849
Prabir Pradhan3e798762022-12-02 21:02:11 +0000850 // See notes about input coordinates in the inputflinger docs:
851 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000852
853 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000854 ui::Transform undoOffsetInRaw;
855 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000856
Prabir Pradhan3e798762022-12-02 21:02:11 +0000857 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
858 // will now be in the same orientation as the display in ROTATION_0.
859 // Note: Negating an ui::Rotation value will give its inverse rotation.
860 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
861 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
862 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
863 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
864 // When rotating raw values, account for the extra unit added when calculating the raw range.
865 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
866 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000867
Prabir Pradhan3e798762022-12-02 21:02:11 +0000868 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
869 // now be in the same orientation as the rotated display. There is no need to rotate the
870 // coordinates to the display rotation if the device is not orientation-aware.
871 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
872 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
873 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
874 : orientedRawSize;
875 // When rotating raw values, account for the extra unit added when calculating the raw range.
876 const auto rotateInRaw = mParameters.orientationAware
877 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
878 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000879
Prabir Pradhan3e798762022-12-02 21:02:11 +0000880 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000881 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
882 // the surface of the display panel. This is usually true for touchscreens.
883 // - In POINTER mode, we cannot assume that the display and the touch device have the same
884 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
885 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
886 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
887 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000888 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
889 // are in the continuous space of the logical display.
890 ui::Transform scaleRawToDisplay;
891 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
892 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000893 if (mDeviceMode == DeviceMode::DIRECT) {
894 scaleRawToDisplay.set(xScale, 0, 0, yScale);
895 } else if (mDeviceMode == DeviceMode::POINTER) {
896 const float fixedScale = std::max(xScale, yScale);
897 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
898 } else {
899 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
900 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000901
Prabir Pradhan3e798762022-12-02 21:02:11 +0000902 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
903 // that InputReader uses.
904 const auto undoRotateInDisplay =
905 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
906 .inverse();
907
908 // Now put it all together!
909 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
910 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
911 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000912}
913
Prabir Pradhan1728b212021-10-19 16:00:03 -0700914void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000915 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700916
917 resolveExternalStylusPresence();
918
919 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100920 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +0900921 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700922 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100923 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700924 if (hasStylus()) {
925 mSource |= AINPUT_SOURCE_STYLUS;
926 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800927 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700928 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100929 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700930 if (hasStylus()) {
931 mSource |= AINPUT_SOURCE_STYLUS;
932 }
Michael Wright227c5542020-07-02 18:30:52 +0100933 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700934 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100935 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700936 } else {
Harry Cutts8722be92024-04-05 14:46:05 +0000937 ALOGW("Touch device '%s' has invalid parameters or configuration. The device will be "
938 "inoperable.",
939 getDeviceName().c_str());
940 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700941 }
942
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000943 const std::optional<DisplayViewport> newViewportOpt = findViewport();
944
945 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700946 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
947 ALOGW("Touch device '%s' did not report support for X or Y axis! "
948 "The device will be inoperable.",
949 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100950 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000951 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700952 ALOGI("Touch device '%s' could not query the properties of its associated "
953 "display. The device will be inoperable until the display size "
954 "becomes available.",
955 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100956 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700957 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000958 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
959 getDeviceName().c_str(), getDeviceId());
960 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000961 }
962
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700963 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000964 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000965 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
966 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
967 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
968 const float rawMeanResolution =
969 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700970
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000971 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
Josh Thielene986aed2023-06-01 14:17:30 +0000972 bool viewportChanged;
973 if (mParameters.enableForInactiveViewport) {
974 // When touch is enabled for an inactive viewport, ignore the
975 // viewport active status when checking whether the viewport has
976 // changed.
977 DisplayViewport tempViewport = mViewport;
978 tempViewport.isActive = newViewport.isActive;
979 viewportChanged = tempViewport != newViewport;
980 } else {
981 viewportChanged = mViewport != newViewport;
982 }
983
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700984 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700985 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000986 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
987 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
988 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700989
Michael Wright227c5542020-07-02 18:30:52 +0100990 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000991 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700992
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000993 mDisplayBounds = getNaturalDisplaySize(mViewport);
994 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
995 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700996
Prabir Pradhan3e798762022-12-02 21:02:11 +0000997 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
998 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
999 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001000 // InputReader works in the un-rotated display coordinate space, so we don't need to do
1001 // anything if the device is already orientation-aware. If the device is not
1002 // orientation-aware, then we need to apply the inverse rotation of the display so that
1003 // when the display rotation is applied later as a part of the per-window transform, we
1004 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001005 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +00001006 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001007 : getInverseRotation(mViewport.orientation);
1008 // For orientation-aware devices that work in the un-rotated coordinate space, the
1009 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001010 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001011 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001012
1013 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001014 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001015 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001016 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001017 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001018 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001019 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001020 mRawToDisplay.reset();
1021 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001022 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001023 }
1024 }
1025
1026 // If moving between pointer modes, need to reset some state.
1027 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1028 if (deviceModeChanged) {
1029 mOrientedRanges.clear();
1030 }
1031
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001032 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001033 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %s, mode %s, "
Linnan Li13bf76a2024-05-05 19:18:02 +08001034 "display id %s",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001035 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001036 ftl::enum_string(mInputDeviceOrientation).c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08001037 ftl::enum_string(mDeviceMode).c_str(), mViewport.displayId.toString().c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001038
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001039 configureVirtualKeys();
1040
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001041 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001042
1043 // Location
1044 updateAffineTransformation();
1045
Michael Wright227c5542020-07-02 18:30:52 +01001046 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001047 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001048 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1049 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001050
1051 // Scale movements such that one whole swipe of the touch pad covers a
1052 // given area relative to the diagonal size of the display when no acceleration
1053 // is applied.
1054 // Assume that the touch pad has a square aspect ratio such that movements in
1055 // X and Y of the same number of raw units cover the same physical distance.
1056 mPointerXMovementScale =
1057 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1058 mPointerYMovementScale = mPointerXMovementScale;
1059
1060 // Scale zooms to cover a smaller range of the display than movements do.
1061 // This value determines the area around the pointer that is affected by freeform
1062 // pointer gestures.
1063 mPointerXZoomScale =
1064 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1065 mPointerYZoomScale = mPointerXZoomScale;
1066
HQ Liue6983c72022-04-19 22:14:56 +00001067 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1068 // axis is non positive value.
1069 const float minFreeformGestureWidth =
1070 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1071
1072 mPointerGestureMaxSwipeWidth =
1073 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1074 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001075 }
1076
1077 // Inform the dispatcher about the changes.
1078 *outResetNeeded = true;
1079 bumpGeneration();
1080 }
1081}
1082
Prabir Pradhan1728b212021-10-19 16:00:03 -07001083void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001084 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001085 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001086 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1087 toString(mPhysicalFrameInRotatedDisplay).c_str());
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001088 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %s\n",
1089 ftl::enum_string(mInputDeviceOrientation).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001090}
1091
1092void TouchInputMapper::configureVirtualKeys() {
1093 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001094 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001095
1096 mVirtualKeys.clear();
1097
1098 if (virtualKeyDefinitions.size() == 0) {
1099 return;
1100 }
1101
1102 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1103 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1104 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1105 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1106
1107 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1108 VirtualKey virtualKey;
1109
1110 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1111 int32_t keyCode;
1112 int32_t dummyKeyMetaState;
1113 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001114 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1115 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001116 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1117 continue; // drop the key
1118 }
1119
1120 virtualKey.keyCode = keyCode;
1121 virtualKey.flags = flags;
1122
1123 // convert the key definition's display coordinates into touch coordinates for a hit box
1124 int32_t halfWidth = virtualKeyDefinition.width / 2;
1125 int32_t halfHeight = virtualKeyDefinition.height / 2;
1126
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001127 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1128 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001129 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001130 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1131 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001132 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001133 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1134 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001136 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1137 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001138 touchScreenTop;
1139 mVirtualKeys.push_back(virtualKey);
1140 }
1141}
1142
1143void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1144 if (!mVirtualKeys.empty()) {
1145 dump += INDENT3 "Virtual Keys:\n";
1146
1147 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1148 const VirtualKey& virtualKey = mVirtualKeys[i];
1149 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1150 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1151 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1152 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1153 }
1154 }
1155}
1156
1157void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001158 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001159 Calibration& out = mCalibration;
1160
1161 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001162 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001163 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1164 if (sizeCalibrationString.has_value()) {
1165 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001166 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001167 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001168 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001169 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001171 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001172 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001173 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001174 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001175 } else if (*sizeCalibrationString != "default") {
1176 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 }
1178 }
1179
Harry Cuttsf13161a2023-03-08 14:15:49 +00001180 out.sizeScale = in.getFloat("touch.size.scale");
1181 out.sizeBias = in.getFloat("touch.size.bias");
1182 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001183
1184 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001186 std::optional<std::string> pressureCalibrationString =
1187 in.getString("touch.pressure.calibration");
1188 if (pressureCalibrationString.has_value()) {
1189 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001191 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001193 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001194 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001195 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001197 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 }
1199 }
1200
Harry Cuttsf13161a2023-03-08 14:15:49 +00001201 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202
1203 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001205 std::optional<std::string> orientationCalibrationString =
1206 in.getString("touch.orientation.calibration");
1207 if (orientationCalibrationString.has_value()) {
1208 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001209 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001210 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001211 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001212 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001213 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001214 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001216 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 }
1218 }
1219
1220 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001221 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001222 std::optional<std::string> distanceCalibrationString =
1223 in.getString("touch.distance.calibration");
1224 if (distanceCalibrationString.has_value()) {
1225 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001226 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001227 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001228 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001229 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001230 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001231 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 }
1233 }
1234
Harry Cuttsf13161a2023-03-08 14:15:49 +00001235 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236}
1237
1238void TouchInputMapper::resolveCalibration() {
1239 // Size
1240 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001241 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1242 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243 }
1244 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001245 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 }
1247
1248 // Pressure
1249 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001250 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1251 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252 }
1253 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001254 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256
1257 // Orientation
1258 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001259 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1260 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 }
1262 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001263 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265
1266 // Distance
1267 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001268 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1269 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270 }
1271 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001272 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001274}
1275
1276void TouchInputMapper::dumpCalibration(std::string& dump) {
1277 dump += INDENT3 "Calibration:\n";
1278
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001279 dump += INDENT4 "touch.size.calibration: ";
1280 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001282 if (mCalibration.sizeScale) {
1283 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 }
1285
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001286 if (mCalibration.sizeBias) {
1287 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288 }
1289
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001290 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001292 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293 }
1294
1295 // Pressure
1296 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001297 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 dump += INDENT4 "touch.pressure.calibration: none\n";
1299 break;
Michael Wright227c5542020-07-02 18:30:52 +01001300 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 dump += INDENT4 "touch.pressure.calibration: physical\n";
1302 break;
Michael Wright227c5542020-07-02 18:30:52 +01001303 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1305 break;
1306 default:
1307 ALOG_ASSERT(false);
1308 }
1309
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001310 if (mCalibration.pressureScale) {
1311 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 }
1313
1314 // Orientation
1315 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001316 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317 dump += INDENT4 "touch.orientation.calibration: none\n";
1318 break;
Michael Wright227c5542020-07-02 18:30:52 +01001319 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1321 break;
Michael Wright227c5542020-07-02 18:30:52 +01001322 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001323 dump += INDENT4 "touch.orientation.calibration: vector\n";
1324 break;
1325 default:
1326 ALOG_ASSERT(false);
1327 }
1328
1329 // Distance
1330 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001331 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 dump += INDENT4 "touch.distance.calibration: none\n";
1333 break;
Michael Wright227c5542020-07-02 18:30:52 +01001334 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001335 dump += INDENT4 "touch.distance.calibration: scaled\n";
1336 break;
1337 default:
1338 ALOG_ASSERT(false);
1339 }
1340
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001341 if (mCalibration.distanceScale) {
1342 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001343 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344}
1345
1346void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1347 dump += INDENT3 "Affine Transformation:\n";
1348
1349 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1350 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1351 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1352 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1353 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1354 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1355}
1356
1357void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001358 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001359 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360}
1361
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001362std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001363 std::list<NotifyArgs> out = cancelTouch(when, when);
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001364
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001365 mCursorButtonAccumulator.reset(getDeviceContext());
1366 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001367 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001368
1369 mPointerVelocityControl.reset();
1370 mWheelXVelocityControl.reset();
1371 mWheelYVelocityControl.reset();
1372
1373 mRawStatesPending.clear();
1374 mCurrentRawState.clear();
1375 mCurrentCookedState.clear();
1376 mLastRawState.clear();
1377 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001378 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001379 mSentHoverEnter = false;
1380 mHavePointerIds = false;
1381 mCurrentMotionAborted = false;
1382 mDownTime = 0;
1383
1384 mCurrentVirtualKey.down = false;
1385
1386 mPointerGesture.reset();
1387 mPointerSimple.reset();
1388 resetExternalStylus();
1389
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001390 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001391}
1392
1393void TouchInputMapper::resetExternalStylus() {
1394 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001395 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001396 mExternalStylusFusionTimeout = LLONG_MAX;
1397 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001398 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001399}
1400
1401void TouchInputMapper::clearStylusDataPendingFlags() {
1402 mExternalStylusDataPending = false;
1403 mExternalStylusFusionTimeout = LLONG_MAX;
1404}
1405
Harry Cuttsa32a1192024-06-04 15:10:31 +00001406std::list<NotifyArgs> TouchInputMapper::process(const RawEvent& rawEvent) {
1407 mCursorButtonAccumulator.process(rawEvent);
1408 mCursorScrollAccumulator.process(rawEvent);
1409 mTouchButtonAccumulator.process(rawEvent);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001410
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001411 std::list<NotifyArgs> out;
Harry Cuttsa32a1192024-06-04 15:10:31 +00001412 if (rawEvent.type == EV_SYN && rawEvent.code == SYN_REPORT) {
1413 out += sync(rawEvent.when, rawEvent.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001414 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001415 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001416}
1417
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001418std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1419 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001420 if (mDeviceMode == DeviceMode::DISABLED) {
1421 // Only save the last pending state when the device is disabled.
1422 mRawStatesPending.clear();
1423 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001424 // Push a new state.
1425 mRawStatesPending.emplace_back();
1426
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001427 RawState& next = mRawStatesPending.back();
1428 next.clear();
1429 next.when = when;
1430 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431
1432 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001433 next.buttonState = filterButtonState(mConfig,
1434 mTouchButtonAccumulator.getButtonState() |
1435 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436
1437 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001438 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1439 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440 mCursorScrollAccumulator.finishSync();
1441
1442 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001443 syncTouch(when, &next);
1444
1445 // The last RawState is the actually second to last, since we just added a new state
1446 const RawState& last =
1447 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001448
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001449 std::tie(next.when, next.readTime) =
1450 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1451 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001452
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001453 // Assign pointer ids.
1454 if (!mHavePointerIds) {
1455 assignPointerIds(last, next);
1456 }
1457
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001458 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001459 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1460 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1461 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1462 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1463 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1464 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001465
Arthur Hung9ad18942021-06-19 02:04:46 +00001466 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1467 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1468 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1469 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1470 next.rawPointerData.hoveringIdBits.value);
1471 }
1472
Harry Cutts33476232023-01-30 19:57:29 +00001473 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001474 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001475}
1476
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001477std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1478 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001479 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001480 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001481 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001482 }
1483
1484 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1485 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1486 // touching the current state will only observe the events that have been dispatched to the
1487 // rest of the pipeline.
1488 const size_t N = mRawStatesPending.size();
1489 size_t count;
1490 for (count = 0; count < N; count++) {
1491 const RawState& next = mRawStatesPending[count];
1492
1493 // A failure to assign the stylus id means that we're waiting on stylus data
1494 // and so should defer the rest of the pipeline.
1495 if (assignExternalStylusId(next, timeout)) {
1496 break;
1497 }
1498
1499 // All ready to go.
1500 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001501 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001502 if (mCurrentRawState.when < mLastRawState.when) {
1503 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001504 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001505 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001506 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001507 }
1508 if (count != 0) {
1509 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1510 }
1511
1512 if (mExternalStylusDataPending) {
1513 if (timeout) {
1514 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1515 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001516 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001517 ALOGD_IF(DEBUG_STYLUS_FUSION,
1518 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001519 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001520 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001521 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1522 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1523 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1524 }
1525 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001526 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001527}
1528
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001529std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1530 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001531 // Always start with a clean state.
1532 mCurrentCookedState.clear();
1533
1534 // Apply stylus buttons to current raw state.
1535 applyExternalStylusButtonState(when);
1536
1537 // Handle policy on initial down or hover events.
1538 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1539 mCurrentRawState.rawPointerData.pointerCount != 0;
1540
1541 uint32_t policyFlags = 0;
1542 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1543 if (initialDown || buttonsPressed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001544 if (mParameters.wake) {
1545 policyFlags |= POLICY_FLAG_WAKE;
1546 }
1547 }
1548
1549 // Consume raw off-screen touches before cooking pointer data.
1550 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001551 bool consumed;
1552 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1553 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001554 mCurrentRawState.rawPointerData.clear();
1555 }
1556
1557 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1558 // with cooked pointer data that has the same ids and indices as the raw data.
1559 // The following code can use either the raw or cooked data, as needed.
1560 cookPointerData();
1561
1562 // Apply stylus pressure to current cooked state.
1563 applyExternalStylusTouchState(when);
1564
1565 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001566 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1567 mSource, mViewport.displayId, policyFlags,
1568 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001569
1570 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001571 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001572 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1573 uint32_t id = idBits.clearFirstMarkedBit();
1574 const RawPointerData::Pointer& pointer =
1575 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001576 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001577 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001578 } else if (pointer.toolType == ToolType::FINGER ||
1579 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001580 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001581 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001582 mCurrentCookedState.mouseIdBits.markBit(id);
1583 }
1584 }
1585 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1586 uint32_t id = idBits.clearFirstMarkedBit();
1587 const RawPointerData::Pointer& pointer =
1588 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001589 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001590 mCurrentCookedState.stylusIdBits.markBit(id);
1591 }
1592 }
1593
1594 // Stylus takes precedence over all tools, then mouse, then finger.
1595 PointerUsage pointerUsage = mPointerUsage;
1596 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1597 mCurrentCookedState.mouseIdBits.clear();
1598 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001599 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001600 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1601 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001602 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001603 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1604 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001605 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001606 }
1607
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001608 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001609 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001610 if (!mCurrentMotionAborted) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001611 out += dispatchButtonRelease(when, readTime, policyFlags);
1612 out += dispatchHoverExit(when, readTime, policyFlags);
1613 out += dispatchTouches(when, readTime, policyFlags);
1614 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1615 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001616 }
1617
1618 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1619 mCurrentMotionAborted = false;
1620 }
1621 }
1622
1623 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001624 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1625 mSource, mViewport.displayId, policyFlags,
1626 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001627
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001628 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1629 mCurrentStreamModifiedByExternalStylus = false;
1630 }
1631
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632 // Clear some transient state.
1633 mCurrentRawState.rawVScroll = 0;
1634 mCurrentRawState.rawHScroll = 0;
1635
1636 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001637 mLastRawState = mCurrentRawState;
1638 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001639 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001640}
1641
Garfield Tanc734e4f2021-01-15 20:01:39 -08001642bool TouchInputMapper::isTouchScreen() {
1643 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1644 mParameters.hasAssociatedDisplay;
1645}
1646
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001647void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001648 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1649 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001650 const int32_t pressedButtons =
1651 filterButtonState(mConfig,
1652 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001653 const int32_t releasedButtons =
1654 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1655
1656 mCurrentRawState.buttonState |= pressedButtons;
1657 mCurrentRawState.buttonState &= ~releasedButtons;
1658
1659 mExternalStylusButtonsApplied |= pressedButtons;
1660 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001661
1662 if (mExternalStylusButtonsApplied != 0 || releasedButtons != 0) {
1663 mCurrentStreamModifiedByExternalStylus = true;
1664 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001665 }
1666}
1667
1668void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1669 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1670 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001671 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1672 return;
1673 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001674
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001675 mCurrentStreamModifiedByExternalStylus = true;
1676
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001677 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1678 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1679 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1680 : 0.f;
1681 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1682 pressure = *mExternalStylusState.pressure;
1683 }
1684 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1685 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001686
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001687 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001688 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001689 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001690 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001691 }
1692}
1693
1694bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001695 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001696 return false;
1697 }
1698
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001699 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001700 if (mFusedStylusPointerId &&
1701 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001702 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001703 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001704 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001705 }
1706
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001707 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1708 state.rawPointerData.pointerCount != 0;
1709 if (!initialDown) {
1710 return false;
1711 }
1712
1713 if (!mExternalStylusState.pressure) {
1714 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1715 return false;
1716 }
1717
1718 if (*mExternalStylusState.pressure != 0.0f) {
1719 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1720 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1721 return false;
1722 }
1723
1724 if (timeout) {
1725 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1726 mFusedStylusPointerId.reset();
1727 mExternalStylusFusionTimeout = LLONG_MAX;
1728 return false;
1729 }
1730
1731 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1732 // being processed until we either get pressure data or timeout.
1733 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1734 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1735 }
1736 ALOGD_IF(DEBUG_STYLUS_FUSION,
1737 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1738 mExternalStylusFusionTimeout);
1739 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1740 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001741}
1742
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001743std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1744 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001745 if (mDeviceMode == DeviceMode::POINTER) {
1746 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001747 // Since this is a synthetic event, we can consider its latency to be zero
1748 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001749 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001750 }
Michael Wright227c5542020-07-02 18:30:52 +01001751 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001752 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001753 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001754 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1755 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1756 }
1757 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001758 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001759}
1760
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001761std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1762 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001763 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001764 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001765 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001766 // The following three cases are handled here:
1767 // - We're in the middle of a fused stream of data;
1768 // - We're waiting on external stylus data before dispatching the initial down; or
1769 // - Only the button state, which is not reported through a specific pointer, has changed.
1770 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001771 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001772 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001773 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001774 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001775}
1776
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001777std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1778 uint32_t policyFlags, bool& outConsumed) {
1779 outConsumed = false;
1780 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001781 // Check for release of a virtual key.
1782 if (mCurrentVirtualKey.down) {
1783 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1784 // Pointer went up while virtual key was down.
1785 mCurrentVirtualKey.down = false;
1786 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001787 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1788 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1789 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001790 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1791 AKEY_EVENT_FLAG_FROM_SYSTEM |
1792 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001793 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001794 outConsumed = true;
1795 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001796 }
1797
1798 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1799 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1800 const RawPointerData::Pointer& pointer =
1801 mCurrentRawState.rawPointerData.pointerForId(id);
1802 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1803 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1804 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001805 outConsumed = true;
1806 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001807 }
1808 }
1809
1810 // Pointer left virtual key area or another pointer also went down.
1811 // Send key cancellation but do not consume the touch yet.
1812 // This is useful when the user swipes through from the virtual key area
1813 // into the main display surface.
1814 mCurrentVirtualKey.down = false;
1815 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001816 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1817 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001818 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1819 AKEY_EVENT_FLAG_FROM_SYSTEM |
1820 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1821 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001822 }
1823 }
1824
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001825 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
Harry Cutts8722be92024-04-05 14:46:05 +00001826 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001827 // We have hovering pointers, and there are no touching pointers.
1828 bool hoveringPointersInFrame = false;
1829 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1830 while (!hoveringIds.isEmpty()) {
1831 uint32_t id = hoveringIds.clearFirstMarkedBit();
1832 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1833 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1834 hoveringPointersInFrame = true;
1835 break;
1836 }
1837 }
1838 if (!hoveringPointersInFrame) {
1839 // All hovering pointers are outside the physical frame.
1840 outConsumed = true;
1841 return out;
1842 }
1843 }
1844
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001845 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1846 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1847 // Pointer just went down. Check for virtual key press or off-screen touches.
1848 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1849 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001850 // Skip checking whether the pointer is inside the physical frame if the device is in
Harry Cutts1db43992023-06-19 17:05:07 +00001851 // unscaled or pointer mode.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001852 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
Harry Cutts8722be92024-04-05 14:46:05 +00001853 mDeviceMode != DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001854 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001855 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001856 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1857 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1858 if (virtualKey) {
1859 mCurrentVirtualKey.down = true;
1860 mCurrentVirtualKey.downTime = when;
1861 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1862 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1863 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001864 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1865 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001866
1867 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001868 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1869 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1870 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001871 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1872 AKEY_EVENT_ACTION_DOWN,
1873 AKEY_EVENT_FLAG_FROM_SYSTEM |
1874 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001875 }
1876 }
1877 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001878 outConsumed = true;
1879 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001880 }
1881 }
1882
1883 // Disable all virtual key touches that happen within a short time interval of the
1884 // most recent touch within the screen area. The idea is to filter out stray
1885 // virtual key presses when interacting with the touch screen.
1886 //
1887 // Problems we're trying to solve:
1888 //
1889 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1890 // virtual key area that is implemented by a separate touch panel and accidentally
1891 // triggers a virtual key.
1892 //
1893 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1894 // area and accidentally triggers a virtual key. This often happens when virtual keys
1895 // are layed out below the screen near to where the on screen keyboard's space bar
1896 // is displayed.
1897 if (mConfig.virtualKeyQuietTime > 0 &&
1898 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001899 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001900 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001901 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001902}
1903
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001904NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1905 uint32_t policyFlags, int32_t keyEventAction,
1906 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001907 int32_t keyCode = mCurrentVirtualKey.keyCode;
1908 int32_t scanCode = mCurrentVirtualKey.scanCode;
1909 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001910 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001911 policyFlags |= POLICY_FLAG_VIRTUAL;
1912
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001913 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1914 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1915 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001916}
1917
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001918std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1919 uint32_t policyFlags) {
1920 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001921 if (mCurrentMotionAborted) {
1922 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001923 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001924 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001925 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1926 if (!currentIdBits.isEmpty()) {
1927 int32_t metaState = getContext()->getGlobalMetaState();
1928 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001929 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001930 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1931 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001932 mCurrentCookedState.cookedPointerData.pointerProperties,
1933 mCurrentCookedState.cookedPointerData.pointerCoords,
1934 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1935 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1936 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001937 mCurrentMotionAborted = true;
1938 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001939 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001940}
1941
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001942// Updates pointer coords and properties for pointers with specified ids that have moved.
1943// Returns true if any of them changed.
1944static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1945 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1946 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1947 BitSet32 idBits) {
1948 bool changed = false;
1949 while (!idBits.isEmpty()) {
1950 uint32_t id = idBits.clearFirstMarkedBit();
1951 uint32_t inIndex = inIdToIndex[id];
1952 uint32_t outIndex = outIdToIndex[id];
1953
1954 const PointerProperties& curInProperties = inProperties[inIndex];
1955 const PointerCoords& curInCoords = inCoords[inIndex];
1956 PointerProperties& curOutProperties = outProperties[outIndex];
1957 PointerCoords& curOutCoords = outCoords[outIndex];
1958
1959 if (curInProperties != curOutProperties) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001960 curOutProperties = curInProperties;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001961 changed = true;
1962 }
1963
1964 if (curInCoords != curOutCoords) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001965 curOutCoords = curInCoords;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001966 changed = true;
1967 }
1968 }
1969 return changed;
1970}
1971
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001972std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1973 uint32_t policyFlags) {
1974 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001975 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1976 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1977 int32_t metaState = getContext()->getGlobalMetaState();
1978 int32_t buttonState = mCurrentCookedState.buttonState;
1979
1980 if (currentIdBits == lastIdBits) {
1981 if (!currentIdBits.isEmpty()) {
1982 // No pointer id changes so this is a move event.
1983 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001984 out.push_back(
1985 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1986 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1987 mCurrentCookedState.cookedPointerData.pointerProperties,
1988 mCurrentCookedState.cookedPointerData.pointerCoords,
1989 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1990 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1991 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001992 }
1993 } else {
1994 // There may be pointers going up and pointers going down and pointers moving
1995 // all at the same time.
1996 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1997 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1998 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1999 BitSet32 dispatchedIdBits(lastIdBits.value);
2000
2001 // Update last coordinates of pointers that have moved so that we observe the new
2002 // pointer positions at the same time as other pointers that have just gone up.
2003 bool moveNeeded =
2004 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2005 mCurrentCookedState.cookedPointerData.pointerCoords,
2006 mCurrentCookedState.cookedPointerData.idToIndex,
2007 mLastCookedState.cookedPointerData.pointerProperties,
2008 mLastCookedState.cookedPointerData.pointerCoords,
2009 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2010 if (buttonState != mLastCookedState.buttonState) {
2011 moveNeeded = true;
2012 }
2013
2014 // Dispatch pointer up events.
2015 while (!upIdBits.isEmpty()) {
2016 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002017 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002018 if (isCanceled) {
2019 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2020 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002021 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2022 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2023 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2024 buttonState, 0,
2025 mLastCookedState.cookedPointerData.pointerProperties,
2026 mLastCookedState.cookedPointerData.pointerCoords,
2027 mLastCookedState.cookedPointerData.idToIndex,
2028 dispatchedIdBits, upId, mOrientedXPrecision,
2029 mOrientedYPrecision, mDownTime,
2030 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002031 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002032 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002033 }
2034
2035 // Dispatch move events if any of the remaining pointers moved from their old locations.
2036 // Although applications receive new locations as part of individual pointer up
2037 // events, they do not generally handle them except when presented in a move event.
2038 if (moveNeeded && !moveIdBits.isEmpty()) {
2039 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002040 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2041 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2042 mCurrentCookedState.cookedPointerData.pointerProperties,
2043 mCurrentCookedState.cookedPointerData.pointerCoords,
2044 mCurrentCookedState.cookedPointerData.idToIndex,
2045 dispatchedIdBits, -1, mOrientedXPrecision,
2046 mOrientedYPrecision, mDownTime,
2047 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002048 }
2049
2050 // Dispatch pointer down events using the new pointer locations.
2051 while (!downIdBits.isEmpty()) {
2052 uint32_t downId = downIdBits.clearFirstMarkedBit();
2053 dispatchedIdBits.markBit(downId);
2054
2055 if (dispatchedIdBits.count() == 1) {
2056 // First pointer is going down. Set down time.
2057 mDownTime = when;
2058 }
2059
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002060 out.push_back(
2061 dispatchMotion(when, readTime, policyFlags, mSource,
2062 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2063 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2064 mCurrentCookedState.cookedPointerData.pointerCoords,
2065 mCurrentCookedState.cookedPointerData.idToIndex,
2066 dispatchedIdBits, downId, mOrientedXPrecision,
2067 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002068 }
2069 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002070 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002071}
2072
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002073std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2074 uint32_t policyFlags) {
2075 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002076 if (mSentHoverEnter &&
2077 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2078 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2079 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002080 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2081 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2082 mLastCookedState.buttonState, 0,
2083 mLastCookedState.cookedPointerData.pointerProperties,
2084 mLastCookedState.cookedPointerData.pointerCoords,
2085 mLastCookedState.cookedPointerData.idToIndex,
2086 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2087 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2088 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089 mSentHoverEnter = false;
2090 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002091 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002092}
2093
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002094std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2095 uint32_t policyFlags) {
2096 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002097 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2098 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2099 int32_t metaState = getContext()->getGlobalMetaState();
2100 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002101 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2102 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2103 mCurrentRawState.buttonState, 0,
2104 mCurrentCookedState.cookedPointerData.pointerProperties,
2105 mCurrentCookedState.cookedPointerData.pointerCoords,
2106 mCurrentCookedState.cookedPointerData.idToIndex,
2107 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2108 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2109 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002110 mSentHoverEnter = true;
2111 }
2112
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002113 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2114 AMOTION_EVENT_ACTION_HOVER_MOVE, 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 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002123 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002124}
2125
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002126std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2127 uint32_t policyFlags) {
2128 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002129 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2130 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2131 const int32_t metaState = getContext()->getGlobalMetaState();
2132 int32_t buttonState = mLastCookedState.buttonState;
2133 while (!releasedButtons.isEmpty()) {
2134 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2135 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002136 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2137 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2138 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002139 mLastCookedState.cookedPointerData.pointerProperties,
2140 mLastCookedState.cookedPointerData.pointerCoords,
2141 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002142 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2143 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002144 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002145 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002146}
2147
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002148std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2149 uint32_t policyFlags) {
2150 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002151 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2152 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2153 const int32_t metaState = getContext()->getGlobalMetaState();
2154 int32_t buttonState = mLastCookedState.buttonState;
2155 while (!pressedButtons.isEmpty()) {
2156 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2157 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002158 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2159 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2160 buttonState, 0,
2161 mCurrentCookedState.cookedPointerData.pointerProperties,
2162 mCurrentCookedState.cookedPointerData.pointerCoords,
2163 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2164 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2165 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002166 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002167 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002168}
2169
LiZhihong758eb562022-11-03 15:28:29 +08002170std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2171 uint32_t policyFlags,
2172 BitSet32 idBits,
2173 nsecs_t readTime) {
2174 std::list<NotifyArgs> out;
2175 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2176 const int32_t metaState = getContext()->getGlobalMetaState();
2177 int32_t buttonState = mLastCookedState.buttonState;
2178
2179 while (!releasedButtons.isEmpty()) {
2180 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2181 buttonState &= ~actionButton;
2182 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2183 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2184 metaState, buttonState, 0,
2185 mPointerGesture.lastGestureProperties,
2186 mPointerGesture.lastGestureCoords,
2187 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2188 mOrientedXPrecision, mOrientedYPrecision,
2189 mPointerGesture.downTime, MotionClassification::NONE));
2190 }
2191 return out;
2192}
2193
2194std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2195 uint32_t policyFlags,
2196 BitSet32 idBits,
2197 nsecs_t readTime) {
2198 std::list<NotifyArgs> out;
2199 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2200 const int32_t metaState = getContext()->getGlobalMetaState();
2201 int32_t buttonState = mLastCookedState.buttonState;
2202
2203 while (!pressedButtons.isEmpty()) {
2204 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2205 buttonState |= actionButton;
2206 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2207 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2208 buttonState, 0, mPointerGesture.currentGestureProperties,
2209 mPointerGesture.currentGestureCoords,
2210 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2211 mOrientedXPrecision, mOrientedYPrecision,
2212 mPointerGesture.downTime, MotionClassification::NONE));
2213 }
2214 return out;
2215}
2216
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002217const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2218 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2219 return cookedPointerData.touchingIdBits;
2220 }
2221 return cookedPointerData.hoveringIdBits;
2222}
2223
2224void TouchInputMapper::cookPointerData() {
2225 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2226
2227 mCurrentCookedState.cookedPointerData.clear();
2228 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2229 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2230 mCurrentRawState.rawPointerData.hoveringIdBits;
2231 mCurrentCookedState.cookedPointerData.touchingIdBits =
2232 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002233 mCurrentCookedState.cookedPointerData.canceledIdBits =
2234 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002235
2236 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2237 mCurrentCookedState.buttonState = 0;
2238 } else {
2239 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2240 }
2241
2242 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002243 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002244 for (uint32_t i = 0; i < currentPointerCount; i++) {
2245 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2246
2247 // Size
2248 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2249 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002250 case Calibration::SizeCalibration::GEOMETRIC:
2251 case Calibration::SizeCalibration::DIAMETER:
2252 case Calibration::SizeCalibration::BOX:
2253 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002254 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2255 touchMajor = in.touchMajor;
2256 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2257 toolMajor = in.toolMajor;
2258 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2259 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2260 : in.touchMajor;
2261 } else if (mRawPointerAxes.touchMajor.valid) {
2262 toolMajor = touchMajor = in.touchMajor;
2263 toolMinor = touchMinor =
2264 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2265 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2266 : in.touchMajor;
2267 } else if (mRawPointerAxes.toolMajor.valid) {
2268 touchMajor = toolMajor = in.toolMajor;
2269 touchMinor = toolMinor =
2270 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2271 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2272 : in.toolMajor;
2273 } else {
2274 ALOG_ASSERT(false,
2275 "No touch or tool axes. "
2276 "Size calibration should have been resolved to NONE.");
2277 touchMajor = 0;
2278 touchMinor = 0;
2279 toolMajor = 0;
2280 toolMinor = 0;
2281 size = 0;
2282 }
2283
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002284 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002285 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2286 if (touchingCount > 1) {
2287 touchMajor /= touchingCount;
2288 touchMinor /= touchingCount;
2289 toolMajor /= touchingCount;
2290 toolMinor /= touchingCount;
2291 size /= touchingCount;
2292 }
2293 }
2294
Michael Wright227c5542020-07-02 18:30:52 +01002295 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 touchMajor *= mGeometricScale;
2297 touchMinor *= mGeometricScale;
2298 toolMajor *= mGeometricScale;
2299 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002300 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002301 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2302 touchMinor = touchMajor;
2303 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2304 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002305 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002306 touchMinor = touchMajor;
2307 toolMinor = toolMajor;
2308 }
2309
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002310 mCalibration.applySizeScaleAndBias(touchMajor);
2311 mCalibration.applySizeScaleAndBias(touchMinor);
2312 mCalibration.applySizeScaleAndBias(toolMajor);
2313 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002314 size *= mSizeScale;
2315 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002316 case Calibration::SizeCalibration::DEFAULT:
2317 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2318 break;
2319 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002320 touchMajor = 0;
2321 touchMinor = 0;
2322 toolMajor = 0;
2323 toolMinor = 0;
2324 size = 0;
2325 break;
2326 }
2327
2328 // Pressure
2329 float pressure;
2330 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002331 case Calibration::PressureCalibration::PHYSICAL:
2332 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002333 pressure = in.pressure * mPressureScale;
2334 break;
2335 default:
2336 pressure = in.isHovering ? 0 : 1;
2337 break;
2338 }
2339
2340 // Tilt and Orientation
2341 float tilt;
2342 float orientation;
2343 if (mHaveTilt) {
2344 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2345 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002346 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2348 } else {
2349 tilt = 0;
2350
2351 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002352 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002353 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354 break;
Michael Wright227c5542020-07-02 18:30:52 +01002355 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2357 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2358 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002359 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002360 float confidence = hypotf(c1, c2);
2361 float scale = 1.0f + confidence / 16.0f;
2362 touchMajor *= scale;
2363 touchMinor /= scale;
2364 toolMajor *= scale;
2365 toolMinor /= scale;
2366 } else {
2367 orientation = 0;
2368 }
2369 break;
2370 }
2371 default:
2372 orientation = 0;
2373 }
2374 }
2375
2376 // Distance
2377 float distance;
2378 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002379 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 distance = in.distance * mDistanceScale;
2381 break;
2382 default:
2383 distance = 0;
2384 }
2385
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002386 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2387 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002388 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2389 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 // Write output coords.
2392 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2393 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002394 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2395 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2397 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2398 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2399 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2400 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2401 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2402 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002403 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2404 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405
Chris Ye364fdb52020-08-05 15:07:56 -07002406 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002407 uint32_t id = in.id;
2408 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2409 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2410 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002411 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2412 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002413 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2414 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2415 }
2416
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002417 // Write output properties.
2418 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419 properties.clear();
2420 properties.id = id;
2421 properties.toolType = in.toolType;
2422
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002423 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002424 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002425 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002426 }
2427}
2428
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002429std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2430 uint32_t policyFlags,
2431 PointerUsage pointerUsage) {
2432 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002433 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002434 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002435 mPointerUsage = pointerUsage;
2436 }
2437
2438 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002439 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002440 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002441 break;
Michael Wright227c5542020-07-02 18:30:52 +01002442 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002443 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002444 break;
Michael Wright227c5542020-07-02 18:30:52 +01002445 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002446 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002447 break;
Michael Wright227c5542020-07-02 18:30:52 +01002448 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002449 break;
2450 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002451 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452}
2453
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002454std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2455 uint32_t policyFlags) {
2456 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002457 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002458 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002459 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 break;
Michael Wright227c5542020-07-02 18:30:52 +01002461 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002462 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463 break;
Michael Wright227c5542020-07-02 18:30:52 +01002464 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002465 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 break;
Michael Wright227c5542020-07-02 18:30:52 +01002467 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 break;
2469 }
2470
Michael Wright227c5542020-07-02 18:30:52 +01002471 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002472 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002473}
2474
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002475std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2476 uint32_t policyFlags,
2477 bool isTimeout) {
2478 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 // Update current gesture coordinates.
2480 bool cancelPreviousGesture, finishPreviousGesture;
2481 bool sendEvents =
2482 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2483 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002484 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002485 }
2486 if (finishPreviousGesture) {
2487 cancelPreviousGesture = false;
2488 }
2489
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002490 // Send events!
2491 int32_t metaState = getContext()->getGlobalMetaState();
2492 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002493 const MotionClassification classification =
2494 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2495 ? MotionClassification::TWO_FINGER_SWIPE
2496 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002497
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002498 uint32_t flags = 0;
2499
2500 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2501 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2502 }
2503
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504 // Update last coordinates of pointers that have moved so that we observe the new
2505 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002506 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2507 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2508 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2509 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2510 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2511 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512 bool moveNeeded = false;
2513 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2514 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2515 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2516 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2517 mPointerGesture.lastGestureIdBits.value);
2518 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2519 mPointerGesture.currentGestureCoords,
2520 mPointerGesture.currentGestureIdToIndex,
2521 mPointerGesture.lastGestureProperties,
2522 mPointerGesture.lastGestureCoords,
2523 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2524 if (buttonState != mLastCookedState.buttonState) {
2525 moveNeeded = true;
2526 }
2527 }
2528
2529 // Send motion events for all pointers that went up or were canceled.
2530 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2531 if (!dispatchedGestureIdBits.isEmpty()) {
2532 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002533 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002534 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002535 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002536 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2537 mPointerGesture.lastGestureProperties,
2538 mPointerGesture.lastGestureCoords,
2539 mPointerGesture.lastGestureIdToIndex,
2540 dispatchedGestureIdBits, -1, 0, 0,
2541 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002542
2543 dispatchedGestureIdBits.clear();
2544 } else {
2545 BitSet32 upGestureIdBits;
2546 if (finishPreviousGesture) {
2547 upGestureIdBits = dispatchedGestureIdBits;
2548 } else {
2549 upGestureIdBits.value =
2550 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2551 }
2552 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002553 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2554 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2555 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2556 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2557 readTime);
2558 }
2559 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002560 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2561 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2562 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2563 mPointerGesture.lastGestureProperties,
2564 mPointerGesture.lastGestureCoords,
2565 mPointerGesture.lastGestureIdToIndex,
2566 dispatchedGestureIdBits, id, 0, 0,
2567 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002568
2569 dispatchedGestureIdBits.clearBit(id);
2570 }
2571 }
2572 }
2573
2574 // Send motion events for all pointers that moved.
2575 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002576 out.push_back(
2577 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2578 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2579 mPointerGesture.currentGestureProperties,
2580 mPointerGesture.currentGestureCoords,
2581 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2582 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002583 }
2584
2585 // Send motion events for all pointers that went down.
2586 if (down) {
2587 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2588 ~dispatchedGestureIdBits.value);
2589 while (!downGestureIdBits.isEmpty()) {
2590 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2591 dispatchedGestureIdBits.markBit(id);
2592
2593 if (dispatchedGestureIdBits.count() == 1) {
2594 mPointerGesture.downTime = when;
2595 }
2596
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002597 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2598 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2599 buttonState, 0, mPointerGesture.currentGestureProperties,
2600 mPointerGesture.currentGestureCoords,
2601 mPointerGesture.currentGestureIdToIndex,
2602 dispatchedGestureIdBits, id, 0, 0,
2603 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002604 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2605 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2606 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2607 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2608 readTime);
2609 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002610 }
2611 }
2612
2613 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002614 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002615 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2616 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2617 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2618 mPointerGesture.currentGestureProperties,
2619 mPointerGesture.currentGestureCoords,
2620 mPointerGesture.currentGestureIdToIndex,
2621 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2622 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002623 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2624 // Synthesize a hover move event after all pointers go up to indicate that
2625 // the pointer is hovering again even if the user is not currently touching
2626 // the touch pad. This ensures that a view will receive a fresh hover enter
2627 // event after a tap.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002628
2629 PointerProperties pointerProperties;
2630 pointerProperties.clear();
2631 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002632 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002633
2634 PointerCoords pointerCoords;
2635 pointerCoords.clear();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002636 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002637 mSource, ui::LogicalDisplayId::INVALID, policyFlags,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002638 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2639 buttonState, MotionClassification::NONE,
2640 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002641 &pointerCoords, 0, 0, 0.f, 0.f, mPointerGesture.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00002642 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002643 }
2644
2645 // Update state.
2646 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2647 if (!down) {
2648 mPointerGesture.lastGestureIdBits.clear();
2649 } else {
2650 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2651 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2652 uint32_t id = idBits.clearFirstMarkedBit();
2653 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002654 mPointerGesture.lastGestureProperties[index] =
2655 mPointerGesture.currentGestureProperties[index];
2656 mPointerGesture.lastGestureCoords[index] = mPointerGesture.currentGestureCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002657 mPointerGesture.lastGestureIdToIndex[id] = index;
2658 }
2659 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002660 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002661}
2662
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002663std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2664 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002665 const MotionClassification classification =
2666 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2667 ? MotionClassification::TWO_FINGER_SWIPE
2668 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002669 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002670 // Cancel previously dispatches pointers.
2671 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2672 int32_t metaState = getContext()->getGlobalMetaState();
2673 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002674 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002675 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2676 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002677 mPointerGesture.lastGestureProperties,
2678 mPointerGesture.lastGestureCoords,
2679 mPointerGesture.lastGestureIdToIndex,
2680 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2681 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002682 }
2683
2684 // Reset the current pointer gesture.
2685 mPointerGesture.reset();
2686 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002687 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002688}
2689
2690bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2691 bool* outFinishPreviousGesture, bool isTimeout) {
2692 *outCancelPreviousGesture = false;
2693 *outFinishPreviousGesture = false;
2694
2695 // Handle TAP timeout.
2696 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002697 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002698
Michael Wright227c5542020-07-02 18:30:52 +01002699 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002700 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2701 // The tap/drag timeout has not yet expired.
2702 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2703 mConfig.pointerGestureTapDragInterval);
2704 } else {
2705 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002706 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002707 *outFinishPreviousGesture = true;
2708
2709 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002710 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002711 mPointerGesture.currentGestureIdBits.clear();
2712
2713 mPointerVelocityControl.reset();
2714 return true;
2715 }
2716 }
2717
2718 // We did not handle this timeout.
2719 return false;
2720 }
2721
2722 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2723 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2724
2725 // Update the velocity tracker.
2726 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002727 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002728 uint32_t id = idBits.clearFirstMarkedBit();
2729 const RawPointerData::Pointer& pointer =
2730 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002731 const float x = pointer.x * mPointerXMovementScale;
2732 const float y = pointer.y * mPointerYMovementScale;
2733 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2734 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002735 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002736 }
2737
2738 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2739 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002740 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2741 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2742 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002743 mPointerGesture.resetTap();
2744 }
2745
2746 // Pick a new active touch id if needed.
2747 // Choose an arbitrary pointer that just went down, if there is one.
2748 // Otherwise choose an arbitrary remaining pointer.
2749 // This guarantees we always have an active touch id when there is at least one pointer.
2750 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002751 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002752 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002753 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002754 mPointerGesture.firstTouchTime = when;
2755 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002756 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2757 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2758 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2759 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002760 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002761 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002762
2763 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002764 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002765 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002766 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2767 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2768 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002769 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002770 *outFinishPreviousGesture = true;
2771 }
2772
2773 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002774 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002775 mPointerGesture.currentGestureIdBits.clear();
2776
2777 mPointerVelocityControl.reset();
2778 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2779 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2780 // The pointer follows the active touch point.
2781 // Emit DOWN, MOVE, UP events at the pointer location.
2782 //
2783 // Only the active touch matters; other fingers are ignored. This policy helps
2784 // to handle the case where the user places a second finger on the touch pad
2785 // to apply the necessary force to depress an integrated button below the surface.
2786 // We don't want the second finger to be delivered to applications.
2787 //
2788 // For this to work well, we need to make sure to track the pointer that is really
2789 // active. If the user first puts one finger down to click then adds another
2790 // finger to drag then the active pointer should switch to the finger that is
2791 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002792 ALOGD_IF(DEBUG_GESTURES,
2793 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2794 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002795 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002796 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002797 *outFinishPreviousGesture = true;
2798 mPointerGesture.activeGestureId = 0;
2799 }
2800
2801 // Switch pointers if needed.
2802 // Find the fastest pointer and follow it.
2803 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002804 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002805 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002806 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002807 ALOGD_IF(DEBUG_GESTURES,
2808 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2809 "bestSpeed=%0.3f",
2810 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002811 }
2812 }
2813
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002814 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002815 // When using spots, the click will occur at the position of the anchor
2816 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002817 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002818 } else {
2819 mPointerVelocityControl.reset();
2820 }
2821
Michael Wright227c5542020-07-02 18:30:52 +01002822 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002823 mPointerGesture.currentGestureIdBits.clear();
2824 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2825 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2826 mPointerGesture.currentGestureProperties[0].clear();
2827 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002828 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002829 mPointerGesture.currentGestureCoords[0].clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2831 } else if (currentFingerCount == 0) {
2832 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002833 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002834 *outFinishPreviousGesture = true;
2835 }
2836
2837 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2838 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2839 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002840 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2841 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002842 lastFingerCount == 1) {
2843 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002844 if (fabs(0.f - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2845 fabs(0.f - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002846 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002847
2848 mPointerGesture.tapUpTime = when;
2849 getContext()->requestTimeoutAtTime(when +
2850 mConfig.pointerGestureTapDragInterval);
2851
2852 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002853 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 mPointerGesture.currentGestureIdBits.clear();
2855 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2856 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2857 mPointerGesture.currentGestureProperties[0].clear();
2858 mPointerGesture.currentGestureProperties[0].id =
2859 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002860 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002861 mPointerGesture.currentGestureCoords[0].clear();
2862 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2863 mPointerGesture.tapX);
2864 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2865 mPointerGesture.tapY);
2866 mPointerGesture.currentGestureCoords[0]
2867 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2868
2869 tapped = true;
2870 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002871 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002872 0.f - mPointerGesture.tapX, 0.f - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002873 }
2874 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002875 if (DEBUG_GESTURES) {
2876 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2877 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2878 (when - mPointerGesture.tapDownTime) * 0.000001f);
2879 } else {
2880 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2881 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002882 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002883 }
2884 }
2885
2886 mPointerVelocityControl.reset();
2887
2888 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002889 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002890 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002891 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892 mPointerGesture.currentGestureIdBits.clear();
2893 }
2894 } else if (currentFingerCount == 1) {
2895 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2896 // The pointer follows the active touch point.
2897 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2898 // When in TAP_DRAG, emit MOVE events at the pointer location.
2899 ALOG_ASSERT(activeTouchId >= 0);
2900
Michael Wright227c5542020-07-02 18:30:52 +01002901 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2902 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002903 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002904 if (fabs(0.f - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2905 fabs(0.f - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002906 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002908 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002909 0.f - mPointerGesture.tapX, 0.f - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002910 }
2911 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002912 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2913 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002914 }
Michael Wright227c5542020-07-02 18:30:52 +01002915 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2916 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002917 }
2918
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002920 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002921 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 } else {
2923 mPointerVelocityControl.reset();
2924 }
2925
2926 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002927 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002928 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002929 down = true;
2930 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002931 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002932 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002933 *outFinishPreviousGesture = true;
2934 }
2935 mPointerGesture.activeGestureId = 0;
2936 down = false;
2937 }
2938
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002939 mPointerGesture.currentGestureIdBits.clear();
2940 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2941 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2942 mPointerGesture.currentGestureProperties[0].clear();
2943 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002944 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002945 mPointerGesture.currentGestureCoords[0].clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002946 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2947 down ? 1.0f : 0.0f);
2948
2949 if (lastFingerCount == 0 && currentFingerCount != 0) {
2950 mPointerGesture.resetTap();
2951 mPointerGesture.tapDownTime = when;
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002952 mPointerGesture.tapX = 0.f;
2953 mPointerGesture.tapY = 0.f;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002954 }
2955 } else {
2956 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002957 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002958 }
2959
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002960 if (DEBUG_GESTURES) {
2961 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00002962 "currentGestureMode=%s, currentGestureIdBits=0x%08x, "
2963 "lastGestureMode=%s, lastGestureIdBits=0x%08x",
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002964 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00002965 ftl::enum_string(mPointerGesture.currentGestureMode).c_str(),
2966 mPointerGesture.currentGestureIdBits.value,
2967 ftl::enum_string(mPointerGesture.lastGestureMode).c_str(),
2968 mPointerGesture.lastGestureIdBits.value);
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002969 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
2970 uint32_t id = idBits.clearFirstMarkedBit();
2971 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2972 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
2973 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002974 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002975 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002976 id, index, ftl::enum_string(properties.toolType).c_str(),
2977 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002978 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
2979 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
2980 }
2981 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
2982 uint32_t id = idBits.clearFirstMarkedBit();
2983 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
2984 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
2985 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002986 ALOGD(" lastGesture[%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 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002993 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002994 return true;
2995}
2996
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002997bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
2998 if (mPointerGesture.activeTouchId < 0) {
2999 mPointerGesture.resetQuietTime();
3000 return false;
3001 }
3002
3003 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3004 return true;
3005 }
3006
3007 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3008 bool isQuietTime = false;
3009 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3010 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3011 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3012 currentFingerCount < 2) {
3013 // Enter quiet time when exiting swipe or freeform state.
3014 // This is to prevent accidentally entering the hover state and flinging the
3015 // pointer when finishing a swipe and there is still one pointer left onscreen.
3016 isQuietTime = true;
3017 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3018 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3019 // Enter quiet time when releasing the button and there are still two or more
3020 // fingers down. This may indicate that one finger was used to press the button
3021 // but it has not gone up yet.
3022 isQuietTime = true;
3023 }
3024 if (isQuietTime) {
3025 mPointerGesture.quietTime = when;
3026 }
3027 return isQuietTime;
3028}
3029
3030std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3031 int32_t bestId = -1;
3032 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3033 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3034 uint32_t id = idBits.clearFirstMarkedBit();
3035 std::optional<float> vx =
3036 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3037 std::optional<float> vy =
3038 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3039 if (vx && vy) {
3040 float speed = hypotf(*vx, *vy);
3041 if (speed > bestSpeed) {
3042 bestId = id;
3043 bestSpeed = speed;
3044 }
3045 }
3046 }
3047 return std::make_pair(bestId, bestSpeed);
3048}
3049
3050void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3051 bool* finishPreviousGesture) {
3052 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3053 // to move before deciding what to do.
3054 //
3055 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3056 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3057 // just a press or long-press at the pointer location.
3058 //
3059 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3060 // pointer location.
3061 //
3062 // When the two fingers move enough or when additional fingers are added, we make a decision to
3063 // transition into SWIPE or FREEFORM mode accordingly.
3064 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3065 ALOG_ASSERT(activeTouchId >= 0);
3066
3067 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3068 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3069 bool settled =
3070 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3071 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3072 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3073 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3074 *finishPreviousGesture = true;
3075 } else if (!settled && currentFingerCount > lastFingerCount) {
3076 // Additional pointers have gone down but not yet settled.
3077 // Reset the gesture.
3078 ALOGD_IF(DEBUG_GESTURES,
3079 "Gestures: Resetting gesture since additional pointers went down for "
3080 "MULTITOUCH, settle time remaining %0.3fms",
3081 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3082 when) * 0.000001f);
3083 *cancelPreviousGesture = true;
3084 } else {
3085 // Continue previous gesture.
3086 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3087 }
3088
3089 if (*finishPreviousGesture || *cancelPreviousGesture) {
3090 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3091 mPointerGesture.activeGestureId = 0;
3092 mPointerGesture.referenceIdBits.clear();
3093 mPointerVelocityControl.reset();
3094
3095 // Use the centroid and pointer location as the reference points for the gesture.
3096 ALOGD_IF(DEBUG_GESTURES,
3097 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3098 "%0.3fms",
3099 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3100 when) * 0.000001f);
3101 mCurrentRawState.rawPointerData
3102 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3103 &mPointerGesture.referenceTouchY);
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00003104 mPointerGesture.referenceGestureX = 0.f;
3105 mPointerGesture.referenceGestureY = 0.f;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003106 }
3107
3108 // Clear the reference deltas for fingers not yet included in the reference calculation.
3109 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3110 ~mPointerGesture.referenceIdBits.value);
3111 !idBits.isEmpty();) {
3112 uint32_t id = idBits.clearFirstMarkedBit();
3113 mPointerGesture.referenceDeltas[id].dx = 0;
3114 mPointerGesture.referenceDeltas[id].dy = 0;
3115 }
3116 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3117
3118 // Add delta for all fingers and calculate a common movement delta.
3119 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3120 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3121 mCurrentCookedState.fingerIdBits.value);
3122 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3123 bool first = (idBits == commonIdBits);
3124 uint32_t id = idBits.clearFirstMarkedBit();
3125 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3126 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3127 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3128 delta.dx += cpd.x - lpd.x;
3129 delta.dy += cpd.y - lpd.y;
3130
3131 if (first) {
3132 commonDeltaRawX = delta.dx;
3133 commonDeltaRawY = delta.dy;
3134 } else {
3135 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3136 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3137 }
3138 }
3139
3140 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3141 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3142 float dist[MAX_POINTER_ID + 1];
3143 int32_t distOverThreshold = 0;
3144 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3145 uint32_t id = idBits.clearFirstMarkedBit();
3146 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3147 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3148 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3149 distOverThreshold += 1;
3150 }
3151 }
3152
3153 // Only transition when at least two pointers have moved further than
3154 // the minimum distance threshold.
3155 if (distOverThreshold >= 2) {
3156 if (currentFingerCount > 2) {
3157 // There are more than two pointers, switch to FREEFORM.
3158 ALOGD_IF(DEBUG_GESTURES,
3159 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3160 currentFingerCount);
3161 *cancelPreviousGesture = true;
3162 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3163 } else {
3164 // There are exactly two pointers.
3165 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3166 uint32_t id1 = idBits.clearFirstMarkedBit();
3167 uint32_t id2 = idBits.firstMarkedBit();
3168 const RawPointerData::Pointer& p1 =
3169 mCurrentRawState.rawPointerData.pointerForId(id1);
3170 const RawPointerData::Pointer& p2 =
3171 mCurrentRawState.rawPointerData.pointerForId(id2);
3172 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3173 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3174 // There are two pointers but they are too far apart for a SWIPE,
3175 // switch to FREEFORM.
3176 ALOGD_IF(DEBUG_GESTURES,
3177 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3178 mutualDistance, mPointerGestureMaxSwipeWidth);
3179 *cancelPreviousGesture = true;
3180 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3181 } else {
3182 // There are two pointers. Wait for both pointers to start moving
3183 // before deciding whether this is a SWIPE or FREEFORM gesture.
3184 float dist1 = dist[id1];
3185 float dist2 = dist[id2];
3186 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3187 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3188 // Calculate the dot product of the displacement vectors.
3189 // When the vectors are oriented in approximately the same direction,
3190 // the angle betweeen them is near zero and the cosine of the angle
3191 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3192 // mag(v2).
3193 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3194 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3195 float dx1 = delta1.dx * mPointerXZoomScale;
3196 float dy1 = delta1.dy * mPointerYZoomScale;
3197 float dx2 = delta2.dx * mPointerXZoomScale;
3198 float dy2 = delta2.dy * mPointerYZoomScale;
3199 float dot = dx1 * dx2 + dy1 * dy2;
3200 float cosine = dot / (dist1 * dist2); // denominator always > 0
3201 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3202 // Pointers are moving in the same direction. Switch to SWIPE.
3203 ALOGD_IF(DEBUG_GESTURES,
3204 "Gestures: PRESS transitioned to SWIPE, "
3205 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3206 "cosine %0.3f >= %0.3f",
3207 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3208 mConfig.pointerGestureMultitouchMinDistance, cosine,
3209 mConfig.pointerGestureSwipeTransitionAngleCosine);
3210 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3211 } else {
3212 // Pointers are moving in different directions. Switch to FREEFORM.
3213 ALOGD_IF(DEBUG_GESTURES,
3214 "Gestures: PRESS transitioned to FREEFORM, "
3215 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3216 "cosine %0.3f < %0.3f",
3217 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3218 mConfig.pointerGestureMultitouchMinDistance, cosine,
3219 mConfig.pointerGestureSwipeTransitionAngleCosine);
3220 *cancelPreviousGesture = true;
3221 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3222 }
3223 }
3224 }
3225 }
3226 }
3227 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3228 // Switch from SWIPE to FREEFORM if additional pointers go down.
3229 // Cancel previous gesture.
3230 if (currentFingerCount > 2) {
3231 ALOGD_IF(DEBUG_GESTURES,
3232 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3233 currentFingerCount);
3234 *cancelPreviousGesture = true;
3235 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3236 }
3237 }
3238
3239 // Move the reference points based on the overall group motion of the fingers
3240 // except in PRESS mode while waiting for a transition to occur.
3241 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3242 (commonDeltaRawX || commonDeltaRawY)) {
3243 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3244 uint32_t id = idBits.clearFirstMarkedBit();
3245 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3246 delta.dx = 0;
3247 delta.dy = 0;
3248 }
3249
3250 mPointerGesture.referenceTouchX += commonDeltaRawX;
3251 mPointerGesture.referenceTouchY += commonDeltaRawY;
3252
3253 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3254 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3255
3256 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3257 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3258
3259 mPointerGesture.referenceGestureX += commonDeltaX;
3260 mPointerGesture.referenceGestureY += commonDeltaY;
3261 }
3262
3263 // Report gestures.
3264 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3265 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3266 // PRESS or SWIPE mode.
3267 ALOGD_IF(DEBUG_GESTURES,
3268 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3269 "currentTouchPointerCount=%d",
3270 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3271 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3272
3273 mPointerGesture.currentGestureIdBits.clear();
3274 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3275 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3276 mPointerGesture.currentGestureProperties[0].clear();
3277 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003278 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003279 mPointerGesture.currentGestureCoords[0].clear();
3280 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3281 mPointerGesture.referenceGestureX);
3282 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3283 mPointerGesture.referenceGestureY);
3284 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3285 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3286 float xOffset = static_cast<float>(commonDeltaRawX) /
3287 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3288 float yOffset = static_cast<float>(commonDeltaRawY) /
3289 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3290 mPointerGesture.currentGestureCoords[0]
3291 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3292 mPointerGesture.currentGestureCoords[0]
3293 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3294 }
3295 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3296 // FREEFORM mode.
3297 ALOGD_IF(DEBUG_GESTURES,
3298 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3299 "currentTouchPointerCount=%d",
3300 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3301 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3302
3303 mPointerGesture.currentGestureIdBits.clear();
3304
3305 BitSet32 mappedTouchIdBits;
3306 BitSet32 usedGestureIdBits;
3307 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3308 // Initially, assign the active gesture id to the active touch point
3309 // if there is one. No other touch id bits are mapped yet.
3310 if (!*cancelPreviousGesture) {
3311 mappedTouchIdBits.markBit(activeTouchId);
3312 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3313 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3314 mPointerGesture.activeGestureId;
3315 } else {
3316 mPointerGesture.activeGestureId = -1;
3317 }
3318 } else {
3319 // Otherwise, assume we mapped all touches from the previous frame.
3320 // Reuse all mappings that are still applicable.
3321 mappedTouchIdBits.value =
3322 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3323 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3324
3325 // Check whether we need to choose a new active gesture id because the
3326 // current went went up.
3327 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3328 ~mCurrentCookedState.fingerIdBits.value);
3329 !upTouchIdBits.isEmpty();) {
3330 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3331 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3332 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3333 mPointerGesture.activeGestureId = -1;
3334 break;
3335 }
3336 }
3337 }
3338
3339 ALOGD_IF(DEBUG_GESTURES,
3340 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3341 "activeGestureId=%d",
3342 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3343
3344 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3345 for (uint32_t i = 0; i < currentFingerCount; i++) {
3346 uint32_t touchId = idBits.clearFirstMarkedBit();
3347 uint32_t gestureId;
3348 if (!mappedTouchIdBits.hasBit(touchId)) {
3349 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3350 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3351 ALOGD_IF(DEBUG_GESTURES,
3352 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3353 gestureId);
3354 } else {
3355 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3356 ALOGD_IF(DEBUG_GESTURES,
3357 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3358 touchId, gestureId);
3359 }
3360 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3361 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3362
3363 const RawPointerData::Pointer& pointer =
3364 mCurrentRawState.rawPointerData.pointerForId(touchId);
3365 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3366 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3367 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3368
3369 mPointerGesture.currentGestureProperties[i].clear();
3370 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003371 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003372 mPointerGesture.currentGestureCoords[i].clear();
3373 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3374 mPointerGesture.referenceGestureX +
3375 deltaX);
3376 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3377 mPointerGesture.referenceGestureY +
3378 deltaY);
3379 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3380 }
3381
3382 if (mPointerGesture.activeGestureId < 0) {
3383 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3384 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3385 mPointerGesture.activeGestureId);
3386 }
3387 }
3388}
3389
Harry Cutts714d1ad2022-08-24 16:36:43 +00003390void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3391 const RawPointerData::Pointer& currentPointer =
3392 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3393 const RawPointerData::Pointer& lastPointer =
3394 mLastRawState.rawPointerData.pointerForId(pointerId);
3395 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3396 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3397
3398 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3399 mPointerVelocityControl.move(when, &deltaX, &deltaY);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003400}
3401
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003402std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3403 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003404 mPointerSimple.currentCoords.clear();
3405 mPointerSimple.currentProperties.clear();
3406
3407 bool down, hovering;
3408 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3409 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3410 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003411 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3412 down = !hovering;
3413
Prabir Pradhane71e5702023-03-29 14:51:38 +00003414 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3415 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Prabir Pradhane71e5702023-03-29 14:51:38 +00003416
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003417 mPointerSimple.currentCoords = mCurrentCookedState.cookedPointerData.pointerCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003418 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3419 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3420 mPointerSimple.currentProperties.id = 0;
3421 mPointerSimple.currentProperties.toolType =
3422 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3423 } else {
3424 down = false;
3425 hovering = false;
3426 }
3427
Prabir Pradhane71e5702023-03-29 14:51:38 +00003428 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003429}
3430
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003431std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3432 uint32_t policyFlags) {
3433 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003434}
3435
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003436std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3437 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003438 mPointerSimple.currentCoords.clear();
3439 mPointerSimple.currentProperties.clear();
3440
3441 bool down, hovering;
3442 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3443 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003444 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003445 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003446 } else {
3447 mPointerVelocityControl.reset();
3448 }
3449
3450 down = isPointerDown(mCurrentRawState.buttonState);
3451 hovering = !down;
3452
Prabir Pradhan2719e822023-02-28 17:39:36 +00003453 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003454 mPointerSimple.currentCoords =
3455 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003456 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3457 hovering ? 0.0f : 1.0f);
3458 mPointerSimple.currentProperties.id = 0;
3459 mPointerSimple.currentProperties.toolType =
3460 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3461 } else {
3462 mPointerVelocityControl.reset();
3463
3464 down = false;
3465 hovering = false;
3466 }
3467
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07003468 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering,
3469 ui::LogicalDisplayId::INVALID);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003470}
3471
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003472std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3473 uint32_t policyFlags) {
3474 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003475
3476 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003477
3478 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003479}
3480
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003481std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3482 uint32_t policyFlags, bool down,
Linnan Li13bf76a2024-05-05 19:18:02 +08003483 bool hovering,
3484 ui::LogicalDisplayId displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003485 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3486 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003487 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003488 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003489 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003490
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003491 if (mPointerSimple.down && !down) {
3492 mPointerSimple.down = false;
3493
3494 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003495 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3496 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3497 0, metaState, mLastRawState.buttonState,
3498 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3499 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003500 mOrientedXPrecision, mOrientedYPrecision,
3501 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3502 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003503 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003504 }
3505
3506 if (mPointerSimple.hovering && !hovering) {
3507 mPointerSimple.hovering = false;
3508
3509 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003510 out.push_back(
3511 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3512 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3513 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3514 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3515 &mPointerSimple.lastCoords, mOrientedXPrecision,
3516 mOrientedYPrecision, mPointerSimple.lastCursorX,
3517 mPointerSimple.lastCursorY, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003518 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003519 }
3520
3521 if (down) {
3522 if (!mPointerSimple.down) {
3523 mPointerSimple.down = true;
3524 mPointerSimple.downTime = when;
3525
3526 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003527 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3528 mSource, displayId, policyFlags,
3529 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3530 mCurrentRawState.buttonState, MotionClassification::NONE,
3531 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3532 &mPointerSimple.currentProperties,
3533 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003534 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003535 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003536 }
3537
3538 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003539 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3540 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3541 0, 0, metaState, mCurrentRawState.buttonState,
3542 MotionClassification::NONE, 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 if (hovering) {
3550 if (!mPointerSimple.hovering) {
3551 mPointerSimple.hovering = true;
3552
3553 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003554 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3555 mSource, displayId, policyFlags,
3556 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3557 mCurrentRawState.buttonState, MotionClassification::NONE,
3558 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3559 &mPointerSimple.currentProperties,
3560 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003561 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003562 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003563 }
3564
3565 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003566 out.push_back(
3567 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3568 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3569 metaState, mCurrentRawState.buttonState,
3570 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3571 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003572 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003573 cursorPosition.y, mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003574 }
3575
3576 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3577 float vscroll = mCurrentRawState.rawVScroll;
3578 float hscroll = mCurrentRawState.rawHScroll;
3579 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3580 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3581
3582 // Send scroll.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003583 PointerCoords pointerCoords = mPointerSimple.currentCoords;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003584 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3585 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3586
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003587 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3588 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3589 0, 0, metaState, mCurrentRawState.buttonState,
3590 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3591 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003592 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3593 cursorPosition.y, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003594 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003595 }
3596
3597 // Save state.
3598 if (down || hovering) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003599 mPointerSimple.lastCoords = mPointerSimple.currentCoords;
3600 mPointerSimple.lastProperties = mPointerSimple.currentProperties;
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003601 mPointerSimple.displayId = displayId;
3602 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003603 mPointerSimple.lastCursorX = cursorPosition.x;
3604 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003605 } else {
3606 mPointerSimple.reset();
3607 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003608 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003609}
3610
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003611std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3612 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003613 std::list<NotifyArgs> out;
3614 if (mPointerSimple.down || mPointerSimple.hovering) {
3615 int32_t metaState = getContext()->getGlobalMetaState();
3616 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3617 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3618 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3619 metaState, mLastRawState.buttonState,
3620 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3621 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3622 mOrientedXPrecision, mOrientedYPrecision,
3623 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3624 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003625 /*videoFrames=*/{}));
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003626 }
3627 mPointerSimple.reset();
3628 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003629}
3630
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003631NotifyMotionArgs TouchInputMapper::dispatchMotion(
3632 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3633 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003634 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3635 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003636 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003637 std::vector<PointerCoords> pointerCoords;
3638 std::vector<PointerProperties> pointerProperties;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003639 uint32_t pointerCount = 0;
3640 while (!idBits.isEmpty()) {
3641 uint32_t id = idBits.clearFirstMarkedBit();
3642 uint32_t index = idToIndex[id];
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003643 pointerProperties.push_back(properties[index]);
3644 pointerCoords.push_back(coords[index]);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003645
3646 if (changedId >= 0 && id == uint32_t(changedId)) {
3647 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3648 }
3649
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003650 pointerCount++;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003651 }
3652
3653 ALOG_ASSERT(pointerCount != 0);
3654
3655 if (changedId >= 0 && pointerCount == 1) {
3656 // Replace initial down and final up action.
3657 // We can compare the action without masking off the changed pointer index
3658 // because we know the index is 0.
3659 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3660 action = AMOTION_EVENT_ACTION_DOWN;
3661 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003662 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3663 action = AMOTION_EVENT_ACTION_CANCEL;
3664 } else {
3665 action = AMOTION_EVENT_ACTION_UP;
3666 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003667 } else {
3668 // Can't happen.
3669 ALOG_ASSERT(false);
3670 }
3671 }
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00003672 if (mCurrentStreamModifiedByExternalStylus) {
3673 source |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3674 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003675
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07003676 const ui::LogicalDisplayId displayId =
3677 getAssociatedDisplayId().value_or(ui::LogicalDisplayId::INVALID);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003678
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003679 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3680 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003681 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00003682 xCursorPosition = yCursorPosition = 0.f;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003683 }
Linnan Li13bf76a2024-05-05 19:18:02 +08003684 const DeviceId deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003685 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003686 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003687 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003688 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3689 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003690 classification, edgeFlags, pointerCount, pointerProperties.data(),
3691 pointerCoords.data(), xPrecision, yPrecision, xCursorPosition,
3692 yCursorPosition, downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003693}
3694
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003695std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3696 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003697 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3698 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003699 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003700}
3701
Prabir Pradhan1728b212021-10-19 16:00:03 -07003702bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003703 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003704 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003705 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003706}
3707
3708const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3709 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003710 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3711 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3712 "left=%d, top=%d, right=%d, bottom=%d",
3713 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3714 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003715
3716 if (virtualKey.isHit(x, y)) {
3717 return &virtualKey;
3718 }
3719 }
3720
3721 return nullptr;
3722}
3723
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003724void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3725 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3726 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003727
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003728 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003729
3730 if (currentPointerCount == 0) {
3731 // No pointers to assign.
3732 return;
3733 }
3734
3735 if (lastPointerCount == 0) {
3736 // All pointers are new.
3737 for (uint32_t i = 0; i < currentPointerCount; i++) {
3738 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003739 current.rawPointerData.pointers[i].id = id;
3740 current.rawPointerData.idToIndex[id] = i;
3741 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003742 }
3743 return;
3744 }
3745
3746 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003747 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003748 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003749 uint32_t id = last.rawPointerData.pointers[0].id;
3750 current.rawPointerData.pointers[0].id = id;
3751 current.rawPointerData.idToIndex[id] = 0;
3752 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003753 return;
3754 }
3755
3756 // General case.
3757 // We build a heap of squared euclidean distances between current and last pointers
3758 // associated with the current and last pointer indices. Then, we find the best
3759 // match (by distance) for each current pointer.
3760 // The pointers must have the same tool type but it is possible for them to
3761 // transition from hovering to touching or vice-versa while retaining the same id.
3762 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3763
3764 uint32_t heapSize = 0;
3765 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3766 currentPointerIndex++) {
3767 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3768 lastPointerIndex++) {
3769 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003770 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003771 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003772 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003773 if (currentPointer.toolType == lastPointer.toolType) {
3774 int64_t deltaX = currentPointer.x - lastPointer.x;
3775 int64_t deltaY = currentPointer.y - lastPointer.y;
3776
3777 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3778
3779 // Insert new element into the heap (sift up).
3780 heap[heapSize].currentPointerIndex = currentPointerIndex;
3781 heap[heapSize].lastPointerIndex = lastPointerIndex;
3782 heap[heapSize].distance = distance;
3783 heapSize += 1;
3784 }
3785 }
3786 }
3787
3788 // Heapify
3789 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3790 startIndex -= 1;
3791 for (uint32_t parentIndex = startIndex;;) {
3792 uint32_t childIndex = parentIndex * 2 + 1;
3793 if (childIndex >= heapSize) {
3794 break;
3795 }
3796
3797 if (childIndex + 1 < heapSize &&
3798 heap[childIndex + 1].distance < heap[childIndex].distance) {
3799 childIndex += 1;
3800 }
3801
3802 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3803 break;
3804 }
3805
3806 swap(heap[parentIndex], heap[childIndex]);
3807 parentIndex = childIndex;
3808 }
3809 }
3810
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003811 if (DEBUG_POINTER_ASSIGNMENT) {
3812 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3813 for (size_t i = 0; i < heapSize; i++) {
3814 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3815 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3816 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003817 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003818
3819 // Pull matches out by increasing order of distance.
3820 // To avoid reassigning pointers that have already been matched, the loop keeps track
3821 // of which last and current pointers have been matched using the matchedXXXBits variables.
3822 // It also tracks the used pointer id bits.
3823 BitSet32 matchedLastBits(0);
3824 BitSet32 matchedCurrentBits(0);
3825 BitSet32 usedIdBits(0);
3826 bool first = true;
3827 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3828 while (heapSize > 0) {
3829 if (first) {
3830 // The first time through the loop, we just consume the root element of
3831 // the heap (the one with smallest distance).
3832 first = false;
3833 } else {
3834 // Previous iterations consumed the root element of the heap.
3835 // Pop root element off of the heap (sift down).
3836 heap[0] = heap[heapSize];
3837 for (uint32_t parentIndex = 0;;) {
3838 uint32_t childIndex = parentIndex * 2 + 1;
3839 if (childIndex >= heapSize) {
3840 break;
3841 }
3842
3843 if (childIndex + 1 < heapSize &&
3844 heap[childIndex + 1].distance < heap[childIndex].distance) {
3845 childIndex += 1;
3846 }
3847
3848 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3849 break;
3850 }
3851
3852 swap(heap[parentIndex], heap[childIndex]);
3853 parentIndex = childIndex;
3854 }
3855
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003856 if (DEBUG_POINTER_ASSIGNMENT) {
3857 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3858 for (size_t j = 0; j < heapSize; j++) {
3859 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3860 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3861 heap[j].distance);
3862 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003863 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003864 }
3865
3866 heapSize -= 1;
3867
3868 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3869 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3870
3871 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3872 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3873
3874 matchedCurrentBits.markBit(currentPointerIndex);
3875 matchedLastBits.markBit(lastPointerIndex);
3876
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003877 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3878 current.rawPointerData.pointers[currentPointerIndex].id = id;
3879 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3880 current.rawPointerData.markIdBit(id,
3881 current.rawPointerData.isHovering(
3882 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003883 usedIdBits.markBit(id);
3884
Harry Cutts45483602022-08-24 14:36:48 +00003885 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3886 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3887 ", distance=%" PRIu64,
3888 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003889 break;
3890 }
3891 }
3892
3893 // Assign fresh ids to pointers that were not matched in the process.
3894 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3895 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3896 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3897
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003898 current.rawPointerData.pointers[currentPointerIndex].id = id;
3899 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3900 current.rawPointerData.markIdBit(id,
3901 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003902
Harry Cutts45483602022-08-24 14:36:48 +00003903 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3904 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
3905 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003906 }
3907}
3908
3909int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3910 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3911 return AKEY_STATE_VIRTUAL;
3912 }
3913
3914 for (const VirtualKey& virtualKey : mVirtualKeys) {
3915 if (virtualKey.keyCode == keyCode) {
3916 return AKEY_STATE_UP;
3917 }
3918 }
3919
3920 return AKEY_STATE_UNKNOWN;
3921}
3922
3923int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3924 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3925 return AKEY_STATE_VIRTUAL;
3926 }
3927
3928 for (const VirtualKey& virtualKey : mVirtualKeys) {
3929 if (virtualKey.scanCode == scanCode) {
3930 return AKEY_STATE_UP;
3931 }
3932 }
3933
3934 return AKEY_STATE_UNKNOWN;
3935}
3936
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003937bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
3938 const std::vector<int32_t>& keyCodes,
3939 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003940 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003941 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003942 if (virtualKey.keyCode == keyCodes[i]) {
3943 outFlags[i] = 1;
3944 }
3945 }
3946 }
3947
3948 return true;
3949}
3950
Linnan Li13bf76a2024-05-05 19:18:02 +08003951std::optional<ui::LogicalDisplayId> TouchInputMapper::getAssociatedDisplayId() {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003952 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003953 if (mDeviceMode == DeviceMode::POINTER) {
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07003954 return ui::LogicalDisplayId::INVALID;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003955 } else {
3956 return std::make_optional(mViewport.displayId);
3957 }
3958 }
3959 return std::nullopt;
3960}
3961
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003962} // namespace android