blob: b0ba8d808c79e49d30070b3e041c8b626caffa8f [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
Antonio Kantek0ac5e092024-04-22 17:10:27 +0000541 const std::optional<std::string> associatedDisplayUniqueIdByDescriptor =
542 getDeviceContext().getAssociatedDisplayUniqueIdByDescriptor();
543 if (associatedDisplayUniqueIdByDescriptor) {
544 return getDeviceContext().getAssociatedViewport();
545 }
546
547 const std::optional<std::string> associatedDisplayUniqueIdByPort =
548 getDeviceContext().getAssociatedDisplayUniqueIdByPort();
549 if (associatedDisplayUniqueIdByPort) {
Christine Franks2a2293c2022-01-18 11:51:16 -0800550 return getDeviceContext().getAssociatedViewport();
551 }
552
Michael Wright227c5542020-07-02 18:30:52 +0100553 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800554 std::optional<DisplayViewport> viewport =
555 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
556 if (viewport) {
557 return viewport;
558 } else {
559 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
560 mConfig.defaultPointerDisplayId);
561 }
562 }
563
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700564 // Check if uniqueDisplayId is specified in idc file.
565 if (!mParameters.uniqueDisplayId.empty()) {
566 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
567 }
568
569 ViewportType viewportTypeToUse;
570 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100571 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700572 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100573 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700574 }
575
576 std::optional<DisplayViewport> viewport =
577 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100578 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700579 ALOGW("Input device %s should be associated with external display, "
580 "fallback to internal one for the external viewport is not found.",
581 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100582 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700583 }
584
585 return viewport;
586 }
587
588 // No associated display, return a non-display viewport.
589 DisplayViewport newViewport;
590 // Raw width and height in the natural orientation.
591 int32_t rawWidth = mRawPointerAxes.getRawWidth();
592 int32_t rawHeight = mRawPointerAxes.getRawHeight();
593 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
594 return std::make_optional(newViewport);
595}
596
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800597int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
598 if (resolution < 0) {
599 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
600 getDeviceName().c_str());
601 return 0;
602 }
603 return resolution;
604}
605
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800606void TouchInputMapper::initializeSizeRanges() {
607 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
608 mSizeScale = 0.0f;
609 return;
610 }
611
612 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000613 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800614
615 // Size factors.
616 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
617 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
618 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
619 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
620 } else {
621 mSizeScale = 0.0f;
622 }
623
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700624 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
625 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
626 .source = mSource,
627 .min = 0,
628 .max = diagonalSize,
629 .flat = 0,
630 .fuzz = 0,
631 .resolution = 0,
632 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800633
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800634 if (mRawPointerAxes.touchMajor.valid) {
635 mRawPointerAxes.touchMajor.resolution =
636 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700637 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800638 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800639
640 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700641 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800642 if (mRawPointerAxes.touchMinor.valid) {
643 mRawPointerAxes.touchMinor.resolution =
644 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700645 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800646 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800647
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700648 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
649 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
650 .source = mSource,
651 .min = 0,
652 .max = diagonalSize,
653 .flat = 0,
654 .fuzz = 0,
655 .resolution = 0,
656 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800657 if (mRawPointerAxes.toolMajor.valid) {
658 mRawPointerAxes.toolMajor.resolution =
659 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700660 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800661 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800662
663 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700664 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800665 if (mRawPointerAxes.toolMinor.valid) {
666 mRawPointerAxes.toolMinor.resolution =
667 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700668 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800669 }
670
671 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700672 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
673 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
674 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
675 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800676 } else {
677 // Support for other calibrations can be added here.
678 ALOGW("%s calibration is not supported for size ranges at the moment. "
679 "Using raw resolution instead",
680 ftl::enum_string(mCalibration.sizeCalibration).c_str());
681 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800682
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700683 mOrientedRanges.size = InputDeviceInfo::MotionRange{
684 .axis = AMOTION_EVENT_AXIS_SIZE,
685 .source = mSource,
686 .min = 0,
687 .max = 1.0,
688 .flat = 0,
689 .fuzz = 0,
690 .resolution = 0,
691 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800692}
693
694void TouchInputMapper::initializeOrientedRanges() {
695 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000696 const float orientedScaleX = mRawToDisplay.getScaleX();
697 const float orientedScaleY = mRawToDisplay.getScaleY();
698 mOrientedXPrecision = 1.0f / orientedScaleX;
699 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800700
701 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
702 mOrientedRanges.x.source = mSource;
703 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
704 mOrientedRanges.y.source = mSource;
705
706 // Scale factor for terms that are not oriented in a particular axis.
707 // If the pixels are square then xScale == yScale otherwise we fake it
708 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000709 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800710
711 initializeSizeRanges();
712
713 // Pressure factors.
714 mPressureScale = 0;
715 float pressureMax = 1.0;
716 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
717 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700718 if (mCalibration.pressureScale) {
719 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800720 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
721 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
722 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
723 }
724 }
725
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700726 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
727 .axis = AMOTION_EVENT_AXIS_PRESSURE,
728 .source = mSource,
729 .min = 0,
730 .max = pressureMax,
731 .flat = 0,
732 .fuzz = 0,
733 .resolution = 0,
734 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800735
736 // Tilt
737 mTiltXCenter = 0;
738 mTiltXScale = 0;
739 mTiltYCenter = 0;
740 mTiltYScale = 0;
741 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
742 if (mHaveTilt) {
743 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
744 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
745 mTiltXScale = M_PI / 180;
746 mTiltYScale = M_PI / 180;
747
748 if (mRawPointerAxes.tiltX.resolution) {
749 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
750 }
751 if (mRawPointerAxes.tiltY.resolution) {
752 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
753 }
754
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700755 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
756 .axis = AMOTION_EVENT_AXIS_TILT,
757 .source = mSource,
758 .min = 0,
759 .max = M_PI_2,
760 .flat = 0,
761 .fuzz = 0,
762 .resolution = 0,
763 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800764 }
765
766 // Orientation
767 mOrientationScale = 0;
768 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700769 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
770 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
771 .source = mSource,
772 .min = -M_PI,
773 .max = M_PI,
774 .flat = 0,
775 .fuzz = 0,
776 .resolution = 0,
777 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800778
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800779 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
780 if (mCalibration.orientationCalibration ==
781 Calibration::OrientationCalibration::INTERPOLATED) {
782 if (mRawPointerAxes.orientation.valid) {
783 if (mRawPointerAxes.orientation.maxValue > 0) {
784 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
785 } else if (mRawPointerAxes.orientation.minValue < 0) {
786 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
787 } else {
788 mOrientationScale = 0;
789 }
790 }
791 }
792
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700793 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
794 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
795 .source = mSource,
796 .min = -M_PI_2,
797 .max = M_PI_2,
798 .flat = 0,
799 .fuzz = 0,
800 .resolution = 0,
801 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800802 }
803
804 // Distance
805 mDistanceScale = 0;
806 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
807 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700808 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800809 }
810
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700811 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800812
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700813 .axis = AMOTION_EVENT_AXIS_DISTANCE,
814 .source = mSource,
815 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
816 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
817 .flat = 0,
818 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
819 .resolution = 0,
820 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800821 }
822
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000823 // Oriented X/Y range (in the rotated display's orientation)
824 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
825 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
826 .toFloatRect();
827 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
828 mOrientedRanges.x.min = orientedRangeRect.left;
829 mOrientedRanges.y.min = orientedRangeRect.top;
830 mOrientedRanges.x.max = orientedRangeRect.right;
831 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800832
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000833 // Oriented flat (in the rotated display's orientation)
834 const auto orientedFlat =
835 transformWithoutTranslation(mRawToRotatedDisplay,
836 {static_cast<float>(mRawPointerAxes.x.flat),
837 static_cast<float>(mRawPointerAxes.y.flat)});
838 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
839 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800840
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000841 // Oriented fuzz (in the rotated display's orientation)
842 const auto orientedFuzz =
843 transformWithoutTranslation(mRawToRotatedDisplay,
844 {static_cast<float>(mRawPointerAxes.x.fuzz),
845 static_cast<float>(mRawPointerAxes.y.fuzz)});
846 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
847 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800848
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000849 // Oriented resolution (in the rotated display's orientation)
850 const auto orientedRes =
851 transformWithoutTranslation(mRawToRotatedDisplay,
852 {static_cast<float>(mRawPointerAxes.x.resolution),
853 static_cast<float>(mRawPointerAxes.y.resolution)});
854 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
855 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800856}
857
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000858void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000859 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
860 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
861 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000862
Prabir Pradhan3e798762022-12-02 21:02:11 +0000863 // See notes about input coordinates in the inputflinger docs:
864 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000865
866 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000867 ui::Transform undoOffsetInRaw;
868 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000869
Prabir Pradhan3e798762022-12-02 21:02:11 +0000870 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
871 // will now be in the same orientation as the display in ROTATION_0.
872 // Note: Negating an ui::Rotation value will give its inverse rotation.
873 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
874 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
875 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
876 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
877 // When rotating raw values, account for the extra unit added when calculating the raw range.
878 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
879 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000880
Prabir Pradhan3e798762022-12-02 21:02:11 +0000881 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
882 // now be in the same orientation as the rotated display. There is no need to rotate the
883 // coordinates to the display rotation if the device is not orientation-aware.
884 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
885 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
886 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
887 : orientedRawSize;
888 // When rotating raw values, account for the extra unit added when calculating the raw range.
889 const auto rotateInRaw = mParameters.orientationAware
890 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
891 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000892
Prabir Pradhan3e798762022-12-02 21:02:11 +0000893 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000894 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
895 // the surface of the display panel. This is usually true for touchscreens.
896 // - In POINTER mode, we cannot assume that the display and the touch device have the same
897 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
898 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
899 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
900 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000901 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
902 // are in the continuous space of the logical display.
903 ui::Transform scaleRawToDisplay;
904 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
905 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000906 if (mDeviceMode == DeviceMode::DIRECT) {
907 scaleRawToDisplay.set(xScale, 0, 0, yScale);
908 } else if (mDeviceMode == DeviceMode::POINTER) {
909 const float fixedScale = std::max(xScale, yScale);
910 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
911 } else {
912 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
913 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000914
Prabir Pradhan3e798762022-12-02 21:02:11 +0000915 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
916 // that InputReader uses.
917 const auto undoRotateInDisplay =
918 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
919 .inverse();
920
921 // Now put it all together!
922 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
923 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
924 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000925}
926
Prabir Pradhan1728b212021-10-19 16:00:03 -0700927void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000928 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700929
930 resolveExternalStylusPresence();
931
932 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100933 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +0900934 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700935 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100936 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700937 if (hasStylus()) {
938 mSource |= AINPUT_SOURCE_STYLUS;
939 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800940 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700941 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100942 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700943 if (hasStylus()) {
944 mSource |= AINPUT_SOURCE_STYLUS;
945 }
Michael Wright227c5542020-07-02 18:30:52 +0100946 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700947 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100948 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700949 } else {
Harry Cutts8722be92024-04-05 14:46:05 +0000950 ALOGW("Touch device '%s' has invalid parameters or configuration. The device will be "
951 "inoperable.",
952 getDeviceName().c_str());
953 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700954 }
955
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000956 const std::optional<DisplayViewport> newViewportOpt = findViewport();
957
958 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700959 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
960 ALOGW("Touch device '%s' did not report support for X or Y axis! "
961 "The device will be inoperable.",
962 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100963 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000964 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700965 ALOGI("Touch device '%s' could not query the properties of its associated "
966 "display. The device will be inoperable until the display size "
967 "becomes available.",
968 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100969 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700970 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000971 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
972 getDeviceName().c_str(), getDeviceId());
973 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000974 }
975
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700976 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000977 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000978 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
979 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
980 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
981 const float rawMeanResolution =
982 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700983
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000984 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
Josh Thielene986aed2023-06-01 14:17:30 +0000985 bool viewportChanged;
986 if (mParameters.enableForInactiveViewport) {
987 // When touch is enabled for an inactive viewport, ignore the
988 // viewport active status when checking whether the viewport has
989 // changed.
990 DisplayViewport tempViewport = mViewport;
991 tempViewport.isActive = newViewport.isActive;
992 viewportChanged = tempViewport != newViewport;
993 } else {
994 viewportChanged = mViewport != newViewport;
995 }
996
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700997 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700998 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000999 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
1000 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
1001 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001002
Michael Wright227c5542020-07-02 18:30:52 +01001003 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +00001004 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001005
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001006 mDisplayBounds = getNaturalDisplaySize(mViewport);
1007 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
1008 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -07001009
Prabir Pradhan3e798762022-12-02 21:02:11 +00001010 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
1011 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
1012 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001013 // InputReader works in the un-rotated display coordinate space, so we don't need to do
1014 // anything if the device is already orientation-aware. If the device is not
1015 // orientation-aware, then we need to apply the inverse rotation of the display so that
1016 // when the display rotation is applied later as a part of the per-window transform, we
1017 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001018 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +00001019 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001020 : getInverseRotation(mViewport.orientation);
1021 // For orientation-aware devices that work in the un-rotated coordinate space, the
1022 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001023 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001024 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001025
1026 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001027 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001028 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001029 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001030 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001031 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001032 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001033 mRawToDisplay.reset();
1034 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001035 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001036 }
1037 }
1038
1039 // If moving between pointer modes, need to reset some state.
1040 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1041 if (deviceModeChanged) {
1042 mOrientedRanges.clear();
1043 }
1044
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001045 // Create and preserve the pointer controller in the following cases:
1046 const bool isPointerControllerNeeded =
1047 // - when the device is in pointer mode, to show the mouse cursor;
1048 (mDeviceMode == DeviceMode::POINTER) ||
1049 // - when pointer capture is enabled, to preserve the mouse cursor position;
1050 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Hiroki Sato25040232024-02-22 17:21:22 +09001051 mConfig.pointerCaptureRequest.isEnable()) ||
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001052 // - when we should be showing touches;
1053 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1054 // - when we should be showing a pointer icon for direct styluses.
1055 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1056 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001057 if (mPointerController == nullptr) {
1058 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001059 }
Hiroki Sato25040232024-02-22 17:21:22 +09001060 if (mConfig.pointerCaptureRequest.isEnable()) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001061 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1062 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001063 } else {
lilinnandef700b2022-06-17 19:32:01 +08001064 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1065 !mConfig.showTouches) {
1066 mPointerController->clearSpots();
1067 }
Michael Wright17db18e2020-06-26 20:51:44 +01001068 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001069 }
1070
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001071 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001072 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001073 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001074 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001075 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001076
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001077 configureVirtualKeys();
1078
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001079 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001080
1081 // Location
1082 updateAffineTransformation();
1083
Michael Wright227c5542020-07-02 18:30:52 +01001084 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001085 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001086 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1087 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001088
1089 // Scale movements such that one whole swipe of the touch pad covers a
1090 // given area relative to the diagonal size of the display when no acceleration
1091 // is applied.
1092 // Assume that the touch pad has a square aspect ratio such that movements in
1093 // X and Y of the same number of raw units cover the same physical distance.
1094 mPointerXMovementScale =
1095 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1096 mPointerYMovementScale = mPointerXMovementScale;
1097
1098 // Scale zooms to cover a smaller range of the display than movements do.
1099 // This value determines the area around the pointer that is affected by freeform
1100 // pointer gestures.
1101 mPointerXZoomScale =
1102 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1103 mPointerYZoomScale = mPointerXZoomScale;
1104
HQ Liue6983c72022-04-19 22:14:56 +00001105 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1106 // axis is non positive value.
1107 const float minFreeformGestureWidth =
1108 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1109
1110 mPointerGestureMaxSwipeWidth =
1111 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1112 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 }
1114
1115 // Inform the dispatcher about the changes.
1116 *outResetNeeded = true;
1117 bumpGeneration();
1118 }
1119}
1120
Prabir Pradhan1728b212021-10-19 16:00:03 -07001121void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001122 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001123 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001124 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1125 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001126 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001127}
1128
1129void TouchInputMapper::configureVirtualKeys() {
1130 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001131 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001132
1133 mVirtualKeys.clear();
1134
1135 if (virtualKeyDefinitions.size() == 0) {
1136 return;
1137 }
1138
1139 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1140 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1141 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1142 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1143
1144 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1145 VirtualKey virtualKey;
1146
1147 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1148 int32_t keyCode;
1149 int32_t dummyKeyMetaState;
1150 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001151 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1152 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001153 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1154 continue; // drop the key
1155 }
1156
1157 virtualKey.keyCode = keyCode;
1158 virtualKey.flags = flags;
1159
1160 // convert the key definition's display coordinates into touch coordinates for a hit box
1161 int32_t halfWidth = virtualKeyDefinition.width / 2;
1162 int32_t halfHeight = virtualKeyDefinition.height / 2;
1163
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001164 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1165 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001167 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1168 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001170 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1171 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001173 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1174 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 touchScreenTop;
1176 mVirtualKeys.push_back(virtualKey);
1177 }
1178}
1179
1180void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1181 if (!mVirtualKeys.empty()) {
1182 dump += INDENT3 "Virtual Keys:\n";
1183
1184 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1185 const VirtualKey& virtualKey = mVirtualKeys[i];
1186 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1187 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1188 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1189 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1190 }
1191 }
1192}
1193
1194void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001195 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 Calibration& out = mCalibration;
1197
1198 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001200 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1201 if (sizeCalibrationString.has_value()) {
1202 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001203 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001204 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001205 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001206 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001207 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001208 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001209 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001210 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001211 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001212 } else if (*sizeCalibrationString != "default") {
1213 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 }
1215 }
1216
Harry Cuttsf13161a2023-03-08 14:15:49 +00001217 out.sizeScale = in.getFloat("touch.size.scale");
1218 out.sizeBias = in.getFloat("touch.size.bias");
1219 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220
1221 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001223 std::optional<std::string> pressureCalibrationString =
1224 in.getString("touch.pressure.calibration");
1225 if (pressureCalibrationString.has_value()) {
1226 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001227 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001228 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001229 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001230 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001231 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001232 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001234 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001235 }
1236 }
1237
Harry Cuttsf13161a2023-03-08 14:15:49 +00001238 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239
1240 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001241 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001242 std::optional<std::string> orientationCalibrationString =
1243 in.getString("touch.orientation.calibration");
1244 if (orientationCalibrationString.has_value()) {
1245 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001246 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001247 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001248 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001249 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001250 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001251 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001253 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 }
1255 }
1256
1257 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001258 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001259 std::optional<std::string> distanceCalibrationString =
1260 in.getString("touch.distance.calibration");
1261 if (distanceCalibrationString.has_value()) {
1262 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001263 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001264 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001265 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001266 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001268 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
1270 }
1271
Harry Cuttsf13161a2023-03-08 14:15:49 +00001272 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273}
1274
1275void TouchInputMapper::resolveCalibration() {
1276 // Size
1277 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001278 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1279 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 }
1281 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001282 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 }
1284
1285 // Pressure
1286 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001287 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1288 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 }
1290 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001291 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001292 }
1293
1294 // Orientation
1295 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001296 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1297 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 }
1299 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001300 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 }
1302
1303 // Distance
1304 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001305 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1306 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 }
1308 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001309 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311}
1312
1313void TouchInputMapper::dumpCalibration(std::string& dump) {
1314 dump += INDENT3 "Calibration:\n";
1315
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001316 dump += INDENT4 "touch.size.calibration: ";
1317 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001319 if (mCalibration.sizeScale) {
1320 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001321 }
1322
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001323 if (mCalibration.sizeBias) {
1324 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 }
1326
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001327 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001329 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 }
1331
1332 // Pressure
1333 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001334 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001335 dump += INDENT4 "touch.pressure.calibration: none\n";
1336 break;
Michael Wright227c5542020-07-02 18:30:52 +01001337 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001338 dump += INDENT4 "touch.pressure.calibration: physical\n";
1339 break;
Michael Wright227c5542020-07-02 18:30:52 +01001340 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1342 break;
1343 default:
1344 ALOG_ASSERT(false);
1345 }
1346
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001347 if (mCalibration.pressureScale) {
1348 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001349 }
1350
1351 // Orientation
1352 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001353 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001354 dump += INDENT4 "touch.orientation.calibration: none\n";
1355 break;
Michael Wright227c5542020-07-02 18:30:52 +01001356 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1358 break;
Michael Wright227c5542020-07-02 18:30:52 +01001359 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360 dump += INDENT4 "touch.orientation.calibration: vector\n";
1361 break;
1362 default:
1363 ALOG_ASSERT(false);
1364 }
1365
1366 // Distance
1367 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001368 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001369 dump += INDENT4 "touch.distance.calibration: none\n";
1370 break;
Michael Wright227c5542020-07-02 18:30:52 +01001371 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001372 dump += INDENT4 "touch.distance.calibration: scaled\n";
1373 break;
1374 default:
1375 ALOG_ASSERT(false);
1376 }
1377
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001378 if (mCalibration.distanceScale) {
1379 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001380 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001381}
1382
1383void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1384 dump += INDENT3 "Affine Transformation:\n";
1385
1386 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1387 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1388 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1389 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1390 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1391 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1392}
1393
1394void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001395 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001396 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001397}
1398
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001399std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001400 std::list<NotifyArgs> out = cancelTouch(when, when);
1401 updateTouchSpots();
1402
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001403 mCursorButtonAccumulator.reset(getDeviceContext());
1404 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001405 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001406
1407 mPointerVelocityControl.reset();
1408 mWheelXVelocityControl.reset();
1409 mWheelYVelocityControl.reset();
1410
1411 mRawStatesPending.clear();
1412 mCurrentRawState.clear();
1413 mCurrentCookedState.clear();
1414 mLastRawState.clear();
1415 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001416 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001417 mSentHoverEnter = false;
1418 mHavePointerIds = false;
1419 mCurrentMotionAborted = false;
1420 mDownTime = 0;
1421
1422 mCurrentVirtualKey.down = false;
1423
1424 mPointerGesture.reset();
1425 mPointerSimple.reset();
1426 resetExternalStylus();
1427
1428 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001429 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001430 mPointerController->clearSpots();
1431 }
1432
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001433 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001434}
1435
1436void TouchInputMapper::resetExternalStylus() {
1437 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001438 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001439 mExternalStylusFusionTimeout = LLONG_MAX;
1440 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001441 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001442}
1443
1444void TouchInputMapper::clearStylusDataPendingFlags() {
1445 mExternalStylusDataPending = false;
1446 mExternalStylusFusionTimeout = LLONG_MAX;
1447}
1448
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001449std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001450 mCursorButtonAccumulator.process(rawEvent);
1451 mCursorScrollAccumulator.process(rawEvent);
1452 mTouchButtonAccumulator.process(rawEvent);
1453
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001454 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001456 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001457 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001458 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001459}
1460
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001461std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1462 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001463 if (mDeviceMode == DeviceMode::DISABLED) {
1464 // Only save the last pending state when the device is disabled.
1465 mRawStatesPending.clear();
1466 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001467 // Push a new state.
1468 mRawStatesPending.emplace_back();
1469
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001470 RawState& next = mRawStatesPending.back();
1471 next.clear();
1472 next.when = when;
1473 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001474
1475 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001476 next.buttonState = filterButtonState(mConfig,
1477 mTouchButtonAccumulator.getButtonState() |
1478 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001479
1480 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001481 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1482 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001483 mCursorScrollAccumulator.finishSync();
1484
1485 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001486 syncTouch(when, &next);
1487
1488 // The last RawState is the actually second to last, since we just added a new state
1489 const RawState& last =
1490 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001491
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001492 std::tie(next.when, next.readTime) =
1493 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1494 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001495
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001496 // Assign pointer ids.
1497 if (!mHavePointerIds) {
1498 assignPointerIds(last, next);
1499 }
1500
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001501 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001502 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1503 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1504 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1505 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1506 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1507 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001508
Arthur Hung9ad18942021-06-19 02:04:46 +00001509 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1510 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1511 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1512 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1513 next.rawPointerData.hoveringIdBits.value);
1514 }
1515
Harry Cutts33476232023-01-30 19:57:29 +00001516 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001517 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001518}
1519
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001520std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1521 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001522 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001523 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001524 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001525 }
1526
1527 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1528 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1529 // touching the current state will only observe the events that have been dispatched to the
1530 // rest of the pipeline.
1531 const size_t N = mRawStatesPending.size();
1532 size_t count;
1533 for (count = 0; count < N; count++) {
1534 const RawState& next = mRawStatesPending[count];
1535
1536 // A failure to assign the stylus id means that we're waiting on stylus data
1537 // and so should defer the rest of the pipeline.
1538 if (assignExternalStylusId(next, timeout)) {
1539 break;
1540 }
1541
1542 // All ready to go.
1543 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001544 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001545 if (mCurrentRawState.when < mLastRawState.when) {
1546 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001547 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001548 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001549 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550 }
1551 if (count != 0) {
1552 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1553 }
1554
1555 if (mExternalStylusDataPending) {
1556 if (timeout) {
1557 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1558 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001559 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001560 ALOGD_IF(DEBUG_STYLUS_FUSION,
1561 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001562 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001563 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001564 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1565 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1566 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1567 }
1568 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001569 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001570}
1571
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001572std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1573 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001574 // Always start with a clean state.
1575 mCurrentCookedState.clear();
1576
1577 // Apply stylus buttons to current raw state.
1578 applyExternalStylusButtonState(when);
1579
1580 // Handle policy on initial down or hover events.
1581 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1582 mCurrentRawState.rawPointerData.pointerCount != 0;
1583
1584 uint32_t policyFlags = 0;
1585 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1586 if (initialDown || buttonsPressed) {
1587 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001588 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001589 getContext()->fadePointer();
1590 }
1591
1592 if (mParameters.wake) {
1593 policyFlags |= POLICY_FLAG_WAKE;
1594 }
1595 }
1596
1597 // Consume raw off-screen touches before cooking pointer data.
1598 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001599 bool consumed;
1600 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1601 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001602 mCurrentRawState.rawPointerData.clear();
1603 }
1604
1605 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1606 // with cooked pointer data that has the same ids and indices as the raw data.
1607 // The following code can use either the raw or cooked data, as needed.
1608 cookPointerData();
1609
1610 // Apply stylus pressure to current cooked state.
1611 applyExternalStylusTouchState(when);
1612
1613 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001614 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1615 mSource, mViewport.displayId, policyFlags,
1616 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617
1618 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001619 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001620 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1621 uint32_t id = idBits.clearFirstMarkedBit();
1622 const RawPointerData::Pointer& pointer =
1623 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001624 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001625 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001626 } else if (pointer.toolType == ToolType::FINGER ||
1627 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001628 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001629 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 mCurrentCookedState.mouseIdBits.markBit(id);
1631 }
1632 }
1633 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1634 uint32_t id = idBits.clearFirstMarkedBit();
1635 const RawPointerData::Pointer& pointer =
1636 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001637 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001638 mCurrentCookedState.stylusIdBits.markBit(id);
1639 }
1640 }
1641
1642 // Stylus takes precedence over all tools, then mouse, then finger.
1643 PointerUsage pointerUsage = mPointerUsage;
1644 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1645 mCurrentCookedState.mouseIdBits.clear();
1646 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001647 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001648 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1649 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001650 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001651 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1652 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001653 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001654 }
1655
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001656 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001657 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001658 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001659 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001660 out += dispatchButtonRelease(when, readTime, policyFlags);
1661 out += dispatchHoverExit(when, readTime, policyFlags);
1662 out += dispatchTouches(when, readTime, policyFlags);
1663 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1664 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001665 }
1666
1667 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1668 mCurrentMotionAborted = false;
1669 }
1670 }
1671
1672 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001673 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1674 mSource, mViewport.displayId, policyFlags,
1675 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001676
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001677 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1678 mCurrentStreamModifiedByExternalStylus = false;
1679 }
1680
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001681 // Clear some transient state.
1682 mCurrentRawState.rawVScroll = 0;
1683 mCurrentRawState.rawHScroll = 0;
1684
1685 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001686 mLastRawState = mCurrentRawState;
1687 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001688 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001689}
1690
Garfield Tanc734e4f2021-01-15 20:01:39 -08001691void TouchInputMapper::updateTouchSpots() {
1692 if (!mConfig.showTouches || mPointerController == nullptr) {
1693 return;
1694 }
1695
1696 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1697 // clear touch spots.
1698 if (mDeviceMode != DeviceMode::DIRECT &&
1699 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1700 return;
1701 }
1702
1703 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1704 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1705
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001706 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1707 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001708 mCurrentCookedState.cookedPointerData.touchingIdBits |
1709 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001710 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001711}
1712
1713bool TouchInputMapper::isTouchScreen() {
1714 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1715 mParameters.hasAssociatedDisplay;
1716}
1717
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001718void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001719 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1720 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001721 const int32_t pressedButtons =
1722 filterButtonState(mConfig,
1723 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001724 const int32_t releasedButtons =
1725 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1726
1727 mCurrentRawState.buttonState |= pressedButtons;
1728 mCurrentRawState.buttonState &= ~releasedButtons;
1729
1730 mExternalStylusButtonsApplied |= pressedButtons;
1731 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001732
1733 if (mExternalStylusButtonsApplied != 0 || releasedButtons != 0) {
1734 mCurrentStreamModifiedByExternalStylus = true;
1735 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001736 }
1737}
1738
1739void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1740 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1741 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001742 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1743 return;
1744 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001745
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001746 mCurrentStreamModifiedByExternalStylus = true;
1747
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001748 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1749 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1750 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1751 : 0.f;
1752 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1753 pressure = *mExternalStylusState.pressure;
1754 }
1755 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1756 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001757
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001758 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001759 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001760 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001761 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001762 }
1763}
1764
1765bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001766 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001767 return false;
1768 }
1769
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001770 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001771 if (mFusedStylusPointerId &&
1772 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001773 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001774 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001775 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001776 }
1777
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001778 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1779 state.rawPointerData.pointerCount != 0;
1780 if (!initialDown) {
1781 return false;
1782 }
1783
1784 if (!mExternalStylusState.pressure) {
1785 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1786 return false;
1787 }
1788
1789 if (*mExternalStylusState.pressure != 0.0f) {
1790 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1791 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1792 return false;
1793 }
1794
1795 if (timeout) {
1796 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1797 mFusedStylusPointerId.reset();
1798 mExternalStylusFusionTimeout = LLONG_MAX;
1799 return false;
1800 }
1801
1802 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1803 // being processed until we either get pressure data or timeout.
1804 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1805 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1806 }
1807 ALOGD_IF(DEBUG_STYLUS_FUSION,
1808 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1809 mExternalStylusFusionTimeout);
1810 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1811 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001812}
1813
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001814std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1815 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001816 if (mDeviceMode == DeviceMode::POINTER) {
1817 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001818 // Since this is a synthetic event, we can consider its latency to be zero
1819 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001820 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001821 }
Michael Wright227c5542020-07-02 18:30:52 +01001822 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001823 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001824 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001825 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1826 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1827 }
1828 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001829 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001830}
1831
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001832std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1833 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001834 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001835 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001836 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001837 // The following three cases are handled here:
1838 // - We're in the middle of a fused stream of data;
1839 // - We're waiting on external stylus data before dispatching the initial down; or
1840 // - Only the button state, which is not reported through a specific pointer, has changed.
1841 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001842 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001843 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001844 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001845 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001846}
1847
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001848std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1849 uint32_t policyFlags, bool& outConsumed) {
1850 outConsumed = false;
1851 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001852 // Check for release of a virtual key.
1853 if (mCurrentVirtualKey.down) {
1854 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1855 // Pointer went up while virtual key was down.
1856 mCurrentVirtualKey.down = false;
1857 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001858 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1859 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1860 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001861 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1862 AKEY_EVENT_FLAG_FROM_SYSTEM |
1863 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001864 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001865 outConsumed = true;
1866 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001867 }
1868
1869 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1870 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1871 const RawPointerData::Pointer& pointer =
1872 mCurrentRawState.rawPointerData.pointerForId(id);
1873 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1874 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1875 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001876 outConsumed = true;
1877 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001878 }
1879 }
1880
1881 // Pointer left virtual key area or another pointer also went down.
1882 // Send key cancellation but do not consume the touch yet.
1883 // This is useful when the user swipes through from the virtual key area
1884 // into the main display surface.
1885 mCurrentVirtualKey.down = false;
1886 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001887 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1888 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001889 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1890 AKEY_EVENT_FLAG_FROM_SYSTEM |
1891 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1892 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001893 }
1894 }
1895
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001896 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
Harry Cutts8722be92024-04-05 14:46:05 +00001897 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001898 // We have hovering pointers, and there are no touching pointers.
1899 bool hoveringPointersInFrame = false;
1900 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1901 while (!hoveringIds.isEmpty()) {
1902 uint32_t id = hoveringIds.clearFirstMarkedBit();
1903 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1904 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1905 hoveringPointersInFrame = true;
1906 break;
1907 }
1908 }
1909 if (!hoveringPointersInFrame) {
1910 // All hovering pointers are outside the physical frame.
1911 outConsumed = true;
1912 return out;
1913 }
1914 }
1915
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001916 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1917 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1918 // Pointer just went down. Check for virtual key press or off-screen touches.
1919 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1920 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001921 // Skip checking whether the pointer is inside the physical frame if the device is in
Harry Cutts1db43992023-06-19 17:05:07 +00001922 // unscaled or pointer mode.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001923 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
Harry Cutts8722be92024-04-05 14:46:05 +00001924 mDeviceMode != DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001925 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001926 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001927 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1928 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1929 if (virtualKey) {
1930 mCurrentVirtualKey.down = true;
1931 mCurrentVirtualKey.downTime = when;
1932 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1933 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1934 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001935 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1936 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001937
1938 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001939 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1940 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1941 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001942 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1943 AKEY_EVENT_ACTION_DOWN,
1944 AKEY_EVENT_FLAG_FROM_SYSTEM |
1945 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001946 }
1947 }
1948 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001949 outConsumed = true;
1950 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001951 }
1952 }
1953
1954 // Disable all virtual key touches that happen within a short time interval of the
1955 // most recent touch within the screen area. The idea is to filter out stray
1956 // virtual key presses when interacting with the touch screen.
1957 //
1958 // Problems we're trying to solve:
1959 //
1960 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1961 // virtual key area that is implemented by a separate touch panel and accidentally
1962 // triggers a virtual key.
1963 //
1964 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1965 // area and accidentally triggers a virtual key. This often happens when virtual keys
1966 // are layed out below the screen near to where the on screen keyboard's space bar
1967 // is displayed.
1968 if (mConfig.virtualKeyQuietTime > 0 &&
1969 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001970 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001971 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001972 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001973}
1974
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001975NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1976 uint32_t policyFlags, int32_t keyEventAction,
1977 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001978 int32_t keyCode = mCurrentVirtualKey.keyCode;
1979 int32_t scanCode = mCurrentVirtualKey.scanCode;
1980 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001981 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001982 policyFlags |= POLICY_FLAG_VIRTUAL;
1983
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001984 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1985 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1986 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001987}
1988
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001989std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1990 uint32_t policyFlags) {
1991 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001992 if (mCurrentMotionAborted) {
1993 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001994 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001995 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001996 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1997 if (!currentIdBits.isEmpty()) {
1998 int32_t metaState = getContext()->getGlobalMetaState();
1999 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002000 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002001 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2002 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002003 mCurrentCookedState.cookedPointerData.pointerProperties,
2004 mCurrentCookedState.cookedPointerData.pointerCoords,
2005 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2006 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2007 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002008 mCurrentMotionAborted = true;
2009 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002010 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002011}
2012
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002013// Updates pointer coords and properties for pointers with specified ids that have moved.
2014// Returns true if any of them changed.
2015static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
2016 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
2017 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
2018 BitSet32 idBits) {
2019 bool changed = false;
2020 while (!idBits.isEmpty()) {
2021 uint32_t id = idBits.clearFirstMarkedBit();
2022 uint32_t inIndex = inIdToIndex[id];
2023 uint32_t outIndex = outIdToIndex[id];
2024
2025 const PointerProperties& curInProperties = inProperties[inIndex];
2026 const PointerCoords& curInCoords = inCoords[inIndex];
2027 PointerProperties& curOutProperties = outProperties[outIndex];
2028 PointerCoords& curOutCoords = outCoords[outIndex];
2029
2030 if (curInProperties != curOutProperties) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002031 curOutProperties = curInProperties;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002032 changed = true;
2033 }
2034
2035 if (curInCoords != curOutCoords) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002036 curOutCoords = curInCoords;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002037 changed = true;
2038 }
2039 }
2040 return changed;
2041}
2042
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002043std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
2044 uint32_t policyFlags) {
2045 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002046 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2047 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2048 int32_t metaState = getContext()->getGlobalMetaState();
2049 int32_t buttonState = mCurrentCookedState.buttonState;
2050
2051 if (currentIdBits == lastIdBits) {
2052 if (!currentIdBits.isEmpty()) {
2053 // No pointer id changes so this is a move event.
2054 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002055 out.push_back(
2056 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2057 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2058 mCurrentCookedState.cookedPointerData.pointerProperties,
2059 mCurrentCookedState.cookedPointerData.pointerCoords,
2060 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2061 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2062 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002063 }
2064 } else {
2065 // There may be pointers going up and pointers going down and pointers moving
2066 // all at the same time.
2067 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2068 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2069 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2070 BitSet32 dispatchedIdBits(lastIdBits.value);
2071
2072 // Update last coordinates of pointers that have moved so that we observe the new
2073 // pointer positions at the same time as other pointers that have just gone up.
2074 bool moveNeeded =
2075 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2076 mCurrentCookedState.cookedPointerData.pointerCoords,
2077 mCurrentCookedState.cookedPointerData.idToIndex,
2078 mLastCookedState.cookedPointerData.pointerProperties,
2079 mLastCookedState.cookedPointerData.pointerCoords,
2080 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2081 if (buttonState != mLastCookedState.buttonState) {
2082 moveNeeded = true;
2083 }
2084
2085 // Dispatch pointer up events.
2086 while (!upIdBits.isEmpty()) {
2087 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002088 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002089 if (isCanceled) {
2090 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2091 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002092 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2093 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2094 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2095 buttonState, 0,
2096 mLastCookedState.cookedPointerData.pointerProperties,
2097 mLastCookedState.cookedPointerData.pointerCoords,
2098 mLastCookedState.cookedPointerData.idToIndex,
2099 dispatchedIdBits, upId, mOrientedXPrecision,
2100 mOrientedYPrecision, mDownTime,
2101 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002102 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002103 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002104 }
2105
2106 // Dispatch move events if any of the remaining pointers moved from their old locations.
2107 // Although applications receive new locations as part of individual pointer up
2108 // events, they do not generally handle them except when presented in a move event.
2109 if (moveNeeded && !moveIdBits.isEmpty()) {
2110 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002111 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2112 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2113 mCurrentCookedState.cookedPointerData.pointerProperties,
2114 mCurrentCookedState.cookedPointerData.pointerCoords,
2115 mCurrentCookedState.cookedPointerData.idToIndex,
2116 dispatchedIdBits, -1, mOrientedXPrecision,
2117 mOrientedYPrecision, mDownTime,
2118 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002119 }
2120
2121 // Dispatch pointer down events using the new pointer locations.
2122 while (!downIdBits.isEmpty()) {
2123 uint32_t downId = downIdBits.clearFirstMarkedBit();
2124 dispatchedIdBits.markBit(downId);
2125
2126 if (dispatchedIdBits.count() == 1) {
2127 // First pointer is going down. Set down time.
2128 mDownTime = when;
2129 }
2130
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002131 out.push_back(
2132 dispatchMotion(when, readTime, policyFlags, mSource,
2133 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2134 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2135 mCurrentCookedState.cookedPointerData.pointerCoords,
2136 mCurrentCookedState.cookedPointerData.idToIndex,
2137 dispatchedIdBits, downId, mOrientedXPrecision,
2138 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002139 }
2140 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002141 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002142}
2143
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002144std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2145 uint32_t policyFlags) {
2146 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002147 if (mSentHoverEnter &&
2148 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2149 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2150 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002151 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2152 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2153 mLastCookedState.buttonState, 0,
2154 mLastCookedState.cookedPointerData.pointerProperties,
2155 mLastCookedState.cookedPointerData.pointerCoords,
2156 mLastCookedState.cookedPointerData.idToIndex,
2157 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2158 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2159 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002160 mSentHoverEnter = false;
2161 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002162 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002163}
2164
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002165std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2166 uint32_t policyFlags) {
2167 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002168 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2169 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2170 int32_t metaState = getContext()->getGlobalMetaState();
2171 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002172 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2173 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2174 mCurrentRawState.buttonState, 0,
2175 mCurrentCookedState.cookedPointerData.pointerProperties,
2176 mCurrentCookedState.cookedPointerData.pointerCoords,
2177 mCurrentCookedState.cookedPointerData.idToIndex,
2178 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2179 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2180 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002181 mSentHoverEnter = true;
2182 }
2183
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002184 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2185 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2186 mCurrentRawState.buttonState, 0,
2187 mCurrentCookedState.cookedPointerData.pointerProperties,
2188 mCurrentCookedState.cookedPointerData.pointerCoords,
2189 mCurrentCookedState.cookedPointerData.idToIndex,
2190 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2191 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2192 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002193 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002194 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002195}
2196
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002197std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2198 uint32_t policyFlags) {
2199 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002200 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2201 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2202 const int32_t metaState = getContext()->getGlobalMetaState();
2203 int32_t buttonState = mLastCookedState.buttonState;
2204 while (!releasedButtons.isEmpty()) {
2205 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2206 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002207 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2208 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2209 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002210 mLastCookedState.cookedPointerData.pointerProperties,
2211 mLastCookedState.cookedPointerData.pointerCoords,
2212 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002213 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2214 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002215 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002216 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002217}
2218
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002219std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2220 uint32_t policyFlags) {
2221 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002222 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2223 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2224 const int32_t metaState = getContext()->getGlobalMetaState();
2225 int32_t buttonState = mLastCookedState.buttonState;
2226 while (!pressedButtons.isEmpty()) {
2227 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2228 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002229 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2230 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2231 buttonState, 0,
2232 mCurrentCookedState.cookedPointerData.pointerProperties,
2233 mCurrentCookedState.cookedPointerData.pointerCoords,
2234 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2235 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2236 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002237 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002238 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002239}
2240
LiZhihong758eb562022-11-03 15:28:29 +08002241std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2242 uint32_t policyFlags,
2243 BitSet32 idBits,
2244 nsecs_t readTime) {
2245 std::list<NotifyArgs> out;
2246 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2247 const int32_t metaState = getContext()->getGlobalMetaState();
2248 int32_t buttonState = mLastCookedState.buttonState;
2249
2250 while (!releasedButtons.isEmpty()) {
2251 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2252 buttonState &= ~actionButton;
2253 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2254 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2255 metaState, buttonState, 0,
2256 mPointerGesture.lastGestureProperties,
2257 mPointerGesture.lastGestureCoords,
2258 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2259 mOrientedXPrecision, mOrientedYPrecision,
2260 mPointerGesture.downTime, MotionClassification::NONE));
2261 }
2262 return out;
2263}
2264
2265std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2266 uint32_t policyFlags,
2267 BitSet32 idBits,
2268 nsecs_t readTime) {
2269 std::list<NotifyArgs> out;
2270 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2271 const int32_t metaState = getContext()->getGlobalMetaState();
2272 int32_t buttonState = mLastCookedState.buttonState;
2273
2274 while (!pressedButtons.isEmpty()) {
2275 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2276 buttonState |= actionButton;
2277 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2278 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2279 buttonState, 0, mPointerGesture.currentGestureProperties,
2280 mPointerGesture.currentGestureCoords,
2281 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2282 mOrientedXPrecision, mOrientedYPrecision,
2283 mPointerGesture.downTime, MotionClassification::NONE));
2284 }
2285 return out;
2286}
2287
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002288const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2289 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2290 return cookedPointerData.touchingIdBits;
2291 }
2292 return cookedPointerData.hoveringIdBits;
2293}
2294
2295void TouchInputMapper::cookPointerData() {
2296 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2297
2298 mCurrentCookedState.cookedPointerData.clear();
2299 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2300 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2301 mCurrentRawState.rawPointerData.hoveringIdBits;
2302 mCurrentCookedState.cookedPointerData.touchingIdBits =
2303 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002304 mCurrentCookedState.cookedPointerData.canceledIdBits =
2305 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002306
2307 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2308 mCurrentCookedState.buttonState = 0;
2309 } else {
2310 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2311 }
2312
2313 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002314 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 for (uint32_t i = 0; i < currentPointerCount; i++) {
2316 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2317
2318 // Size
2319 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2320 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002321 case Calibration::SizeCalibration::GEOMETRIC:
2322 case Calibration::SizeCalibration::DIAMETER:
2323 case Calibration::SizeCalibration::BOX:
2324 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002325 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2326 touchMajor = in.touchMajor;
2327 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2328 toolMajor = in.toolMajor;
2329 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2330 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2331 : in.touchMajor;
2332 } else if (mRawPointerAxes.touchMajor.valid) {
2333 toolMajor = touchMajor = in.touchMajor;
2334 toolMinor = touchMinor =
2335 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2336 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2337 : in.touchMajor;
2338 } else if (mRawPointerAxes.toolMajor.valid) {
2339 touchMajor = toolMajor = in.toolMajor;
2340 touchMinor = toolMinor =
2341 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2342 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2343 : in.toolMajor;
2344 } else {
2345 ALOG_ASSERT(false,
2346 "No touch or tool axes. "
2347 "Size calibration should have been resolved to NONE.");
2348 touchMajor = 0;
2349 touchMinor = 0;
2350 toolMajor = 0;
2351 toolMinor = 0;
2352 size = 0;
2353 }
2354
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002355 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2357 if (touchingCount > 1) {
2358 touchMajor /= touchingCount;
2359 touchMinor /= touchingCount;
2360 toolMajor /= touchingCount;
2361 toolMinor /= touchingCount;
2362 size /= touchingCount;
2363 }
2364 }
2365
Michael Wright227c5542020-07-02 18:30:52 +01002366 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002367 touchMajor *= mGeometricScale;
2368 touchMinor *= mGeometricScale;
2369 toolMajor *= mGeometricScale;
2370 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002371 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2373 touchMinor = touchMajor;
2374 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2375 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002376 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 touchMinor = touchMajor;
2378 toolMinor = toolMajor;
2379 }
2380
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002381 mCalibration.applySizeScaleAndBias(touchMajor);
2382 mCalibration.applySizeScaleAndBias(touchMinor);
2383 mCalibration.applySizeScaleAndBias(toolMajor);
2384 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 size *= mSizeScale;
2386 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002387 case Calibration::SizeCalibration::DEFAULT:
2388 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2389 break;
2390 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 touchMajor = 0;
2392 touchMinor = 0;
2393 toolMajor = 0;
2394 toolMinor = 0;
2395 size = 0;
2396 break;
2397 }
2398
2399 // Pressure
2400 float pressure;
2401 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002402 case Calibration::PressureCalibration::PHYSICAL:
2403 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 pressure = in.pressure * mPressureScale;
2405 break;
2406 default:
2407 pressure = in.isHovering ? 0 : 1;
2408 break;
2409 }
2410
2411 // Tilt and Orientation
2412 float tilt;
2413 float orientation;
2414 if (mHaveTilt) {
2415 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2416 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002417 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002418 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2419 } else {
2420 tilt = 0;
2421
2422 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002423 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002424 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 break;
Michael Wright227c5542020-07-02 18:30:52 +01002426 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2428 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2429 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002430 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002431 float confidence = hypotf(c1, c2);
2432 float scale = 1.0f + confidence / 16.0f;
2433 touchMajor *= scale;
2434 touchMinor /= scale;
2435 toolMajor *= scale;
2436 toolMinor /= scale;
2437 } else {
2438 orientation = 0;
2439 }
2440 break;
2441 }
2442 default:
2443 orientation = 0;
2444 }
2445 }
2446
2447 // Distance
2448 float distance;
2449 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002450 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002451 distance = in.distance * mDistanceScale;
2452 break;
2453 default:
2454 distance = 0;
2455 }
2456
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002457 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2458 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002459 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2460 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002462 // Write output coords.
2463 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2464 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002465 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2466 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2468 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2469 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2470 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2471 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2472 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2473 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002474 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2475 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002476
Chris Ye364fdb52020-08-05 15:07:56 -07002477 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002478 uint32_t id = in.id;
2479 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2480 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2481 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002482 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2483 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002484 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2485 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2486 }
2487
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002488 // Write output properties.
2489 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002490 properties.clear();
2491 properties.id = id;
2492 properties.toolType = in.toolType;
2493
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002494 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002495 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002496 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002497 }
2498}
2499
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002500std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2501 uint32_t policyFlags,
2502 PointerUsage pointerUsage) {
2503 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002505 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002506 mPointerUsage = pointerUsage;
2507 }
2508
2509 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002510 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002511 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512 break;
Michael Wright227c5542020-07-02 18:30:52 +01002513 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002514 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002515 break;
Michael Wright227c5542020-07-02 18:30:52 +01002516 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002517 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002518 break;
Michael Wright227c5542020-07-02 18:30:52 +01002519 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002520 break;
2521 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002522 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002523}
2524
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002525std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2526 uint32_t policyFlags) {
2527 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002528 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002529 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002530 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002531 break;
Michael Wright227c5542020-07-02 18:30:52 +01002532 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002533 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 break;
Michael Wright227c5542020-07-02 18:30:52 +01002535 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002536 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002537 break;
Michael Wright227c5542020-07-02 18:30:52 +01002538 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002539 break;
2540 }
2541
Michael Wright227c5542020-07-02 18:30:52 +01002542 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002543 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544}
2545
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002546std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2547 uint32_t policyFlags,
2548 bool isTimeout) {
2549 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002550 // Update current gesture coordinates.
2551 bool cancelPreviousGesture, finishPreviousGesture;
2552 bool sendEvents =
2553 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2554 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002555 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002556 }
2557 if (finishPreviousGesture) {
2558 cancelPreviousGesture = false;
2559 }
2560
2561 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002562 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002563 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002564 if (finishPreviousGesture || cancelPreviousGesture) {
2565 mPointerController->clearSpots();
2566 }
2567
Michael Wright227c5542020-07-02 18:30:52 +01002568 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002569 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2570 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002571 mPointerGesture.currentGestureIdBits,
2572 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002573 }
2574 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002575 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002576 }
2577
2578 // Show or hide the pointer if needed.
2579 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002580 case PointerGesture::Mode::NEUTRAL:
2581 case PointerGesture::Mode::QUIET:
2582 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2583 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002584 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002585 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002586 }
2587 break;
Michael Wright227c5542020-07-02 18:30:52 +01002588 case PointerGesture::Mode::TAP:
2589 case PointerGesture::Mode::TAP_DRAG:
2590 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2591 case PointerGesture::Mode::HOVER:
2592 case PointerGesture::Mode::PRESS:
2593 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002594 // Unfade the pointer when the current gesture manipulates the
2595 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002596 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002597 break;
Michael Wright227c5542020-07-02 18:30:52 +01002598 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002599 // Fade the pointer when the current gesture manipulates a different
2600 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002601 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002602 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002603 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002604 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002605 }
2606 break;
2607 }
2608
2609 // Send events!
2610 int32_t metaState = getContext()->getGlobalMetaState();
2611 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002612 const MotionClassification classification =
2613 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2614 ? MotionClassification::TWO_FINGER_SWIPE
2615 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002616
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002617 uint32_t flags = 0;
2618
2619 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2620 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2621 }
2622
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002623 // Update last coordinates of pointers that have moved so that we observe the new
2624 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002625 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2626 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2627 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2628 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2629 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2630 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002631 bool moveNeeded = false;
2632 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2633 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2634 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2635 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2636 mPointerGesture.lastGestureIdBits.value);
2637 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2638 mPointerGesture.currentGestureCoords,
2639 mPointerGesture.currentGestureIdToIndex,
2640 mPointerGesture.lastGestureProperties,
2641 mPointerGesture.lastGestureCoords,
2642 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2643 if (buttonState != mLastCookedState.buttonState) {
2644 moveNeeded = true;
2645 }
2646 }
2647
2648 // Send motion events for all pointers that went up or were canceled.
2649 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2650 if (!dispatchedGestureIdBits.isEmpty()) {
2651 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002652 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002653 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002654 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002655 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2656 mPointerGesture.lastGestureProperties,
2657 mPointerGesture.lastGestureCoords,
2658 mPointerGesture.lastGestureIdToIndex,
2659 dispatchedGestureIdBits, -1, 0, 0,
2660 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002661
2662 dispatchedGestureIdBits.clear();
2663 } else {
2664 BitSet32 upGestureIdBits;
2665 if (finishPreviousGesture) {
2666 upGestureIdBits = dispatchedGestureIdBits;
2667 } else {
2668 upGestureIdBits.value =
2669 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2670 }
2671 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002672 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2673 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2674 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2675 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2676 readTime);
2677 }
2678 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002679 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2680 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2681 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2682 mPointerGesture.lastGestureProperties,
2683 mPointerGesture.lastGestureCoords,
2684 mPointerGesture.lastGestureIdToIndex,
2685 dispatchedGestureIdBits, id, 0, 0,
2686 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002687
2688 dispatchedGestureIdBits.clearBit(id);
2689 }
2690 }
2691 }
2692
2693 // Send motion events for all pointers that moved.
2694 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002695 out.push_back(
2696 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2697 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2698 mPointerGesture.currentGestureProperties,
2699 mPointerGesture.currentGestureCoords,
2700 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2701 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002702 }
2703
2704 // Send motion events for all pointers that went down.
2705 if (down) {
2706 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2707 ~dispatchedGestureIdBits.value);
2708 while (!downGestureIdBits.isEmpty()) {
2709 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2710 dispatchedGestureIdBits.markBit(id);
2711
2712 if (dispatchedGestureIdBits.count() == 1) {
2713 mPointerGesture.downTime = when;
2714 }
2715
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002716 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2717 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2718 buttonState, 0, mPointerGesture.currentGestureProperties,
2719 mPointerGesture.currentGestureCoords,
2720 mPointerGesture.currentGestureIdToIndex,
2721 dispatchedGestureIdBits, id, 0, 0,
2722 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002723 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2724 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2725 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2726 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2727 readTime);
2728 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002729 }
2730 }
2731
2732 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002733 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002734 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2735 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2736 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2737 mPointerGesture.currentGestureProperties,
2738 mPointerGesture.currentGestureCoords,
2739 mPointerGesture.currentGestureIdToIndex,
2740 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2741 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002742 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2743 // Synthesize a hover move event after all pointers go up to indicate that
2744 // the pointer is hovering again even if the user is not currently touching
2745 // the touch pad. This ensures that a view will receive a fresh hover enter
2746 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002747 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002748
2749 PointerProperties pointerProperties;
2750 pointerProperties.clear();
2751 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002752 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002753
2754 PointerCoords pointerCoords;
2755 pointerCoords.clear();
2756 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2757 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2758
2759 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002760 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2761 mSource, displayId, policyFlags,
2762 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2763 buttonState, MotionClassification::NONE,
2764 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2765 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00002766 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002767 }
2768
2769 // Update state.
2770 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2771 if (!down) {
2772 mPointerGesture.lastGestureIdBits.clear();
2773 } else {
2774 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2775 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2776 uint32_t id = idBits.clearFirstMarkedBit();
2777 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002778 mPointerGesture.lastGestureProperties[index] =
2779 mPointerGesture.currentGestureProperties[index];
2780 mPointerGesture.lastGestureCoords[index] = mPointerGesture.currentGestureCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002781 mPointerGesture.lastGestureIdToIndex[id] = index;
2782 }
2783 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002784 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002785}
2786
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002787std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2788 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002789 const MotionClassification classification =
2790 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2791 ? MotionClassification::TWO_FINGER_SWIPE
2792 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002793 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002794 // Cancel previously dispatches pointers.
2795 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2796 int32_t metaState = getContext()->getGlobalMetaState();
2797 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002798 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002799 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2800 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002801 mPointerGesture.lastGestureProperties,
2802 mPointerGesture.lastGestureCoords,
2803 mPointerGesture.lastGestureIdToIndex,
2804 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2805 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806 }
2807
2808 // Reset the current pointer gesture.
2809 mPointerGesture.reset();
2810 mPointerVelocityControl.reset();
2811
2812 // Remove any current spots.
2813 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002814 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002815 mPointerController->clearSpots();
2816 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002817 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002818}
2819
2820bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2821 bool* outFinishPreviousGesture, bool isTimeout) {
2822 *outCancelPreviousGesture = false;
2823 *outFinishPreviousGesture = false;
2824
2825 // Handle TAP timeout.
2826 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002827 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002828
Michael Wright227c5542020-07-02 18:30:52 +01002829 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2831 // The tap/drag timeout has not yet expired.
2832 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2833 mConfig.pointerGestureTapDragInterval);
2834 } else {
2835 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002836 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002837 *outFinishPreviousGesture = true;
2838
2839 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002840 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002841 mPointerGesture.currentGestureIdBits.clear();
2842
2843 mPointerVelocityControl.reset();
2844 return true;
2845 }
2846 }
2847
2848 // We did not handle this timeout.
2849 return false;
2850 }
2851
2852 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2853 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2854
2855 // Update the velocity tracker.
2856 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002857 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002858 uint32_t id = idBits.clearFirstMarkedBit();
2859 const RawPointerData::Pointer& pointer =
2860 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002861 const float x = pointer.x * mPointerXMovementScale;
2862 const float y = pointer.y * mPointerYMovementScale;
2863 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2864 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002865 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002866 }
2867
2868 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2869 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002870 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2871 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2872 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002873 mPointerGesture.resetTap();
2874 }
2875
2876 // Pick a new active touch id if needed.
2877 // Choose an arbitrary pointer that just went down, if there is one.
2878 // Otherwise choose an arbitrary remaining pointer.
2879 // This guarantees we always have an active touch id when there is at least one pointer.
2880 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002881 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002882 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002883 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884 mPointerGesture.firstTouchTime = when;
2885 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002886 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2887 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2888 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2889 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002890 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002891 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892
2893 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002894 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002896 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2897 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2898 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002899 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002900 *outFinishPreviousGesture = true;
2901 }
2902
2903 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002904 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002905 mPointerGesture.currentGestureIdBits.clear();
2906
2907 mPointerVelocityControl.reset();
2908 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2909 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2910 // The pointer follows the active touch point.
2911 // Emit DOWN, MOVE, UP events at the pointer location.
2912 //
2913 // Only the active touch matters; other fingers are ignored. This policy helps
2914 // to handle the case where the user places a second finger on the touch pad
2915 // to apply the necessary force to depress an integrated button below the surface.
2916 // We don't want the second finger to be delivered to applications.
2917 //
2918 // For this to work well, we need to make sure to track the pointer that is really
2919 // active. If the user first puts one finger down to click then adds another
2920 // finger to drag then the active pointer should switch to the finger that is
2921 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002922 ALOGD_IF(DEBUG_GESTURES,
2923 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2924 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002925 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002926 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002927 *outFinishPreviousGesture = true;
2928 mPointerGesture.activeGestureId = 0;
2929 }
2930
2931 // Switch pointers if needed.
2932 // Find the fastest pointer and follow it.
2933 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002934 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002935 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002936 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002937 ALOGD_IF(DEBUG_GESTURES,
2938 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2939 "bestSpeed=%0.3f",
2940 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002941 }
2942 }
2943
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002945 // When using spots, the click will occur at the position of the anchor
2946 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002947 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002948 } else {
2949 mPointerVelocityControl.reset();
2950 }
2951
Prabir Pradhan2719e822023-02-28 17:39:36 +00002952 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002953
Michael Wright227c5542020-07-02 18:30:52 +01002954 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002955 mPointerGesture.currentGestureIdBits.clear();
2956 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2957 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2958 mPointerGesture.currentGestureProperties[0].clear();
2959 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002960 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002961 mPointerGesture.currentGestureCoords[0].clear();
2962 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2963 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2964 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2965 } else if (currentFingerCount == 0) {
2966 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002967 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002968 *outFinishPreviousGesture = true;
2969 }
2970
2971 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2972 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2973 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002974 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2975 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002976 lastFingerCount == 1) {
2977 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002978 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002979 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2980 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002981 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002982
2983 mPointerGesture.tapUpTime = when;
2984 getContext()->requestTimeoutAtTime(when +
2985 mConfig.pointerGestureTapDragInterval);
2986
2987 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002988 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002989 mPointerGesture.currentGestureIdBits.clear();
2990 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2991 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2992 mPointerGesture.currentGestureProperties[0].clear();
2993 mPointerGesture.currentGestureProperties[0].id =
2994 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002995 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002996 mPointerGesture.currentGestureCoords[0].clear();
2997 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2998 mPointerGesture.tapX);
2999 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3000 mPointerGesture.tapY);
3001 mPointerGesture.currentGestureCoords[0]
3002 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3003
3004 tapped = true;
3005 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003006 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
3007 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003008 }
3009 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003010 if (DEBUG_GESTURES) {
3011 if (mPointerGesture.tapDownTime != LLONG_MIN) {
3012 ALOGD("Gestures: Not a TAP, %0.3fms since down",
3013 (when - mPointerGesture.tapDownTime) * 0.000001f);
3014 } else {
3015 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
3016 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003017 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003018 }
3019 }
3020
3021 mPointerVelocityControl.reset();
3022
3023 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00003024 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003025 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01003026 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003027 mPointerGesture.currentGestureIdBits.clear();
3028 }
3029 } else if (currentFingerCount == 1) {
3030 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3031 // The pointer follows the active touch point.
3032 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3033 // When in TAP_DRAG, emit MOVE events at the pointer location.
3034 ALOG_ASSERT(activeTouchId >= 0);
3035
Michael Wright227c5542020-07-02 18:30:52 +01003036 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3037 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003038 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003039 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003040 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3041 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003042 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003043 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003044 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3045 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003046 }
3047 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003048 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3049 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003050 }
Michael Wright227c5542020-07-02 18:30:52 +01003051 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3052 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003053 }
3054
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003055 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003056 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003057 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003058 } else {
3059 mPointerVelocityControl.reset();
3060 }
3061
3062 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003063 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003064 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003065 down = true;
3066 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003067 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003068 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003069 *outFinishPreviousGesture = true;
3070 }
3071 mPointerGesture.activeGestureId = 0;
3072 down = false;
3073 }
3074
Prabir Pradhan2719e822023-02-28 17:39:36 +00003075 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003076
3077 mPointerGesture.currentGestureIdBits.clear();
3078 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3079 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3080 mPointerGesture.currentGestureProperties[0].clear();
3081 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003082 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003083 mPointerGesture.currentGestureCoords[0].clear();
3084 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3085 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3086 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3087 down ? 1.0f : 0.0f);
3088
3089 if (lastFingerCount == 0 && currentFingerCount != 0) {
3090 mPointerGesture.resetTap();
3091 mPointerGesture.tapDownTime = when;
3092 mPointerGesture.tapX = x;
3093 mPointerGesture.tapY = y;
3094 }
3095 } else {
3096 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003097 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003098 }
3099
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003100 if (DEBUG_GESTURES) {
3101 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3102 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3103 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3104 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3105 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3106 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3107 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3108 uint32_t id = idBits.clearFirstMarkedBit();
3109 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3110 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3111 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003112 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003113 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003114 id, index, ftl::enum_string(properties.toolType).c_str(),
3115 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003116 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3117 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3118 }
3119 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3120 uint32_t id = idBits.clearFirstMarkedBit();
3121 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3122 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3123 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003124 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003125 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003126 id, index, ftl::enum_string(properties.toolType).c_str(),
3127 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003128 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3129 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3130 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003131 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003132 return true;
3133}
3134
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003135bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3136 if (mPointerGesture.activeTouchId < 0) {
3137 mPointerGesture.resetQuietTime();
3138 return false;
3139 }
3140
3141 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3142 return true;
3143 }
3144
3145 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3146 bool isQuietTime = false;
3147 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3148 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3149 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3150 currentFingerCount < 2) {
3151 // Enter quiet time when exiting swipe or freeform state.
3152 // This is to prevent accidentally entering the hover state and flinging the
3153 // pointer when finishing a swipe and there is still one pointer left onscreen.
3154 isQuietTime = true;
3155 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3156 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3157 // Enter quiet time when releasing the button and there are still two or more
3158 // fingers down. This may indicate that one finger was used to press the button
3159 // but it has not gone up yet.
3160 isQuietTime = true;
3161 }
3162 if (isQuietTime) {
3163 mPointerGesture.quietTime = when;
3164 }
3165 return isQuietTime;
3166}
3167
3168std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3169 int32_t bestId = -1;
3170 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3171 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3172 uint32_t id = idBits.clearFirstMarkedBit();
3173 std::optional<float> vx =
3174 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3175 std::optional<float> vy =
3176 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3177 if (vx && vy) {
3178 float speed = hypotf(*vx, *vy);
3179 if (speed > bestSpeed) {
3180 bestId = id;
3181 bestSpeed = speed;
3182 }
3183 }
3184 }
3185 return std::make_pair(bestId, bestSpeed);
3186}
3187
3188void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3189 bool* finishPreviousGesture) {
3190 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3191 // to move before deciding what to do.
3192 //
3193 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3194 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3195 // just a press or long-press at the pointer location.
3196 //
3197 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3198 // pointer location.
3199 //
3200 // When the two fingers move enough or when additional fingers are added, we make a decision to
3201 // transition into SWIPE or FREEFORM mode accordingly.
3202 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3203 ALOG_ASSERT(activeTouchId >= 0);
3204
3205 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3206 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3207 bool settled =
3208 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3209 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3210 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3211 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3212 *finishPreviousGesture = true;
3213 } else if (!settled && currentFingerCount > lastFingerCount) {
3214 // Additional pointers have gone down but not yet settled.
3215 // Reset the gesture.
3216 ALOGD_IF(DEBUG_GESTURES,
3217 "Gestures: Resetting gesture since additional pointers went down for "
3218 "MULTITOUCH, settle time remaining %0.3fms",
3219 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3220 when) * 0.000001f);
3221 *cancelPreviousGesture = true;
3222 } else {
3223 // Continue previous gesture.
3224 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3225 }
3226
3227 if (*finishPreviousGesture || *cancelPreviousGesture) {
3228 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3229 mPointerGesture.activeGestureId = 0;
3230 mPointerGesture.referenceIdBits.clear();
3231 mPointerVelocityControl.reset();
3232
3233 // Use the centroid and pointer location as the reference points for the gesture.
3234 ALOGD_IF(DEBUG_GESTURES,
3235 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3236 "%0.3fms",
3237 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3238 when) * 0.000001f);
3239 mCurrentRawState.rawPointerData
3240 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3241 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003242 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3243 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003244 }
3245
3246 // Clear the reference deltas for fingers not yet included in the reference calculation.
3247 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3248 ~mPointerGesture.referenceIdBits.value);
3249 !idBits.isEmpty();) {
3250 uint32_t id = idBits.clearFirstMarkedBit();
3251 mPointerGesture.referenceDeltas[id].dx = 0;
3252 mPointerGesture.referenceDeltas[id].dy = 0;
3253 }
3254 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3255
3256 // Add delta for all fingers and calculate a common movement delta.
3257 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3258 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3259 mCurrentCookedState.fingerIdBits.value);
3260 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3261 bool first = (idBits == commonIdBits);
3262 uint32_t id = idBits.clearFirstMarkedBit();
3263 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3264 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3265 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3266 delta.dx += cpd.x - lpd.x;
3267 delta.dy += cpd.y - lpd.y;
3268
3269 if (first) {
3270 commonDeltaRawX = delta.dx;
3271 commonDeltaRawY = delta.dy;
3272 } else {
3273 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3274 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3275 }
3276 }
3277
3278 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3279 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3280 float dist[MAX_POINTER_ID + 1];
3281 int32_t distOverThreshold = 0;
3282 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3283 uint32_t id = idBits.clearFirstMarkedBit();
3284 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3285 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3286 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3287 distOverThreshold += 1;
3288 }
3289 }
3290
3291 // Only transition when at least two pointers have moved further than
3292 // the minimum distance threshold.
3293 if (distOverThreshold >= 2) {
3294 if (currentFingerCount > 2) {
3295 // There are more than two pointers, switch to FREEFORM.
3296 ALOGD_IF(DEBUG_GESTURES,
3297 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3298 currentFingerCount);
3299 *cancelPreviousGesture = true;
3300 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3301 } else {
3302 // There are exactly two pointers.
3303 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3304 uint32_t id1 = idBits.clearFirstMarkedBit();
3305 uint32_t id2 = idBits.firstMarkedBit();
3306 const RawPointerData::Pointer& p1 =
3307 mCurrentRawState.rawPointerData.pointerForId(id1);
3308 const RawPointerData::Pointer& p2 =
3309 mCurrentRawState.rawPointerData.pointerForId(id2);
3310 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3311 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3312 // There are two pointers but they are too far apart for a SWIPE,
3313 // switch to FREEFORM.
3314 ALOGD_IF(DEBUG_GESTURES,
3315 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3316 mutualDistance, mPointerGestureMaxSwipeWidth);
3317 *cancelPreviousGesture = true;
3318 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3319 } else {
3320 // There are two pointers. Wait for both pointers to start moving
3321 // before deciding whether this is a SWIPE or FREEFORM gesture.
3322 float dist1 = dist[id1];
3323 float dist2 = dist[id2];
3324 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3325 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3326 // Calculate the dot product of the displacement vectors.
3327 // When the vectors are oriented in approximately the same direction,
3328 // the angle betweeen them is near zero and the cosine of the angle
3329 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3330 // mag(v2).
3331 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3332 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3333 float dx1 = delta1.dx * mPointerXZoomScale;
3334 float dy1 = delta1.dy * mPointerYZoomScale;
3335 float dx2 = delta2.dx * mPointerXZoomScale;
3336 float dy2 = delta2.dy * mPointerYZoomScale;
3337 float dot = dx1 * dx2 + dy1 * dy2;
3338 float cosine = dot / (dist1 * dist2); // denominator always > 0
3339 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3340 // Pointers are moving in the same direction. Switch to SWIPE.
3341 ALOGD_IF(DEBUG_GESTURES,
3342 "Gestures: PRESS transitioned to SWIPE, "
3343 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3344 "cosine %0.3f >= %0.3f",
3345 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3346 mConfig.pointerGestureMultitouchMinDistance, cosine,
3347 mConfig.pointerGestureSwipeTransitionAngleCosine);
3348 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3349 } else {
3350 // Pointers are moving in different directions. Switch to FREEFORM.
3351 ALOGD_IF(DEBUG_GESTURES,
3352 "Gestures: PRESS transitioned to FREEFORM, "
3353 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3354 "cosine %0.3f < %0.3f",
3355 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3356 mConfig.pointerGestureMultitouchMinDistance, cosine,
3357 mConfig.pointerGestureSwipeTransitionAngleCosine);
3358 *cancelPreviousGesture = true;
3359 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3360 }
3361 }
3362 }
3363 }
3364 }
3365 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3366 // Switch from SWIPE to FREEFORM if additional pointers go down.
3367 // Cancel previous gesture.
3368 if (currentFingerCount > 2) {
3369 ALOGD_IF(DEBUG_GESTURES,
3370 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3371 currentFingerCount);
3372 *cancelPreviousGesture = true;
3373 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3374 }
3375 }
3376
3377 // Move the reference points based on the overall group motion of the fingers
3378 // except in PRESS mode while waiting for a transition to occur.
3379 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3380 (commonDeltaRawX || commonDeltaRawY)) {
3381 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3382 uint32_t id = idBits.clearFirstMarkedBit();
3383 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3384 delta.dx = 0;
3385 delta.dy = 0;
3386 }
3387
3388 mPointerGesture.referenceTouchX += commonDeltaRawX;
3389 mPointerGesture.referenceTouchY += commonDeltaRawY;
3390
3391 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3392 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3393
3394 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3395 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3396
3397 mPointerGesture.referenceGestureX += commonDeltaX;
3398 mPointerGesture.referenceGestureY += commonDeltaY;
3399 }
3400
3401 // Report gestures.
3402 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3403 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3404 // PRESS or SWIPE mode.
3405 ALOGD_IF(DEBUG_GESTURES,
3406 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3407 "currentTouchPointerCount=%d",
3408 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3409 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3410
3411 mPointerGesture.currentGestureIdBits.clear();
3412 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3413 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3414 mPointerGesture.currentGestureProperties[0].clear();
3415 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003416 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003417 mPointerGesture.currentGestureCoords[0].clear();
3418 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3419 mPointerGesture.referenceGestureX);
3420 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3421 mPointerGesture.referenceGestureY);
3422 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3423 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3424 float xOffset = static_cast<float>(commonDeltaRawX) /
3425 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3426 float yOffset = static_cast<float>(commonDeltaRawY) /
3427 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3428 mPointerGesture.currentGestureCoords[0]
3429 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3430 mPointerGesture.currentGestureCoords[0]
3431 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3432 }
3433 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3434 // FREEFORM mode.
3435 ALOGD_IF(DEBUG_GESTURES,
3436 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3437 "currentTouchPointerCount=%d",
3438 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3439 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3440
3441 mPointerGesture.currentGestureIdBits.clear();
3442
3443 BitSet32 mappedTouchIdBits;
3444 BitSet32 usedGestureIdBits;
3445 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3446 // Initially, assign the active gesture id to the active touch point
3447 // if there is one. No other touch id bits are mapped yet.
3448 if (!*cancelPreviousGesture) {
3449 mappedTouchIdBits.markBit(activeTouchId);
3450 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3451 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3452 mPointerGesture.activeGestureId;
3453 } else {
3454 mPointerGesture.activeGestureId = -1;
3455 }
3456 } else {
3457 // Otherwise, assume we mapped all touches from the previous frame.
3458 // Reuse all mappings that are still applicable.
3459 mappedTouchIdBits.value =
3460 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3461 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3462
3463 // Check whether we need to choose a new active gesture id because the
3464 // current went went up.
3465 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3466 ~mCurrentCookedState.fingerIdBits.value);
3467 !upTouchIdBits.isEmpty();) {
3468 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3469 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3470 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3471 mPointerGesture.activeGestureId = -1;
3472 break;
3473 }
3474 }
3475 }
3476
3477 ALOGD_IF(DEBUG_GESTURES,
3478 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3479 "activeGestureId=%d",
3480 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3481
3482 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3483 for (uint32_t i = 0; i < currentFingerCount; i++) {
3484 uint32_t touchId = idBits.clearFirstMarkedBit();
3485 uint32_t gestureId;
3486 if (!mappedTouchIdBits.hasBit(touchId)) {
3487 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3488 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3489 ALOGD_IF(DEBUG_GESTURES,
3490 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3491 gestureId);
3492 } else {
3493 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3494 ALOGD_IF(DEBUG_GESTURES,
3495 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3496 touchId, gestureId);
3497 }
3498 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3499 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3500
3501 const RawPointerData::Pointer& pointer =
3502 mCurrentRawState.rawPointerData.pointerForId(touchId);
3503 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3504 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3505 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3506
3507 mPointerGesture.currentGestureProperties[i].clear();
3508 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003509 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003510 mPointerGesture.currentGestureCoords[i].clear();
3511 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3512 mPointerGesture.referenceGestureX +
3513 deltaX);
3514 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3515 mPointerGesture.referenceGestureY +
3516 deltaY);
3517 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3518 }
3519
3520 if (mPointerGesture.activeGestureId < 0) {
3521 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3522 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3523 mPointerGesture.activeGestureId);
3524 }
3525 }
3526}
3527
Harry Cutts714d1ad2022-08-24 16:36:43 +00003528void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3529 const RawPointerData::Pointer& currentPointer =
3530 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3531 const RawPointerData::Pointer& lastPointer =
3532 mLastRawState.rawPointerData.pointerForId(pointerId);
3533 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3534 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3535
3536 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3537 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3538
3539 mPointerController->move(deltaX, deltaY);
3540}
3541
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003542std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3543 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003544 mPointerSimple.currentCoords.clear();
3545 mPointerSimple.currentProperties.clear();
3546
3547 bool down, hovering;
3548 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3549 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3550 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003551 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3552 down = !hovering;
3553
Prabir Pradhane71e5702023-03-29 14:51:38 +00003554 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3555 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3556 // Styluses are configured specifically for one display. We only update the
3557 // PointerController for this stylus if the PointerController is configured for
3558 // the same display as this stylus,
3559 if (getAssociatedDisplayId() == mViewport.displayId) {
3560 mPointerController->setPosition(x, y);
3561 std::tie(x, y) = mPointerController->getPosition();
3562 }
3563
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003564 mPointerSimple.currentCoords = mCurrentCookedState.cookedPointerData.pointerCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003565 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3566 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3567 mPointerSimple.currentProperties.id = 0;
3568 mPointerSimple.currentProperties.toolType =
3569 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3570 } else {
3571 down = false;
3572 hovering = false;
3573 }
3574
Prabir Pradhane71e5702023-03-29 14:51:38 +00003575 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003576}
3577
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003578std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3579 uint32_t policyFlags) {
3580 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003581}
3582
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003583std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3584 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003585 mPointerSimple.currentCoords.clear();
3586 mPointerSimple.currentProperties.clear();
3587
3588 bool down, hovering;
3589 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3590 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003591 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003592 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593 } else {
3594 mPointerVelocityControl.reset();
3595 }
3596
3597 down = isPointerDown(mCurrentRawState.buttonState);
3598 hovering = !down;
3599
Prabir Pradhan2719e822023-02-28 17:39:36 +00003600 const auto [x, y] = mPointerController->getPosition();
3601 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003602 mPointerSimple.currentCoords =
3603 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003604 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3605 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3606 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3607 hovering ? 0.0f : 1.0f);
3608 mPointerSimple.currentProperties.id = 0;
3609 mPointerSimple.currentProperties.toolType =
3610 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3611 } else {
3612 mPointerVelocityControl.reset();
3613
3614 down = false;
3615 hovering = false;
3616 }
3617
Prabir Pradhane71e5702023-03-29 14:51:38 +00003618 const int32_t displayId = mPointerController->getDisplayId();
3619 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003620}
3621
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003622std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3623 uint32_t policyFlags) {
3624 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003625
3626 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003627
3628 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003629}
3630
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003631std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3632 uint32_t policyFlags, bool down,
Prabir Pradhane71e5702023-03-29 14:51:38 +00003633 bool hovering, int32_t displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003634 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3635 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003636 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003637 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003638 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003639
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003640 if (displayId == mPointerController->getDisplayId()) {
3641 std::tie(cursorPosition.x, cursorPosition.y) = mPointerController->getPosition();
3642 if (down || hovering) {
3643 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
3644 mPointerController->clearSpots();
3645 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3646 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
3647 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3648 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003649 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003650
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003651 if (mPointerSimple.down && !down) {
3652 mPointerSimple.down = false;
3653
3654 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003655 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3656 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3657 0, metaState, mLastRawState.buttonState,
3658 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3659 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003660 mOrientedXPrecision, mOrientedYPrecision,
3661 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3662 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003663 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003664 }
3665
3666 if (mPointerSimple.hovering && !hovering) {
3667 mPointerSimple.hovering = false;
3668
3669 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003670 out.push_back(
3671 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3672 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3673 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3674 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3675 &mPointerSimple.lastCoords, mOrientedXPrecision,
3676 mOrientedYPrecision, mPointerSimple.lastCursorX,
3677 mPointerSimple.lastCursorY, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003678 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003679 }
3680
3681 if (down) {
3682 if (!mPointerSimple.down) {
3683 mPointerSimple.down = true;
3684 mPointerSimple.downTime = when;
3685
3686 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003687 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3688 mSource, displayId, policyFlags,
3689 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3690 mCurrentRawState.buttonState, MotionClassification::NONE,
3691 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3692 &mPointerSimple.currentProperties,
3693 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003694 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003695 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003696 }
3697
3698 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003699 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3700 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3701 0, 0, metaState, mCurrentRawState.buttonState,
3702 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3703 &mPointerSimple.currentProperties,
3704 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003705 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003706 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003707 }
3708
3709 if (hovering) {
3710 if (!mPointerSimple.hovering) {
3711 mPointerSimple.hovering = true;
3712
3713 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003714 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3715 mSource, displayId, policyFlags,
3716 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3717 mCurrentRawState.buttonState, MotionClassification::NONE,
3718 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3719 &mPointerSimple.currentProperties,
3720 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003721 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003722 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003723 }
3724
3725 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003726 out.push_back(
3727 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3728 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3729 metaState, mCurrentRawState.buttonState,
3730 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3731 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003732 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003733 cursorPosition.y, mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003734 }
3735
3736 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3737 float vscroll = mCurrentRawState.rawVScroll;
3738 float hscroll = mCurrentRawState.rawHScroll;
3739 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3740 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3741
3742 // Send scroll.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003743 PointerCoords pointerCoords = mPointerSimple.currentCoords;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003744 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3745 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3746
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003747 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3748 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3749 0, 0, metaState, mCurrentRawState.buttonState,
3750 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3751 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003752 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3753 cursorPosition.y, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003754 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003755 }
3756
3757 // Save state.
3758 if (down || hovering) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003759 mPointerSimple.lastCoords = mPointerSimple.currentCoords;
3760 mPointerSimple.lastProperties = mPointerSimple.currentProperties;
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003761 mPointerSimple.displayId = displayId;
3762 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003763 mPointerSimple.lastCursorX = cursorPosition.x;
3764 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003765 } else {
3766 mPointerSimple.reset();
3767 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003768 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003769}
3770
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003771std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3772 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003773 std::list<NotifyArgs> out;
3774 if (mPointerSimple.down || mPointerSimple.hovering) {
3775 int32_t metaState = getContext()->getGlobalMetaState();
3776 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3777 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3778 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3779 metaState, mLastRawState.buttonState,
3780 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3781 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3782 mOrientedXPrecision, mOrientedYPrecision,
3783 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3784 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003785 /*videoFrames=*/{}));
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003786 if (mPointerController != nullptr) {
3787 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3788 }
3789 }
3790 mPointerSimple.reset();
3791 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003792}
3793
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003794NotifyMotionArgs TouchInputMapper::dispatchMotion(
3795 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3796 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003797 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3798 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003799 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003800 std::vector<PointerCoords> pointerCoords;
3801 std::vector<PointerProperties> pointerProperties;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003802 uint32_t pointerCount = 0;
3803 while (!idBits.isEmpty()) {
3804 uint32_t id = idBits.clearFirstMarkedBit();
3805 uint32_t index = idToIndex[id];
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003806 pointerProperties.push_back(properties[index]);
3807 pointerCoords.push_back(coords[index]);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003808
3809 if (changedId >= 0 && id == uint32_t(changedId)) {
3810 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3811 }
3812
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003813 pointerCount++;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003814 }
3815
3816 ALOG_ASSERT(pointerCount != 0);
3817
3818 if (changedId >= 0 && pointerCount == 1) {
3819 // Replace initial down and final up action.
3820 // We can compare the action without masking off the changed pointer index
3821 // because we know the index is 0.
3822 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3823 action = AMOTION_EVENT_ACTION_DOWN;
3824 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003825 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3826 action = AMOTION_EVENT_ACTION_CANCEL;
3827 } else {
3828 action = AMOTION_EVENT_ACTION_UP;
3829 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003830 } else {
3831 // Can't happen.
3832 ALOG_ASSERT(false);
3833 }
3834 }
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00003835 if (mCurrentStreamModifiedByExternalStylus) {
3836 source |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3837 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003838
3839 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3840 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003841 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003842 mPointerController && displayId != ADISPLAY_ID_NONE &&
3843 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003844 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003845 switch (action & AMOTION_EVENT_ACTION_MASK) {
3846 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3847 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3848 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003849 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003850 mPointerController
3851 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3852 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3853 .getY());
3854 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3855 break;
3856 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3857 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3858 break;
3859 }
3860 }
3861
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003862 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3863 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003864 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003865 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003866 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003867 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003868 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003869 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003870 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003871 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3872 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003873 classification, edgeFlags, pointerCount, pointerProperties.data(),
3874 pointerCoords.data(), xPrecision, yPrecision, xCursorPosition,
3875 yCursorPosition, downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003876}
3877
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003878std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3879 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003880 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3881 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003882 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003883}
3884
Prabir Pradhan1728b212021-10-19 16:00:03 -07003885bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003886 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003887 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003888 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003889}
3890
3891const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3892 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003893 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3894 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3895 "left=%d, top=%d, right=%d, bottom=%d",
3896 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3897 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003898
3899 if (virtualKey.isHit(x, y)) {
3900 return &virtualKey;
3901 }
3902 }
3903
3904 return nullptr;
3905}
3906
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003907void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3908 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3909 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003910
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003911 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003912
3913 if (currentPointerCount == 0) {
3914 // No pointers to assign.
3915 return;
3916 }
3917
3918 if (lastPointerCount == 0) {
3919 // All pointers are new.
3920 for (uint32_t i = 0; i < currentPointerCount; i++) {
3921 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003922 current.rawPointerData.pointers[i].id = id;
3923 current.rawPointerData.idToIndex[id] = i;
3924 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003925 }
3926 return;
3927 }
3928
3929 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003930 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003931 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003932 uint32_t id = last.rawPointerData.pointers[0].id;
3933 current.rawPointerData.pointers[0].id = id;
3934 current.rawPointerData.idToIndex[id] = 0;
3935 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003936 return;
3937 }
3938
3939 // General case.
3940 // We build a heap of squared euclidean distances between current and last pointers
3941 // associated with the current and last pointer indices. Then, we find the best
3942 // match (by distance) for each current pointer.
3943 // The pointers must have the same tool type but it is possible for them to
3944 // transition from hovering to touching or vice-versa while retaining the same id.
3945 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3946
3947 uint32_t heapSize = 0;
3948 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3949 currentPointerIndex++) {
3950 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3951 lastPointerIndex++) {
3952 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003953 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003954 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003955 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003956 if (currentPointer.toolType == lastPointer.toolType) {
3957 int64_t deltaX = currentPointer.x - lastPointer.x;
3958 int64_t deltaY = currentPointer.y - lastPointer.y;
3959
3960 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3961
3962 // Insert new element into the heap (sift up).
3963 heap[heapSize].currentPointerIndex = currentPointerIndex;
3964 heap[heapSize].lastPointerIndex = lastPointerIndex;
3965 heap[heapSize].distance = distance;
3966 heapSize += 1;
3967 }
3968 }
3969 }
3970
3971 // Heapify
3972 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3973 startIndex -= 1;
3974 for (uint32_t parentIndex = startIndex;;) {
3975 uint32_t childIndex = parentIndex * 2 + 1;
3976 if (childIndex >= heapSize) {
3977 break;
3978 }
3979
3980 if (childIndex + 1 < heapSize &&
3981 heap[childIndex + 1].distance < heap[childIndex].distance) {
3982 childIndex += 1;
3983 }
3984
3985 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3986 break;
3987 }
3988
3989 swap(heap[parentIndex], heap[childIndex]);
3990 parentIndex = childIndex;
3991 }
3992 }
3993
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003994 if (DEBUG_POINTER_ASSIGNMENT) {
3995 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3996 for (size_t i = 0; i < heapSize; i++) {
3997 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3998 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3999 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004000 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004001
4002 // Pull matches out by increasing order of distance.
4003 // To avoid reassigning pointers that have already been matched, the loop keeps track
4004 // of which last and current pointers have been matched using the matchedXXXBits variables.
4005 // It also tracks the used pointer id bits.
4006 BitSet32 matchedLastBits(0);
4007 BitSet32 matchedCurrentBits(0);
4008 BitSet32 usedIdBits(0);
4009 bool first = true;
4010 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
4011 while (heapSize > 0) {
4012 if (first) {
4013 // The first time through the loop, we just consume the root element of
4014 // the heap (the one with smallest distance).
4015 first = false;
4016 } else {
4017 // Previous iterations consumed the root element of the heap.
4018 // Pop root element off of the heap (sift down).
4019 heap[0] = heap[heapSize];
4020 for (uint32_t parentIndex = 0;;) {
4021 uint32_t childIndex = parentIndex * 2 + 1;
4022 if (childIndex >= heapSize) {
4023 break;
4024 }
4025
4026 if (childIndex + 1 < heapSize &&
4027 heap[childIndex + 1].distance < heap[childIndex].distance) {
4028 childIndex += 1;
4029 }
4030
4031 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4032 break;
4033 }
4034
4035 swap(heap[parentIndex], heap[childIndex]);
4036 parentIndex = childIndex;
4037 }
4038
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004039 if (DEBUG_POINTER_ASSIGNMENT) {
4040 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4041 for (size_t j = 0; j < heapSize; j++) {
4042 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4043 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4044 heap[j].distance);
4045 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004046 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004047 }
4048
4049 heapSize -= 1;
4050
4051 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4052 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4053
4054 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4055 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4056
4057 matchedCurrentBits.markBit(currentPointerIndex);
4058 matchedLastBits.markBit(lastPointerIndex);
4059
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004060 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4061 current.rawPointerData.pointers[currentPointerIndex].id = id;
4062 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4063 current.rawPointerData.markIdBit(id,
4064 current.rawPointerData.isHovering(
4065 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004066 usedIdBits.markBit(id);
4067
Harry Cutts45483602022-08-24 14:36:48 +00004068 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4069 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4070 ", distance=%" PRIu64,
4071 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004072 break;
4073 }
4074 }
4075
4076 // Assign fresh ids to pointers that were not matched in the process.
4077 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4078 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4079 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4080
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004081 current.rawPointerData.pointers[currentPointerIndex].id = id;
4082 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4083 current.rawPointerData.markIdBit(id,
4084 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004085
Harry Cutts45483602022-08-24 14:36:48 +00004086 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4087 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4088 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004089 }
4090}
4091
4092int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4093 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4094 return AKEY_STATE_VIRTUAL;
4095 }
4096
4097 for (const VirtualKey& virtualKey : mVirtualKeys) {
4098 if (virtualKey.keyCode == keyCode) {
4099 return AKEY_STATE_UP;
4100 }
4101 }
4102
4103 return AKEY_STATE_UNKNOWN;
4104}
4105
4106int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4107 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4108 return AKEY_STATE_VIRTUAL;
4109 }
4110
4111 for (const VirtualKey& virtualKey : mVirtualKeys) {
4112 if (virtualKey.scanCode == scanCode) {
4113 return AKEY_STATE_UP;
4114 }
4115 }
4116
4117 return AKEY_STATE_UNKNOWN;
4118}
4119
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004120bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4121 const std::vector<int32_t>& keyCodes,
4122 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004123 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004124 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004125 if (virtualKey.keyCode == keyCodes[i]) {
4126 outFlags[i] = 1;
4127 }
4128 }
4129 }
4130
4131 return true;
4132}
4133
4134std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4135 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004136 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004137 return std::make_optional(mPointerController->getDisplayId());
4138 } else {
4139 return std::make_optional(mViewport.displayId);
4140 }
4141 }
4142 return std::nullopt;
4143}
4144
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004145} // namespace android