blob: 984e217efc896abaa8345ef5324448595aeb1adb [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.
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000603 if (mRawPointerAxes.touchMajor && mRawPointerAxes.touchMajor->maxValue != 0) {
604 mSizeScale = 1.0f / mRawPointerAxes.touchMajor->maxValue;
605 } else if (mRawPointerAxes.toolMajor && mRawPointerAxes.toolMajor->maxValue != 0) {
606 mSizeScale = 1.0f / mRawPointerAxes.toolMajor->maxValue;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800607 } 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
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000621 if (mRawPointerAxes.touchMajor) {
622 mRawPointerAxes.touchMajor->resolution =
623 clampResolution("touchMajor", mRawPointerAxes.touchMajor->resolution);
624 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;
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000629 if (mRawPointerAxes.touchMinor) {
630 mRawPointerAxes.touchMinor->resolution =
631 clampResolution("touchMinor", mRawPointerAxes.touchMinor->resolution);
632 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 };
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000644 if (mRawPointerAxes.toolMajor) {
645 mRawPointerAxes.toolMajor->resolution =
646 clampResolution("toolMajor", mRawPointerAxes.toolMajor->resolution);
647 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;
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000652 if (mRawPointerAxes.toolMinor) {
653 mRawPointerAxes.toolMinor->resolution =
654 clampResolution("toolMinor", mRawPointerAxes.toolMinor->resolution);
655 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;
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000707 pressureMax = mPressureScale *
708 (mRawPointerAxes.pressure ? mRawPointerAxes.pressure->maxValue : 0);
709 } else if (mRawPointerAxes.pressure && mRawPointerAxes.pressure->maxValue != 0) {
710 mPressureScale = 1.0f / mRawPointerAxes.pressure->maxValue;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800711 }
712 }
713
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700714 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
715 .axis = AMOTION_EVENT_AXIS_PRESSURE,
716 .source = mSource,
717 .min = 0,
718 .max = pressureMax,
719 .flat = 0,
720 .fuzz = 0,
721 .resolution = 0,
722 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800723
724 // Tilt
725 mTiltXCenter = 0;
726 mTiltXScale = 0;
727 mTiltYCenter = 0;
728 mTiltYScale = 0;
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000729 mHaveTilt = mRawPointerAxes.tiltX && mRawPointerAxes.tiltY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800730 if (mHaveTilt) {
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000731 mTiltXCenter = avg(mRawPointerAxes.tiltX->minValue, mRawPointerAxes.tiltX->maxValue);
732 mTiltYCenter = avg(mRawPointerAxes.tiltY->minValue, mRawPointerAxes.tiltY->maxValue);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800733 mTiltXScale = M_PI / 180;
734 mTiltYScale = M_PI / 180;
735
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000736 if (mRawPointerAxes.tiltX->resolution) {
737 mTiltXScale = 1.0 / mRawPointerAxes.tiltX->resolution;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800738 }
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000739 if (mRawPointerAxes.tiltY->resolution) {
740 mTiltYScale = 1.0 / mRawPointerAxes.tiltY->resolution;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800741 }
742
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700743 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
744 .axis = AMOTION_EVENT_AXIS_TILT,
745 .source = mSource,
746 .min = 0,
747 .max = M_PI_2,
748 .flat = 0,
749 .fuzz = 0,
750 .resolution = 0,
751 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800752 }
753
754 // Orientation
755 mOrientationScale = 0;
756 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700757 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
758 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
759 .source = mSource,
760 .min = -M_PI,
761 .max = M_PI,
762 .flat = 0,
763 .fuzz = 0,
764 .resolution = 0,
765 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800766
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800767 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
768 if (mCalibration.orientationCalibration ==
769 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000770 if (mRawPointerAxes.orientation) {
771 if (mRawPointerAxes.orientation->maxValue > 0) {
772 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation->maxValue;
773 } else if (mRawPointerAxes.orientation->minValue < 0) {
774 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation->minValue;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800775 } else {
776 mOrientationScale = 0;
777 }
778 }
779 }
780
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700781 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
782 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
783 .source = mSource,
784 .min = -M_PI_2,
785 .max = M_PI_2,
786 .flat = 0,
787 .fuzz = 0,
788 .resolution = 0,
789 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800790 }
791
792 // Distance
793 mDistanceScale = 0;
794 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
795 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700796 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800797 }
798
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000799 const bool hasDistance = mRawPointerAxes.distance.has_value();
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700800 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700801 .axis = AMOTION_EVENT_AXIS_DISTANCE,
802 .source = mSource,
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000803 .min = hasDistance ? mRawPointerAxes.distance->minValue * mDistanceScale : 0,
804 .max = hasDistance ? mRawPointerAxes.distance->maxValue * mDistanceScale : 0,
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700805 .flat = 0,
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000806 .fuzz = hasDistance ? mRawPointerAxes.distance->fuzz * mDistanceScale : 0,
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700807 .resolution = 0,
808 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800809 }
810
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000811 // Oriented X/Y range (in the rotated display's orientation)
812 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
813 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
814 .toFloatRect();
815 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
816 mOrientedRanges.x.min = orientedRangeRect.left;
817 mOrientedRanges.y.min = orientedRangeRect.top;
818 mOrientedRanges.x.max = orientedRangeRect.right;
819 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800820
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000821 // Oriented flat (in the rotated display's orientation)
822 const auto orientedFlat =
823 transformWithoutTranslation(mRawToRotatedDisplay,
824 {static_cast<float>(mRawPointerAxes.x.flat),
825 static_cast<float>(mRawPointerAxes.y.flat)});
826 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
827 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800828
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000829 // Oriented fuzz (in the rotated display's orientation)
830 const auto orientedFuzz =
831 transformWithoutTranslation(mRawToRotatedDisplay,
832 {static_cast<float>(mRawPointerAxes.x.fuzz),
833 static_cast<float>(mRawPointerAxes.y.fuzz)});
834 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
835 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800836
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000837 // Oriented resolution (in the rotated display's orientation)
838 const auto orientedRes =
839 transformWithoutTranslation(mRawToRotatedDisplay,
840 {static_cast<float>(mRawPointerAxes.x.resolution),
841 static_cast<float>(mRawPointerAxes.y.resolution)});
842 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
843 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800844}
845
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000846void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000847 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
848 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
849 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000850
Prabir Pradhan3e798762022-12-02 21:02:11 +0000851 // See notes about input coordinates in the inputflinger docs:
852 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000853
854 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000855 ui::Transform undoOffsetInRaw;
856 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000857
Prabir Pradhan3e798762022-12-02 21:02:11 +0000858 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
859 // will now be in the same orientation as the display in ROTATION_0.
860 // Note: Negating an ui::Rotation value will give its inverse rotation.
861 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
862 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
863 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
864 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
865 // When rotating raw values, account for the extra unit added when calculating the raw range.
866 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
867 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000868
Prabir Pradhan3e798762022-12-02 21:02:11 +0000869 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
870 // now be in the same orientation as the rotated display. There is no need to rotate the
871 // coordinates to the display rotation if the device is not orientation-aware.
872 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
873 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
874 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
875 : orientedRawSize;
876 // When rotating raw values, account for the extra unit added when calculating the raw range.
877 const auto rotateInRaw = mParameters.orientationAware
878 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
879 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000880
Prabir Pradhan3e798762022-12-02 21:02:11 +0000881 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000882 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
883 // the surface of the display panel. This is usually true for touchscreens.
884 // - In POINTER mode, we cannot assume that the display and the touch device have the same
885 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
886 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
887 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
888 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000889 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
890 // are in the continuous space of the logical display.
891 ui::Transform scaleRawToDisplay;
892 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
893 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000894 if (mDeviceMode == DeviceMode::DIRECT) {
895 scaleRawToDisplay.set(xScale, 0, 0, yScale);
896 } else if (mDeviceMode == DeviceMode::POINTER) {
897 const float fixedScale = std::max(xScale, yScale);
898 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
899 } else {
900 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
901 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000902
Prabir Pradhan3e798762022-12-02 21:02:11 +0000903 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
904 // that InputReader uses.
905 const auto undoRotateInDisplay =
906 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
907 .inverse();
908
909 // Now put it all together!
910 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
911 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
912 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000913}
914
Prabir Pradhan1728b212021-10-19 16:00:03 -0700915void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000916 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700917
918 resolveExternalStylusPresence();
919
920 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100921 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +0900922 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700923 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100924 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700925 if (hasStylus()) {
926 mSource |= AINPUT_SOURCE_STYLUS;
927 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800928 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700929 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100930 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700931 if (hasStylus()) {
932 mSource |= AINPUT_SOURCE_STYLUS;
933 }
Michael Wright227c5542020-07-02 18:30:52 +0100934 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhan9cf8f322024-06-18 20:22:42 +0000935 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION | AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100936 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700937 } else {
Harry Cutts8722be92024-04-05 14:46:05 +0000938 ALOGW("Touch device '%s' has invalid parameters or configuration. The device will be "
939 "inoperable.",
940 getDeviceName().c_str());
941 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700942 }
943
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000944 const std::optional<DisplayViewport> newViewportOpt = findViewport();
945
946 // Ensure the device is valid and can be used.
Prabir Pradhan132f21c2024-07-25 16:48:30 +0000947 if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700948 ALOGI("Touch device '%s' could not query the properties of its associated "
949 "display. The device will be inoperable until the display size "
950 "becomes available.",
951 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100952 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700953 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000954 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
955 getDeviceName().c_str(), getDeviceId());
956 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000957 }
958
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700959 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000960 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000961 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
962 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
963 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
964 const float rawMeanResolution =
965 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000967 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
Josh Thielene986aed2023-06-01 14:17:30 +0000968 bool viewportChanged;
969 if (mParameters.enableForInactiveViewport) {
970 // When touch is enabled for an inactive viewport, ignore the
971 // viewport active status when checking whether the viewport has
972 // changed.
973 DisplayViewport tempViewport = mViewport;
974 tempViewport.isActive = newViewport.isActive;
975 viewportChanged = tempViewport != newViewport;
976 } else {
977 viewportChanged = mViewport != newViewport;
978 }
979
Biswarup Pal9ce4d9f2024-06-14 15:05:27 +0000980 const bool deviceModeChanged = mDeviceMode != oldDeviceMode;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700981 bool skipViewportUpdate = false;
Biswarup Pal9ce4d9f2024-06-14 15:05:27 +0000982 if (viewportChanged || deviceModeChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000983 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
984 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
985 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700986
Michael Wright227c5542020-07-02 18:30:52 +0100987 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000988 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700989
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000990 mDisplayBounds = getNaturalDisplaySize(mViewport);
991 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
992 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700993
Prabir Pradhan3e798762022-12-02 21:02:11 +0000994 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
995 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
996 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000997 // InputReader works in the un-rotated display coordinate space, so we don't need to do
998 // anything if the device is already orientation-aware. If the device is not
999 // orientation-aware, then we need to apply the inverse rotation of the display so that
1000 // when the display rotation is applied later as a part of the per-window transform, we
1001 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001002 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +00001003 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001004 : getInverseRotation(mViewport.orientation);
1005 // For orientation-aware devices that work in the un-rotated coordinate space, the
1006 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001007 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001008 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001009
1010 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001011 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001012 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001013 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001014 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001015 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001016 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001017 mRawToDisplay.reset();
1018 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001019 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001020 }
1021 }
1022
1023 // If moving between pointer modes, need to reset some state.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001024 if (deviceModeChanged) {
1025 mOrientedRanges.clear();
1026 }
1027
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001028 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001029 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %s, mode %s, "
Linnan Li13bf76a2024-05-05 19:18:02 +08001030 "display id %s",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001031 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001032 ftl::enum_string(mInputDeviceOrientation).c_str(),
Linnan Li13bf76a2024-05-05 19:18:02 +08001033 ftl::enum_string(mDeviceMode).c_str(), mViewport.displayId.toString().c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001034
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001035 configureVirtualKeys();
1036
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001037 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001038
1039 // Location
1040 updateAffineTransformation();
1041
Michael Wright227c5542020-07-02 18:30:52 +01001042 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001043 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001044 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1045 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001046
1047 // Scale movements such that one whole swipe of the touch pad covers a
1048 // given area relative to the diagonal size of the display when no acceleration
1049 // is applied.
1050 // Assume that the touch pad has a square aspect ratio such that movements in
1051 // X and Y of the same number of raw units cover the same physical distance.
1052 mPointerXMovementScale =
1053 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1054 mPointerYMovementScale = mPointerXMovementScale;
1055
1056 // Scale zooms to cover a smaller range of the display than movements do.
1057 // This value determines the area around the pointer that is affected by freeform
1058 // pointer gestures.
1059 mPointerXZoomScale =
1060 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1061 mPointerYZoomScale = mPointerXZoomScale;
1062
HQ Liue6983c72022-04-19 22:14:56 +00001063 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1064 // axis is non positive value.
1065 const float minFreeformGestureWidth =
1066 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1067
1068 mPointerGestureMaxSwipeWidth =
1069 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1070 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001071 }
1072
1073 // Inform the dispatcher about the changes.
1074 *outResetNeeded = true;
1075 bumpGeneration();
1076 }
1077}
1078
Prabir Pradhan1728b212021-10-19 16:00:03 -07001079void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001080 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001081 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001082 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1083 toString(mPhysicalFrameInRotatedDisplay).c_str());
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001084 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %s\n",
1085 ftl::enum_string(mInputDeviceOrientation).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086}
1087
1088void TouchInputMapper::configureVirtualKeys() {
1089 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001090 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001091
1092 mVirtualKeys.clear();
1093
1094 if (virtualKeyDefinitions.size() == 0) {
1095 return;
1096 }
1097
1098 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1099 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1100 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1101 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1102
1103 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1104 VirtualKey virtualKey;
1105
1106 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1107 int32_t keyCode;
1108 int32_t dummyKeyMetaState;
1109 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001110 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1111 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001112 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1113 continue; // drop the key
1114 }
1115
1116 virtualKey.keyCode = keyCode;
1117 virtualKey.flags = flags;
1118
1119 // convert the key definition's display coordinates into touch coordinates for a hit box
1120 int32_t halfWidth = virtualKeyDefinition.width / 2;
1121 int32_t halfHeight = virtualKeyDefinition.height / 2;
1122
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001123 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1124 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001125 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001126 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1127 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001128 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001129 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1130 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001131 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001132 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1133 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001134 touchScreenTop;
1135 mVirtualKeys.push_back(virtualKey);
1136 }
1137}
1138
1139void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1140 if (!mVirtualKeys.empty()) {
1141 dump += INDENT3 "Virtual Keys:\n";
1142
1143 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1144 const VirtualKey& virtualKey = mVirtualKeys[i];
1145 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1146 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1147 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1148 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1149 }
1150 }
1151}
1152
1153void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001154 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001155 Calibration& out = mCalibration;
1156
1157 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001158 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001159 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1160 if (sizeCalibrationString.has_value()) {
1161 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001162 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001163 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001164 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001165 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001166 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001167 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001168 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001169 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001171 } else if (*sizeCalibrationString != "default") {
1172 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001173 }
1174 }
1175
Harry Cuttsf13161a2023-03-08 14:15:49 +00001176 out.sizeScale = in.getFloat("touch.size.scale");
1177 out.sizeBias = in.getFloat("touch.size.bias");
1178 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179
1180 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001182 std::optional<std::string> pressureCalibrationString =
1183 in.getString("touch.pressure.calibration");
1184 if (pressureCalibrationString.has_value()) {
1185 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001186 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001187 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001189 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001191 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001193 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001194 }
1195 }
1196
Harry Cuttsf13161a2023-03-08 14:15:49 +00001197 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198
1199 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001201 std::optional<std::string> orientationCalibrationString =
1202 in.getString("touch.orientation.calibration");
1203 if (orientationCalibrationString.has_value()) {
1204 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001205 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001206 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001207 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001208 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001209 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001210 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001212 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 }
1214 }
1215
1216 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001217 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001218 std::optional<std::string> distanceCalibrationString =
1219 in.getString("touch.distance.calibration");
1220 if (distanceCalibrationString.has_value()) {
1221 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001223 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001224 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001225 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001226 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001227 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001228 }
1229 }
1230
Harry Cuttsf13161a2023-03-08 14:15:49 +00001231 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232}
1233
1234void TouchInputMapper::resolveCalibration() {
1235 // Size
Prabir Pradhan132f21c2024-07-25 16:48:30 +00001236 if (mRawPointerAxes.touchMajor || mRawPointerAxes.toolMajor) {
Michael Wright227c5542020-07-02 18:30:52 +01001237 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1238 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 }
1240 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001241 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 }
1243
1244 // Pressure
Prabir Pradhan132f21c2024-07-25 16:48:30 +00001245 if (mRawPointerAxes.pressure) {
Michael Wright227c5542020-07-02 18:30:52 +01001246 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1247 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 }
1249 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001250 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001251 }
1252
1253 // Orientation
Prabir Pradhan132f21c2024-07-25 16:48:30 +00001254 if (mRawPointerAxes.orientation) {
Michael Wright227c5542020-07-02 18:30:52 +01001255 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1256 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 }
1258 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001259 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 }
1261
1262 // Distance
Prabir Pradhan132f21c2024-07-25 16:48:30 +00001263 if (mRawPointerAxes.distance) {
Michael Wright227c5542020-07-02 18:30:52 +01001264 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1265 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 }
1267 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001268 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270}
1271
1272void TouchInputMapper::dumpCalibration(std::string& dump) {
1273 dump += INDENT3 "Calibration:\n";
1274
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001275 dump += INDENT4 "touch.size.calibration: ";
1276 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001278 if (mCalibration.sizeScale) {
1279 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 }
1281
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001282 if (mCalibration.sizeBias) {
1283 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 }
1285
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001286 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001288 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 }
1290
1291 // Pressure
1292 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001293 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 dump += INDENT4 "touch.pressure.calibration: none\n";
1295 break;
Michael Wright227c5542020-07-02 18:30:52 +01001296 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 dump += INDENT4 "touch.pressure.calibration: physical\n";
1298 break;
Michael Wright227c5542020-07-02 18:30:52 +01001299 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1301 break;
1302 default:
1303 ALOG_ASSERT(false);
1304 }
1305
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001306 if (mCalibration.pressureScale) {
1307 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 }
1309
1310 // Orientation
1311 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001312 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.orientation.calibration: none\n";
1314 break;
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1317 break;
Michael Wright227c5542020-07-02 18:30:52 +01001318 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.orientation.calibration: vector\n";
1320 break;
1321 default:
1322 ALOG_ASSERT(false);
1323 }
1324
1325 // Distance
1326 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001327 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 dump += INDENT4 "touch.distance.calibration: none\n";
1329 break;
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.distance.calibration: scaled\n";
1332 break;
1333 default:
1334 ALOG_ASSERT(false);
1335 }
1336
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001337 if (mCalibration.distanceScale) {
1338 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001339 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001340}
1341
1342void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1343 dump += INDENT3 "Affine Transformation:\n";
1344
1345 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1346 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1347 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1348 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1349 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1350 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1351}
1352
1353void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001354 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001355 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356}
1357
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001358std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001359 std::list<NotifyArgs> out = cancelTouch(when, when);
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001360
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001361 mCursorButtonAccumulator.reset(getDeviceContext());
1362 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001363 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001364
1365 mPointerVelocityControl.reset();
1366 mWheelXVelocityControl.reset();
1367 mWheelYVelocityControl.reset();
1368
1369 mRawStatesPending.clear();
1370 mCurrentRawState.clear();
1371 mCurrentCookedState.clear();
1372 mLastRawState.clear();
1373 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001374 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001375 mSentHoverEnter = false;
1376 mHavePointerIds = false;
1377 mCurrentMotionAborted = false;
1378 mDownTime = 0;
1379
1380 mCurrentVirtualKey.down = false;
1381
1382 mPointerGesture.reset();
1383 mPointerSimple.reset();
1384 resetExternalStylus();
1385
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001386 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001387}
1388
1389void TouchInputMapper::resetExternalStylus() {
1390 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001391 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001392 mExternalStylusFusionTimeout = LLONG_MAX;
1393 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001394 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001395}
1396
1397void TouchInputMapper::clearStylusDataPendingFlags() {
1398 mExternalStylusDataPending = false;
1399 mExternalStylusFusionTimeout = LLONG_MAX;
1400}
1401
Harry Cuttsa32a1192024-06-04 15:10:31 +00001402std::list<NotifyArgs> TouchInputMapper::process(const RawEvent& rawEvent) {
1403 mCursorButtonAccumulator.process(rawEvent);
1404 mCursorScrollAccumulator.process(rawEvent);
1405 mTouchButtonAccumulator.process(rawEvent);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001406
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001407 std::list<NotifyArgs> out;
Harry Cuttsa32a1192024-06-04 15:10:31 +00001408 if (rawEvent.type == EV_SYN && rawEvent.code == SYN_REPORT) {
1409 out += sync(rawEvent.when, rawEvent.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001410 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001411 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001412}
1413
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001414std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1415 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001416 if (mDeviceMode == DeviceMode::DISABLED) {
1417 // Only save the last pending state when the device is disabled.
1418 mRawStatesPending.clear();
1419 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001420 // Push a new state.
1421 mRawStatesPending.emplace_back();
1422
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001423 RawState& next = mRawStatesPending.back();
1424 next.clear();
1425 next.when = when;
1426 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001427
1428 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001429 next.buttonState = filterButtonState(mConfig,
1430 mTouchButtonAccumulator.getButtonState() |
1431 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001432
1433 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001434 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1435 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436 mCursorScrollAccumulator.finishSync();
1437
1438 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001439 syncTouch(when, &next);
1440
1441 // The last RawState is the actually second to last, since we just added a new state
1442 const RawState& last =
1443 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001445 std::tie(next.when, next.readTime) =
1446 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1447 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001448
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001449 // Assign pointer ids.
1450 if (!mHavePointerIds) {
1451 assignPointerIds(last, next);
1452 }
1453
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001454 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001455 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1456 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1457 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1458 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1459 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1460 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001461
Arthur Hung9ad18942021-06-19 02:04:46 +00001462 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1463 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1464 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1465 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1466 next.rawPointerData.hoveringIdBits.value);
1467 }
1468
Harry Cutts33476232023-01-30 19:57:29 +00001469 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001470 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001471}
1472
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001473std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1474 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001475 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001476 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001477 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001478 }
1479
1480 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1481 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1482 // touching the current state will only observe the events that have been dispatched to the
1483 // rest of the pipeline.
1484 const size_t N = mRawStatesPending.size();
1485 size_t count;
1486 for (count = 0; count < N; count++) {
1487 const RawState& next = mRawStatesPending[count];
1488
1489 // A failure to assign the stylus id means that we're waiting on stylus data
1490 // and so should defer the rest of the pipeline.
1491 if (assignExternalStylusId(next, timeout)) {
1492 break;
1493 }
1494
1495 // All ready to go.
1496 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001497 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498 if (mCurrentRawState.when < mLastRawState.when) {
1499 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001500 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001501 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001502 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001503 }
1504 if (count != 0) {
1505 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1506 }
1507
1508 if (mExternalStylusDataPending) {
1509 if (timeout) {
1510 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1511 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001512 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001513 ALOGD_IF(DEBUG_STYLUS_FUSION,
1514 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001515 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001516 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001517 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1518 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1519 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1520 }
1521 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001522 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001523}
1524
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001525std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1526 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001527 // Always start with a clean state.
1528 mCurrentCookedState.clear();
1529
1530 // Apply stylus buttons to current raw state.
1531 applyExternalStylusButtonState(when);
1532
1533 // Handle policy on initial down or hover events.
1534 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1535 mCurrentRawState.rawPointerData.pointerCount != 0;
1536
1537 uint32_t policyFlags = 0;
1538 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1539 if (initialDown || buttonsPressed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001540 if (mParameters.wake) {
1541 policyFlags |= POLICY_FLAG_WAKE;
1542 }
1543 }
1544
1545 // Consume raw off-screen touches before cooking pointer data.
1546 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001547 bool consumed;
1548 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1549 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550 mCurrentRawState.rawPointerData.clear();
1551 }
1552
1553 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1554 // with cooked pointer data that has the same ids and indices as the raw data.
1555 // The following code can use either the raw or cooked data, as needed.
1556 cookPointerData();
1557
1558 // Apply stylus pressure to current cooked state.
1559 applyExternalStylusTouchState(when);
1560
1561 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001562 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1563 mSource, mViewport.displayId, policyFlags,
1564 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001565
1566 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001567 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001568 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1569 uint32_t id = idBits.clearFirstMarkedBit();
1570 const RawPointerData::Pointer& pointer =
1571 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001572 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001573 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001574 } else if (pointer.toolType == ToolType::FINGER ||
1575 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001576 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001577 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001578 mCurrentCookedState.mouseIdBits.markBit(id);
1579 }
1580 }
1581 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1582 uint32_t id = idBits.clearFirstMarkedBit();
1583 const RawPointerData::Pointer& pointer =
1584 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001585 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001586 mCurrentCookedState.stylusIdBits.markBit(id);
1587 }
1588 }
1589
1590 // Stylus takes precedence over all tools, then mouse, then finger.
1591 PointerUsage pointerUsage = mPointerUsage;
1592 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1593 mCurrentCookedState.mouseIdBits.clear();
1594 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001595 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1597 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001598 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001599 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1600 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001601 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001602 }
1603
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001604 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001605 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001606 if (!mCurrentMotionAborted) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001607 out += dispatchButtonRelease(when, readTime, policyFlags);
1608 out += dispatchHoverExit(when, readTime, policyFlags);
1609 out += dispatchTouches(when, readTime, policyFlags);
1610 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1611 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001612 }
1613
1614 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1615 mCurrentMotionAborted = false;
1616 }
1617 }
1618
1619 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001620 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1621 mSource, mViewport.displayId, policyFlags,
1622 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001623
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001624 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1625 mCurrentStreamModifiedByExternalStylus = false;
1626 }
1627
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001628 // Clear some transient state.
1629 mCurrentRawState.rawVScroll = 0;
1630 mCurrentRawState.rawHScroll = 0;
1631
1632 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001633 mLastRawState = mCurrentRawState;
1634 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001635 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001636}
1637
Garfield Tanc734e4f2021-01-15 20:01:39 -08001638bool TouchInputMapper::isTouchScreen() {
1639 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1640 mParameters.hasAssociatedDisplay;
1641}
1642
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001643void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001644 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1645 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001646 const int32_t pressedButtons =
1647 filterButtonState(mConfig,
1648 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001649 const int32_t releasedButtons =
1650 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1651
1652 mCurrentRawState.buttonState |= pressedButtons;
1653 mCurrentRawState.buttonState &= ~releasedButtons;
1654
1655 mExternalStylusButtonsApplied |= pressedButtons;
1656 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001657
1658 if (mExternalStylusButtonsApplied != 0 || releasedButtons != 0) {
1659 mCurrentStreamModifiedByExternalStylus = true;
1660 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001661 }
1662}
1663
1664void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1665 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1666 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001667 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1668 return;
1669 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001670
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001671 mCurrentStreamModifiedByExternalStylus = true;
1672
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001673 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1674 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1675 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1676 : 0.f;
1677 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1678 pressure = *mExternalStylusState.pressure;
1679 }
1680 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1681 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001682
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001683 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001684 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001685 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001686 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001687 }
1688}
1689
1690bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001691 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001692 return false;
1693 }
1694
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001695 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001696 if (mFusedStylusPointerId &&
1697 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001698 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001699 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001700 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001701 }
1702
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001703 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1704 state.rawPointerData.pointerCount != 0;
1705 if (!initialDown) {
1706 return false;
1707 }
1708
1709 if (!mExternalStylusState.pressure) {
1710 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1711 return false;
1712 }
1713
1714 if (*mExternalStylusState.pressure != 0.0f) {
1715 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1716 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1717 return false;
1718 }
1719
1720 if (timeout) {
1721 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1722 mFusedStylusPointerId.reset();
1723 mExternalStylusFusionTimeout = LLONG_MAX;
1724 return false;
1725 }
1726
1727 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1728 // being processed until we either get pressure data or timeout.
1729 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1730 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1731 }
1732 ALOGD_IF(DEBUG_STYLUS_FUSION,
1733 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1734 mExternalStylusFusionTimeout);
1735 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1736 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001737}
1738
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001739std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1740 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001741 if (mDeviceMode == DeviceMode::POINTER) {
1742 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001743 // Since this is a synthetic event, we can consider its latency to be zero
1744 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001745 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001746 }
Michael Wright227c5542020-07-02 18:30:52 +01001747 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001748 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001749 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001750 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1751 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1752 }
1753 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001754 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001755}
1756
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001757std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1758 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001759 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001760 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001761 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001762 // The following three cases are handled here:
1763 // - We're in the middle of a fused stream of data;
1764 // - We're waiting on external stylus data before dispatching the initial down; or
1765 // - Only the button state, which is not reported through a specific pointer, has changed.
1766 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001767 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001768 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001769 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001770 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001771}
1772
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001773std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1774 uint32_t policyFlags, bool& outConsumed) {
1775 outConsumed = false;
1776 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001777 // Check for release of a virtual key.
1778 if (mCurrentVirtualKey.down) {
1779 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1780 // Pointer went up while virtual key was down.
1781 mCurrentVirtualKey.down = false;
1782 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001783 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1784 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1785 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001786 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1787 AKEY_EVENT_FLAG_FROM_SYSTEM |
1788 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001789 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001790 outConsumed = true;
1791 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001792 }
1793
1794 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1795 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1796 const RawPointerData::Pointer& pointer =
1797 mCurrentRawState.rawPointerData.pointerForId(id);
1798 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1799 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1800 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001801 outConsumed = true;
1802 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001803 }
1804 }
1805
1806 // Pointer left virtual key area or another pointer also went down.
1807 // Send key cancellation but do not consume the touch yet.
1808 // This is useful when the user swipes through from the virtual key area
1809 // into the main display surface.
1810 mCurrentVirtualKey.down = false;
1811 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001812 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1813 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001814 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1815 AKEY_EVENT_FLAG_FROM_SYSTEM |
1816 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1817 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001818 }
1819 }
1820
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001821 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
Harry Cutts8722be92024-04-05 14:46:05 +00001822 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001823 // We have hovering pointers, and there are no touching pointers.
1824 bool hoveringPointersInFrame = false;
1825 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1826 while (!hoveringIds.isEmpty()) {
1827 uint32_t id = hoveringIds.clearFirstMarkedBit();
1828 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1829 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1830 hoveringPointersInFrame = true;
1831 break;
1832 }
1833 }
1834 if (!hoveringPointersInFrame) {
1835 // All hovering pointers are outside the physical frame.
1836 outConsumed = true;
1837 return out;
1838 }
1839 }
1840
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001841 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1842 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1843 // Pointer just went down. Check for virtual key press or off-screen touches.
1844 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1845 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001846 // Skip checking whether the pointer is inside the physical frame if the device is in
Harry Cutts1db43992023-06-19 17:05:07 +00001847 // unscaled or pointer mode.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001848 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
Harry Cutts8722be92024-04-05 14:46:05 +00001849 mDeviceMode != DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001850 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001851 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001852 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1853 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1854 if (virtualKey) {
1855 mCurrentVirtualKey.down = true;
1856 mCurrentVirtualKey.downTime = when;
1857 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1858 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1859 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001860 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1861 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001862
1863 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001864 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1865 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1866 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001867 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1868 AKEY_EVENT_ACTION_DOWN,
1869 AKEY_EVENT_FLAG_FROM_SYSTEM |
1870 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001871 }
1872 }
1873 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001874 outConsumed = true;
1875 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001876 }
1877 }
1878
1879 // Disable all virtual key touches that happen within a short time interval of the
1880 // most recent touch within the screen area. The idea is to filter out stray
1881 // virtual key presses when interacting with the touch screen.
1882 //
1883 // Problems we're trying to solve:
1884 //
1885 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1886 // virtual key area that is implemented by a separate touch panel and accidentally
1887 // triggers a virtual key.
1888 //
1889 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1890 // area and accidentally triggers a virtual key. This often happens when virtual keys
1891 // are layed out below the screen near to where the on screen keyboard's space bar
1892 // is displayed.
1893 if (mConfig.virtualKeyQuietTime > 0 &&
1894 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001895 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001896 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001897 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001898}
1899
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001900NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1901 uint32_t policyFlags, int32_t keyEventAction,
1902 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001903 int32_t keyCode = mCurrentVirtualKey.keyCode;
1904 int32_t scanCode = mCurrentVirtualKey.scanCode;
1905 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001906 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001907 policyFlags |= POLICY_FLAG_VIRTUAL;
1908
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001909 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1910 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1911 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001912}
1913
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001914std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1915 uint32_t policyFlags) {
1916 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001917 if (mCurrentMotionAborted) {
1918 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001919 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001920 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1922 if (!currentIdBits.isEmpty()) {
1923 int32_t metaState = getContext()->getGlobalMetaState();
1924 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001925 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001926 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1927 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001928 mCurrentCookedState.cookedPointerData.pointerProperties,
1929 mCurrentCookedState.cookedPointerData.pointerCoords,
1930 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1931 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1932 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001933 mCurrentMotionAborted = true;
1934 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001935 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001936}
1937
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001938// Updates pointer coords and properties for pointers with specified ids that have moved.
1939// Returns true if any of them changed.
1940static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1941 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1942 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1943 BitSet32 idBits) {
1944 bool changed = false;
1945 while (!idBits.isEmpty()) {
1946 uint32_t id = idBits.clearFirstMarkedBit();
1947 uint32_t inIndex = inIdToIndex[id];
1948 uint32_t outIndex = outIdToIndex[id];
1949
1950 const PointerProperties& curInProperties = inProperties[inIndex];
1951 const PointerCoords& curInCoords = inCoords[inIndex];
1952 PointerProperties& curOutProperties = outProperties[outIndex];
1953 PointerCoords& curOutCoords = outCoords[outIndex];
1954
1955 if (curInProperties != curOutProperties) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001956 curOutProperties = curInProperties;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001957 changed = true;
1958 }
1959
1960 if (curInCoords != curOutCoords) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001961 curOutCoords = curInCoords;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001962 changed = true;
1963 }
1964 }
1965 return changed;
1966}
1967
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001968std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1969 uint32_t policyFlags) {
1970 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001971 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1972 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1973 int32_t metaState = getContext()->getGlobalMetaState();
1974 int32_t buttonState = mCurrentCookedState.buttonState;
1975
1976 if (currentIdBits == lastIdBits) {
1977 if (!currentIdBits.isEmpty()) {
1978 // No pointer id changes so this is a move event.
1979 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001980 out.push_back(
1981 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1982 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1983 mCurrentCookedState.cookedPointerData.pointerProperties,
1984 mCurrentCookedState.cookedPointerData.pointerCoords,
1985 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1986 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1987 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001988 }
1989 } else {
1990 // There may be pointers going up and pointers going down and pointers moving
1991 // all at the same time.
1992 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1993 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1994 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1995 BitSet32 dispatchedIdBits(lastIdBits.value);
1996
1997 // Update last coordinates of pointers that have moved so that we observe the new
1998 // pointer positions at the same time as other pointers that have just gone up.
1999 bool moveNeeded =
2000 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2001 mCurrentCookedState.cookedPointerData.pointerCoords,
2002 mCurrentCookedState.cookedPointerData.idToIndex,
2003 mLastCookedState.cookedPointerData.pointerProperties,
2004 mLastCookedState.cookedPointerData.pointerCoords,
2005 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2006 if (buttonState != mLastCookedState.buttonState) {
2007 moveNeeded = true;
2008 }
2009
2010 // Dispatch pointer up events.
2011 while (!upIdBits.isEmpty()) {
2012 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002013 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002014 if (isCanceled) {
2015 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2016 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002017 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2018 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2019 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2020 buttonState, 0,
2021 mLastCookedState.cookedPointerData.pointerProperties,
2022 mLastCookedState.cookedPointerData.pointerCoords,
2023 mLastCookedState.cookedPointerData.idToIndex,
2024 dispatchedIdBits, upId, mOrientedXPrecision,
2025 mOrientedYPrecision, mDownTime,
2026 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002027 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002028 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002029 }
2030
2031 // Dispatch move events if any of the remaining pointers moved from their old locations.
2032 // Although applications receive new locations as part of individual pointer up
2033 // events, they do not generally handle them except when presented in a move event.
2034 if (moveNeeded && !moveIdBits.isEmpty()) {
2035 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002036 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2037 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2038 mCurrentCookedState.cookedPointerData.pointerProperties,
2039 mCurrentCookedState.cookedPointerData.pointerCoords,
2040 mCurrentCookedState.cookedPointerData.idToIndex,
2041 dispatchedIdBits, -1, mOrientedXPrecision,
2042 mOrientedYPrecision, mDownTime,
2043 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002044 }
2045
2046 // Dispatch pointer down events using the new pointer locations.
2047 while (!downIdBits.isEmpty()) {
2048 uint32_t downId = downIdBits.clearFirstMarkedBit();
2049 dispatchedIdBits.markBit(downId);
2050
2051 if (dispatchedIdBits.count() == 1) {
2052 // First pointer is going down. Set down time.
2053 mDownTime = when;
2054 }
2055
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002056 out.push_back(
2057 dispatchMotion(when, readTime, policyFlags, mSource,
2058 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2059 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2060 mCurrentCookedState.cookedPointerData.pointerCoords,
2061 mCurrentCookedState.cookedPointerData.idToIndex,
2062 dispatchedIdBits, downId, mOrientedXPrecision,
2063 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002064 }
2065 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002066 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002067}
2068
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002069std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2070 uint32_t policyFlags) {
2071 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002072 if (mSentHoverEnter &&
2073 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2074 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2075 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002076 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2077 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2078 mLastCookedState.buttonState, 0,
2079 mLastCookedState.cookedPointerData.pointerProperties,
2080 mLastCookedState.cookedPointerData.pointerCoords,
2081 mLastCookedState.cookedPointerData.idToIndex,
2082 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2083 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2084 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002085 mSentHoverEnter = false;
2086 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002087 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002088}
2089
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002090std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2091 uint32_t policyFlags) {
2092 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002093 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2094 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2095 int32_t metaState = getContext()->getGlobalMetaState();
2096 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002097 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2098 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2099 mCurrentRawState.buttonState, 0,
2100 mCurrentCookedState.cookedPointerData.pointerProperties,
2101 mCurrentCookedState.cookedPointerData.pointerCoords,
2102 mCurrentCookedState.cookedPointerData.idToIndex,
2103 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2104 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2105 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002106 mSentHoverEnter = true;
2107 }
2108
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002109 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2110 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2111 mCurrentRawState.buttonState, 0,
2112 mCurrentCookedState.cookedPointerData.pointerProperties,
2113 mCurrentCookedState.cookedPointerData.pointerCoords,
2114 mCurrentCookedState.cookedPointerData.idToIndex,
2115 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2116 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2117 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002118 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002119 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002120}
2121
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002122std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2123 uint32_t policyFlags) {
2124 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002125 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2126 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2127 const int32_t metaState = getContext()->getGlobalMetaState();
2128 int32_t buttonState = mLastCookedState.buttonState;
2129 while (!releasedButtons.isEmpty()) {
2130 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2131 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002132 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2133 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2134 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002135 mLastCookedState.cookedPointerData.pointerProperties,
2136 mLastCookedState.cookedPointerData.pointerCoords,
2137 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002138 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2139 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002140 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002141 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002142}
2143
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002144std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2145 uint32_t policyFlags) {
2146 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002147 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2148 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2149 const int32_t metaState = getContext()->getGlobalMetaState();
2150 int32_t buttonState = mLastCookedState.buttonState;
2151 while (!pressedButtons.isEmpty()) {
2152 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2153 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002154 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2155 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2156 buttonState, 0,
2157 mCurrentCookedState.cookedPointerData.pointerProperties,
2158 mCurrentCookedState.cookedPointerData.pointerCoords,
2159 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2160 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2161 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002162 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002163 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002164}
2165
LiZhihong758eb562022-11-03 15:28:29 +08002166std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2167 uint32_t policyFlags,
2168 BitSet32 idBits,
2169 nsecs_t readTime) {
2170 std::list<NotifyArgs> out;
2171 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2172 const int32_t metaState = getContext()->getGlobalMetaState();
2173 int32_t buttonState = mLastCookedState.buttonState;
2174
2175 while (!releasedButtons.isEmpty()) {
2176 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2177 buttonState &= ~actionButton;
2178 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2179 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2180 metaState, buttonState, 0,
2181 mPointerGesture.lastGestureProperties,
2182 mPointerGesture.lastGestureCoords,
2183 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2184 mOrientedXPrecision, mOrientedYPrecision,
2185 mPointerGesture.downTime, MotionClassification::NONE));
2186 }
2187 return out;
2188}
2189
2190std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2191 uint32_t policyFlags,
2192 BitSet32 idBits,
2193 nsecs_t readTime) {
2194 std::list<NotifyArgs> out;
2195 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2196 const int32_t metaState = getContext()->getGlobalMetaState();
2197 int32_t buttonState = mLastCookedState.buttonState;
2198
2199 while (!pressedButtons.isEmpty()) {
2200 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2201 buttonState |= actionButton;
2202 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2203 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2204 buttonState, 0, mPointerGesture.currentGestureProperties,
2205 mPointerGesture.currentGestureCoords,
2206 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2207 mOrientedXPrecision, mOrientedYPrecision,
2208 mPointerGesture.downTime, MotionClassification::NONE));
2209 }
2210 return out;
2211}
2212
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002213const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2214 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2215 return cookedPointerData.touchingIdBits;
2216 }
2217 return cookedPointerData.hoveringIdBits;
2218}
2219
2220void TouchInputMapper::cookPointerData() {
2221 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2222
2223 mCurrentCookedState.cookedPointerData.clear();
2224 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2225 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2226 mCurrentRawState.rawPointerData.hoveringIdBits;
2227 mCurrentCookedState.cookedPointerData.touchingIdBits =
2228 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002229 mCurrentCookedState.cookedPointerData.canceledIdBits =
2230 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002231
2232 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2233 mCurrentCookedState.buttonState = 0;
2234 } else {
2235 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2236 }
2237
2238 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002239 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002240 for (uint32_t i = 0; i < currentPointerCount; i++) {
2241 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2242
2243 // Size
2244 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2245 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002246 case Calibration::SizeCalibration::GEOMETRIC:
2247 case Calibration::SizeCalibration::DIAMETER:
2248 case Calibration::SizeCalibration::BOX:
2249 case Calibration::SizeCalibration::AREA:
Prabir Pradhan132f21c2024-07-25 16:48:30 +00002250 if (mRawPointerAxes.touchMajor && mRawPointerAxes.toolMajor) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002251 touchMajor = in.touchMajor;
Prabir Pradhan132f21c2024-07-25 16:48:30 +00002252 touchMinor = mRawPointerAxes.touchMinor ? in.touchMinor : in.touchMajor;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002253 toolMajor = in.toolMajor;
Prabir Pradhan132f21c2024-07-25 16:48:30 +00002254 toolMinor = mRawPointerAxes.toolMinor ? in.toolMinor : in.toolMajor;
2255 size = mRawPointerAxes.touchMinor ? avg(in.touchMajor, in.touchMinor)
2256 : in.touchMajor;
2257 } else if (mRawPointerAxes.touchMajor) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002258 toolMajor = touchMajor = in.touchMajor;
2259 toolMinor = touchMinor =
Prabir Pradhan132f21c2024-07-25 16:48:30 +00002260 mRawPointerAxes.touchMinor ? in.touchMinor : in.touchMajor;
2261 size = mRawPointerAxes.touchMinor ? avg(in.touchMajor, in.touchMinor)
2262 : in.touchMajor;
2263 } else if (mRawPointerAxes.toolMajor) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002264 touchMajor = toolMajor = in.toolMajor;
2265 touchMinor = toolMinor =
Prabir Pradhan132f21c2024-07-25 16:48:30 +00002266 mRawPointerAxes.toolMinor ? in.toolMinor : in.toolMajor;
2267 size = mRawPointerAxes.toolMinor ? avg(in.toolMajor, in.toolMinor)
2268 : in.toolMajor;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002269 } else {
2270 ALOG_ASSERT(false,
2271 "No touch or tool axes. "
2272 "Size calibration should have been resolved to NONE.");
2273 touchMajor = 0;
2274 touchMinor = 0;
2275 toolMajor = 0;
2276 toolMinor = 0;
2277 size = 0;
2278 }
2279
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002280 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002281 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2282 if (touchingCount > 1) {
2283 touchMajor /= touchingCount;
2284 touchMinor /= touchingCount;
2285 toolMajor /= touchingCount;
2286 toolMinor /= touchingCount;
2287 size /= touchingCount;
2288 }
2289 }
2290
Michael Wright227c5542020-07-02 18:30:52 +01002291 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002292 touchMajor *= mGeometricScale;
2293 touchMinor *= mGeometricScale;
2294 toolMajor *= mGeometricScale;
2295 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002296 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2298 touchMinor = touchMajor;
2299 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2300 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002301 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002302 touchMinor = touchMajor;
2303 toolMinor = toolMajor;
2304 }
2305
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002306 mCalibration.applySizeScaleAndBias(touchMajor);
2307 mCalibration.applySizeScaleAndBias(touchMinor);
2308 mCalibration.applySizeScaleAndBias(toolMajor);
2309 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002310 size *= mSizeScale;
2311 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002312 case Calibration::SizeCalibration::DEFAULT:
2313 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2314 break;
2315 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002316 touchMajor = 0;
2317 touchMinor = 0;
2318 toolMajor = 0;
2319 toolMinor = 0;
2320 size = 0;
2321 break;
2322 }
2323
2324 // Pressure
2325 float pressure;
2326 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002327 case Calibration::PressureCalibration::PHYSICAL:
2328 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002329 pressure = in.pressure * mPressureScale;
2330 break;
2331 default:
2332 pressure = in.isHovering ? 0 : 1;
2333 break;
2334 }
2335
2336 // Tilt and Orientation
2337 float tilt;
2338 float orientation;
2339 if (mHaveTilt) {
2340 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2341 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhan9a53b552024-06-04 02:59:40 +00002342 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)),
2343 /*isDirectional=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2345 } else {
2346 tilt = 0;
2347
2348 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002349 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhan9a53b552024-06-04 02:59:40 +00002350 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale,
2351 /*isDirectional=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 break;
Michael Wright227c5542020-07-02 18:30:52 +01002353 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2355 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2356 if (c1 != 0 || c2 != 0) {
Prabir Pradhan9a53b552024-06-04 02:59:40 +00002357 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f,
2358 /*isDirectional=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 float confidence = hypotf(c1, c2);
2360 float scale = 1.0f + confidence / 16.0f;
2361 touchMajor *= scale;
2362 touchMinor /= scale;
2363 toolMajor *= scale;
2364 toolMinor /= scale;
2365 } else {
2366 orientation = 0;
2367 }
2368 break;
2369 }
2370 default:
2371 orientation = 0;
2372 }
2373 }
2374
2375 // Distance
2376 float distance;
2377 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002378 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 distance = in.distance * mDistanceScale;
2380 break;
2381 default:
2382 distance = 0;
2383 }
2384
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002385 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2386 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002387 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2388 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390 // Write output coords.
2391 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2392 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002393 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2394 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002395 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2396 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2397 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2398 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2399 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2400 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2401 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002402 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2403 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404
Chris Ye364fdb52020-08-05 15:07:56 -07002405 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002406 uint32_t id = in.id;
2407 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2408 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2409 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002410 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2411 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002412 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2413 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2414 }
2415
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002416 // Write output properties.
2417 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002418 properties.clear();
2419 properties.id = id;
2420 properties.toolType = in.toolType;
2421
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002422 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002423 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002424 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 }
2426}
2427
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002428std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2429 uint32_t policyFlags,
2430 PointerUsage pointerUsage) {
2431 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002432 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002433 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 mPointerUsage = pointerUsage;
2435 }
2436
2437 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002438 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002439 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 break;
Michael Wright227c5542020-07-02 18:30:52 +01002441 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002442 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002443 break;
Michael Wright227c5542020-07-02 18:30:52 +01002444 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002445 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002446 break;
Michael Wright227c5542020-07-02 18:30:52 +01002447 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002448 break;
2449 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002450 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002451}
2452
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002453std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2454 uint32_t policyFlags) {
2455 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002457 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002458 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002459 break;
Michael Wright227c5542020-07-02 18:30:52 +01002460 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002461 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002462 break;
Michael Wright227c5542020-07-02 18:30:52 +01002463 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002464 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002465 break;
Michael Wright227c5542020-07-02 18:30:52 +01002466 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 break;
2468 }
2469
Michael Wright227c5542020-07-02 18:30:52 +01002470 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002471 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472}
2473
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002474std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2475 uint32_t policyFlags,
2476 bool isTimeout) {
2477 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 // Update current gesture coordinates.
2479 bool cancelPreviousGesture, finishPreviousGesture;
2480 bool sendEvents =
2481 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2482 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002483 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002484 }
2485 if (finishPreviousGesture) {
2486 cancelPreviousGesture = false;
2487 }
2488
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002489 // Send events!
2490 int32_t metaState = getContext()->getGlobalMetaState();
2491 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002492 const MotionClassification classification =
2493 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2494 ? MotionClassification::TWO_FINGER_SWIPE
2495 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002496
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002497 uint32_t flags = 0;
2498
2499 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2500 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2501 }
2502
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 // Update last coordinates of pointers that have moved so that we observe the new
2504 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002505 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2506 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2507 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2508 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2509 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2510 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002511 bool moveNeeded = false;
2512 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2513 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2514 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2515 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2516 mPointerGesture.lastGestureIdBits.value);
2517 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2518 mPointerGesture.currentGestureCoords,
2519 mPointerGesture.currentGestureIdToIndex,
2520 mPointerGesture.lastGestureProperties,
2521 mPointerGesture.lastGestureCoords,
2522 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2523 if (buttonState != mLastCookedState.buttonState) {
2524 moveNeeded = true;
2525 }
2526 }
2527
2528 // Send motion events for all pointers that went up or were canceled.
2529 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2530 if (!dispatchedGestureIdBits.isEmpty()) {
2531 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002532 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002533 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002534 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002535 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2536 mPointerGesture.lastGestureProperties,
2537 mPointerGesture.lastGestureCoords,
2538 mPointerGesture.lastGestureIdToIndex,
2539 dispatchedGestureIdBits, -1, 0, 0,
2540 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002541
2542 dispatchedGestureIdBits.clear();
2543 } else {
2544 BitSet32 upGestureIdBits;
2545 if (finishPreviousGesture) {
2546 upGestureIdBits = dispatchedGestureIdBits;
2547 } else {
2548 upGestureIdBits.value =
2549 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2550 }
2551 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002552 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2553 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2554 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2555 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2556 readTime);
2557 }
2558 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002559 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2560 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2561 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2562 mPointerGesture.lastGestureProperties,
2563 mPointerGesture.lastGestureCoords,
2564 mPointerGesture.lastGestureIdToIndex,
2565 dispatchedGestureIdBits, id, 0, 0,
2566 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002567
2568 dispatchedGestureIdBits.clearBit(id);
2569 }
2570 }
2571 }
2572
2573 // Send motion events for all pointers that moved.
2574 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002575 out.push_back(
2576 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2577 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2578 mPointerGesture.currentGestureProperties,
2579 mPointerGesture.currentGestureCoords,
2580 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2581 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002582 }
2583
2584 // Send motion events for all pointers that went down.
2585 if (down) {
2586 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2587 ~dispatchedGestureIdBits.value);
2588 while (!downGestureIdBits.isEmpty()) {
2589 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2590 dispatchedGestureIdBits.markBit(id);
2591
2592 if (dispatchedGestureIdBits.count() == 1) {
2593 mPointerGesture.downTime = when;
2594 }
2595
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002596 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2597 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2598 buttonState, 0, mPointerGesture.currentGestureProperties,
2599 mPointerGesture.currentGestureCoords,
2600 mPointerGesture.currentGestureIdToIndex,
2601 dispatchedGestureIdBits, id, 0, 0,
2602 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002603 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2604 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2605 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2606 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2607 readTime);
2608 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002609 }
2610 }
2611
2612 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002613 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002614 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2615 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2616 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2617 mPointerGesture.currentGestureProperties,
2618 mPointerGesture.currentGestureCoords,
2619 mPointerGesture.currentGestureIdToIndex,
2620 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2621 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002622 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2623 // Synthesize a hover move event after all pointers go up to indicate that
2624 // the pointer is hovering again even if the user is not currently touching
2625 // the touch pad. This ensures that a view will receive a fresh hover enter
2626 // event after a tap.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002627
2628 PointerProperties pointerProperties;
2629 pointerProperties.clear();
2630 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002631 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002632
2633 PointerCoords pointerCoords;
2634 pointerCoords.clear();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002635 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07002636 mSource, ui::LogicalDisplayId::INVALID, policyFlags,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002637 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2638 buttonState, MotionClassification::NONE,
2639 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002640 &pointerCoords, 0, 0, 0.f, 0.f, mPointerGesture.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00002641 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002642 }
2643
2644 // Update state.
2645 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2646 if (!down) {
2647 mPointerGesture.lastGestureIdBits.clear();
2648 } else {
2649 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2650 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2651 uint32_t id = idBits.clearFirstMarkedBit();
2652 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002653 mPointerGesture.lastGestureProperties[index] =
2654 mPointerGesture.currentGestureProperties[index];
2655 mPointerGesture.lastGestureCoords[index] = mPointerGesture.currentGestureCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002656 mPointerGesture.lastGestureIdToIndex[id] = index;
2657 }
2658 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002659 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002660}
2661
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002662std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2663 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002664 const MotionClassification classification =
2665 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2666 ? MotionClassification::TWO_FINGER_SWIPE
2667 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002668 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002669 // Cancel previously dispatches pointers.
2670 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2671 int32_t metaState = getContext()->getGlobalMetaState();
2672 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002673 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002674 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2675 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002676 mPointerGesture.lastGestureProperties,
2677 mPointerGesture.lastGestureCoords,
2678 mPointerGesture.lastGestureIdToIndex,
2679 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2680 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002681 }
2682
2683 // Reset the current pointer gesture.
2684 mPointerGesture.reset();
2685 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002686 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002687}
2688
2689bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2690 bool* outFinishPreviousGesture, bool isTimeout) {
2691 *outCancelPreviousGesture = false;
2692 *outFinishPreviousGesture = false;
2693
2694 // Handle TAP timeout.
2695 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002696 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002697
Michael Wright227c5542020-07-02 18:30:52 +01002698 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002699 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2700 // The tap/drag timeout has not yet expired.
2701 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2702 mConfig.pointerGestureTapDragInterval);
2703 } else {
2704 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002705 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002706 *outFinishPreviousGesture = true;
2707
2708 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002709 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002710 mPointerGesture.currentGestureIdBits.clear();
2711
2712 mPointerVelocityControl.reset();
2713 return true;
2714 }
2715 }
2716
2717 // We did not handle this timeout.
2718 return false;
2719 }
2720
2721 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2722 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2723
2724 // Update the velocity tracker.
2725 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002726 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002727 uint32_t id = idBits.clearFirstMarkedBit();
2728 const RawPointerData::Pointer& pointer =
2729 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002730 const float x = pointer.x * mPointerXMovementScale;
2731 const float y = pointer.y * mPointerYMovementScale;
2732 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2733 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002734 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002735 }
2736
2737 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2738 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002739 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2740 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2741 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002742 mPointerGesture.resetTap();
2743 }
2744
2745 // Pick a new active touch id if needed.
2746 // Choose an arbitrary pointer that just went down, if there is one.
2747 // Otherwise choose an arbitrary remaining pointer.
2748 // This guarantees we always have an active touch id when there is at least one pointer.
2749 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002750 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002751 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002752 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002753 mPointerGesture.firstTouchTime = when;
2754 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002755 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2756 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2757 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2758 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002759 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002760 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002761
2762 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002763 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002764 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002765 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2766 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2767 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002768 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002769 *outFinishPreviousGesture = true;
2770 }
2771
2772 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002773 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002774 mPointerGesture.currentGestureIdBits.clear();
2775
2776 mPointerVelocityControl.reset();
2777 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2778 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2779 // The pointer follows the active touch point.
2780 // Emit DOWN, MOVE, UP events at the pointer location.
2781 //
2782 // Only the active touch matters; other fingers are ignored. This policy helps
2783 // to handle the case where the user places a second finger on the touch pad
2784 // to apply the necessary force to depress an integrated button below the surface.
2785 // We don't want the second finger to be delivered to applications.
2786 //
2787 // For this to work well, we need to make sure to track the pointer that is really
2788 // active. If the user first puts one finger down to click then adds another
2789 // finger to drag then the active pointer should switch to the finger that is
2790 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002791 ALOGD_IF(DEBUG_GESTURES,
2792 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2793 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002794 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002795 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002796 *outFinishPreviousGesture = true;
2797 mPointerGesture.activeGestureId = 0;
2798 }
2799
2800 // Switch pointers if needed.
2801 // Find the fastest pointer and follow it.
2802 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002803 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002804 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002805 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002806 ALOGD_IF(DEBUG_GESTURES,
2807 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2808 "bestSpeed=%0.3f",
2809 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002810 }
2811 }
2812
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002813 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002814 // When using spots, the click will occur at the position of the anchor
2815 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002816 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002817 } else {
2818 mPointerVelocityControl.reset();
2819 }
2820
Michael Wright227c5542020-07-02 18:30:52 +01002821 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002822 mPointerGesture.currentGestureIdBits.clear();
2823 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2824 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2825 mPointerGesture.currentGestureProperties[0].clear();
2826 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002827 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002828 mPointerGesture.currentGestureCoords[0].clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002829 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2830 } else if (currentFingerCount == 0) {
2831 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002832 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002833 *outFinishPreviousGesture = true;
2834 }
2835
2836 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2837 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2838 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002839 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2840 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002841 lastFingerCount == 1) {
2842 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002843 if (fabs(0.f - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2844 fabs(0.f - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002845 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002846
2847 mPointerGesture.tapUpTime = when;
2848 getContext()->requestTimeoutAtTime(when +
2849 mConfig.pointerGestureTapDragInterval);
2850
2851 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002852 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002853 mPointerGesture.currentGestureIdBits.clear();
2854 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2855 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2856 mPointerGesture.currentGestureProperties[0].clear();
2857 mPointerGesture.currentGestureProperties[0].id =
2858 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002859 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002860 mPointerGesture.currentGestureCoords[0].clear();
2861 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2862 mPointerGesture.tapX);
2863 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2864 mPointerGesture.tapY);
2865 mPointerGesture.currentGestureCoords[0]
2866 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2867
2868 tapped = true;
2869 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002870 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002871 0.f - mPointerGesture.tapX, 0.f - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 }
2873 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002874 if (DEBUG_GESTURES) {
2875 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2876 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2877 (when - mPointerGesture.tapDownTime) * 0.000001f);
2878 } else {
2879 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2880 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002881 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002882 }
2883 }
2884
2885 mPointerVelocityControl.reset();
2886
2887 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002888 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002889 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002890 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891 mPointerGesture.currentGestureIdBits.clear();
2892 }
2893 } else if (currentFingerCount == 1) {
2894 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2895 // The pointer follows the active touch point.
2896 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2897 // When in TAP_DRAG, emit MOVE events at the pointer location.
2898 ALOG_ASSERT(activeTouchId >= 0);
2899
Michael Wright227c5542020-07-02 18:30:52 +01002900 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2901 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002902 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002903 if (fabs(0.f - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2904 fabs(0.f - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002905 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002906 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002907 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002908 0.f - mPointerGesture.tapX, 0.f - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002909 }
2910 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002911 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2912 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002913 }
Michael Wright227c5542020-07-02 18:30:52 +01002914 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2915 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002916 }
2917
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002918 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002920 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002921 } else {
2922 mPointerVelocityControl.reset();
2923 }
2924
2925 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002926 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002927 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002928 down = true;
2929 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002930 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002931 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002932 *outFinishPreviousGesture = true;
2933 }
2934 mPointerGesture.activeGestureId = 0;
2935 down = false;
2936 }
2937
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002938 mPointerGesture.currentGestureIdBits.clear();
2939 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2940 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2941 mPointerGesture.currentGestureProperties[0].clear();
2942 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002943 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944 mPointerGesture.currentGestureCoords[0].clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002945 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2946 down ? 1.0f : 0.0f);
2947
2948 if (lastFingerCount == 0 && currentFingerCount != 0) {
2949 mPointerGesture.resetTap();
2950 mPointerGesture.tapDownTime = when;
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00002951 mPointerGesture.tapX = 0.f;
2952 mPointerGesture.tapY = 0.f;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002953 }
2954 } else {
2955 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002956 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002957 }
2958
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002959 if (DEBUG_GESTURES) {
2960 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00002961 "currentGestureMode=%s, currentGestureIdBits=0x%08x, "
2962 "lastGestureMode=%s, lastGestureIdBits=0x%08x",
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002963 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00002964 ftl::enum_string(mPointerGesture.currentGestureMode).c_str(),
2965 mPointerGesture.currentGestureIdBits.value,
2966 ftl::enum_string(mPointerGesture.lastGestureMode).c_str(),
2967 mPointerGesture.lastGestureIdBits.value);
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002968 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
2969 uint32_t id = idBits.clearFirstMarkedBit();
2970 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2971 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
2972 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002973 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002974 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002975 id, index, ftl::enum_string(properties.toolType).c_str(),
2976 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002977 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
2978 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
2979 }
2980 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
2981 uint32_t id = idBits.clearFirstMarkedBit();
2982 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
2983 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
2984 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002985 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002986 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002987 id, index, ftl::enum_string(properties.toolType).c_str(),
2988 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002989 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
2990 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
2991 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002992 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002993 return true;
2994}
2995
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002996bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
2997 if (mPointerGesture.activeTouchId < 0) {
2998 mPointerGesture.resetQuietTime();
2999 return false;
3000 }
3001
3002 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3003 return true;
3004 }
3005
3006 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3007 bool isQuietTime = false;
3008 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3009 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3010 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3011 currentFingerCount < 2) {
3012 // Enter quiet time when exiting swipe or freeform state.
3013 // This is to prevent accidentally entering the hover state and flinging the
3014 // pointer when finishing a swipe and there is still one pointer left onscreen.
3015 isQuietTime = true;
3016 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3017 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3018 // Enter quiet time when releasing the button and there are still two or more
3019 // fingers down. This may indicate that one finger was used to press the button
3020 // but it has not gone up yet.
3021 isQuietTime = true;
3022 }
3023 if (isQuietTime) {
3024 mPointerGesture.quietTime = when;
3025 }
3026 return isQuietTime;
3027}
3028
3029std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3030 int32_t bestId = -1;
3031 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3032 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3033 uint32_t id = idBits.clearFirstMarkedBit();
3034 std::optional<float> vx =
3035 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3036 std::optional<float> vy =
3037 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3038 if (vx && vy) {
3039 float speed = hypotf(*vx, *vy);
3040 if (speed > bestSpeed) {
3041 bestId = id;
3042 bestSpeed = speed;
3043 }
3044 }
3045 }
3046 return std::make_pair(bestId, bestSpeed);
3047}
3048
3049void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3050 bool* finishPreviousGesture) {
3051 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3052 // to move before deciding what to do.
3053 //
3054 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3055 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3056 // just a press or long-press at the pointer location.
3057 //
3058 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3059 // pointer location.
3060 //
3061 // When the two fingers move enough or when additional fingers are added, we make a decision to
3062 // transition into SWIPE or FREEFORM mode accordingly.
3063 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3064 ALOG_ASSERT(activeTouchId >= 0);
3065
3066 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3067 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3068 bool settled =
3069 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3070 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3071 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3072 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3073 *finishPreviousGesture = true;
3074 } else if (!settled && currentFingerCount > lastFingerCount) {
3075 // Additional pointers have gone down but not yet settled.
3076 // Reset the gesture.
3077 ALOGD_IF(DEBUG_GESTURES,
3078 "Gestures: Resetting gesture since additional pointers went down for "
3079 "MULTITOUCH, settle time remaining %0.3fms",
3080 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3081 when) * 0.000001f);
3082 *cancelPreviousGesture = true;
3083 } else {
3084 // Continue previous gesture.
3085 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3086 }
3087
3088 if (*finishPreviousGesture || *cancelPreviousGesture) {
3089 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3090 mPointerGesture.activeGestureId = 0;
3091 mPointerGesture.referenceIdBits.clear();
3092 mPointerVelocityControl.reset();
3093
3094 // Use the centroid and pointer location as the reference points for the gesture.
3095 ALOGD_IF(DEBUG_GESTURES,
3096 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3097 "%0.3fms",
3098 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3099 when) * 0.000001f);
3100 mCurrentRawState.rawPointerData
3101 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3102 &mPointerGesture.referenceTouchY);
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00003103 mPointerGesture.referenceGestureX = 0.f;
3104 mPointerGesture.referenceGestureY = 0.f;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003105 }
3106
3107 // Clear the reference deltas for fingers not yet included in the reference calculation.
3108 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3109 ~mPointerGesture.referenceIdBits.value);
3110 !idBits.isEmpty();) {
3111 uint32_t id = idBits.clearFirstMarkedBit();
3112 mPointerGesture.referenceDeltas[id].dx = 0;
3113 mPointerGesture.referenceDeltas[id].dy = 0;
3114 }
3115 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3116
3117 // Add delta for all fingers and calculate a common movement delta.
3118 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3119 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3120 mCurrentCookedState.fingerIdBits.value);
3121 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3122 bool first = (idBits == commonIdBits);
3123 uint32_t id = idBits.clearFirstMarkedBit();
3124 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3125 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3126 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3127 delta.dx += cpd.x - lpd.x;
3128 delta.dy += cpd.y - lpd.y;
3129
3130 if (first) {
3131 commonDeltaRawX = delta.dx;
3132 commonDeltaRawY = delta.dy;
3133 } else {
3134 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3135 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3136 }
3137 }
3138
3139 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3140 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3141 float dist[MAX_POINTER_ID + 1];
3142 int32_t distOverThreshold = 0;
3143 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3144 uint32_t id = idBits.clearFirstMarkedBit();
3145 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3146 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3147 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3148 distOverThreshold += 1;
3149 }
3150 }
3151
3152 // Only transition when at least two pointers have moved further than
3153 // the minimum distance threshold.
3154 if (distOverThreshold >= 2) {
3155 if (currentFingerCount > 2) {
3156 // There are more than two pointers, switch to FREEFORM.
3157 ALOGD_IF(DEBUG_GESTURES,
3158 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3159 currentFingerCount);
3160 *cancelPreviousGesture = true;
3161 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3162 } else {
3163 // There are exactly two pointers.
3164 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3165 uint32_t id1 = idBits.clearFirstMarkedBit();
3166 uint32_t id2 = idBits.firstMarkedBit();
3167 const RawPointerData::Pointer& p1 =
3168 mCurrentRawState.rawPointerData.pointerForId(id1);
3169 const RawPointerData::Pointer& p2 =
3170 mCurrentRawState.rawPointerData.pointerForId(id2);
3171 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3172 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3173 // There are two pointers but they are too far apart for a SWIPE,
3174 // switch to FREEFORM.
3175 ALOGD_IF(DEBUG_GESTURES,
3176 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3177 mutualDistance, mPointerGestureMaxSwipeWidth);
3178 *cancelPreviousGesture = true;
3179 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3180 } else {
3181 // There are two pointers. Wait for both pointers to start moving
3182 // before deciding whether this is a SWIPE or FREEFORM gesture.
3183 float dist1 = dist[id1];
3184 float dist2 = dist[id2];
3185 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3186 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3187 // Calculate the dot product of the displacement vectors.
3188 // When the vectors are oriented in approximately the same direction,
3189 // the angle betweeen them is near zero and the cosine of the angle
3190 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3191 // mag(v2).
3192 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3193 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3194 float dx1 = delta1.dx * mPointerXZoomScale;
3195 float dy1 = delta1.dy * mPointerYZoomScale;
3196 float dx2 = delta2.dx * mPointerXZoomScale;
3197 float dy2 = delta2.dy * mPointerYZoomScale;
3198 float dot = dx1 * dx2 + dy1 * dy2;
3199 float cosine = dot / (dist1 * dist2); // denominator always > 0
3200 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3201 // Pointers are moving in the same direction. Switch to SWIPE.
3202 ALOGD_IF(DEBUG_GESTURES,
3203 "Gestures: PRESS transitioned to SWIPE, "
3204 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3205 "cosine %0.3f >= %0.3f",
3206 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3207 mConfig.pointerGestureMultitouchMinDistance, cosine,
3208 mConfig.pointerGestureSwipeTransitionAngleCosine);
3209 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3210 } else {
3211 // Pointers are moving in different directions. Switch to FREEFORM.
3212 ALOGD_IF(DEBUG_GESTURES,
3213 "Gestures: PRESS transitioned to FREEFORM, "
3214 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3215 "cosine %0.3f < %0.3f",
3216 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3217 mConfig.pointerGestureMultitouchMinDistance, cosine,
3218 mConfig.pointerGestureSwipeTransitionAngleCosine);
3219 *cancelPreviousGesture = true;
3220 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3221 }
3222 }
3223 }
3224 }
3225 }
3226 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3227 // Switch from SWIPE to FREEFORM if additional pointers go down.
3228 // Cancel previous gesture.
3229 if (currentFingerCount > 2) {
3230 ALOGD_IF(DEBUG_GESTURES,
3231 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3232 currentFingerCount);
3233 *cancelPreviousGesture = true;
3234 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3235 }
3236 }
3237
3238 // Move the reference points based on the overall group motion of the fingers
3239 // except in PRESS mode while waiting for a transition to occur.
3240 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3241 (commonDeltaRawX || commonDeltaRawY)) {
3242 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3243 uint32_t id = idBits.clearFirstMarkedBit();
3244 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3245 delta.dx = 0;
3246 delta.dy = 0;
3247 }
3248
3249 mPointerGesture.referenceTouchX += commonDeltaRawX;
3250 mPointerGesture.referenceTouchY += commonDeltaRawY;
3251
3252 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3253 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3254
3255 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3256 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3257
3258 mPointerGesture.referenceGestureX += commonDeltaX;
3259 mPointerGesture.referenceGestureY += commonDeltaY;
3260 }
3261
3262 // Report gestures.
3263 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3264 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3265 // PRESS or SWIPE mode.
3266 ALOGD_IF(DEBUG_GESTURES,
3267 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3268 "currentTouchPointerCount=%d",
3269 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3270 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3271
3272 mPointerGesture.currentGestureIdBits.clear();
3273 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3274 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3275 mPointerGesture.currentGestureProperties[0].clear();
3276 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003277 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003278 mPointerGesture.currentGestureCoords[0].clear();
3279 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3280 mPointerGesture.referenceGestureX);
3281 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3282 mPointerGesture.referenceGestureY);
3283 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3284 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3285 float xOffset = static_cast<float>(commonDeltaRawX) /
3286 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3287 float yOffset = static_cast<float>(commonDeltaRawY) /
3288 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3289 mPointerGesture.currentGestureCoords[0]
3290 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3291 mPointerGesture.currentGestureCoords[0]
3292 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3293 }
3294 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3295 // FREEFORM mode.
3296 ALOGD_IF(DEBUG_GESTURES,
3297 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3298 "currentTouchPointerCount=%d",
3299 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3300 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3301
3302 mPointerGesture.currentGestureIdBits.clear();
3303
3304 BitSet32 mappedTouchIdBits;
3305 BitSet32 usedGestureIdBits;
3306 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3307 // Initially, assign the active gesture id to the active touch point
3308 // if there is one. No other touch id bits are mapped yet.
3309 if (!*cancelPreviousGesture) {
3310 mappedTouchIdBits.markBit(activeTouchId);
3311 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3312 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3313 mPointerGesture.activeGestureId;
3314 } else {
3315 mPointerGesture.activeGestureId = -1;
3316 }
3317 } else {
3318 // Otherwise, assume we mapped all touches from the previous frame.
3319 // Reuse all mappings that are still applicable.
3320 mappedTouchIdBits.value =
3321 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3322 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3323
3324 // Check whether we need to choose a new active gesture id because the
3325 // current went went up.
3326 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3327 ~mCurrentCookedState.fingerIdBits.value);
3328 !upTouchIdBits.isEmpty();) {
3329 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3330 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3331 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3332 mPointerGesture.activeGestureId = -1;
3333 break;
3334 }
3335 }
3336 }
3337
3338 ALOGD_IF(DEBUG_GESTURES,
3339 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3340 "activeGestureId=%d",
3341 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3342
3343 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3344 for (uint32_t i = 0; i < currentFingerCount; i++) {
3345 uint32_t touchId = idBits.clearFirstMarkedBit();
3346 uint32_t gestureId;
3347 if (!mappedTouchIdBits.hasBit(touchId)) {
3348 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3349 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3350 ALOGD_IF(DEBUG_GESTURES,
3351 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3352 gestureId);
3353 } else {
3354 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3355 ALOGD_IF(DEBUG_GESTURES,
3356 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3357 touchId, gestureId);
3358 }
3359 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3360 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3361
3362 const RawPointerData::Pointer& pointer =
3363 mCurrentRawState.rawPointerData.pointerForId(touchId);
3364 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3365 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3366 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3367
3368 mPointerGesture.currentGestureProperties[i].clear();
3369 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003370 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003371 mPointerGesture.currentGestureCoords[i].clear();
3372 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3373 mPointerGesture.referenceGestureX +
3374 deltaX);
3375 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3376 mPointerGesture.referenceGestureY +
3377 deltaY);
3378 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3379 }
3380
3381 if (mPointerGesture.activeGestureId < 0) {
3382 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3383 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3384 mPointerGesture.activeGestureId);
3385 }
3386 }
3387}
3388
Harry Cutts714d1ad2022-08-24 16:36:43 +00003389void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3390 const RawPointerData::Pointer& currentPointer =
3391 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3392 const RawPointerData::Pointer& lastPointer =
3393 mLastRawState.rawPointerData.pointerForId(pointerId);
3394 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3395 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3396
3397 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3398 mPointerVelocityControl.move(when, &deltaX, &deltaY);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003399}
3400
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003401std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3402 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003403 mPointerSimple.currentCoords.clear();
3404 mPointerSimple.currentProperties.clear();
3405
3406 bool down, hovering;
3407 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3408 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3409 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003410 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3411 down = !hovering;
3412
Prabir Pradhane71e5702023-03-29 14:51:38 +00003413 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3414 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Prabir Pradhane71e5702023-03-29 14:51:38 +00003415
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003416 mPointerSimple.currentCoords = mCurrentCookedState.cookedPointerData.pointerCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003417 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3418 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3419 mPointerSimple.currentProperties.id = 0;
3420 mPointerSimple.currentProperties.toolType =
3421 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3422 } else {
3423 down = false;
3424 hovering = false;
3425 }
3426
Prabir Pradhane71e5702023-03-29 14:51:38 +00003427 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003428}
3429
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003430std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3431 uint32_t policyFlags) {
3432 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003433}
3434
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003435std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3436 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003437 mPointerSimple.currentCoords.clear();
3438 mPointerSimple.currentProperties.clear();
3439
3440 bool down, hovering;
3441 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3442 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003443 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003444 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003445 } else {
3446 mPointerVelocityControl.reset();
3447 }
3448
3449 down = isPointerDown(mCurrentRawState.buttonState);
3450 hovering = !down;
3451
Prabir Pradhan2719e822023-02-28 17:39:36 +00003452 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003453 mPointerSimple.currentCoords =
3454 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003455 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3456 hovering ? 0.0f : 1.0f);
3457 mPointerSimple.currentProperties.id = 0;
3458 mPointerSimple.currentProperties.toolType =
3459 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3460 } else {
3461 mPointerVelocityControl.reset();
3462
3463 down = false;
3464 hovering = false;
3465 }
3466
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07003467 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering,
3468 ui::LogicalDisplayId::INVALID);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003469}
3470
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003471std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3472 uint32_t policyFlags) {
3473 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003474
3475 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003476
3477 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003478}
3479
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003480std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3481 uint32_t policyFlags, bool down,
Linnan Li13bf76a2024-05-05 19:18:02 +08003482 bool hovering,
3483 ui::LogicalDisplayId displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003484 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3485 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003486 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003487 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003488 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003489
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003490 if (mPointerSimple.down && !down) {
3491 mPointerSimple.down = false;
3492
3493 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003494 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3495 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3496 0, metaState, mLastRawState.buttonState,
3497 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3498 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003499 mOrientedXPrecision, mOrientedYPrecision,
3500 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3501 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003502 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003503 }
3504
3505 if (mPointerSimple.hovering && !hovering) {
3506 mPointerSimple.hovering = false;
3507
3508 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003509 out.push_back(
3510 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3511 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3512 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3513 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3514 &mPointerSimple.lastCoords, mOrientedXPrecision,
3515 mOrientedYPrecision, mPointerSimple.lastCursorX,
3516 mPointerSimple.lastCursorY, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003517 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003518 }
3519
3520 if (down) {
3521 if (!mPointerSimple.down) {
3522 mPointerSimple.down = true;
3523 mPointerSimple.downTime = when;
3524
3525 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003526 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3527 mSource, displayId, policyFlags,
3528 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3529 mCurrentRawState.buttonState, MotionClassification::NONE,
3530 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3531 &mPointerSimple.currentProperties,
3532 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003533 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003534 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003535 }
3536
3537 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003538 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3539 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3540 0, 0, metaState, mCurrentRawState.buttonState,
3541 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3542 &mPointerSimple.currentProperties,
3543 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003544 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003545 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003546 }
3547
3548 if (hovering) {
3549 if (!mPointerSimple.hovering) {
3550 mPointerSimple.hovering = true;
3551
3552 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003553 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3554 mSource, displayId, policyFlags,
3555 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3556 mCurrentRawState.buttonState, MotionClassification::NONE,
3557 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3558 &mPointerSimple.currentProperties,
3559 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003560 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003561 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003562 }
3563
3564 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003565 out.push_back(
3566 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3567 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3568 metaState, mCurrentRawState.buttonState,
3569 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3570 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003571 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003572 cursorPosition.y, mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003573 }
3574
3575 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3576 float vscroll = mCurrentRawState.rawVScroll;
3577 float hscroll = mCurrentRawState.rawHScroll;
3578 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3579 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3580
3581 // Send scroll.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003582 PointerCoords pointerCoords = mPointerSimple.currentCoords;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003583 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3584 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3585
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003586 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3587 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3588 0, 0, metaState, mCurrentRawState.buttonState,
3589 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3590 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003591 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3592 cursorPosition.y, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003593 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003594 }
3595
3596 // Save state.
3597 if (down || hovering) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003598 mPointerSimple.lastCoords = mPointerSimple.currentCoords;
3599 mPointerSimple.lastProperties = mPointerSimple.currentProperties;
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003600 mPointerSimple.displayId = displayId;
3601 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003602 mPointerSimple.lastCursorX = cursorPosition.x;
3603 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003604 } else {
3605 mPointerSimple.reset();
3606 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003607 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003608}
3609
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003610std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3611 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003612 std::list<NotifyArgs> out;
3613 if (mPointerSimple.down || mPointerSimple.hovering) {
3614 int32_t metaState = getContext()->getGlobalMetaState();
3615 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3616 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3617 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3618 metaState, mLastRawState.buttonState,
3619 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3620 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3621 mOrientedXPrecision, mOrientedYPrecision,
3622 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3623 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003624 /*videoFrames=*/{}));
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003625 }
3626 mPointerSimple.reset();
3627 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003628}
3629
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003630NotifyMotionArgs TouchInputMapper::dispatchMotion(
3631 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3632 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003633 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3634 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003635 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003636 std::vector<PointerCoords> pointerCoords;
3637 std::vector<PointerProperties> pointerProperties;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003638 uint32_t pointerCount = 0;
3639 while (!idBits.isEmpty()) {
3640 uint32_t id = idBits.clearFirstMarkedBit();
3641 uint32_t index = idToIndex[id];
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003642 pointerProperties.push_back(properties[index]);
3643 pointerCoords.push_back(coords[index]);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003644
3645 if (changedId >= 0 && id == uint32_t(changedId)) {
3646 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3647 }
3648
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003649 pointerCount++;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003650 }
3651
3652 ALOG_ASSERT(pointerCount != 0);
3653
3654 if (changedId >= 0 && pointerCount == 1) {
3655 // Replace initial down and final up action.
3656 // We can compare the action without masking off the changed pointer index
3657 // because we know the index is 0.
3658 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3659 action = AMOTION_EVENT_ACTION_DOWN;
3660 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003661 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3662 action = AMOTION_EVENT_ACTION_CANCEL;
3663 } else {
3664 action = AMOTION_EVENT_ACTION_UP;
3665 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003666 } else {
3667 // Can't happen.
3668 ALOG_ASSERT(false);
3669 }
3670 }
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00003671 if (mCurrentStreamModifiedByExternalStylus) {
3672 source |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3673 }
Prabir Pradhan9a53b552024-06-04 02:59:40 +00003674 if (mOrientedRanges.orientation.has_value()) {
3675 flags |= AMOTION_EVENT_PRIVATE_FLAG_SUPPORTS_ORIENTATION;
3676 if (mOrientedRanges.tilt.has_value()) {
3677 // In the current implementation, only devices that report a value for tilt supports
3678 // directional orientation.
3679 flags |= AMOTION_EVENT_PRIVATE_FLAG_SUPPORTS_DIRECTIONAL_ORIENTATION;
3680 }
3681 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003682
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07003683 const ui::LogicalDisplayId displayId =
3684 getAssociatedDisplayId().value_or(ui::LogicalDisplayId::INVALID);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003685
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003686 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3687 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003688 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan3ed7e352024-05-03 23:59:43 +00003689 xCursorPosition = yCursorPosition = 0.f;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003690 }
Linnan Li13bf76a2024-05-05 19:18:02 +08003691 const DeviceId deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003692 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003693 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003694 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003695 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3696 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003697 classification, edgeFlags, pointerCount, pointerProperties.data(),
3698 pointerCoords.data(), xPrecision, yPrecision, xCursorPosition,
3699 yCursorPosition, downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003700}
3701
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003702std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3703 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003704 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3705 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003706 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003707}
3708
Prabir Pradhan1728b212021-10-19 16:00:03 -07003709bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003710 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003711 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003712 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003713}
3714
3715const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3716 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003717 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3718 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3719 "left=%d, top=%d, right=%d, bottom=%d",
3720 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3721 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003722
3723 if (virtualKey.isHit(x, y)) {
3724 return &virtualKey;
3725 }
3726 }
3727
3728 return nullptr;
3729}
3730
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003731void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3732 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3733 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003734
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003735 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003736
3737 if (currentPointerCount == 0) {
3738 // No pointers to assign.
3739 return;
3740 }
3741
3742 if (lastPointerCount == 0) {
3743 // All pointers are new.
3744 for (uint32_t i = 0; i < currentPointerCount; i++) {
3745 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003746 current.rawPointerData.pointers[i].id = id;
3747 current.rawPointerData.idToIndex[id] = i;
3748 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003749 }
3750 return;
3751 }
3752
3753 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003754 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003755 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003756 uint32_t id = last.rawPointerData.pointers[0].id;
3757 current.rawPointerData.pointers[0].id = id;
3758 current.rawPointerData.idToIndex[id] = 0;
3759 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003760 return;
3761 }
3762
3763 // General case.
3764 // We build a heap of squared euclidean distances between current and last pointers
3765 // associated with the current and last pointer indices. Then, we find the best
3766 // match (by distance) for each current pointer.
3767 // The pointers must have the same tool type but it is possible for them to
3768 // transition from hovering to touching or vice-versa while retaining the same id.
3769 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3770
3771 uint32_t heapSize = 0;
3772 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3773 currentPointerIndex++) {
3774 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3775 lastPointerIndex++) {
3776 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003777 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003778 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003779 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003780 if (currentPointer.toolType == lastPointer.toolType) {
3781 int64_t deltaX = currentPointer.x - lastPointer.x;
3782 int64_t deltaY = currentPointer.y - lastPointer.y;
3783
3784 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3785
3786 // Insert new element into the heap (sift up).
3787 heap[heapSize].currentPointerIndex = currentPointerIndex;
3788 heap[heapSize].lastPointerIndex = lastPointerIndex;
3789 heap[heapSize].distance = distance;
3790 heapSize += 1;
3791 }
3792 }
3793 }
3794
3795 // Heapify
3796 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3797 startIndex -= 1;
3798 for (uint32_t parentIndex = startIndex;;) {
3799 uint32_t childIndex = parentIndex * 2 + 1;
3800 if (childIndex >= heapSize) {
3801 break;
3802 }
3803
3804 if (childIndex + 1 < heapSize &&
3805 heap[childIndex + 1].distance < heap[childIndex].distance) {
3806 childIndex += 1;
3807 }
3808
3809 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3810 break;
3811 }
3812
3813 swap(heap[parentIndex], heap[childIndex]);
3814 parentIndex = childIndex;
3815 }
3816 }
3817
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003818 if (DEBUG_POINTER_ASSIGNMENT) {
3819 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3820 for (size_t i = 0; i < heapSize; i++) {
3821 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3822 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3823 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003824 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003825
3826 // Pull matches out by increasing order of distance.
3827 // To avoid reassigning pointers that have already been matched, the loop keeps track
3828 // of which last and current pointers have been matched using the matchedXXXBits variables.
3829 // It also tracks the used pointer id bits.
3830 BitSet32 matchedLastBits(0);
3831 BitSet32 matchedCurrentBits(0);
3832 BitSet32 usedIdBits(0);
3833 bool first = true;
3834 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3835 while (heapSize > 0) {
3836 if (first) {
3837 // The first time through the loop, we just consume the root element of
3838 // the heap (the one with smallest distance).
3839 first = false;
3840 } else {
3841 // Previous iterations consumed the root element of the heap.
3842 // Pop root element off of the heap (sift down).
3843 heap[0] = heap[heapSize];
3844 for (uint32_t parentIndex = 0;;) {
3845 uint32_t childIndex = parentIndex * 2 + 1;
3846 if (childIndex >= heapSize) {
3847 break;
3848 }
3849
3850 if (childIndex + 1 < heapSize &&
3851 heap[childIndex + 1].distance < heap[childIndex].distance) {
3852 childIndex += 1;
3853 }
3854
3855 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3856 break;
3857 }
3858
3859 swap(heap[parentIndex], heap[childIndex]);
3860 parentIndex = childIndex;
3861 }
3862
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003863 if (DEBUG_POINTER_ASSIGNMENT) {
3864 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3865 for (size_t j = 0; j < heapSize; j++) {
3866 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3867 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3868 heap[j].distance);
3869 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003870 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003871 }
3872
3873 heapSize -= 1;
3874
3875 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3876 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3877
3878 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3879 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3880
3881 matchedCurrentBits.markBit(currentPointerIndex);
3882 matchedLastBits.markBit(lastPointerIndex);
3883
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003884 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3885 current.rawPointerData.pointers[currentPointerIndex].id = id;
3886 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3887 current.rawPointerData.markIdBit(id,
3888 current.rawPointerData.isHovering(
3889 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003890 usedIdBits.markBit(id);
3891
Harry Cutts45483602022-08-24 14:36:48 +00003892 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3893 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3894 ", distance=%" PRIu64,
3895 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003896 break;
3897 }
3898 }
3899
3900 // Assign fresh ids to pointers that were not matched in the process.
3901 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3902 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3903 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3904
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003905 current.rawPointerData.pointers[currentPointerIndex].id = id;
3906 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3907 current.rawPointerData.markIdBit(id,
3908 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003909
Harry Cutts45483602022-08-24 14:36:48 +00003910 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3911 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
3912 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003913 }
3914}
3915
3916int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3917 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3918 return AKEY_STATE_VIRTUAL;
3919 }
3920
3921 for (const VirtualKey& virtualKey : mVirtualKeys) {
3922 if (virtualKey.keyCode == keyCode) {
3923 return AKEY_STATE_UP;
3924 }
3925 }
3926
3927 return AKEY_STATE_UNKNOWN;
3928}
3929
3930int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3931 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3932 return AKEY_STATE_VIRTUAL;
3933 }
3934
3935 for (const VirtualKey& virtualKey : mVirtualKeys) {
3936 if (virtualKey.scanCode == scanCode) {
3937 return AKEY_STATE_UP;
3938 }
3939 }
3940
3941 return AKEY_STATE_UNKNOWN;
3942}
3943
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003944bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
3945 const std::vector<int32_t>& keyCodes,
3946 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003947 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003948 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003949 if (virtualKey.keyCode == keyCodes[i]) {
3950 outFlags[i] = 1;
3951 }
3952 }
3953 }
3954
3955 return true;
3956}
3957
Linnan Li13bf76a2024-05-05 19:18:02 +08003958std::optional<ui::LogicalDisplayId> TouchInputMapper::getAssociatedDisplayId() {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003959 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003960 if (mDeviceMode == DeviceMode::POINTER) {
Siarhei Vishniakoucfbee532024-05-10 13:41:35 -07003961 return ui::LogicalDisplayId::INVALID;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003962 } else {
3963 return std::make_optional(mViewport.displayId);
3964 }
3965 }
3966 return std::nullopt;
3967}
3968
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003969} // namespace android