blob: 8d915996f7214b19757f5d463254642fe786e99e [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 |
339 InputReaderConfiguration::Change::SHOW_TOUCHES |
340 InputReaderConfiguration::Change::EXTERNAL_STYLUS_PRESENCE |
341 InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700342 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700343 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700344 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700345 }
346
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000347 if (changes.any() && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700348 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000349
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350 // Send reset, unless this is the first time the device has been configured,
351 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000352 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700353 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700354 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700355}
356
357void TouchInputMapper::resolveExternalStylusPresence() {
358 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800359 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700360 mExternalStylusConnected = !devices.empty();
361
362 if (!mExternalStylusConnected) {
363 resetExternalStylus();
364 }
365}
366
Arpit Singh403e53c2023-04-18 11:46:56 +0000367TouchInputMapper::Parameters TouchInputMapper::computeParameters(
368 const InputDeviceContext& deviceContext) {
369 Parameters parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700370 // Use the pointer presentation mode for devices that do not support distinct
371 // multitouch. The spot-based presentation relies on being able to accurately
372 // locate two or more fingers on the touch pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000373 parameters.gestureMode = deviceContext.hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100374 ? Parameters::GestureMode::SINGLE_TOUCH
375 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700376
Arpit Singh403e53c2023-04-18 11:46:56 +0000377 const PropertyMap& config = deviceContext.getConfiguration();
Harry Cuttsf13161a2023-03-08 14:15:49 +0000378 std::optional<std::string> gestureModeString = config.getString("touch.gestureMode");
379 if (gestureModeString.has_value()) {
380 if (*gestureModeString == "single-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000381 parameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000382 } else if (*gestureModeString == "multi-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000383 parameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000384 } else if (*gestureModeString != "default") {
385 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700386 }
387 }
388
Arpit Singh403e53c2023-04-18 11:46:56 +0000389 parameters.deviceType = computeDeviceType(deviceContext);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700390
Arpit Singh403e53c2023-04-18 11:46:56 +0000391 parameters.hasButtonUnderPad = deviceContext.hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700392
Arpit Singh403e53c2023-04-18 11:46:56 +0000393 parameters.orientationAware =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000394 config.getBool("touch.orientationAware")
Arpit Singh403e53c2023-04-18 11:46:56 +0000395 .value_or(parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700396
Arpit Singh403e53c2023-04-18 11:46:56 +0000397 parameters.orientation = ui::ROTATION_0;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000398 std::optional<std::string> orientationString = config.getString("touch.orientation");
399 if (orientationString.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000400 if (parameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700401 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
Harry Cuttsf13161a2023-03-08 14:15:49 +0000402 } else if (*orientationString == "ORIENTATION_90") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000403 parameters.orientation = ui::ROTATION_90;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000404 } else if (*orientationString == "ORIENTATION_180") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000405 parameters.orientation = ui::ROTATION_180;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000406 } else if (*orientationString == "ORIENTATION_270") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000407 parameters.orientation = ui::ROTATION_270;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000408 } else if (*orientationString != "ORIENTATION_0") {
409 ALOGW("Invalid value for touch.orientation: '%s'", orientationString->c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700410 }
411 }
412
Arpit Singh403e53c2023-04-18 11:46:56 +0000413 parameters.hasAssociatedDisplay = false;
414 parameters.associatedDisplayIsExternal = false;
415 if (parameters.orientationAware ||
416 parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
417 parameters.deviceType == Parameters::DeviceType::POINTER ||
418 (parameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
419 deviceContext.getAssociatedViewport())) {
420 parameters.hasAssociatedDisplay = true;
421 if (parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
422 parameters.associatedDisplayIsExternal = deviceContext.isExternal();
423 parameters.uniqueDisplayId = config.getString("touch.displayId").value_or("").c_str();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700424 }
425 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000426 if (deviceContext.getAssociatedDisplayPort()) {
427 parameters.hasAssociatedDisplay = true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 }
429
430 // Initial downs on external touch devices should wake the device.
431 // Normally we don't do this for internal touch screens to prevent them from waking
432 // up in your pocket but you can enable it using the input device configuration.
Arpit Singh403e53c2023-04-18 11:46:56 +0000433 parameters.wake = config.getBool("touch.wake").value_or(deviceContext.isExternal());
Prabir Pradhan167c2702022-09-14 00:37:24 +0000434
Harry Cuttsf13161a2023-03-08 14:15:49 +0000435 std::optional<int32_t> usiVersionMajor = config.getInt("touch.usiVersionMajor");
436 std::optional<int32_t> usiVersionMinor = config.getInt("touch.usiVersionMinor");
437 if (usiVersionMajor.has_value() && usiVersionMinor.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000438 parameters.usiVersion = {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000439 .majorVersion = *usiVersionMajor,
440 .minorVersion = *usiVersionMinor,
441 };
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000442 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700443
Arpit Singh403e53c2023-04-18 11:46:56 +0000444 parameters.enableForInactiveViewport =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000445 config.getBool("touch.enableForInactiveViewport").value_or(false);
Arpit Singh403e53c2023-04-18 11:46:56 +0000446
447 return parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700448}
449
Arpit Singh403e53c2023-04-18 11:46:56 +0000450TouchInputMapper::Parameters::DeviceType TouchInputMapper::computeDeviceType(
451 const InputDeviceContext& deviceContext) {
452 Parameters::DeviceType deviceType;
453 if (deviceContext.hasInputProperty(INPUT_PROP_DIRECT)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000454 // The device is a touch screen.
Arpit Singh403e53c2023-04-18 11:46:56 +0000455 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
456 } else if (deviceContext.hasInputProperty(INPUT_PROP_POINTER)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000457 // The device is a pointing device like a track pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000458 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000459 } else {
460 // The device is a touch pad of unknown purpose.
Arpit Singh403e53c2023-04-18 11:46:56 +0000461 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000462 }
463
464 // Type association takes precedence over the device type found in the idc file.
Arpit Singh403e53c2023-04-18 11:46:56 +0000465 std::string deviceTypeString = deviceContext.getDeviceTypeAssociation().value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000466 if (deviceTypeString.empty()) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000467 deviceTypeString =
Arpit Singh403e53c2023-04-18 11:46:56 +0000468 deviceContext.getConfiguration().getString("touch.deviceType").value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000469 }
470 if (deviceTypeString == "touchScreen") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000471 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000472 } else if (deviceTypeString == "touchNavigation") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000473 deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000474 } else if (deviceTypeString == "pointer") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000475 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000476 } else if (deviceTypeString != "default" && deviceTypeString != "") {
477 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
478 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000479 return deviceType;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000480}
481
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700482void TouchInputMapper::dumpParameters(std::string& dump) {
483 dump += INDENT3 "Parameters:\n";
484
Dominik Laskowski75788452021-02-09 18:51:25 -0800485 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700486
Dominik Laskowski75788452021-02-09 18:51:25 -0800487 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700488
489 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
490 "displayId='%s'\n",
491 toString(mParameters.hasAssociatedDisplay),
492 toString(mParameters.associatedDisplayIsExternal),
493 mParameters.uniqueDisplayId.c_str());
494 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800495 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000496 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
497 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700498 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
499 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700500}
501
502void TouchInputMapper::configureRawPointerAxes() {
503 mRawPointerAxes.clear();
504}
505
506void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
507 dump += INDENT3 "Raw Touch Axes:\n";
508 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
509 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
510 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
511 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
512 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
513 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
514 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
515 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
516 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
517 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
518 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
520 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
521}
522
523bool TouchInputMapper::hasExternalStylus() const {
524 return mExternalStylusConnected;
525}
526
527/**
528 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000529 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800530 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000531 * 3. Get the matching viewport by either unique id in idc file or by the display type
532 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800533 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700534 */
535std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Harry Cutts8722be92024-04-05 14:46:05 +0000536 if (mParameters.hasAssociatedDisplay) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000537 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800538 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700539 }
540
Prabir Pradhan3138b122024-04-19 17:43:00 +0000541 const std::optional<std::string> associatedDisplayUniqueId =
542 getDeviceContext().getAssociatedDisplayUniqueId();
543 if (associatedDisplayUniqueId) {
Christine Franks2a2293c2022-01-18 11:51:16 -0800544 return getDeviceContext().getAssociatedViewport();
545 }
546
Michael Wright227c5542020-07-02 18:30:52 +0100547 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800548 std::optional<DisplayViewport> viewport =
549 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
550 if (viewport) {
551 return viewport;
552 } else {
553 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
554 mConfig.defaultPointerDisplayId);
555 }
556 }
557
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700558 // Check if uniqueDisplayId is specified in idc file.
559 if (!mParameters.uniqueDisplayId.empty()) {
560 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
561 }
562
563 ViewportType viewportTypeToUse;
564 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100565 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100567 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700568 }
569
570 std::optional<DisplayViewport> viewport =
571 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100572 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700573 ALOGW("Input device %s should be associated with external display, "
574 "fallback to internal one for the external viewport is not found.",
575 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100576 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700577 }
578
579 return viewport;
580 }
581
582 // No associated display, return a non-display viewport.
583 DisplayViewport newViewport;
584 // Raw width and height in the natural orientation.
585 int32_t rawWidth = mRawPointerAxes.getRawWidth();
586 int32_t rawHeight = mRawPointerAxes.getRawHeight();
587 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
588 return std::make_optional(newViewport);
589}
590
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800591int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
592 if (resolution < 0) {
593 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
594 getDeviceName().c_str());
595 return 0;
596 }
597 return resolution;
598}
599
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800600void TouchInputMapper::initializeSizeRanges() {
601 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
602 mSizeScale = 0.0f;
603 return;
604 }
605
606 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000607 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800608
609 // Size factors.
610 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
611 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
612 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
613 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
614 } else {
615 mSizeScale = 0.0f;
616 }
617
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700618 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
619 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
620 .source = mSource,
621 .min = 0,
622 .max = diagonalSize,
623 .flat = 0,
624 .fuzz = 0,
625 .resolution = 0,
626 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800627
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800628 if (mRawPointerAxes.touchMajor.valid) {
629 mRawPointerAxes.touchMajor.resolution =
630 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700631 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800632 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800633
634 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700635 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800636 if (mRawPointerAxes.touchMinor.valid) {
637 mRawPointerAxes.touchMinor.resolution =
638 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700639 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800640 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800641
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700642 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
643 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
644 .source = mSource,
645 .min = 0,
646 .max = diagonalSize,
647 .flat = 0,
648 .fuzz = 0,
649 .resolution = 0,
650 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800651 if (mRawPointerAxes.toolMajor.valid) {
652 mRawPointerAxes.toolMajor.resolution =
653 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700654 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800655 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800656
657 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700658 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800659 if (mRawPointerAxes.toolMinor.valid) {
660 mRawPointerAxes.toolMinor.resolution =
661 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700662 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800663 }
664
665 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700666 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
667 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
668 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
669 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800670 } else {
671 // Support for other calibrations can be added here.
672 ALOGW("%s calibration is not supported for size ranges at the moment. "
673 "Using raw resolution instead",
674 ftl::enum_string(mCalibration.sizeCalibration).c_str());
675 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800676
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700677 mOrientedRanges.size = InputDeviceInfo::MotionRange{
678 .axis = AMOTION_EVENT_AXIS_SIZE,
679 .source = mSource,
680 .min = 0,
681 .max = 1.0,
682 .flat = 0,
683 .fuzz = 0,
684 .resolution = 0,
685 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800686}
687
688void TouchInputMapper::initializeOrientedRanges() {
689 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000690 const float orientedScaleX = mRawToDisplay.getScaleX();
691 const float orientedScaleY = mRawToDisplay.getScaleY();
692 mOrientedXPrecision = 1.0f / orientedScaleX;
693 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800694
695 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
696 mOrientedRanges.x.source = mSource;
697 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
698 mOrientedRanges.y.source = mSource;
699
700 // Scale factor for terms that are not oriented in a particular axis.
701 // If the pixels are square then xScale == yScale otherwise we fake it
702 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000703 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800704
705 initializeSizeRanges();
706
707 // Pressure factors.
708 mPressureScale = 0;
709 float pressureMax = 1.0;
710 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
711 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700712 if (mCalibration.pressureScale) {
713 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800714 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
715 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
716 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
717 }
718 }
719
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700720 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
721 .axis = AMOTION_EVENT_AXIS_PRESSURE,
722 .source = mSource,
723 .min = 0,
724 .max = pressureMax,
725 .flat = 0,
726 .fuzz = 0,
727 .resolution = 0,
728 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800729
730 // Tilt
731 mTiltXCenter = 0;
732 mTiltXScale = 0;
733 mTiltYCenter = 0;
734 mTiltYScale = 0;
735 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
736 if (mHaveTilt) {
737 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
738 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
739 mTiltXScale = M_PI / 180;
740 mTiltYScale = M_PI / 180;
741
742 if (mRawPointerAxes.tiltX.resolution) {
743 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
744 }
745 if (mRawPointerAxes.tiltY.resolution) {
746 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
747 }
748
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700749 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
750 .axis = AMOTION_EVENT_AXIS_TILT,
751 .source = mSource,
752 .min = 0,
753 .max = M_PI_2,
754 .flat = 0,
755 .fuzz = 0,
756 .resolution = 0,
757 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800758 }
759
760 // Orientation
761 mOrientationScale = 0;
762 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700763 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
764 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
765 .source = mSource,
766 .min = -M_PI,
767 .max = M_PI,
768 .flat = 0,
769 .fuzz = 0,
770 .resolution = 0,
771 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800772
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800773 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
774 if (mCalibration.orientationCalibration ==
775 Calibration::OrientationCalibration::INTERPOLATED) {
776 if (mRawPointerAxes.orientation.valid) {
777 if (mRawPointerAxes.orientation.maxValue > 0) {
778 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
779 } else if (mRawPointerAxes.orientation.minValue < 0) {
780 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
781 } else {
782 mOrientationScale = 0;
783 }
784 }
785 }
786
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700787 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
788 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
789 .source = mSource,
790 .min = -M_PI_2,
791 .max = M_PI_2,
792 .flat = 0,
793 .fuzz = 0,
794 .resolution = 0,
795 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800796 }
797
798 // Distance
799 mDistanceScale = 0;
800 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
801 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700802 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800803 }
804
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700805 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800806
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700807 .axis = AMOTION_EVENT_AXIS_DISTANCE,
808 .source = mSource,
809 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
810 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
811 .flat = 0,
812 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
813 .resolution = 0,
814 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800815 }
816
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000817 // Oriented X/Y range (in the rotated display's orientation)
818 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
819 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
820 .toFloatRect();
821 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
822 mOrientedRanges.x.min = orientedRangeRect.left;
823 mOrientedRanges.y.min = orientedRangeRect.top;
824 mOrientedRanges.x.max = orientedRangeRect.right;
825 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800826
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000827 // Oriented flat (in the rotated display's orientation)
828 const auto orientedFlat =
829 transformWithoutTranslation(mRawToRotatedDisplay,
830 {static_cast<float>(mRawPointerAxes.x.flat),
831 static_cast<float>(mRawPointerAxes.y.flat)});
832 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
833 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800834
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000835 // Oriented fuzz (in the rotated display's orientation)
836 const auto orientedFuzz =
837 transformWithoutTranslation(mRawToRotatedDisplay,
838 {static_cast<float>(mRawPointerAxes.x.fuzz),
839 static_cast<float>(mRawPointerAxes.y.fuzz)});
840 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
841 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800842
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000843 // Oriented resolution (in the rotated display's orientation)
844 const auto orientedRes =
845 transformWithoutTranslation(mRawToRotatedDisplay,
846 {static_cast<float>(mRawPointerAxes.x.resolution),
847 static_cast<float>(mRawPointerAxes.y.resolution)});
848 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
849 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800850}
851
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000852void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000853 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
854 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
855 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000856
Prabir Pradhan3e798762022-12-02 21:02:11 +0000857 // See notes about input coordinates in the inputflinger docs:
858 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000859
860 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000861 ui::Transform undoOffsetInRaw;
862 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000863
Prabir Pradhan3e798762022-12-02 21:02:11 +0000864 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
865 // will now be in the same orientation as the display in ROTATION_0.
866 // Note: Negating an ui::Rotation value will give its inverse rotation.
867 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
868 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
869 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
870 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
871 // When rotating raw values, account for the extra unit added when calculating the raw range.
872 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
873 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000874
Prabir Pradhan3e798762022-12-02 21:02:11 +0000875 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
876 // now be in the same orientation as the rotated display. There is no need to rotate the
877 // coordinates to the display rotation if the device is not orientation-aware.
878 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
879 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
880 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
881 : orientedRawSize;
882 // When rotating raw values, account for the extra unit added when calculating the raw range.
883 const auto rotateInRaw = mParameters.orientationAware
884 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
885 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000886
Prabir Pradhan3e798762022-12-02 21:02:11 +0000887 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000888 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
889 // the surface of the display panel. This is usually true for touchscreens.
890 // - In POINTER mode, we cannot assume that the display and the touch device have the same
891 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
892 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
893 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
894 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000895 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
896 // are in the continuous space of the logical display.
897 ui::Transform scaleRawToDisplay;
898 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
899 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000900 if (mDeviceMode == DeviceMode::DIRECT) {
901 scaleRawToDisplay.set(xScale, 0, 0, yScale);
902 } else if (mDeviceMode == DeviceMode::POINTER) {
903 const float fixedScale = std::max(xScale, yScale);
904 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
905 } else {
906 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
907 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000908
Prabir Pradhan3e798762022-12-02 21:02:11 +0000909 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
910 // that InputReader uses.
911 const auto undoRotateInDisplay =
912 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
913 .inverse();
914
915 // Now put it all together!
916 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
917 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
918 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000919}
920
Prabir Pradhan1728b212021-10-19 16:00:03 -0700921void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000922 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700923
924 resolveExternalStylusPresence();
925
926 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100927 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +0900928 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700929 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100930 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700931 if (hasStylus()) {
932 mSource |= AINPUT_SOURCE_STYLUS;
933 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800934 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700935 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100936 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700937 if (hasStylus()) {
938 mSource |= AINPUT_SOURCE_STYLUS;
939 }
Michael Wright227c5542020-07-02 18:30:52 +0100940 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700941 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100942 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700943 } else {
Harry Cutts8722be92024-04-05 14:46:05 +0000944 ALOGW("Touch device '%s' has invalid parameters or configuration. The device will be "
945 "inoperable.",
946 getDeviceName().c_str());
947 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700948 }
949
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000950 const std::optional<DisplayViewport> newViewportOpt = findViewport();
951
952 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700953 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
954 ALOGW("Touch device '%s' did not report support for X or Y axis! "
955 "The device will be inoperable.",
956 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100957 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000958 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700959 ALOGI("Touch device '%s' could not query the properties of its associated "
960 "display. The device will be inoperable until the display size "
961 "becomes available.",
962 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100963 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700964 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000965 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
966 getDeviceName().c_str(), getDeviceId());
967 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000968 }
969
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700970 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000971 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000972 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
973 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
974 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
975 const float rawMeanResolution =
976 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700977
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000978 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
Josh Thielene986aed2023-06-01 14:17:30 +0000979 bool viewportChanged;
980 if (mParameters.enableForInactiveViewport) {
981 // When touch is enabled for an inactive viewport, ignore the
982 // viewport active status when checking whether the viewport has
983 // changed.
984 DisplayViewport tempViewport = mViewport;
985 tempViewport.isActive = newViewport.isActive;
986 viewportChanged = tempViewport != newViewport;
987 } else {
988 viewportChanged = mViewport != newViewport;
989 }
990
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700991 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700992 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000993 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
994 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
995 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700996
Michael Wright227c5542020-07-02 18:30:52 +0100997 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000998 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700999
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001000 mDisplayBounds = getNaturalDisplaySize(mViewport);
1001 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
1002 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -07001003
Prabir Pradhan3e798762022-12-02 21:02:11 +00001004 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
1005 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
1006 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001007 // InputReader works in the un-rotated display coordinate space, so we don't need to do
1008 // anything if the device is already orientation-aware. If the device is not
1009 // orientation-aware, then we need to apply the inverse rotation of the display so that
1010 // when the display rotation is applied later as a part of the per-window transform, we
1011 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001012 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +00001013 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001014 : getInverseRotation(mViewport.orientation);
1015 // For orientation-aware devices that work in the un-rotated coordinate space, the
1016 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001017 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001018 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001019
1020 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001021 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001022 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001023 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001024 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001025 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001026 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001027 mRawToDisplay.reset();
1028 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001029 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001030 }
1031 }
1032
1033 // If moving between pointer modes, need to reset some state.
1034 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1035 if (deviceModeChanged) {
1036 mOrientedRanges.clear();
1037 }
1038
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001039 // Create and preserve the pointer controller in the following cases:
1040 const bool isPointerControllerNeeded =
1041 // - when the device is in pointer mode, to show the mouse cursor;
1042 (mDeviceMode == DeviceMode::POINTER) ||
1043 // - when pointer capture is enabled, to preserve the mouse cursor position;
1044 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +09001045 mConfig.pointerCaptureRequest.isEnable()) ||
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001046 // - when we should be showing touches;
1047 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1048 // - when we should be showing a pointer icon for direct styluses.
1049 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1050 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001051 if (mPointerController == nullptr) {
1052 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001053 }
Hiroki Sato25040232024-02-22 17:21:22 +09001054 if (mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001055 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1056 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057 } else {
lilinnandef700b2022-06-17 19:32:01 +08001058 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1059 !mConfig.showTouches) {
1060 mPointerController->clearSpots();
1061 }
Michael Wright17db18e2020-06-26 20:51:44 +01001062 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001063 }
1064
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001065 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001066 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001067 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001068 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001069 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001070
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001071 configureVirtualKeys();
1072
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001073 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001074
1075 // Location
1076 updateAffineTransformation();
1077
Michael Wright227c5542020-07-02 18:30:52 +01001078 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001079 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001080 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1081 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001082
1083 // Scale movements such that one whole swipe of the touch pad covers a
1084 // given area relative to the diagonal size of the display when no acceleration
1085 // is applied.
1086 // Assume that the touch pad has a square aspect ratio such that movements in
1087 // X and Y of the same number of raw units cover the same physical distance.
1088 mPointerXMovementScale =
1089 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1090 mPointerYMovementScale = mPointerXMovementScale;
1091
1092 // Scale zooms to cover a smaller range of the display than movements do.
1093 // This value determines the area around the pointer that is affected by freeform
1094 // pointer gestures.
1095 mPointerXZoomScale =
1096 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1097 mPointerYZoomScale = mPointerXZoomScale;
1098
HQ Liue6983c72022-04-19 22:14:56 +00001099 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1100 // axis is non positive value.
1101 const float minFreeformGestureWidth =
1102 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1103
1104 mPointerGestureMaxSwipeWidth =
1105 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1106 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001107 }
1108
1109 // Inform the dispatcher about the changes.
1110 *outResetNeeded = true;
1111 bumpGeneration();
1112 }
1113}
1114
Prabir Pradhan1728b212021-10-19 16:00:03 -07001115void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001116 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001117 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001118 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1119 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001120 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001121}
1122
1123void TouchInputMapper::configureVirtualKeys() {
1124 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001125 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126
1127 mVirtualKeys.clear();
1128
1129 if (virtualKeyDefinitions.size() == 0) {
1130 return;
1131 }
1132
1133 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1134 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1135 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1136 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1137
1138 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1139 VirtualKey virtualKey;
1140
1141 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1142 int32_t keyCode;
1143 int32_t dummyKeyMetaState;
1144 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001145 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1146 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1148 continue; // drop the key
1149 }
1150
1151 virtualKey.keyCode = keyCode;
1152 virtualKey.flags = flags;
1153
1154 // convert the key definition's display coordinates into touch coordinates for a hit box
1155 int32_t halfWidth = virtualKeyDefinition.width / 2;
1156 int32_t halfHeight = virtualKeyDefinition.height / 2;
1157
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001158 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1159 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001161 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1162 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001163 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001164 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1165 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001167 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1168 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 touchScreenTop;
1170 mVirtualKeys.push_back(virtualKey);
1171 }
1172}
1173
1174void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1175 if (!mVirtualKeys.empty()) {
1176 dump += INDENT3 "Virtual Keys:\n";
1177
1178 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1179 const VirtualKey& virtualKey = mVirtualKeys[i];
1180 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1181 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1182 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1183 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1184 }
1185 }
1186}
1187
1188void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001189 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190 Calibration& out = mCalibration;
1191
1192 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001193 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001194 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1195 if (sizeCalibrationString.has_value()) {
1196 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001197 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001198 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001200 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001202 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001203 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001204 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001205 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001206 } else if (*sizeCalibrationString != "default") {
1207 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001208 }
1209 }
1210
Harry Cuttsf13161a2023-03-08 14:15:49 +00001211 out.sizeScale = in.getFloat("touch.size.scale");
1212 out.sizeBias = in.getFloat("touch.size.bias");
1213 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214
1215 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001216 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001217 std::optional<std::string> pressureCalibrationString =
1218 in.getString("touch.pressure.calibration");
1219 if (pressureCalibrationString.has_value()) {
1220 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001221 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001222 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001223 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001224 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001225 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001226 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001228 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 }
1230 }
1231
Harry Cuttsf13161a2023-03-08 14:15:49 +00001232 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233
1234 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001235 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001236 std::optional<std::string> orientationCalibrationString =
1237 in.getString("touch.orientation.calibration");
1238 if (orientationCalibrationString.has_value()) {
1239 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001240 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001241 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001242 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001243 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001244 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001245 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001247 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 }
1249 }
1250
1251 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001252 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001253 std::optional<std::string> distanceCalibrationString =
1254 in.getString("touch.distance.calibration");
1255 if (distanceCalibrationString.has_value()) {
1256 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001257 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001258 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001259 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001260 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001262 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 }
1264 }
1265
Harry Cuttsf13161a2023-03-08 14:15:49 +00001266 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267}
1268
1269void TouchInputMapper::resolveCalibration() {
1270 // Size
1271 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001272 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1273 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001274 }
1275 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001276 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277 }
1278
1279 // Pressure
1280 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001281 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1282 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 }
1284 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001285 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001286 }
1287
1288 // Orientation
1289 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001290 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1291 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001292 }
1293 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001294 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 }
1296
1297 // Distance
1298 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001299 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1300 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 }
1302 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001303 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001305}
1306
1307void TouchInputMapper::dumpCalibration(std::string& dump) {
1308 dump += INDENT3 "Calibration:\n";
1309
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001310 dump += INDENT4 "touch.size.calibration: ";
1311 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001313 if (mCalibration.sizeScale) {
1314 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 }
1316
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001317 if (mCalibration.sizeBias) {
1318 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 }
1320
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001321 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001323 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324 }
1325
1326 // Pressure
1327 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001328 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329 dump += INDENT4 "touch.pressure.calibration: none\n";
1330 break;
Michael Wright227c5542020-07-02 18:30:52 +01001331 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 dump += INDENT4 "touch.pressure.calibration: physical\n";
1333 break;
Michael Wright227c5542020-07-02 18:30:52 +01001334 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001335 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1336 break;
1337 default:
1338 ALOG_ASSERT(false);
1339 }
1340
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001341 if (mCalibration.pressureScale) {
1342 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001343 }
1344
1345 // Orientation
1346 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001347 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001348 dump += INDENT4 "touch.orientation.calibration: none\n";
1349 break;
Michael Wright227c5542020-07-02 18:30:52 +01001350 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001351 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1352 break;
Michael Wright227c5542020-07-02 18:30:52 +01001353 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001354 dump += INDENT4 "touch.orientation.calibration: vector\n";
1355 break;
1356 default:
1357 ALOG_ASSERT(false);
1358 }
1359
1360 // Distance
1361 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001362 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001363 dump += INDENT4 "touch.distance.calibration: none\n";
1364 break;
Michael Wright227c5542020-07-02 18:30:52 +01001365 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001366 dump += INDENT4 "touch.distance.calibration: scaled\n";
1367 break;
1368 default:
1369 ALOG_ASSERT(false);
1370 }
1371
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001372 if (mCalibration.distanceScale) {
1373 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001374 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001375}
1376
1377void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1378 dump += INDENT3 "Affine Transformation:\n";
1379
1380 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1381 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1382 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1383 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1384 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1385 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1386}
1387
1388void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001389 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001390 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001391}
1392
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001393std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001394 std::list<NotifyArgs> out = cancelTouch(when, when);
1395 updateTouchSpots();
1396
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001397 mCursorButtonAccumulator.reset(getDeviceContext());
1398 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001399 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001400
1401 mPointerVelocityControl.reset();
1402 mWheelXVelocityControl.reset();
1403 mWheelYVelocityControl.reset();
1404
1405 mRawStatesPending.clear();
1406 mCurrentRawState.clear();
1407 mCurrentCookedState.clear();
1408 mLastRawState.clear();
1409 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001410 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411 mSentHoverEnter = false;
1412 mHavePointerIds = false;
1413 mCurrentMotionAborted = false;
1414 mDownTime = 0;
1415
1416 mCurrentVirtualKey.down = false;
1417
1418 mPointerGesture.reset();
1419 mPointerSimple.reset();
1420 resetExternalStylus();
1421
1422 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001423 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001424 mPointerController->clearSpots();
1425 }
1426
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001427 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001428}
1429
1430void TouchInputMapper::resetExternalStylus() {
1431 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001432 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001433 mExternalStylusFusionTimeout = LLONG_MAX;
1434 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001435 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436}
1437
1438void TouchInputMapper::clearStylusDataPendingFlags() {
1439 mExternalStylusDataPending = false;
1440 mExternalStylusFusionTimeout = LLONG_MAX;
1441}
1442
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001443std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444 mCursorButtonAccumulator.process(rawEvent);
1445 mCursorScrollAccumulator.process(rawEvent);
1446 mTouchButtonAccumulator.process(rawEvent);
1447
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001448 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001449 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001450 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001452 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001453}
1454
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001455std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1456 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001457 if (mDeviceMode == DeviceMode::DISABLED) {
1458 // Only save the last pending state when the device is disabled.
1459 mRawStatesPending.clear();
1460 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001461 // Push a new state.
1462 mRawStatesPending.emplace_back();
1463
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001464 RawState& next = mRawStatesPending.back();
1465 next.clear();
1466 next.when = when;
1467 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001468
1469 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001470 next.buttonState = filterButtonState(mConfig,
1471 mTouchButtonAccumulator.getButtonState() |
1472 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001473
1474 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001475 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1476 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001477 mCursorScrollAccumulator.finishSync();
1478
1479 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001480 syncTouch(when, &next);
1481
1482 // The last RawState is the actually second to last, since we just added a new state
1483 const RawState& last =
1484 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001485
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001486 std::tie(next.when, next.readTime) =
1487 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1488 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001489
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001490 // Assign pointer ids.
1491 if (!mHavePointerIds) {
1492 assignPointerIds(last, next);
1493 }
1494
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001495 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001496 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1497 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1498 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1499 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1500 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1501 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001502
Arthur Hung9ad18942021-06-19 02:04:46 +00001503 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1504 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1505 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1506 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1507 next.rawPointerData.hoveringIdBits.value);
1508 }
1509
Harry Cutts33476232023-01-30 19:57:29 +00001510 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001511 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001512}
1513
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001514std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1515 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001516 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001517 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001518 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001519 }
1520
1521 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1522 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1523 // touching the current state will only observe the events that have been dispatched to the
1524 // rest of the pipeline.
1525 const size_t N = mRawStatesPending.size();
1526 size_t count;
1527 for (count = 0; count < N; count++) {
1528 const RawState& next = mRawStatesPending[count];
1529
1530 // A failure to assign the stylus id means that we're waiting on stylus data
1531 // and so should defer the rest of the pipeline.
1532 if (assignExternalStylusId(next, timeout)) {
1533 break;
1534 }
1535
1536 // All ready to go.
1537 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001538 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001539 if (mCurrentRawState.when < mLastRawState.when) {
1540 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001541 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001542 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001543 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001544 }
1545 if (count != 0) {
1546 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1547 }
1548
1549 if (mExternalStylusDataPending) {
1550 if (timeout) {
1551 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1552 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001553 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001554 ALOGD_IF(DEBUG_STYLUS_FUSION,
1555 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001556 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001557 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001558 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1559 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1560 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1561 }
1562 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001563 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001564}
1565
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001566std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1567 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001568 // Always start with a clean state.
1569 mCurrentCookedState.clear();
1570
1571 // Apply stylus buttons to current raw state.
1572 applyExternalStylusButtonState(when);
1573
1574 // Handle policy on initial down or hover events.
1575 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1576 mCurrentRawState.rawPointerData.pointerCount != 0;
1577
1578 uint32_t policyFlags = 0;
1579 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1580 if (initialDown || buttonsPressed) {
1581 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001582 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001583 getContext()->fadePointer();
1584 }
1585
1586 if (mParameters.wake) {
1587 policyFlags |= POLICY_FLAG_WAKE;
1588 }
1589 }
1590
1591 // Consume raw off-screen touches before cooking pointer data.
1592 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001593 bool consumed;
1594 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1595 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596 mCurrentRawState.rawPointerData.clear();
1597 }
1598
1599 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1600 // with cooked pointer data that has the same ids and indices as the raw data.
1601 // The following code can use either the raw or cooked data, as needed.
1602 cookPointerData();
1603
1604 // Apply stylus pressure to current cooked state.
1605 applyExternalStylusTouchState(when);
1606
1607 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001608 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1609 mSource, mViewport.displayId, policyFlags,
1610 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001611
1612 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001613 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001614 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1615 uint32_t id = idBits.clearFirstMarkedBit();
1616 const RawPointerData::Pointer& pointer =
1617 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001618 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001619 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001620 } else if (pointer.toolType == ToolType::FINGER ||
1621 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001622 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001623 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 mCurrentCookedState.mouseIdBits.markBit(id);
1625 }
1626 }
1627 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1628 uint32_t id = idBits.clearFirstMarkedBit();
1629 const RawPointerData::Pointer& pointer =
1630 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001631 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632 mCurrentCookedState.stylusIdBits.markBit(id);
1633 }
1634 }
1635
1636 // Stylus takes precedence over all tools, then mouse, then finger.
1637 PointerUsage pointerUsage = mPointerUsage;
1638 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1639 mCurrentCookedState.mouseIdBits.clear();
1640 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001641 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001642 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1643 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001644 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001645 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1646 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001647 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001648 }
1649
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001650 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001651 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001652 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001653 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001654 out += dispatchButtonRelease(when, readTime, policyFlags);
1655 out += dispatchHoverExit(when, readTime, policyFlags);
1656 out += dispatchTouches(when, readTime, policyFlags);
1657 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1658 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001659 }
1660
1661 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1662 mCurrentMotionAborted = false;
1663 }
1664 }
1665
1666 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001667 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1668 mSource, mViewport.displayId, policyFlags,
1669 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001670
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001671 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1672 mCurrentStreamModifiedByExternalStylus = false;
1673 }
1674
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001675 // Clear some transient state.
1676 mCurrentRawState.rawVScroll = 0;
1677 mCurrentRawState.rawHScroll = 0;
1678
1679 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001680 mLastRawState = mCurrentRawState;
1681 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001682 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001683}
1684
Garfield Tanc734e4f2021-01-15 20:01:39 -08001685void TouchInputMapper::updateTouchSpots() {
1686 if (!mConfig.showTouches || mPointerController == nullptr) {
1687 return;
1688 }
1689
1690 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1691 // clear touch spots.
1692 if (mDeviceMode != DeviceMode::DIRECT &&
1693 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1694 return;
1695 }
1696
1697 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1698 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1699
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001700 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1701 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001702 mCurrentCookedState.cookedPointerData.touchingIdBits |
1703 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001704 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001705}
1706
1707bool TouchInputMapper::isTouchScreen() {
1708 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1709 mParameters.hasAssociatedDisplay;
1710}
1711
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001712void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001713 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1714 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001715 const int32_t pressedButtons =
1716 filterButtonState(mConfig,
1717 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001718 const int32_t releasedButtons =
1719 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1720
1721 mCurrentRawState.buttonState |= pressedButtons;
1722 mCurrentRawState.buttonState &= ~releasedButtons;
1723
1724 mExternalStylusButtonsApplied |= pressedButtons;
1725 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001726
1727 if (mExternalStylusButtonsApplied != 0 || releasedButtons != 0) {
1728 mCurrentStreamModifiedByExternalStylus = true;
1729 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001730 }
1731}
1732
1733void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1734 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1735 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001736 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1737 return;
1738 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001739
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001740 mCurrentStreamModifiedByExternalStylus = true;
1741
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001742 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1743 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1744 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1745 : 0.f;
1746 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1747 pressure = *mExternalStylusState.pressure;
1748 }
1749 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1750 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001751
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001752 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001753 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001754 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001755 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001756 }
1757}
1758
1759bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001760 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001761 return false;
1762 }
1763
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001764 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001765 if (mFusedStylusPointerId &&
1766 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001767 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001768 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001769 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001770 }
1771
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001772 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1773 state.rawPointerData.pointerCount != 0;
1774 if (!initialDown) {
1775 return false;
1776 }
1777
1778 if (!mExternalStylusState.pressure) {
1779 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1780 return false;
1781 }
1782
1783 if (*mExternalStylusState.pressure != 0.0f) {
1784 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1785 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1786 return false;
1787 }
1788
1789 if (timeout) {
1790 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1791 mFusedStylusPointerId.reset();
1792 mExternalStylusFusionTimeout = LLONG_MAX;
1793 return false;
1794 }
1795
1796 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1797 // being processed until we either get pressure data or timeout.
1798 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1799 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1800 }
1801 ALOGD_IF(DEBUG_STYLUS_FUSION,
1802 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1803 mExternalStylusFusionTimeout);
1804 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1805 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001806}
1807
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001808std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1809 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001810 if (mDeviceMode == DeviceMode::POINTER) {
1811 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001812 // Since this is a synthetic event, we can consider its latency to be zero
1813 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001814 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001815 }
Michael Wright227c5542020-07-02 18:30:52 +01001816 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001817 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001818 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001819 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1820 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1821 }
1822 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001823 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001824}
1825
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001826std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1827 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001828 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001829 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001830 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001831 // The following three cases are handled here:
1832 // - We're in the middle of a fused stream of data;
1833 // - We're waiting on external stylus data before dispatching the initial down; or
1834 // - Only the button state, which is not reported through a specific pointer, has changed.
1835 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001836 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001837 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001838 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001839 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001840}
1841
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001842std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1843 uint32_t policyFlags, bool& outConsumed) {
1844 outConsumed = false;
1845 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001846 // Check for release of a virtual key.
1847 if (mCurrentVirtualKey.down) {
1848 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1849 // Pointer went up while virtual key was down.
1850 mCurrentVirtualKey.down = false;
1851 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001852 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1853 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1854 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001855 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1856 AKEY_EVENT_FLAG_FROM_SYSTEM |
1857 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001858 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001859 outConsumed = true;
1860 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001861 }
1862
1863 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1864 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1865 const RawPointerData::Pointer& pointer =
1866 mCurrentRawState.rawPointerData.pointerForId(id);
1867 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1868 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1869 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001870 outConsumed = true;
1871 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001872 }
1873 }
1874
1875 // Pointer left virtual key area or another pointer also went down.
1876 // Send key cancellation but do not consume the touch yet.
1877 // This is useful when the user swipes through from the virtual key area
1878 // into the main display surface.
1879 mCurrentVirtualKey.down = false;
1880 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001881 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1882 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001883 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1884 AKEY_EVENT_FLAG_FROM_SYSTEM |
1885 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1886 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001887 }
1888 }
1889
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001890 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
Harry Cutts8722be92024-04-05 14:46:05 +00001891 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001892 // We have hovering pointers, and there are no touching pointers.
1893 bool hoveringPointersInFrame = false;
1894 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1895 while (!hoveringIds.isEmpty()) {
1896 uint32_t id = hoveringIds.clearFirstMarkedBit();
1897 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1898 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1899 hoveringPointersInFrame = true;
1900 break;
1901 }
1902 }
1903 if (!hoveringPointersInFrame) {
1904 // All hovering pointers are outside the physical frame.
1905 outConsumed = true;
1906 return out;
1907 }
1908 }
1909
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001910 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1911 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1912 // Pointer just went down. Check for virtual key press or off-screen touches.
1913 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1914 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001915 // Skip checking whether the pointer is inside the physical frame if the device is in
Harry Cutts1db43992023-06-19 17:05:07 +00001916 // unscaled or pointer mode.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001917 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
Harry Cutts8722be92024-04-05 14:46:05 +00001918 mDeviceMode != DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001919 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001920 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1922 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1923 if (virtualKey) {
1924 mCurrentVirtualKey.down = true;
1925 mCurrentVirtualKey.downTime = when;
1926 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1927 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1928 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001929 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1930 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001931
1932 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001933 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1934 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1935 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001936 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1937 AKEY_EVENT_ACTION_DOWN,
1938 AKEY_EVENT_FLAG_FROM_SYSTEM |
1939 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001940 }
1941 }
1942 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001943 outConsumed = true;
1944 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001945 }
1946 }
1947
1948 // Disable all virtual key touches that happen within a short time interval of the
1949 // most recent touch within the screen area. The idea is to filter out stray
1950 // virtual key presses when interacting with the touch screen.
1951 //
1952 // Problems we're trying to solve:
1953 //
1954 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1955 // virtual key area that is implemented by a separate touch panel and accidentally
1956 // triggers a virtual key.
1957 //
1958 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1959 // area and accidentally triggers a virtual key. This often happens when virtual keys
1960 // are layed out below the screen near to where the on screen keyboard's space bar
1961 // is displayed.
1962 if (mConfig.virtualKeyQuietTime > 0 &&
1963 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001964 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001965 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001966 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001967}
1968
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001969NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1970 uint32_t policyFlags, int32_t keyEventAction,
1971 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001972 int32_t keyCode = mCurrentVirtualKey.keyCode;
1973 int32_t scanCode = mCurrentVirtualKey.scanCode;
1974 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001975 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001976 policyFlags |= POLICY_FLAG_VIRTUAL;
1977
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001978 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1979 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1980 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001981}
1982
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001983std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1984 uint32_t policyFlags) {
1985 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001986 if (mCurrentMotionAborted) {
1987 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001988 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001989 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001990 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1991 if (!currentIdBits.isEmpty()) {
1992 int32_t metaState = getContext()->getGlobalMetaState();
1993 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001994 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001995 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1996 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001997 mCurrentCookedState.cookedPointerData.pointerProperties,
1998 mCurrentCookedState.cookedPointerData.pointerCoords,
1999 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2000 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2001 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002002 mCurrentMotionAborted = true;
2003 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002004 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002005}
2006
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002007// Updates pointer coords and properties for pointers with specified ids that have moved.
2008// Returns true if any of them changed.
2009static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
2010 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
2011 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
2012 BitSet32 idBits) {
2013 bool changed = false;
2014 while (!idBits.isEmpty()) {
2015 uint32_t id = idBits.clearFirstMarkedBit();
2016 uint32_t inIndex = inIdToIndex[id];
2017 uint32_t outIndex = outIdToIndex[id];
2018
2019 const PointerProperties& curInProperties = inProperties[inIndex];
2020 const PointerCoords& curInCoords = inCoords[inIndex];
2021 PointerProperties& curOutProperties = outProperties[outIndex];
2022 PointerCoords& curOutCoords = outCoords[outIndex];
2023
2024 if (curInProperties != curOutProperties) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002025 curOutProperties = curInProperties;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002026 changed = true;
2027 }
2028
2029 if (curInCoords != curOutCoords) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002030 curOutCoords = curInCoords;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002031 changed = true;
2032 }
2033 }
2034 return changed;
2035}
2036
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002037std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
2038 uint32_t policyFlags) {
2039 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002040 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2041 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2042 int32_t metaState = getContext()->getGlobalMetaState();
2043 int32_t buttonState = mCurrentCookedState.buttonState;
2044
2045 if (currentIdBits == lastIdBits) {
2046 if (!currentIdBits.isEmpty()) {
2047 // No pointer id changes so this is a move event.
2048 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002049 out.push_back(
2050 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2051 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2052 mCurrentCookedState.cookedPointerData.pointerProperties,
2053 mCurrentCookedState.cookedPointerData.pointerCoords,
2054 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2055 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2056 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002057 }
2058 } else {
2059 // There may be pointers going up and pointers going down and pointers moving
2060 // all at the same time.
2061 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2062 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2063 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2064 BitSet32 dispatchedIdBits(lastIdBits.value);
2065
2066 // Update last coordinates of pointers that have moved so that we observe the new
2067 // pointer positions at the same time as other pointers that have just gone up.
2068 bool moveNeeded =
2069 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2070 mCurrentCookedState.cookedPointerData.pointerCoords,
2071 mCurrentCookedState.cookedPointerData.idToIndex,
2072 mLastCookedState.cookedPointerData.pointerProperties,
2073 mLastCookedState.cookedPointerData.pointerCoords,
2074 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2075 if (buttonState != mLastCookedState.buttonState) {
2076 moveNeeded = true;
2077 }
2078
2079 // Dispatch pointer up events.
2080 while (!upIdBits.isEmpty()) {
2081 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002082 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002083 if (isCanceled) {
2084 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2085 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002086 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2087 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2088 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2089 buttonState, 0,
2090 mLastCookedState.cookedPointerData.pointerProperties,
2091 mLastCookedState.cookedPointerData.pointerCoords,
2092 mLastCookedState.cookedPointerData.idToIndex,
2093 dispatchedIdBits, upId, mOrientedXPrecision,
2094 mOrientedYPrecision, mDownTime,
2095 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002096 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002097 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002098 }
2099
2100 // Dispatch move events if any of the remaining pointers moved from their old locations.
2101 // Although applications receive new locations as part of individual pointer up
2102 // events, they do not generally handle them except when presented in a move event.
2103 if (moveNeeded && !moveIdBits.isEmpty()) {
2104 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002105 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2106 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2107 mCurrentCookedState.cookedPointerData.pointerProperties,
2108 mCurrentCookedState.cookedPointerData.pointerCoords,
2109 mCurrentCookedState.cookedPointerData.idToIndex,
2110 dispatchedIdBits, -1, mOrientedXPrecision,
2111 mOrientedYPrecision, mDownTime,
2112 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002113 }
2114
2115 // Dispatch pointer down events using the new pointer locations.
2116 while (!downIdBits.isEmpty()) {
2117 uint32_t downId = downIdBits.clearFirstMarkedBit();
2118 dispatchedIdBits.markBit(downId);
2119
2120 if (dispatchedIdBits.count() == 1) {
2121 // First pointer is going down. Set down time.
2122 mDownTime = when;
2123 }
2124
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002125 out.push_back(
2126 dispatchMotion(when, readTime, policyFlags, mSource,
2127 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2128 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2129 mCurrentCookedState.cookedPointerData.pointerCoords,
2130 mCurrentCookedState.cookedPointerData.idToIndex,
2131 dispatchedIdBits, downId, mOrientedXPrecision,
2132 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002133 }
2134 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002135 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002136}
2137
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002138std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2139 uint32_t policyFlags) {
2140 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002141 if (mSentHoverEnter &&
2142 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2143 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2144 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002145 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2146 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2147 mLastCookedState.buttonState, 0,
2148 mLastCookedState.cookedPointerData.pointerProperties,
2149 mLastCookedState.cookedPointerData.pointerCoords,
2150 mLastCookedState.cookedPointerData.idToIndex,
2151 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2152 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2153 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002154 mSentHoverEnter = false;
2155 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002156 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002157}
2158
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002159std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2160 uint32_t policyFlags) {
2161 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002162 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2163 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2164 int32_t metaState = getContext()->getGlobalMetaState();
2165 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002166 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2167 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2168 mCurrentRawState.buttonState, 0,
2169 mCurrentCookedState.cookedPointerData.pointerProperties,
2170 mCurrentCookedState.cookedPointerData.pointerCoords,
2171 mCurrentCookedState.cookedPointerData.idToIndex,
2172 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2173 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2174 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002175 mSentHoverEnter = true;
2176 }
2177
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002178 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2179 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2180 mCurrentRawState.buttonState, 0,
2181 mCurrentCookedState.cookedPointerData.pointerProperties,
2182 mCurrentCookedState.cookedPointerData.pointerCoords,
2183 mCurrentCookedState.cookedPointerData.idToIndex,
2184 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2185 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2186 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002187 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002188 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002189}
2190
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002191std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2192 uint32_t policyFlags) {
2193 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002194 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2195 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2196 const int32_t metaState = getContext()->getGlobalMetaState();
2197 int32_t buttonState = mLastCookedState.buttonState;
2198 while (!releasedButtons.isEmpty()) {
2199 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2200 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002201 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2202 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2203 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002204 mLastCookedState.cookedPointerData.pointerProperties,
2205 mLastCookedState.cookedPointerData.pointerCoords,
2206 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002207 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2208 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002209 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002210 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002211}
2212
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002213std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2214 uint32_t policyFlags) {
2215 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002216 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2217 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2218 const int32_t metaState = getContext()->getGlobalMetaState();
2219 int32_t buttonState = mLastCookedState.buttonState;
2220 while (!pressedButtons.isEmpty()) {
2221 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2222 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002223 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2224 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2225 buttonState, 0,
2226 mCurrentCookedState.cookedPointerData.pointerProperties,
2227 mCurrentCookedState.cookedPointerData.pointerCoords,
2228 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2229 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2230 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002231 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002232 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002233}
2234
LiZhihong758eb562022-11-03 15:28:29 +08002235std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2236 uint32_t policyFlags,
2237 BitSet32 idBits,
2238 nsecs_t readTime) {
2239 std::list<NotifyArgs> out;
2240 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2241 const int32_t metaState = getContext()->getGlobalMetaState();
2242 int32_t buttonState = mLastCookedState.buttonState;
2243
2244 while (!releasedButtons.isEmpty()) {
2245 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2246 buttonState &= ~actionButton;
2247 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2248 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2249 metaState, buttonState, 0,
2250 mPointerGesture.lastGestureProperties,
2251 mPointerGesture.lastGestureCoords,
2252 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2253 mOrientedXPrecision, mOrientedYPrecision,
2254 mPointerGesture.downTime, MotionClassification::NONE));
2255 }
2256 return out;
2257}
2258
2259std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2260 uint32_t policyFlags,
2261 BitSet32 idBits,
2262 nsecs_t readTime) {
2263 std::list<NotifyArgs> out;
2264 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2265 const int32_t metaState = getContext()->getGlobalMetaState();
2266 int32_t buttonState = mLastCookedState.buttonState;
2267
2268 while (!pressedButtons.isEmpty()) {
2269 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2270 buttonState |= actionButton;
2271 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2272 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2273 buttonState, 0, mPointerGesture.currentGestureProperties,
2274 mPointerGesture.currentGestureCoords,
2275 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2276 mOrientedXPrecision, mOrientedYPrecision,
2277 mPointerGesture.downTime, MotionClassification::NONE));
2278 }
2279 return out;
2280}
2281
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002282const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2283 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2284 return cookedPointerData.touchingIdBits;
2285 }
2286 return cookedPointerData.hoveringIdBits;
2287}
2288
2289void TouchInputMapper::cookPointerData() {
2290 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2291
2292 mCurrentCookedState.cookedPointerData.clear();
2293 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2294 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2295 mCurrentRawState.rawPointerData.hoveringIdBits;
2296 mCurrentCookedState.cookedPointerData.touchingIdBits =
2297 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002298 mCurrentCookedState.cookedPointerData.canceledIdBits =
2299 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002300
2301 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2302 mCurrentCookedState.buttonState = 0;
2303 } else {
2304 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2305 }
2306
2307 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002308 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002309 for (uint32_t i = 0; i < currentPointerCount; i++) {
2310 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2311
2312 // Size
2313 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2314 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002315 case Calibration::SizeCalibration::GEOMETRIC:
2316 case Calibration::SizeCalibration::DIAMETER:
2317 case Calibration::SizeCalibration::BOX:
2318 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002319 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2320 touchMajor = in.touchMajor;
2321 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2322 toolMajor = in.toolMajor;
2323 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2324 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2325 : in.touchMajor;
2326 } else if (mRawPointerAxes.touchMajor.valid) {
2327 toolMajor = touchMajor = in.touchMajor;
2328 toolMinor = touchMinor =
2329 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2330 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2331 : in.touchMajor;
2332 } else if (mRawPointerAxes.toolMajor.valid) {
2333 touchMajor = toolMajor = in.toolMajor;
2334 touchMinor = toolMinor =
2335 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2336 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2337 : in.toolMajor;
2338 } else {
2339 ALOG_ASSERT(false,
2340 "No touch or tool axes. "
2341 "Size calibration should have been resolved to NONE.");
2342 touchMajor = 0;
2343 touchMinor = 0;
2344 toolMajor = 0;
2345 toolMinor = 0;
2346 size = 0;
2347 }
2348
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002349 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002350 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2351 if (touchingCount > 1) {
2352 touchMajor /= touchingCount;
2353 touchMinor /= touchingCount;
2354 toolMajor /= touchingCount;
2355 toolMinor /= touchingCount;
2356 size /= touchingCount;
2357 }
2358 }
2359
Michael Wright227c5542020-07-02 18:30:52 +01002360 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 touchMajor *= mGeometricScale;
2362 touchMinor *= mGeometricScale;
2363 toolMajor *= mGeometricScale;
2364 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002365 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2367 touchMinor = touchMajor;
2368 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2369 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002370 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002371 touchMinor = touchMajor;
2372 toolMinor = toolMajor;
2373 }
2374
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002375 mCalibration.applySizeScaleAndBias(touchMajor);
2376 mCalibration.applySizeScaleAndBias(touchMinor);
2377 mCalibration.applySizeScaleAndBias(toolMajor);
2378 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 size *= mSizeScale;
2380 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002381 case Calibration::SizeCalibration::DEFAULT:
2382 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2383 break;
2384 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 touchMajor = 0;
2386 touchMinor = 0;
2387 toolMajor = 0;
2388 toolMinor = 0;
2389 size = 0;
2390 break;
2391 }
2392
2393 // Pressure
2394 float pressure;
2395 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002396 case Calibration::PressureCalibration::PHYSICAL:
2397 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 pressure = in.pressure * mPressureScale;
2399 break;
2400 default:
2401 pressure = in.isHovering ? 0 : 1;
2402 break;
2403 }
2404
2405 // Tilt and Orientation
2406 float tilt;
2407 float orientation;
2408 if (mHaveTilt) {
2409 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2410 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002411 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002412 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2413 } else {
2414 tilt = 0;
2415
2416 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002417 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002418 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419 break;
Michael Wright227c5542020-07-02 18:30:52 +01002420 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002421 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2422 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2423 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002424 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 float confidence = hypotf(c1, c2);
2426 float scale = 1.0f + confidence / 16.0f;
2427 touchMajor *= scale;
2428 touchMinor /= scale;
2429 toolMajor *= scale;
2430 toolMinor /= scale;
2431 } else {
2432 orientation = 0;
2433 }
2434 break;
2435 }
2436 default:
2437 orientation = 0;
2438 }
2439 }
2440
2441 // Distance
2442 float distance;
2443 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002444 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 distance = in.distance * mDistanceScale;
2446 break;
2447 default:
2448 distance = 0;
2449 }
2450
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002451 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2452 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002453 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2454 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002455
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 // Write output coords.
2457 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2458 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002459 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2460 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2462 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2463 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2464 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2465 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2466 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2467 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002468 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2469 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470
Chris Ye364fdb52020-08-05 15:07:56 -07002471 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002472 uint32_t id = in.id;
2473 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2474 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2475 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002476 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2477 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002478 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2479 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2480 }
2481
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002482 // Write output properties.
2483 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002484 properties.clear();
2485 properties.id = id;
2486 properties.toolType = in.toolType;
2487
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002488 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002489 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002490 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002491 }
2492}
2493
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002494std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2495 uint32_t policyFlags,
2496 PointerUsage pointerUsage) {
2497 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002498 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002499 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002500 mPointerUsage = pointerUsage;
2501 }
2502
2503 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002504 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002505 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002506 break;
Michael Wright227c5542020-07-02 18:30:52 +01002507 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002508 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 break;
Michael Wright227c5542020-07-02 18:30:52 +01002510 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002511 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512 break;
Michael Wright227c5542020-07-02 18:30:52 +01002513 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514 break;
2515 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002516 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002517}
2518
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002519std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2520 uint32_t policyFlags) {
2521 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002523 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002524 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002525 break;
Michael Wright227c5542020-07-02 18:30:52 +01002526 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002527 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002528 break;
Michael Wright227c5542020-07-02 18:30:52 +01002529 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002530 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002531 break;
Michael Wright227c5542020-07-02 18:30:52 +01002532 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002533 break;
2534 }
2535
Michael Wright227c5542020-07-02 18:30:52 +01002536 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002537 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002538}
2539
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002540std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2541 uint32_t policyFlags,
2542 bool isTimeout) {
2543 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544 // Update current gesture coordinates.
2545 bool cancelPreviousGesture, finishPreviousGesture;
2546 bool sendEvents =
2547 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2548 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002549 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002550 }
2551 if (finishPreviousGesture) {
2552 cancelPreviousGesture = false;
2553 }
2554
2555 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002556 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002557 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002558 if (finishPreviousGesture || cancelPreviousGesture) {
2559 mPointerController->clearSpots();
2560 }
2561
Michael Wright227c5542020-07-02 18:30:52 +01002562 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002563 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2564 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002565 mPointerGesture.currentGestureIdBits,
2566 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002567 }
2568 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002569 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002570 }
2571
2572 // Show or hide the pointer if needed.
2573 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002574 case PointerGesture::Mode::NEUTRAL:
2575 case PointerGesture::Mode::QUIET:
2576 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2577 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002578 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002579 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002580 }
2581 break;
Michael Wright227c5542020-07-02 18:30:52 +01002582 case PointerGesture::Mode::TAP:
2583 case PointerGesture::Mode::TAP_DRAG:
2584 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2585 case PointerGesture::Mode::HOVER:
2586 case PointerGesture::Mode::PRESS:
2587 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002588 // Unfade the pointer when the current gesture manipulates the
2589 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002590 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002591 break;
Michael Wright227c5542020-07-02 18:30:52 +01002592 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002593 // Fade the pointer when the current gesture manipulates a different
2594 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002595 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002596 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002597 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002598 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002599 }
2600 break;
2601 }
2602
2603 // Send events!
2604 int32_t metaState = getContext()->getGlobalMetaState();
2605 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002606 const MotionClassification classification =
2607 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2608 ? MotionClassification::TWO_FINGER_SWIPE
2609 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002610
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002611 uint32_t flags = 0;
2612
2613 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2614 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2615 }
2616
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002617 // Update last coordinates of pointers that have moved so that we observe the new
2618 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002619 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2620 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2621 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2622 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2623 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2624 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002625 bool moveNeeded = false;
2626 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2627 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2628 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2629 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2630 mPointerGesture.lastGestureIdBits.value);
2631 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2632 mPointerGesture.currentGestureCoords,
2633 mPointerGesture.currentGestureIdToIndex,
2634 mPointerGesture.lastGestureProperties,
2635 mPointerGesture.lastGestureCoords,
2636 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2637 if (buttonState != mLastCookedState.buttonState) {
2638 moveNeeded = true;
2639 }
2640 }
2641
2642 // Send motion events for all pointers that went up or were canceled.
2643 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2644 if (!dispatchedGestureIdBits.isEmpty()) {
2645 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002646 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002647 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002648 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002649 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2650 mPointerGesture.lastGestureProperties,
2651 mPointerGesture.lastGestureCoords,
2652 mPointerGesture.lastGestureIdToIndex,
2653 dispatchedGestureIdBits, -1, 0, 0,
2654 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002655
2656 dispatchedGestureIdBits.clear();
2657 } else {
2658 BitSet32 upGestureIdBits;
2659 if (finishPreviousGesture) {
2660 upGestureIdBits = dispatchedGestureIdBits;
2661 } else {
2662 upGestureIdBits.value =
2663 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2664 }
2665 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002666 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2667 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2668 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2669 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2670 readTime);
2671 }
2672 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002673 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2674 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2675 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2676 mPointerGesture.lastGestureProperties,
2677 mPointerGesture.lastGestureCoords,
2678 mPointerGesture.lastGestureIdToIndex,
2679 dispatchedGestureIdBits, id, 0, 0,
2680 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002681
2682 dispatchedGestureIdBits.clearBit(id);
2683 }
2684 }
2685 }
2686
2687 // Send motion events for all pointers that moved.
2688 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002689 out.push_back(
2690 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2691 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2692 mPointerGesture.currentGestureProperties,
2693 mPointerGesture.currentGestureCoords,
2694 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2695 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002696 }
2697
2698 // Send motion events for all pointers that went down.
2699 if (down) {
2700 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2701 ~dispatchedGestureIdBits.value);
2702 while (!downGestureIdBits.isEmpty()) {
2703 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2704 dispatchedGestureIdBits.markBit(id);
2705
2706 if (dispatchedGestureIdBits.count() == 1) {
2707 mPointerGesture.downTime = when;
2708 }
2709
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002710 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2711 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2712 buttonState, 0, mPointerGesture.currentGestureProperties,
2713 mPointerGesture.currentGestureCoords,
2714 mPointerGesture.currentGestureIdToIndex,
2715 dispatchedGestureIdBits, id, 0, 0,
2716 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002717 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2718 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2719 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2720 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2721 readTime);
2722 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002723 }
2724 }
2725
2726 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002727 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002728 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2729 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2730 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2731 mPointerGesture.currentGestureProperties,
2732 mPointerGesture.currentGestureCoords,
2733 mPointerGesture.currentGestureIdToIndex,
2734 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2735 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002736 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2737 // Synthesize a hover move event after all pointers go up to indicate that
2738 // the pointer is hovering again even if the user is not currently touching
2739 // the touch pad. This ensures that a view will receive a fresh hover enter
2740 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002741 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002742
2743 PointerProperties pointerProperties;
2744 pointerProperties.clear();
2745 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002746 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002747
2748 PointerCoords pointerCoords;
2749 pointerCoords.clear();
2750 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2751 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2752
2753 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002754 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2755 mSource, displayId, policyFlags,
2756 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2757 buttonState, MotionClassification::NONE,
2758 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2759 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00002760 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002761 }
2762
2763 // Update state.
2764 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2765 if (!down) {
2766 mPointerGesture.lastGestureIdBits.clear();
2767 } else {
2768 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2769 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2770 uint32_t id = idBits.clearFirstMarkedBit();
2771 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002772 mPointerGesture.lastGestureProperties[index] =
2773 mPointerGesture.currentGestureProperties[index];
2774 mPointerGesture.lastGestureCoords[index] = mPointerGesture.currentGestureCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002775 mPointerGesture.lastGestureIdToIndex[id] = index;
2776 }
2777 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002778 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002779}
2780
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002781std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2782 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002783 const MotionClassification classification =
2784 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2785 ? MotionClassification::TWO_FINGER_SWIPE
2786 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002787 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002788 // Cancel previously dispatches pointers.
2789 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2790 int32_t metaState = getContext()->getGlobalMetaState();
2791 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002792 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002793 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2794 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002795 mPointerGesture.lastGestureProperties,
2796 mPointerGesture.lastGestureCoords,
2797 mPointerGesture.lastGestureIdToIndex,
2798 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2799 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002800 }
2801
2802 // Reset the current pointer gesture.
2803 mPointerGesture.reset();
2804 mPointerVelocityControl.reset();
2805
2806 // Remove any current spots.
2807 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002808 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002809 mPointerController->clearSpots();
2810 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002811 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002812}
2813
2814bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2815 bool* outFinishPreviousGesture, bool isTimeout) {
2816 *outCancelPreviousGesture = false;
2817 *outFinishPreviousGesture = false;
2818
2819 // Handle TAP timeout.
2820 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002821 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002822
Michael Wright227c5542020-07-02 18:30:52 +01002823 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002824 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2825 // The tap/drag timeout has not yet expired.
2826 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2827 mConfig.pointerGestureTapDragInterval);
2828 } else {
2829 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002830 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002831 *outFinishPreviousGesture = true;
2832
2833 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002834 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002835 mPointerGesture.currentGestureIdBits.clear();
2836
2837 mPointerVelocityControl.reset();
2838 return true;
2839 }
2840 }
2841
2842 // We did not handle this timeout.
2843 return false;
2844 }
2845
2846 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2847 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2848
2849 // Update the velocity tracker.
2850 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002851 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002852 uint32_t id = idBits.clearFirstMarkedBit();
2853 const RawPointerData::Pointer& pointer =
2854 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002855 const float x = pointer.x * mPointerXMovementScale;
2856 const float y = pointer.y * mPointerYMovementScale;
2857 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2858 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002859 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002860 }
2861
2862 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2863 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002864 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2865 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2866 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002867 mPointerGesture.resetTap();
2868 }
2869
2870 // Pick a new active touch id if needed.
2871 // Choose an arbitrary pointer that just went down, if there is one.
2872 // Otherwise choose an arbitrary remaining pointer.
2873 // This guarantees we always have an active touch id when there is at least one pointer.
2874 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002875 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002876 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002877 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002878 mPointerGesture.firstTouchTime = when;
2879 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002880 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2881 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2882 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2883 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002885 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002886
2887 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002888 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002889 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002890 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2891 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2892 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002893 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002894 *outFinishPreviousGesture = true;
2895 }
2896
2897 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002898 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002899 mPointerGesture.currentGestureIdBits.clear();
2900
2901 mPointerVelocityControl.reset();
2902 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2903 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2904 // The pointer follows the active touch point.
2905 // Emit DOWN, MOVE, UP events at the pointer location.
2906 //
2907 // Only the active touch matters; other fingers are ignored. This policy helps
2908 // to handle the case where the user places a second finger on the touch pad
2909 // to apply the necessary force to depress an integrated button below the surface.
2910 // We don't want the second finger to be delivered to applications.
2911 //
2912 // For this to work well, we need to make sure to track the pointer that is really
2913 // active. If the user first puts one finger down to click then adds another
2914 // finger to drag then the active pointer should switch to the finger that is
2915 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002916 ALOGD_IF(DEBUG_GESTURES,
2917 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2918 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002920 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002921 *outFinishPreviousGesture = true;
2922 mPointerGesture.activeGestureId = 0;
2923 }
2924
2925 // Switch pointers if needed.
2926 // Find the fastest pointer and follow it.
2927 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002928 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002929 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002930 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002931 ALOGD_IF(DEBUG_GESTURES,
2932 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2933 "bestSpeed=%0.3f",
2934 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002935 }
2936 }
2937
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002938 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002939 // When using spots, the click will occur at the position of the anchor
2940 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002941 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002942 } else {
2943 mPointerVelocityControl.reset();
2944 }
2945
Prabir Pradhan2719e822023-02-28 17:39:36 +00002946 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002947
Michael Wright227c5542020-07-02 18:30:52 +01002948 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002949 mPointerGesture.currentGestureIdBits.clear();
2950 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2951 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2952 mPointerGesture.currentGestureProperties[0].clear();
2953 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002954 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002955 mPointerGesture.currentGestureCoords[0].clear();
2956 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2957 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2958 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2959 } else if (currentFingerCount == 0) {
2960 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002961 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002962 *outFinishPreviousGesture = true;
2963 }
2964
2965 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2966 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2967 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002968 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2969 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002970 lastFingerCount == 1) {
2971 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002972 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002973 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2974 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002975 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002976
2977 mPointerGesture.tapUpTime = when;
2978 getContext()->requestTimeoutAtTime(when +
2979 mConfig.pointerGestureTapDragInterval);
2980
2981 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002982 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002983 mPointerGesture.currentGestureIdBits.clear();
2984 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2985 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2986 mPointerGesture.currentGestureProperties[0].clear();
2987 mPointerGesture.currentGestureProperties[0].id =
2988 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002989 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002990 mPointerGesture.currentGestureCoords[0].clear();
2991 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2992 mPointerGesture.tapX);
2993 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2994 mPointerGesture.tapY);
2995 mPointerGesture.currentGestureCoords[0]
2996 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2997
2998 tapped = true;
2999 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003000 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
3001 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003002 }
3003 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003004 if (DEBUG_GESTURES) {
3005 if (mPointerGesture.tapDownTime != LLONG_MIN) {
3006 ALOGD("Gestures: Not a TAP, %0.3fms since down",
3007 (when - mPointerGesture.tapDownTime) * 0.000001f);
3008 } else {
3009 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
3010 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003011 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003012 }
3013 }
3014
3015 mPointerVelocityControl.reset();
3016
3017 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00003018 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003019 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01003020 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003021 mPointerGesture.currentGestureIdBits.clear();
3022 }
3023 } else if (currentFingerCount == 1) {
3024 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3025 // The pointer follows the active touch point.
3026 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3027 // When in TAP_DRAG, emit MOVE events at the pointer location.
3028 ALOG_ASSERT(activeTouchId >= 0);
3029
Michael Wright227c5542020-07-02 18:30:52 +01003030 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3031 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003032 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003033 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003034 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3035 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003036 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003037 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003038 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3039 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003040 }
3041 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003042 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3043 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003044 }
Michael Wright227c5542020-07-02 18:30:52 +01003045 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3046 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003047 }
3048
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003049 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003050 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003051 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003052 } else {
3053 mPointerVelocityControl.reset();
3054 }
3055
3056 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003057 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003058 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003059 down = true;
3060 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003061 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003062 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003063 *outFinishPreviousGesture = true;
3064 }
3065 mPointerGesture.activeGestureId = 0;
3066 down = false;
3067 }
3068
Prabir Pradhan2719e822023-02-28 17:39:36 +00003069 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003070
3071 mPointerGesture.currentGestureIdBits.clear();
3072 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3073 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3074 mPointerGesture.currentGestureProperties[0].clear();
3075 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003076 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003077 mPointerGesture.currentGestureCoords[0].clear();
3078 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3079 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3080 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3081 down ? 1.0f : 0.0f);
3082
3083 if (lastFingerCount == 0 && currentFingerCount != 0) {
3084 mPointerGesture.resetTap();
3085 mPointerGesture.tapDownTime = when;
3086 mPointerGesture.tapX = x;
3087 mPointerGesture.tapY = y;
3088 }
3089 } else {
3090 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003091 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003092 }
3093
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003094 if (DEBUG_GESTURES) {
3095 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3096 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3097 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3098 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3099 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3100 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3101 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3102 uint32_t id = idBits.clearFirstMarkedBit();
3103 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3104 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3105 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003106 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003107 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003108 id, index, ftl::enum_string(properties.toolType).c_str(),
3109 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003110 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3111 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3112 }
3113 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3114 uint32_t id = idBits.clearFirstMarkedBit();
3115 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3116 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3117 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003118 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003119 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003120 id, index, ftl::enum_string(properties.toolType).c_str(),
3121 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003122 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3123 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3124 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003125 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003126 return true;
3127}
3128
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003129bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3130 if (mPointerGesture.activeTouchId < 0) {
3131 mPointerGesture.resetQuietTime();
3132 return false;
3133 }
3134
3135 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3136 return true;
3137 }
3138
3139 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3140 bool isQuietTime = false;
3141 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3142 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3143 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3144 currentFingerCount < 2) {
3145 // Enter quiet time when exiting swipe or freeform state.
3146 // This is to prevent accidentally entering the hover state and flinging the
3147 // pointer when finishing a swipe and there is still one pointer left onscreen.
3148 isQuietTime = true;
3149 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3150 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3151 // Enter quiet time when releasing the button and there are still two or more
3152 // fingers down. This may indicate that one finger was used to press the button
3153 // but it has not gone up yet.
3154 isQuietTime = true;
3155 }
3156 if (isQuietTime) {
3157 mPointerGesture.quietTime = when;
3158 }
3159 return isQuietTime;
3160}
3161
3162std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3163 int32_t bestId = -1;
3164 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3165 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3166 uint32_t id = idBits.clearFirstMarkedBit();
3167 std::optional<float> vx =
3168 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3169 std::optional<float> vy =
3170 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3171 if (vx && vy) {
3172 float speed = hypotf(*vx, *vy);
3173 if (speed > bestSpeed) {
3174 bestId = id;
3175 bestSpeed = speed;
3176 }
3177 }
3178 }
3179 return std::make_pair(bestId, bestSpeed);
3180}
3181
3182void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3183 bool* finishPreviousGesture) {
3184 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3185 // to move before deciding what to do.
3186 //
3187 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3188 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3189 // just a press or long-press at the pointer location.
3190 //
3191 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3192 // pointer location.
3193 //
3194 // When the two fingers move enough or when additional fingers are added, we make a decision to
3195 // transition into SWIPE or FREEFORM mode accordingly.
3196 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3197 ALOG_ASSERT(activeTouchId >= 0);
3198
3199 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3200 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3201 bool settled =
3202 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3203 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3204 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3205 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3206 *finishPreviousGesture = true;
3207 } else if (!settled && currentFingerCount > lastFingerCount) {
3208 // Additional pointers have gone down but not yet settled.
3209 // Reset the gesture.
3210 ALOGD_IF(DEBUG_GESTURES,
3211 "Gestures: Resetting gesture since additional pointers went down for "
3212 "MULTITOUCH, settle time remaining %0.3fms",
3213 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3214 when) * 0.000001f);
3215 *cancelPreviousGesture = true;
3216 } else {
3217 // Continue previous gesture.
3218 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3219 }
3220
3221 if (*finishPreviousGesture || *cancelPreviousGesture) {
3222 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3223 mPointerGesture.activeGestureId = 0;
3224 mPointerGesture.referenceIdBits.clear();
3225 mPointerVelocityControl.reset();
3226
3227 // Use the centroid and pointer location as the reference points for the gesture.
3228 ALOGD_IF(DEBUG_GESTURES,
3229 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3230 "%0.3fms",
3231 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3232 when) * 0.000001f);
3233 mCurrentRawState.rawPointerData
3234 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3235 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003236 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3237 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003238 }
3239
3240 // Clear the reference deltas for fingers not yet included in the reference calculation.
3241 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3242 ~mPointerGesture.referenceIdBits.value);
3243 !idBits.isEmpty();) {
3244 uint32_t id = idBits.clearFirstMarkedBit();
3245 mPointerGesture.referenceDeltas[id].dx = 0;
3246 mPointerGesture.referenceDeltas[id].dy = 0;
3247 }
3248 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3249
3250 // Add delta for all fingers and calculate a common movement delta.
3251 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3252 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3253 mCurrentCookedState.fingerIdBits.value);
3254 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3255 bool first = (idBits == commonIdBits);
3256 uint32_t id = idBits.clearFirstMarkedBit();
3257 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3258 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3259 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3260 delta.dx += cpd.x - lpd.x;
3261 delta.dy += cpd.y - lpd.y;
3262
3263 if (first) {
3264 commonDeltaRawX = delta.dx;
3265 commonDeltaRawY = delta.dy;
3266 } else {
3267 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3268 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3269 }
3270 }
3271
3272 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3273 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3274 float dist[MAX_POINTER_ID + 1];
3275 int32_t distOverThreshold = 0;
3276 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3277 uint32_t id = idBits.clearFirstMarkedBit();
3278 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3279 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3280 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3281 distOverThreshold += 1;
3282 }
3283 }
3284
3285 // Only transition when at least two pointers have moved further than
3286 // the minimum distance threshold.
3287 if (distOverThreshold >= 2) {
3288 if (currentFingerCount > 2) {
3289 // There are more than two pointers, switch to FREEFORM.
3290 ALOGD_IF(DEBUG_GESTURES,
3291 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3292 currentFingerCount);
3293 *cancelPreviousGesture = true;
3294 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3295 } else {
3296 // There are exactly two pointers.
3297 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3298 uint32_t id1 = idBits.clearFirstMarkedBit();
3299 uint32_t id2 = idBits.firstMarkedBit();
3300 const RawPointerData::Pointer& p1 =
3301 mCurrentRawState.rawPointerData.pointerForId(id1);
3302 const RawPointerData::Pointer& p2 =
3303 mCurrentRawState.rawPointerData.pointerForId(id2);
3304 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3305 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3306 // There are two pointers but they are too far apart for a SWIPE,
3307 // switch to FREEFORM.
3308 ALOGD_IF(DEBUG_GESTURES,
3309 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3310 mutualDistance, mPointerGestureMaxSwipeWidth);
3311 *cancelPreviousGesture = true;
3312 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3313 } else {
3314 // There are two pointers. Wait for both pointers to start moving
3315 // before deciding whether this is a SWIPE or FREEFORM gesture.
3316 float dist1 = dist[id1];
3317 float dist2 = dist[id2];
3318 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3319 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3320 // Calculate the dot product of the displacement vectors.
3321 // When the vectors are oriented in approximately the same direction,
3322 // the angle betweeen them is near zero and the cosine of the angle
3323 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3324 // mag(v2).
3325 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3326 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3327 float dx1 = delta1.dx * mPointerXZoomScale;
3328 float dy1 = delta1.dy * mPointerYZoomScale;
3329 float dx2 = delta2.dx * mPointerXZoomScale;
3330 float dy2 = delta2.dy * mPointerYZoomScale;
3331 float dot = dx1 * dx2 + dy1 * dy2;
3332 float cosine = dot / (dist1 * dist2); // denominator always > 0
3333 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3334 // Pointers are moving in the same direction. Switch to SWIPE.
3335 ALOGD_IF(DEBUG_GESTURES,
3336 "Gestures: PRESS transitioned to SWIPE, "
3337 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3338 "cosine %0.3f >= %0.3f",
3339 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3340 mConfig.pointerGestureMultitouchMinDistance, cosine,
3341 mConfig.pointerGestureSwipeTransitionAngleCosine);
3342 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3343 } else {
3344 // Pointers are moving in different directions. Switch to FREEFORM.
3345 ALOGD_IF(DEBUG_GESTURES,
3346 "Gestures: PRESS transitioned to FREEFORM, "
3347 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3348 "cosine %0.3f < %0.3f",
3349 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3350 mConfig.pointerGestureMultitouchMinDistance, cosine,
3351 mConfig.pointerGestureSwipeTransitionAngleCosine);
3352 *cancelPreviousGesture = true;
3353 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3354 }
3355 }
3356 }
3357 }
3358 }
3359 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3360 // Switch from SWIPE to FREEFORM if additional pointers go down.
3361 // Cancel previous gesture.
3362 if (currentFingerCount > 2) {
3363 ALOGD_IF(DEBUG_GESTURES,
3364 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3365 currentFingerCount);
3366 *cancelPreviousGesture = true;
3367 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3368 }
3369 }
3370
3371 // Move the reference points based on the overall group motion of the fingers
3372 // except in PRESS mode while waiting for a transition to occur.
3373 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3374 (commonDeltaRawX || commonDeltaRawY)) {
3375 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3376 uint32_t id = idBits.clearFirstMarkedBit();
3377 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3378 delta.dx = 0;
3379 delta.dy = 0;
3380 }
3381
3382 mPointerGesture.referenceTouchX += commonDeltaRawX;
3383 mPointerGesture.referenceTouchY += commonDeltaRawY;
3384
3385 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3386 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3387
3388 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3389 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3390
3391 mPointerGesture.referenceGestureX += commonDeltaX;
3392 mPointerGesture.referenceGestureY += commonDeltaY;
3393 }
3394
3395 // Report gestures.
3396 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3397 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3398 // PRESS or SWIPE mode.
3399 ALOGD_IF(DEBUG_GESTURES,
3400 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3401 "currentTouchPointerCount=%d",
3402 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3403 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3404
3405 mPointerGesture.currentGestureIdBits.clear();
3406 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3407 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3408 mPointerGesture.currentGestureProperties[0].clear();
3409 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003410 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003411 mPointerGesture.currentGestureCoords[0].clear();
3412 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3413 mPointerGesture.referenceGestureX);
3414 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3415 mPointerGesture.referenceGestureY);
3416 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3417 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3418 float xOffset = static_cast<float>(commonDeltaRawX) /
3419 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3420 float yOffset = static_cast<float>(commonDeltaRawY) /
3421 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3422 mPointerGesture.currentGestureCoords[0]
3423 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3424 mPointerGesture.currentGestureCoords[0]
3425 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3426 }
3427 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3428 // FREEFORM mode.
3429 ALOGD_IF(DEBUG_GESTURES,
3430 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3431 "currentTouchPointerCount=%d",
3432 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3433 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3434
3435 mPointerGesture.currentGestureIdBits.clear();
3436
3437 BitSet32 mappedTouchIdBits;
3438 BitSet32 usedGestureIdBits;
3439 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3440 // Initially, assign the active gesture id to the active touch point
3441 // if there is one. No other touch id bits are mapped yet.
3442 if (!*cancelPreviousGesture) {
3443 mappedTouchIdBits.markBit(activeTouchId);
3444 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3445 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3446 mPointerGesture.activeGestureId;
3447 } else {
3448 mPointerGesture.activeGestureId = -1;
3449 }
3450 } else {
3451 // Otherwise, assume we mapped all touches from the previous frame.
3452 // Reuse all mappings that are still applicable.
3453 mappedTouchIdBits.value =
3454 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3455 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3456
3457 // Check whether we need to choose a new active gesture id because the
3458 // current went went up.
3459 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3460 ~mCurrentCookedState.fingerIdBits.value);
3461 !upTouchIdBits.isEmpty();) {
3462 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3463 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3464 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3465 mPointerGesture.activeGestureId = -1;
3466 break;
3467 }
3468 }
3469 }
3470
3471 ALOGD_IF(DEBUG_GESTURES,
3472 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3473 "activeGestureId=%d",
3474 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3475
3476 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3477 for (uint32_t i = 0; i < currentFingerCount; i++) {
3478 uint32_t touchId = idBits.clearFirstMarkedBit();
3479 uint32_t gestureId;
3480 if (!mappedTouchIdBits.hasBit(touchId)) {
3481 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3482 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3483 ALOGD_IF(DEBUG_GESTURES,
3484 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3485 gestureId);
3486 } else {
3487 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3488 ALOGD_IF(DEBUG_GESTURES,
3489 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3490 touchId, gestureId);
3491 }
3492 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3493 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3494
3495 const RawPointerData::Pointer& pointer =
3496 mCurrentRawState.rawPointerData.pointerForId(touchId);
3497 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3498 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3499 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3500
3501 mPointerGesture.currentGestureProperties[i].clear();
3502 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003503 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003504 mPointerGesture.currentGestureCoords[i].clear();
3505 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3506 mPointerGesture.referenceGestureX +
3507 deltaX);
3508 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3509 mPointerGesture.referenceGestureY +
3510 deltaY);
3511 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3512 }
3513
3514 if (mPointerGesture.activeGestureId < 0) {
3515 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3516 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3517 mPointerGesture.activeGestureId);
3518 }
3519 }
3520}
3521
Harry Cutts714d1ad2022-08-24 16:36:43 +00003522void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3523 const RawPointerData::Pointer& currentPointer =
3524 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3525 const RawPointerData::Pointer& lastPointer =
3526 mLastRawState.rawPointerData.pointerForId(pointerId);
3527 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3528 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3529
3530 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3531 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3532
3533 mPointerController->move(deltaX, deltaY);
3534}
3535
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003536std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3537 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003538 mPointerSimple.currentCoords.clear();
3539 mPointerSimple.currentProperties.clear();
3540
3541 bool down, hovering;
3542 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3543 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3544 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003545 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3546 down = !hovering;
3547
Prabir Pradhane71e5702023-03-29 14:51:38 +00003548 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3549 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3550 // Styluses are configured specifically for one display. We only update the
3551 // PointerController for this stylus if the PointerController is configured for
3552 // the same display as this stylus,
3553 if (getAssociatedDisplayId() == mViewport.displayId) {
3554 mPointerController->setPosition(x, y);
3555 std::tie(x, y) = mPointerController->getPosition();
3556 }
3557
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003558 mPointerSimple.currentCoords = mCurrentCookedState.cookedPointerData.pointerCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003559 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3560 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3561 mPointerSimple.currentProperties.id = 0;
3562 mPointerSimple.currentProperties.toolType =
3563 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3564 } else {
3565 down = false;
3566 hovering = false;
3567 }
3568
Prabir Pradhane71e5702023-03-29 14:51:38 +00003569 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003570}
3571
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003572std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3573 uint32_t policyFlags) {
3574 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003575}
3576
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003577std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3578 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003579 mPointerSimple.currentCoords.clear();
3580 mPointerSimple.currentProperties.clear();
3581
3582 bool down, hovering;
3583 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3584 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003585 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003586 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003587 } else {
3588 mPointerVelocityControl.reset();
3589 }
3590
3591 down = isPointerDown(mCurrentRawState.buttonState);
3592 hovering = !down;
3593
Prabir Pradhan2719e822023-02-28 17:39:36 +00003594 const auto [x, y] = mPointerController->getPosition();
3595 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003596 mPointerSimple.currentCoords =
3597 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3599 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3600 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3601 hovering ? 0.0f : 1.0f);
3602 mPointerSimple.currentProperties.id = 0;
3603 mPointerSimple.currentProperties.toolType =
3604 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3605 } else {
3606 mPointerVelocityControl.reset();
3607
3608 down = false;
3609 hovering = false;
3610 }
3611
Prabir Pradhane71e5702023-03-29 14:51:38 +00003612 const int32_t displayId = mPointerController->getDisplayId();
3613 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003614}
3615
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003616std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3617 uint32_t policyFlags) {
3618 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003619
3620 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003621
3622 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003623}
3624
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003625std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3626 uint32_t policyFlags, bool down,
Prabir Pradhane71e5702023-03-29 14:51:38 +00003627 bool hovering, int32_t displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003628 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3629 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003630 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003631 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003632 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003633
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003634 if (displayId == mPointerController->getDisplayId()) {
3635 std::tie(cursorPosition.x, cursorPosition.y) = mPointerController->getPosition();
3636 if (down || hovering) {
3637 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
3638 mPointerController->clearSpots();
3639 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3640 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
3641 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3642 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003643 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003644
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003645 if (mPointerSimple.down && !down) {
3646 mPointerSimple.down = false;
3647
3648 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003649 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3650 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3651 0, metaState, mLastRawState.buttonState,
3652 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3653 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003654 mOrientedXPrecision, mOrientedYPrecision,
3655 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3656 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003657 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003658 }
3659
3660 if (mPointerSimple.hovering && !hovering) {
3661 mPointerSimple.hovering = false;
3662
3663 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003664 out.push_back(
3665 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3666 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3667 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3668 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3669 &mPointerSimple.lastCoords, mOrientedXPrecision,
3670 mOrientedYPrecision, mPointerSimple.lastCursorX,
3671 mPointerSimple.lastCursorY, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003672 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003673 }
3674
3675 if (down) {
3676 if (!mPointerSimple.down) {
3677 mPointerSimple.down = true;
3678 mPointerSimple.downTime = when;
3679
3680 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003681 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3682 mSource, displayId, policyFlags,
3683 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3684 mCurrentRawState.buttonState, MotionClassification::NONE,
3685 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3686 &mPointerSimple.currentProperties,
3687 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003688 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003689 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003690 }
3691
3692 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003693 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3694 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3695 0, 0, metaState, mCurrentRawState.buttonState,
3696 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3697 &mPointerSimple.currentProperties,
3698 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003699 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003700 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003701 }
3702
3703 if (hovering) {
3704 if (!mPointerSimple.hovering) {
3705 mPointerSimple.hovering = true;
3706
3707 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003708 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3709 mSource, displayId, policyFlags,
3710 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3711 mCurrentRawState.buttonState, MotionClassification::NONE,
3712 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3713 &mPointerSimple.currentProperties,
3714 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003715 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003716 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003717 }
3718
3719 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003720 out.push_back(
3721 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3722 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3723 metaState, mCurrentRawState.buttonState,
3724 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3725 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003726 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003727 cursorPosition.y, mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003728 }
3729
3730 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3731 float vscroll = mCurrentRawState.rawVScroll;
3732 float hscroll = mCurrentRawState.rawHScroll;
3733 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3734 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3735
3736 // Send scroll.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003737 PointerCoords pointerCoords = mPointerSimple.currentCoords;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003738 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3739 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3740
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003741 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3742 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3743 0, 0, metaState, mCurrentRawState.buttonState,
3744 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3745 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003746 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3747 cursorPosition.y, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003748 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003749 }
3750
3751 // Save state.
3752 if (down || hovering) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003753 mPointerSimple.lastCoords = mPointerSimple.currentCoords;
3754 mPointerSimple.lastProperties = mPointerSimple.currentProperties;
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003755 mPointerSimple.displayId = displayId;
3756 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003757 mPointerSimple.lastCursorX = cursorPosition.x;
3758 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003759 } else {
3760 mPointerSimple.reset();
3761 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003762 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003763}
3764
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003765std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3766 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003767 std::list<NotifyArgs> out;
3768 if (mPointerSimple.down || mPointerSimple.hovering) {
3769 int32_t metaState = getContext()->getGlobalMetaState();
3770 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3771 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3772 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3773 metaState, mLastRawState.buttonState,
3774 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3775 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3776 mOrientedXPrecision, mOrientedYPrecision,
3777 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3778 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003779 /*videoFrames=*/{}));
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003780 if (mPointerController != nullptr) {
3781 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3782 }
3783 }
3784 mPointerSimple.reset();
3785 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003786}
3787
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003788NotifyMotionArgs TouchInputMapper::dispatchMotion(
3789 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3790 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003791 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3792 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003793 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003794 std::vector<PointerCoords> pointerCoords;
3795 std::vector<PointerProperties> pointerProperties;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003796 uint32_t pointerCount = 0;
3797 while (!idBits.isEmpty()) {
3798 uint32_t id = idBits.clearFirstMarkedBit();
3799 uint32_t index = idToIndex[id];
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003800 pointerProperties.push_back(properties[index]);
3801 pointerCoords.push_back(coords[index]);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003802
3803 if (changedId >= 0 && id == uint32_t(changedId)) {
3804 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3805 }
3806
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003807 pointerCount++;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003808 }
3809
3810 ALOG_ASSERT(pointerCount != 0);
3811
3812 if (changedId >= 0 && pointerCount == 1) {
3813 // Replace initial down and final up action.
3814 // We can compare the action without masking off the changed pointer index
3815 // because we know the index is 0.
3816 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3817 action = AMOTION_EVENT_ACTION_DOWN;
3818 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003819 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3820 action = AMOTION_EVENT_ACTION_CANCEL;
3821 } else {
3822 action = AMOTION_EVENT_ACTION_UP;
3823 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003824 } else {
3825 // Can't happen.
3826 ALOG_ASSERT(false);
3827 }
3828 }
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00003829 if (mCurrentStreamModifiedByExternalStylus) {
3830 source |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3831 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003832
3833 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3834 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003835 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003836 mPointerController && displayId != ADISPLAY_ID_NONE &&
3837 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003838 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003839 switch (action & AMOTION_EVENT_ACTION_MASK) {
3840 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3841 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3842 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003843 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003844 mPointerController
3845 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3846 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3847 .getY());
3848 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3849 break;
3850 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3851 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3852 break;
3853 }
3854 }
3855
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003856 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3857 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003858 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003859 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003860 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003861 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003862 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003863 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003864 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003865 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3866 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003867 classification, edgeFlags, pointerCount, pointerProperties.data(),
3868 pointerCoords.data(), xPrecision, yPrecision, xCursorPosition,
3869 yCursorPosition, downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003870}
3871
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003872std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3873 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003874 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3875 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003876 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003877}
3878
Prabir Pradhan1728b212021-10-19 16:00:03 -07003879bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003880 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003881 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003882 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003883}
3884
3885const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3886 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003887 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3888 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3889 "left=%d, top=%d, right=%d, bottom=%d",
3890 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3891 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003892
3893 if (virtualKey.isHit(x, y)) {
3894 return &virtualKey;
3895 }
3896 }
3897
3898 return nullptr;
3899}
3900
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003901void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3902 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3903 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003904
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003905 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003906
3907 if (currentPointerCount == 0) {
3908 // No pointers to assign.
3909 return;
3910 }
3911
3912 if (lastPointerCount == 0) {
3913 // All pointers are new.
3914 for (uint32_t i = 0; i < currentPointerCount; i++) {
3915 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003916 current.rawPointerData.pointers[i].id = id;
3917 current.rawPointerData.idToIndex[id] = i;
3918 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003919 }
3920 return;
3921 }
3922
3923 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003924 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003925 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003926 uint32_t id = last.rawPointerData.pointers[0].id;
3927 current.rawPointerData.pointers[0].id = id;
3928 current.rawPointerData.idToIndex[id] = 0;
3929 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003930 return;
3931 }
3932
3933 // General case.
3934 // We build a heap of squared euclidean distances between current and last pointers
3935 // associated with the current and last pointer indices. Then, we find the best
3936 // match (by distance) for each current pointer.
3937 // The pointers must have the same tool type but it is possible for them to
3938 // transition from hovering to touching or vice-versa while retaining the same id.
3939 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3940
3941 uint32_t heapSize = 0;
3942 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3943 currentPointerIndex++) {
3944 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3945 lastPointerIndex++) {
3946 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003947 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003948 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003949 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003950 if (currentPointer.toolType == lastPointer.toolType) {
3951 int64_t deltaX = currentPointer.x - lastPointer.x;
3952 int64_t deltaY = currentPointer.y - lastPointer.y;
3953
3954 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3955
3956 // Insert new element into the heap (sift up).
3957 heap[heapSize].currentPointerIndex = currentPointerIndex;
3958 heap[heapSize].lastPointerIndex = lastPointerIndex;
3959 heap[heapSize].distance = distance;
3960 heapSize += 1;
3961 }
3962 }
3963 }
3964
3965 // Heapify
3966 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3967 startIndex -= 1;
3968 for (uint32_t parentIndex = startIndex;;) {
3969 uint32_t childIndex = parentIndex * 2 + 1;
3970 if (childIndex >= heapSize) {
3971 break;
3972 }
3973
3974 if (childIndex + 1 < heapSize &&
3975 heap[childIndex + 1].distance < heap[childIndex].distance) {
3976 childIndex += 1;
3977 }
3978
3979 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3980 break;
3981 }
3982
3983 swap(heap[parentIndex], heap[childIndex]);
3984 parentIndex = childIndex;
3985 }
3986 }
3987
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003988 if (DEBUG_POINTER_ASSIGNMENT) {
3989 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3990 for (size_t i = 0; i < heapSize; i++) {
3991 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3992 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3993 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003994 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003995
3996 // Pull matches out by increasing order of distance.
3997 // To avoid reassigning pointers that have already been matched, the loop keeps track
3998 // of which last and current pointers have been matched using the matchedXXXBits variables.
3999 // It also tracks the used pointer id bits.
4000 BitSet32 matchedLastBits(0);
4001 BitSet32 matchedCurrentBits(0);
4002 BitSet32 usedIdBits(0);
4003 bool first = true;
4004 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
4005 while (heapSize > 0) {
4006 if (first) {
4007 // The first time through the loop, we just consume the root element of
4008 // the heap (the one with smallest distance).
4009 first = false;
4010 } else {
4011 // Previous iterations consumed the root element of the heap.
4012 // Pop root element off of the heap (sift down).
4013 heap[0] = heap[heapSize];
4014 for (uint32_t parentIndex = 0;;) {
4015 uint32_t childIndex = parentIndex * 2 + 1;
4016 if (childIndex >= heapSize) {
4017 break;
4018 }
4019
4020 if (childIndex + 1 < heapSize &&
4021 heap[childIndex + 1].distance < heap[childIndex].distance) {
4022 childIndex += 1;
4023 }
4024
4025 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4026 break;
4027 }
4028
4029 swap(heap[parentIndex], heap[childIndex]);
4030 parentIndex = childIndex;
4031 }
4032
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004033 if (DEBUG_POINTER_ASSIGNMENT) {
4034 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4035 for (size_t j = 0; j < heapSize; j++) {
4036 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4037 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4038 heap[j].distance);
4039 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004040 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004041 }
4042
4043 heapSize -= 1;
4044
4045 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4046 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4047
4048 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4049 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4050
4051 matchedCurrentBits.markBit(currentPointerIndex);
4052 matchedLastBits.markBit(lastPointerIndex);
4053
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004054 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4055 current.rawPointerData.pointers[currentPointerIndex].id = id;
4056 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4057 current.rawPointerData.markIdBit(id,
4058 current.rawPointerData.isHovering(
4059 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004060 usedIdBits.markBit(id);
4061
Harry Cutts45483602022-08-24 14:36:48 +00004062 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4063 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4064 ", distance=%" PRIu64,
4065 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004066 break;
4067 }
4068 }
4069
4070 // Assign fresh ids to pointers that were not matched in the process.
4071 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4072 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4073 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4074
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004075 current.rawPointerData.pointers[currentPointerIndex].id = id;
4076 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4077 current.rawPointerData.markIdBit(id,
4078 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004079
Harry Cutts45483602022-08-24 14:36:48 +00004080 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4081 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4082 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004083 }
4084}
4085
4086int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4087 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4088 return AKEY_STATE_VIRTUAL;
4089 }
4090
4091 for (const VirtualKey& virtualKey : mVirtualKeys) {
4092 if (virtualKey.keyCode == keyCode) {
4093 return AKEY_STATE_UP;
4094 }
4095 }
4096
4097 return AKEY_STATE_UNKNOWN;
4098}
4099
4100int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4101 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4102 return AKEY_STATE_VIRTUAL;
4103 }
4104
4105 for (const VirtualKey& virtualKey : mVirtualKeys) {
4106 if (virtualKey.scanCode == scanCode) {
4107 return AKEY_STATE_UP;
4108 }
4109 }
4110
4111 return AKEY_STATE_UNKNOWN;
4112}
4113
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004114bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4115 const std::vector<int32_t>& keyCodes,
4116 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004117 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004118 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004119 if (virtualKey.keyCode == keyCodes[i]) {
4120 outFlags[i] = 1;
4121 }
4122 }
4123 }
4124
4125 return true;
4126}
4127
4128std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4129 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004130 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004131 return std::make_optional(mPointerController->getDisplayId());
4132 } else {
4133 return std::make_optional(mViewport.displayId);
4134 }
4135 }
4136 return std::nullopt;
4137}
4138
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004139} // namespace android