blob: 81449d15887e864280eeb6e55ea2e959b055a520 [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
Michael Crimandob12a7492023-05-22 11:01:17 -0400541 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) {
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001072 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %s, mode %s, "
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(),
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001075 ftl::enum_string(mInputDeviceOrientation).c_str(),
1076 ftl::enum_string(mDeviceMode).c_str(), mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001077
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001078 configureVirtualKeys();
1079
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001080 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001081
1082 // Location
1083 updateAffineTransformation();
1084
Michael Wright227c5542020-07-02 18:30:52 +01001085 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001087 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1088 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001089
1090 // Scale movements such that one whole swipe of the touch pad covers a
1091 // given area relative to the diagonal size of the display when no acceleration
1092 // is applied.
1093 // Assume that the touch pad has a square aspect ratio such that movements in
1094 // X and Y of the same number of raw units cover the same physical distance.
1095 mPointerXMovementScale =
1096 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1097 mPointerYMovementScale = mPointerXMovementScale;
1098
1099 // Scale zooms to cover a smaller range of the display than movements do.
1100 // This value determines the area around the pointer that is affected by freeform
1101 // pointer gestures.
1102 mPointerXZoomScale =
1103 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1104 mPointerYZoomScale = mPointerXZoomScale;
1105
HQ Liue6983c72022-04-19 22:14:56 +00001106 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1107 // axis is non positive value.
1108 const float minFreeformGestureWidth =
1109 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1110
1111 mPointerGestureMaxSwipeWidth =
1112 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1113 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001114 }
1115
1116 // Inform the dispatcher about the changes.
1117 *outResetNeeded = true;
1118 bumpGeneration();
1119 }
1120}
1121
Prabir Pradhan1728b212021-10-19 16:00:03 -07001122void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001123 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001124 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001125 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1126 toString(mPhysicalFrameInRotatedDisplay).c_str());
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00001127 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %s\n",
1128 ftl::enum_string(mInputDeviceOrientation).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001129}
1130
1131void TouchInputMapper::configureVirtualKeys() {
1132 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001133 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001134
1135 mVirtualKeys.clear();
1136
1137 if (virtualKeyDefinitions.size() == 0) {
1138 return;
1139 }
1140
1141 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1142 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1143 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1144 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1145
1146 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1147 VirtualKey virtualKey;
1148
1149 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1150 int32_t keyCode;
1151 int32_t dummyKeyMetaState;
1152 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001153 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1154 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001155 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1156 continue; // drop the key
1157 }
1158
1159 virtualKey.keyCode = keyCode;
1160 virtualKey.flags = flags;
1161
1162 // convert the key definition's display coordinates into touch coordinates for a hit box
1163 int32_t halfWidth = virtualKeyDefinition.width / 2;
1164 int32_t halfHeight = virtualKeyDefinition.height / 2;
1165
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001166 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1167 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001169 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1170 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001172 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1173 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001175 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1176 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 touchScreenTop;
1178 mVirtualKeys.push_back(virtualKey);
1179 }
1180}
1181
1182void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1183 if (!mVirtualKeys.empty()) {
1184 dump += INDENT3 "Virtual Keys:\n";
1185
1186 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1187 const VirtualKey& virtualKey = mVirtualKeys[i];
1188 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1189 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1190 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1191 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1192 }
1193 }
1194}
1195
1196void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001197 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 Calibration& out = mCalibration;
1199
1200 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001202 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1203 if (sizeCalibrationString.has_value()) {
1204 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001205 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001206 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001207 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001208 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001209 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001210 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001211 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001212 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001213 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001214 } else if (*sizeCalibrationString != "default") {
1215 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 }
1217 }
1218
Harry Cuttsf13161a2023-03-08 14:15:49 +00001219 out.sizeScale = in.getFloat("touch.size.scale");
1220 out.sizeBias = in.getFloat("touch.size.bias");
1221 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222
1223 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001224 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001225 std::optional<std::string> pressureCalibrationString =
1226 in.getString("touch.pressure.calibration");
1227 if (pressureCalibrationString.has_value()) {
1228 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001229 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001230 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001231 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001232 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001233 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001234 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001235 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001236 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 }
1238 }
1239
Harry Cuttsf13161a2023-03-08 14:15:49 +00001240 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241
1242 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001243 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001244 std::optional<std::string> orientationCalibrationString =
1245 in.getString("touch.orientation.calibration");
1246 if (orientationCalibrationString.has_value()) {
1247 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001248 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001249 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001250 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001251 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001252 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001253 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001255 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001256 }
1257 }
1258
1259 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001260 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001261 std::optional<std::string> distanceCalibrationString =
1262 in.getString("touch.distance.calibration");
1263 if (distanceCalibrationString.has_value()) {
1264 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001265 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001266 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001267 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001268 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001270 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 }
1272 }
1273
Harry Cuttsf13161a2023-03-08 14:15:49 +00001274 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275}
1276
1277void TouchInputMapper::resolveCalibration() {
1278 // Size
1279 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001280 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1281 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 }
1283 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001284 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 }
1286
1287 // Pressure
1288 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001289 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1290 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291 }
1292 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001293 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 }
1295
1296 // Orientation
1297 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001298 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1299 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 }
1301 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001302 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 }
1304
1305 // Distance
1306 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001307 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1308 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001309 }
1310 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001311 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313}
1314
1315void TouchInputMapper::dumpCalibration(std::string& dump) {
1316 dump += INDENT3 "Calibration:\n";
1317
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001318 dump += INDENT4 "touch.size.calibration: ";
1319 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001321 if (mCalibration.sizeScale) {
1322 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001323 }
1324
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001325 if (mCalibration.sizeBias) {
1326 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001327 }
1328
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001329 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001331 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 }
1333
1334 // Pressure
1335 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001336 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001337 dump += INDENT4 "touch.pressure.calibration: none\n";
1338 break;
Michael Wright227c5542020-07-02 18:30:52 +01001339 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001340 dump += INDENT4 "touch.pressure.calibration: physical\n";
1341 break;
Michael Wright227c5542020-07-02 18:30:52 +01001342 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001343 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1344 break;
1345 default:
1346 ALOG_ASSERT(false);
1347 }
1348
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001349 if (mCalibration.pressureScale) {
1350 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001351 }
1352
1353 // Orientation
1354 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001355 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356 dump += INDENT4 "touch.orientation.calibration: none\n";
1357 break;
Michael Wright227c5542020-07-02 18:30:52 +01001358 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001359 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1360 break;
Michael Wright227c5542020-07-02 18:30:52 +01001361 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001362 dump += INDENT4 "touch.orientation.calibration: vector\n";
1363 break;
1364 default:
1365 ALOG_ASSERT(false);
1366 }
1367
1368 // Distance
1369 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001370 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001371 dump += INDENT4 "touch.distance.calibration: none\n";
1372 break;
Michael Wright227c5542020-07-02 18:30:52 +01001373 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001374 dump += INDENT4 "touch.distance.calibration: scaled\n";
1375 break;
1376 default:
1377 ALOG_ASSERT(false);
1378 }
1379
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001380 if (mCalibration.distanceScale) {
1381 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001382 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001383}
1384
1385void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1386 dump += INDENT3 "Affine Transformation:\n";
1387
1388 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1389 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1390 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1391 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1392 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1393 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1394}
1395
1396void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001397 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001398 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001399}
1400
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001401std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001402 std::list<NotifyArgs> out = cancelTouch(when, when);
1403 updateTouchSpots();
1404
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001405 mCursorButtonAccumulator.reset(getDeviceContext());
1406 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001407 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001408
1409 mPointerVelocityControl.reset();
1410 mWheelXVelocityControl.reset();
1411 mWheelYVelocityControl.reset();
1412
1413 mRawStatesPending.clear();
1414 mCurrentRawState.clear();
1415 mCurrentCookedState.clear();
1416 mLastRawState.clear();
1417 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001418 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001419 mSentHoverEnter = false;
1420 mHavePointerIds = false;
1421 mCurrentMotionAborted = false;
1422 mDownTime = 0;
1423
1424 mCurrentVirtualKey.down = false;
1425
1426 mPointerGesture.reset();
1427 mPointerSimple.reset();
1428 resetExternalStylus();
1429
1430 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001431 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001432 mPointerController->clearSpots();
1433 }
1434
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001435 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436}
1437
1438void TouchInputMapper::resetExternalStylus() {
1439 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001440 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001441 mExternalStylusFusionTimeout = LLONG_MAX;
1442 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001443 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444}
1445
1446void TouchInputMapper::clearStylusDataPendingFlags() {
1447 mExternalStylusDataPending = false;
1448 mExternalStylusFusionTimeout = LLONG_MAX;
1449}
1450
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001451std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001452 mCursorButtonAccumulator.process(rawEvent);
1453 mCursorScrollAccumulator.process(rawEvent);
1454 mTouchButtonAccumulator.process(rawEvent);
1455
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001456 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001457 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001458 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001459 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001460 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001461}
1462
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001463std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1464 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001465 if (mDeviceMode == DeviceMode::DISABLED) {
1466 // Only save the last pending state when the device is disabled.
1467 mRawStatesPending.clear();
1468 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001469 // Push a new state.
1470 mRawStatesPending.emplace_back();
1471
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001472 RawState& next = mRawStatesPending.back();
1473 next.clear();
1474 next.when = when;
1475 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001476
1477 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001478 next.buttonState = filterButtonState(mConfig,
1479 mTouchButtonAccumulator.getButtonState() |
1480 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001481
1482 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001483 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1484 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001485 mCursorScrollAccumulator.finishSync();
1486
1487 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001488 syncTouch(when, &next);
1489
1490 // The last RawState is the actually second to last, since we just added a new state
1491 const RawState& last =
1492 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001493
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001494 std::tie(next.when, next.readTime) =
1495 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1496 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001497
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498 // Assign pointer ids.
1499 if (!mHavePointerIds) {
1500 assignPointerIds(last, next);
1501 }
1502
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001503 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001504 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1505 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1506 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1507 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1508 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1509 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001510
Arthur Hung9ad18942021-06-19 02:04:46 +00001511 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1512 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1513 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1514 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1515 next.rawPointerData.hoveringIdBits.value);
1516 }
1517
Harry Cutts33476232023-01-30 19:57:29 +00001518 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001519 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001520}
1521
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001522std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1523 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001524 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001525 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001526 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001527 }
1528
1529 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1530 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1531 // touching the current state will only observe the events that have been dispatched to the
1532 // rest of the pipeline.
1533 const size_t N = mRawStatesPending.size();
1534 size_t count;
1535 for (count = 0; count < N; count++) {
1536 const RawState& next = mRawStatesPending[count];
1537
1538 // A failure to assign the stylus id means that we're waiting on stylus data
1539 // and so should defer the rest of the pipeline.
1540 if (assignExternalStylusId(next, timeout)) {
1541 break;
1542 }
1543
1544 // All ready to go.
1545 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001546 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001547 if (mCurrentRawState.when < mLastRawState.when) {
1548 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001549 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001551 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001552 }
1553 if (count != 0) {
1554 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1555 }
1556
1557 if (mExternalStylusDataPending) {
1558 if (timeout) {
1559 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1560 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001561 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001562 ALOGD_IF(DEBUG_STYLUS_FUSION,
1563 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001564 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001565 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001566 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1567 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1568 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1569 }
1570 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001571 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001572}
1573
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001574std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1575 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001576 // Always start with a clean state.
1577 mCurrentCookedState.clear();
1578
1579 // Apply stylus buttons to current raw state.
1580 applyExternalStylusButtonState(when);
1581
1582 // Handle policy on initial down or hover events.
1583 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1584 mCurrentRawState.rawPointerData.pointerCount != 0;
1585
1586 uint32_t policyFlags = 0;
1587 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1588 if (initialDown || buttonsPressed) {
1589 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001590 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001591 getContext()->fadePointer();
1592 }
1593
1594 if (mParameters.wake) {
1595 policyFlags |= POLICY_FLAG_WAKE;
1596 }
1597 }
1598
1599 // Consume raw off-screen touches before cooking pointer data.
1600 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001601 bool consumed;
1602 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1603 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001604 mCurrentRawState.rawPointerData.clear();
1605 }
1606
1607 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1608 // with cooked pointer data that has the same ids and indices as the raw data.
1609 // The following code can use either the raw or cooked data, as needed.
1610 cookPointerData();
1611
1612 // Apply stylus pressure to current cooked state.
1613 applyExternalStylusTouchState(when);
1614
1615 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001616 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1617 mSource, mViewport.displayId, policyFlags,
1618 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001619
1620 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001621 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001622 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1623 uint32_t id = idBits.clearFirstMarkedBit();
1624 const RawPointerData::Pointer& pointer =
1625 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001626 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001627 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001628 } else if (pointer.toolType == ToolType::FINGER ||
1629 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001631 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001632 mCurrentCookedState.mouseIdBits.markBit(id);
1633 }
1634 }
1635 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1636 uint32_t id = idBits.clearFirstMarkedBit();
1637 const RawPointerData::Pointer& pointer =
1638 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001639 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001640 mCurrentCookedState.stylusIdBits.markBit(id);
1641 }
1642 }
1643
1644 // Stylus takes precedence over all tools, then mouse, then finger.
1645 PointerUsage pointerUsage = mPointerUsage;
1646 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1647 mCurrentCookedState.mouseIdBits.clear();
1648 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001649 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001650 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1651 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001652 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001653 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1654 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001655 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001656 }
1657
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001658 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001659 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001660 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001661 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001662 out += dispatchButtonRelease(when, readTime, policyFlags);
1663 out += dispatchHoverExit(when, readTime, policyFlags);
1664 out += dispatchTouches(when, readTime, policyFlags);
1665 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1666 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001667 }
1668
1669 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1670 mCurrentMotionAborted = false;
1671 }
1672 }
1673
1674 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001675 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1676 mSource, mViewport.displayId, policyFlags,
1677 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001678
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001679 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1680 mCurrentStreamModifiedByExternalStylus = false;
1681 }
1682
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001683 // Clear some transient state.
1684 mCurrentRawState.rawVScroll = 0;
1685 mCurrentRawState.rawHScroll = 0;
1686
1687 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001688 mLastRawState = mCurrentRawState;
1689 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001690 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001691}
1692
Garfield Tanc734e4f2021-01-15 20:01:39 -08001693void TouchInputMapper::updateTouchSpots() {
1694 if (!mConfig.showTouches || mPointerController == nullptr) {
1695 return;
1696 }
1697
1698 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1699 // clear touch spots.
1700 if (mDeviceMode != DeviceMode::DIRECT &&
1701 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1702 return;
1703 }
1704
1705 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1706 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1707
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001708 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1709 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001710 mCurrentCookedState.cookedPointerData.touchingIdBits |
1711 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001712 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001713}
1714
1715bool TouchInputMapper::isTouchScreen() {
1716 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1717 mParameters.hasAssociatedDisplay;
1718}
1719
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001720void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001721 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1722 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001723 const int32_t pressedButtons =
1724 filterButtonState(mConfig,
1725 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001726 const int32_t releasedButtons =
1727 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1728
1729 mCurrentRawState.buttonState |= pressedButtons;
1730 mCurrentRawState.buttonState &= ~releasedButtons;
1731
1732 mExternalStylusButtonsApplied |= pressedButtons;
1733 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001734
1735 if (mExternalStylusButtonsApplied != 0 || releasedButtons != 0) {
1736 mCurrentStreamModifiedByExternalStylus = true;
1737 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001738 }
1739}
1740
1741void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1742 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1743 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001744 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1745 return;
1746 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001747
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00001748 mCurrentStreamModifiedByExternalStylus = true;
1749
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001750 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1751 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1752 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1753 : 0.f;
1754 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1755 pressure = *mExternalStylusState.pressure;
1756 }
1757 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1758 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001759
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001760 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001761 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001762 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001763 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001764 }
1765}
1766
1767bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001768 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001769 return false;
1770 }
1771
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001772 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001773 if (mFusedStylusPointerId &&
1774 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001775 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001776 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001777 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001778 }
1779
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001780 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1781 state.rawPointerData.pointerCount != 0;
1782 if (!initialDown) {
1783 return false;
1784 }
1785
1786 if (!mExternalStylusState.pressure) {
1787 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1788 return false;
1789 }
1790
1791 if (*mExternalStylusState.pressure != 0.0f) {
1792 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1793 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1794 return false;
1795 }
1796
1797 if (timeout) {
1798 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1799 mFusedStylusPointerId.reset();
1800 mExternalStylusFusionTimeout = LLONG_MAX;
1801 return false;
1802 }
1803
1804 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1805 // being processed until we either get pressure data or timeout.
1806 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1807 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1808 }
1809 ALOGD_IF(DEBUG_STYLUS_FUSION,
1810 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1811 mExternalStylusFusionTimeout);
1812 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1813 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001814}
1815
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001816std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1817 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001818 if (mDeviceMode == DeviceMode::POINTER) {
1819 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001820 // Since this is a synthetic event, we can consider its latency to be zero
1821 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001822 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001823 }
Michael Wright227c5542020-07-02 18:30:52 +01001824 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001825 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001826 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001827 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1828 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1829 }
1830 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001831 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001832}
1833
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001834std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1835 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001836 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001837 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001838 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001839 // The following three cases are handled here:
1840 // - We're in the middle of a fused stream of data;
1841 // - We're waiting on external stylus data before dispatching the initial down; or
1842 // - Only the button state, which is not reported through a specific pointer, has changed.
1843 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001844 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001845 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001846 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001847 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001848}
1849
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001850std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1851 uint32_t policyFlags, bool& outConsumed) {
1852 outConsumed = false;
1853 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001854 // Check for release of a virtual key.
1855 if (mCurrentVirtualKey.down) {
1856 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1857 // Pointer went up while virtual key was down.
1858 mCurrentVirtualKey.down = false;
1859 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001860 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1861 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1862 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001863 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1864 AKEY_EVENT_FLAG_FROM_SYSTEM |
1865 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001866 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001867 outConsumed = true;
1868 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001869 }
1870
1871 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1872 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1873 const RawPointerData::Pointer& pointer =
1874 mCurrentRawState.rawPointerData.pointerForId(id);
1875 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1876 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1877 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001878 outConsumed = true;
1879 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001880 }
1881 }
1882
1883 // Pointer left virtual key area or another pointer also went down.
1884 // Send key cancellation but do not consume the touch yet.
1885 // This is useful when the user swipes through from the virtual key area
1886 // into the main display surface.
1887 mCurrentVirtualKey.down = false;
1888 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001889 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1890 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001891 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1892 AKEY_EVENT_FLAG_FROM_SYSTEM |
1893 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1894 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001895 }
1896 }
1897
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001898 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
Harry Cutts8722be92024-04-05 14:46:05 +00001899 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001900 // We have hovering pointers, and there are no touching pointers.
1901 bool hoveringPointersInFrame = false;
1902 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1903 while (!hoveringIds.isEmpty()) {
1904 uint32_t id = hoveringIds.clearFirstMarkedBit();
1905 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1906 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1907 hoveringPointersInFrame = true;
1908 break;
1909 }
1910 }
1911 if (!hoveringPointersInFrame) {
1912 // All hovering pointers are outside the physical frame.
1913 outConsumed = true;
1914 return out;
1915 }
1916 }
1917
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001918 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1919 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1920 // Pointer just went down. Check for virtual key press or off-screen touches.
1921 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1922 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001923 // Skip checking whether the pointer is inside the physical frame if the device is in
Harry Cutts1db43992023-06-19 17:05:07 +00001924 // unscaled or pointer mode.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001925 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
Harry Cutts8722be92024-04-05 14:46:05 +00001926 mDeviceMode != DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001927 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001928 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001929 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1930 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1931 if (virtualKey) {
1932 mCurrentVirtualKey.down = true;
1933 mCurrentVirtualKey.downTime = when;
1934 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1935 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1936 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001937 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1938 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001939
1940 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001941 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1942 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1943 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001944 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1945 AKEY_EVENT_ACTION_DOWN,
1946 AKEY_EVENT_FLAG_FROM_SYSTEM |
1947 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001948 }
1949 }
1950 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001951 outConsumed = true;
1952 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001953 }
1954 }
1955
1956 // Disable all virtual key touches that happen within a short time interval of the
1957 // most recent touch within the screen area. The idea is to filter out stray
1958 // virtual key presses when interacting with the touch screen.
1959 //
1960 // Problems we're trying to solve:
1961 //
1962 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1963 // virtual key area that is implemented by a separate touch panel and accidentally
1964 // triggers a virtual key.
1965 //
1966 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1967 // area and accidentally triggers a virtual key. This often happens when virtual keys
1968 // are layed out below the screen near to where the on screen keyboard's space bar
1969 // is displayed.
1970 if (mConfig.virtualKeyQuietTime > 0 &&
1971 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001972 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001973 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001974 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001975}
1976
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001977NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1978 uint32_t policyFlags, int32_t keyEventAction,
1979 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001980 int32_t keyCode = mCurrentVirtualKey.keyCode;
1981 int32_t scanCode = mCurrentVirtualKey.scanCode;
1982 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001983 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001984 policyFlags |= POLICY_FLAG_VIRTUAL;
1985
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001986 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1987 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1988 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001989}
1990
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001991std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1992 uint32_t policyFlags) {
1993 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001994 if (mCurrentMotionAborted) {
1995 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001996 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001997 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001998 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1999 if (!currentIdBits.isEmpty()) {
2000 int32_t metaState = getContext()->getGlobalMetaState();
2001 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002002 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002003 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2004 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002005 mCurrentCookedState.cookedPointerData.pointerProperties,
2006 mCurrentCookedState.cookedPointerData.pointerCoords,
2007 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2008 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2009 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002010 mCurrentMotionAborted = true;
2011 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002012 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002013}
2014
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002015// Updates pointer coords and properties for pointers with specified ids that have moved.
2016// Returns true if any of them changed.
2017static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
2018 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
2019 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
2020 BitSet32 idBits) {
2021 bool changed = false;
2022 while (!idBits.isEmpty()) {
2023 uint32_t id = idBits.clearFirstMarkedBit();
2024 uint32_t inIndex = inIdToIndex[id];
2025 uint32_t outIndex = outIdToIndex[id];
2026
2027 const PointerProperties& curInProperties = inProperties[inIndex];
2028 const PointerCoords& curInCoords = inCoords[inIndex];
2029 PointerProperties& curOutProperties = outProperties[outIndex];
2030 PointerCoords& curOutCoords = outCoords[outIndex];
2031
2032 if (curInProperties != curOutProperties) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002033 curOutProperties = curInProperties;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002034 changed = true;
2035 }
2036
2037 if (curInCoords != curOutCoords) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002038 curOutCoords = curInCoords;
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002039 changed = true;
2040 }
2041 }
2042 return changed;
2043}
2044
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002045std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
2046 uint32_t policyFlags) {
2047 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002048 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2049 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2050 int32_t metaState = getContext()->getGlobalMetaState();
2051 int32_t buttonState = mCurrentCookedState.buttonState;
2052
2053 if (currentIdBits == lastIdBits) {
2054 if (!currentIdBits.isEmpty()) {
2055 // No pointer id changes so this is a move event.
2056 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002057 out.push_back(
2058 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2059 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2060 mCurrentCookedState.cookedPointerData.pointerProperties,
2061 mCurrentCookedState.cookedPointerData.pointerCoords,
2062 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2063 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2064 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002065 }
2066 } else {
2067 // There may be pointers going up and pointers going down and pointers moving
2068 // all at the same time.
2069 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2070 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2071 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2072 BitSet32 dispatchedIdBits(lastIdBits.value);
2073
2074 // Update last coordinates of pointers that have moved so that we observe the new
2075 // pointer positions at the same time as other pointers that have just gone up.
2076 bool moveNeeded =
2077 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2078 mCurrentCookedState.cookedPointerData.pointerCoords,
2079 mCurrentCookedState.cookedPointerData.idToIndex,
2080 mLastCookedState.cookedPointerData.pointerProperties,
2081 mLastCookedState.cookedPointerData.pointerCoords,
2082 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2083 if (buttonState != mLastCookedState.buttonState) {
2084 moveNeeded = true;
2085 }
2086
2087 // Dispatch pointer up events.
2088 while (!upIdBits.isEmpty()) {
2089 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002090 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002091 if (isCanceled) {
2092 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2093 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002094 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2095 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2096 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2097 buttonState, 0,
2098 mLastCookedState.cookedPointerData.pointerProperties,
2099 mLastCookedState.cookedPointerData.pointerCoords,
2100 mLastCookedState.cookedPointerData.idToIndex,
2101 dispatchedIdBits, upId, mOrientedXPrecision,
2102 mOrientedYPrecision, mDownTime,
2103 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002104 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002105 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002106 }
2107
2108 // Dispatch move events if any of the remaining pointers moved from their old locations.
2109 // Although applications receive new locations as part of individual pointer up
2110 // events, they do not generally handle them except when presented in a move event.
2111 if (moveNeeded && !moveIdBits.isEmpty()) {
2112 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002113 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2114 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2115 mCurrentCookedState.cookedPointerData.pointerProperties,
2116 mCurrentCookedState.cookedPointerData.pointerCoords,
2117 mCurrentCookedState.cookedPointerData.idToIndex,
2118 dispatchedIdBits, -1, mOrientedXPrecision,
2119 mOrientedYPrecision, mDownTime,
2120 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002121 }
2122
2123 // Dispatch pointer down events using the new pointer locations.
2124 while (!downIdBits.isEmpty()) {
2125 uint32_t downId = downIdBits.clearFirstMarkedBit();
2126 dispatchedIdBits.markBit(downId);
2127
2128 if (dispatchedIdBits.count() == 1) {
2129 // First pointer is going down. Set down time.
2130 mDownTime = when;
2131 }
2132
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002133 out.push_back(
2134 dispatchMotion(when, readTime, policyFlags, mSource,
2135 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2136 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2137 mCurrentCookedState.cookedPointerData.pointerCoords,
2138 mCurrentCookedState.cookedPointerData.idToIndex,
2139 dispatchedIdBits, downId, mOrientedXPrecision,
2140 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002141 }
2142 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002143 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002144}
2145
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002146std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2147 uint32_t policyFlags) {
2148 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002149 if (mSentHoverEnter &&
2150 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2151 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2152 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002153 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2154 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2155 mLastCookedState.buttonState, 0,
2156 mLastCookedState.cookedPointerData.pointerProperties,
2157 mLastCookedState.cookedPointerData.pointerCoords,
2158 mLastCookedState.cookedPointerData.idToIndex,
2159 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2160 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2161 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002162 mSentHoverEnter = false;
2163 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002164 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002165}
2166
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002167std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2168 uint32_t policyFlags) {
2169 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002170 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2171 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2172 int32_t metaState = getContext()->getGlobalMetaState();
2173 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002174 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2175 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2176 mCurrentRawState.buttonState, 0,
2177 mCurrentCookedState.cookedPointerData.pointerProperties,
2178 mCurrentCookedState.cookedPointerData.pointerCoords,
2179 mCurrentCookedState.cookedPointerData.idToIndex,
2180 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2181 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2182 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002183 mSentHoverEnter = true;
2184 }
2185
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002186 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2187 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2188 mCurrentRawState.buttonState, 0,
2189 mCurrentCookedState.cookedPointerData.pointerProperties,
2190 mCurrentCookedState.cookedPointerData.pointerCoords,
2191 mCurrentCookedState.cookedPointerData.idToIndex,
2192 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2193 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2194 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002195 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002196 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002197}
2198
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002199std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2200 uint32_t policyFlags) {
2201 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002202 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2203 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2204 const int32_t metaState = getContext()->getGlobalMetaState();
2205 int32_t buttonState = mLastCookedState.buttonState;
2206 while (!releasedButtons.isEmpty()) {
2207 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2208 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002209 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2210 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2211 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002212 mLastCookedState.cookedPointerData.pointerProperties,
2213 mLastCookedState.cookedPointerData.pointerCoords,
2214 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002215 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2216 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002217 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002218 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002219}
2220
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002221std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2222 uint32_t policyFlags) {
2223 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002224 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2225 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2226 const int32_t metaState = getContext()->getGlobalMetaState();
2227 int32_t buttonState = mLastCookedState.buttonState;
2228 while (!pressedButtons.isEmpty()) {
2229 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2230 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002231 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2232 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2233 buttonState, 0,
2234 mCurrentCookedState.cookedPointerData.pointerProperties,
2235 mCurrentCookedState.cookedPointerData.pointerCoords,
2236 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2237 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2238 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002239 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002240 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002241}
2242
LiZhihong758eb562022-11-03 15:28:29 +08002243std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2244 uint32_t policyFlags,
2245 BitSet32 idBits,
2246 nsecs_t readTime) {
2247 std::list<NotifyArgs> out;
2248 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2249 const int32_t metaState = getContext()->getGlobalMetaState();
2250 int32_t buttonState = mLastCookedState.buttonState;
2251
2252 while (!releasedButtons.isEmpty()) {
2253 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2254 buttonState &= ~actionButton;
2255 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2256 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2257 metaState, buttonState, 0,
2258 mPointerGesture.lastGestureProperties,
2259 mPointerGesture.lastGestureCoords,
2260 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2261 mOrientedXPrecision, mOrientedYPrecision,
2262 mPointerGesture.downTime, MotionClassification::NONE));
2263 }
2264 return out;
2265}
2266
2267std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2268 uint32_t policyFlags,
2269 BitSet32 idBits,
2270 nsecs_t readTime) {
2271 std::list<NotifyArgs> out;
2272 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2273 const int32_t metaState = getContext()->getGlobalMetaState();
2274 int32_t buttonState = mLastCookedState.buttonState;
2275
2276 while (!pressedButtons.isEmpty()) {
2277 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2278 buttonState |= actionButton;
2279 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2280 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2281 buttonState, 0, mPointerGesture.currentGestureProperties,
2282 mPointerGesture.currentGestureCoords,
2283 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2284 mOrientedXPrecision, mOrientedYPrecision,
2285 mPointerGesture.downTime, MotionClassification::NONE));
2286 }
2287 return out;
2288}
2289
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002290const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2291 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2292 return cookedPointerData.touchingIdBits;
2293 }
2294 return cookedPointerData.hoveringIdBits;
2295}
2296
2297void TouchInputMapper::cookPointerData() {
2298 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2299
2300 mCurrentCookedState.cookedPointerData.clear();
2301 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2302 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2303 mCurrentRawState.rawPointerData.hoveringIdBits;
2304 mCurrentCookedState.cookedPointerData.touchingIdBits =
2305 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002306 mCurrentCookedState.cookedPointerData.canceledIdBits =
2307 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002308
2309 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2310 mCurrentCookedState.buttonState = 0;
2311 } else {
2312 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2313 }
2314
2315 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002316 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002317 for (uint32_t i = 0; i < currentPointerCount; i++) {
2318 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2319
2320 // Size
2321 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2322 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002323 case Calibration::SizeCalibration::GEOMETRIC:
2324 case Calibration::SizeCalibration::DIAMETER:
2325 case Calibration::SizeCalibration::BOX:
2326 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002327 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2328 touchMajor = in.touchMajor;
2329 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2330 toolMajor = in.toolMajor;
2331 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2332 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2333 : in.touchMajor;
2334 } else if (mRawPointerAxes.touchMajor.valid) {
2335 toolMajor = touchMajor = in.touchMajor;
2336 toolMinor = touchMinor =
2337 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2338 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2339 : in.touchMajor;
2340 } else if (mRawPointerAxes.toolMajor.valid) {
2341 touchMajor = toolMajor = in.toolMajor;
2342 touchMinor = toolMinor =
2343 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2344 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2345 : in.toolMajor;
2346 } else {
2347 ALOG_ASSERT(false,
2348 "No touch or tool axes. "
2349 "Size calibration should have been resolved to NONE.");
2350 touchMajor = 0;
2351 touchMinor = 0;
2352 toolMajor = 0;
2353 toolMinor = 0;
2354 size = 0;
2355 }
2356
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002357 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2359 if (touchingCount > 1) {
2360 touchMajor /= touchingCount;
2361 touchMinor /= touchingCount;
2362 toolMajor /= touchingCount;
2363 toolMinor /= touchingCount;
2364 size /= touchingCount;
2365 }
2366 }
2367
Michael Wright227c5542020-07-02 18:30:52 +01002368 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 touchMajor *= mGeometricScale;
2370 touchMinor *= mGeometricScale;
2371 toolMajor *= mGeometricScale;
2372 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002373 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2375 touchMinor = touchMajor;
2376 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2377 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002378 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 touchMinor = touchMajor;
2380 toolMinor = toolMajor;
2381 }
2382
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002383 mCalibration.applySizeScaleAndBias(touchMajor);
2384 mCalibration.applySizeScaleAndBias(touchMinor);
2385 mCalibration.applySizeScaleAndBias(toolMajor);
2386 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 size *= mSizeScale;
2388 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002389 case Calibration::SizeCalibration::DEFAULT:
2390 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2391 break;
2392 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002393 touchMajor = 0;
2394 touchMinor = 0;
2395 toolMajor = 0;
2396 toolMinor = 0;
2397 size = 0;
2398 break;
2399 }
2400
2401 // Pressure
2402 float pressure;
2403 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002404 case Calibration::PressureCalibration::PHYSICAL:
2405 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406 pressure = in.pressure * mPressureScale;
2407 break;
2408 default:
2409 pressure = in.isHovering ? 0 : 1;
2410 break;
2411 }
2412
2413 // Tilt and Orientation
2414 float tilt;
2415 float orientation;
2416 if (mHaveTilt) {
2417 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2418 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002419 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002420 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2421 } else {
2422 tilt = 0;
2423
2424 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002425 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002426 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 break;
Michael Wright227c5542020-07-02 18:30:52 +01002428 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002429 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2430 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2431 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002432 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002433 float confidence = hypotf(c1, c2);
2434 float scale = 1.0f + confidence / 16.0f;
2435 touchMajor *= scale;
2436 touchMinor /= scale;
2437 toolMajor *= scale;
2438 toolMinor /= scale;
2439 } else {
2440 orientation = 0;
2441 }
2442 break;
2443 }
2444 default:
2445 orientation = 0;
2446 }
2447 }
2448
2449 // Distance
2450 float distance;
2451 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002452 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002453 distance = in.distance * mDistanceScale;
2454 break;
2455 default:
2456 distance = 0;
2457 }
2458
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002459 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2460 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002461 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2462 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464 // Write output coords.
2465 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2466 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002467 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2468 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2470 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2471 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2472 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2473 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2474 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2475 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002476 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2477 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478
Chris Ye364fdb52020-08-05 15:07:56 -07002479 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002480 uint32_t id = in.id;
2481 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2482 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2483 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002484 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2485 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002486 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2487 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2488 }
2489
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002490 // Write output properties.
2491 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002492 properties.clear();
2493 properties.id = id;
2494 properties.toolType = in.toolType;
2495
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002496 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002497 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002498 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002499 }
2500}
2501
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002502std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2503 uint32_t policyFlags,
2504 PointerUsage pointerUsage) {
2505 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002506 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002507 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002508 mPointerUsage = pointerUsage;
2509 }
2510
2511 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002512 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002513 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514 break;
Michael Wright227c5542020-07-02 18:30:52 +01002515 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002516 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002517 break;
Michael Wright227c5542020-07-02 18:30:52 +01002518 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002519 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002520 break;
Michael Wright227c5542020-07-02 18:30:52 +01002521 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 break;
2523 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002524 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002525}
2526
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002527std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2528 uint32_t policyFlags) {
2529 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002530 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002531 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002532 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002533 break;
Michael Wright227c5542020-07-02 18:30:52 +01002534 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002535 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002536 break;
Michael Wright227c5542020-07-02 18:30:52 +01002537 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002538 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002539 break;
Michael Wright227c5542020-07-02 18:30:52 +01002540 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002541 break;
2542 }
2543
Michael Wright227c5542020-07-02 18:30:52 +01002544 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002545 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002546}
2547
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002548std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2549 uint32_t policyFlags,
2550 bool isTimeout) {
2551 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002552 // Update current gesture coordinates.
2553 bool cancelPreviousGesture, finishPreviousGesture;
2554 bool sendEvents =
2555 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2556 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002557 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002558 }
2559 if (finishPreviousGesture) {
2560 cancelPreviousGesture = false;
2561 }
2562
2563 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002564 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002565 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002566 if (finishPreviousGesture || cancelPreviousGesture) {
2567 mPointerController->clearSpots();
2568 }
2569
Michael Wright227c5542020-07-02 18:30:52 +01002570 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002571 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2572 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002573 mPointerGesture.currentGestureIdBits,
2574 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002575 }
2576 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002577 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002578 }
2579
2580 // Show or hide the pointer if needed.
2581 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002582 case PointerGesture::Mode::NEUTRAL:
2583 case PointerGesture::Mode::QUIET:
2584 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2585 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002586 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002587 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002588 }
2589 break;
Michael Wright227c5542020-07-02 18:30:52 +01002590 case PointerGesture::Mode::TAP:
2591 case PointerGesture::Mode::TAP_DRAG:
2592 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2593 case PointerGesture::Mode::HOVER:
2594 case PointerGesture::Mode::PRESS:
2595 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002596 // Unfade the pointer when the current gesture manipulates the
2597 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002598 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002599 break;
Michael Wright227c5542020-07-02 18:30:52 +01002600 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002601 // Fade the pointer when the current gesture manipulates a different
2602 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002603 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002604 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002605 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002606 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002607 }
2608 break;
2609 }
2610
2611 // Send events!
2612 int32_t metaState = getContext()->getGlobalMetaState();
2613 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002614 const MotionClassification classification =
2615 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2616 ? MotionClassification::TWO_FINGER_SWIPE
2617 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002618
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002619 uint32_t flags = 0;
2620
2621 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2622 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2623 }
2624
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002625 // Update last coordinates of pointers that have moved so that we observe the new
2626 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002627 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2628 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2629 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2630 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2631 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2632 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002633 bool moveNeeded = false;
2634 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2635 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2636 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2637 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2638 mPointerGesture.lastGestureIdBits.value);
2639 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2640 mPointerGesture.currentGestureCoords,
2641 mPointerGesture.currentGestureIdToIndex,
2642 mPointerGesture.lastGestureProperties,
2643 mPointerGesture.lastGestureCoords,
2644 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2645 if (buttonState != mLastCookedState.buttonState) {
2646 moveNeeded = true;
2647 }
2648 }
2649
2650 // Send motion events for all pointers that went up or were canceled.
2651 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2652 if (!dispatchedGestureIdBits.isEmpty()) {
2653 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002654 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002655 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002656 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002657 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2658 mPointerGesture.lastGestureProperties,
2659 mPointerGesture.lastGestureCoords,
2660 mPointerGesture.lastGestureIdToIndex,
2661 dispatchedGestureIdBits, -1, 0, 0,
2662 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002663
2664 dispatchedGestureIdBits.clear();
2665 } else {
2666 BitSet32 upGestureIdBits;
2667 if (finishPreviousGesture) {
2668 upGestureIdBits = dispatchedGestureIdBits;
2669 } else {
2670 upGestureIdBits.value =
2671 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2672 }
2673 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002674 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2675 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2676 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2677 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2678 readTime);
2679 }
2680 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002681 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2682 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2683 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2684 mPointerGesture.lastGestureProperties,
2685 mPointerGesture.lastGestureCoords,
2686 mPointerGesture.lastGestureIdToIndex,
2687 dispatchedGestureIdBits, id, 0, 0,
2688 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002689
2690 dispatchedGestureIdBits.clearBit(id);
2691 }
2692 }
2693 }
2694
2695 // Send motion events for all pointers that moved.
2696 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002697 out.push_back(
2698 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2699 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2700 mPointerGesture.currentGestureProperties,
2701 mPointerGesture.currentGestureCoords,
2702 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2703 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002704 }
2705
2706 // Send motion events for all pointers that went down.
2707 if (down) {
2708 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2709 ~dispatchedGestureIdBits.value);
2710 while (!downGestureIdBits.isEmpty()) {
2711 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2712 dispatchedGestureIdBits.markBit(id);
2713
2714 if (dispatchedGestureIdBits.count() == 1) {
2715 mPointerGesture.downTime = when;
2716 }
2717
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002718 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2719 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2720 buttonState, 0, mPointerGesture.currentGestureProperties,
2721 mPointerGesture.currentGestureCoords,
2722 mPointerGesture.currentGestureIdToIndex,
2723 dispatchedGestureIdBits, id, 0, 0,
2724 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002725 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2726 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2727 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2728 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2729 readTime);
2730 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002731 }
2732 }
2733
2734 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002735 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002736 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2737 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2738 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2739 mPointerGesture.currentGestureProperties,
2740 mPointerGesture.currentGestureCoords,
2741 mPointerGesture.currentGestureIdToIndex,
2742 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2743 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002744 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2745 // Synthesize a hover move event after all pointers go up to indicate that
2746 // the pointer is hovering again even if the user is not currently touching
2747 // the touch pad. This ensures that a view will receive a fresh hover enter
2748 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002749 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002750
2751 PointerProperties pointerProperties;
2752 pointerProperties.clear();
2753 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002754 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002755
2756 PointerCoords pointerCoords;
2757 pointerCoords.clear();
2758 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2759 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2760
2761 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002762 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2763 mSource, displayId, policyFlags,
2764 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2765 buttonState, MotionClassification::NONE,
2766 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2767 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00002768 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002769 }
2770
2771 // Update state.
2772 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2773 if (!down) {
2774 mPointerGesture.lastGestureIdBits.clear();
2775 } else {
2776 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2777 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2778 uint32_t id = idBits.clearFirstMarkedBit();
2779 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07002780 mPointerGesture.lastGestureProperties[index] =
2781 mPointerGesture.currentGestureProperties[index];
2782 mPointerGesture.lastGestureCoords[index] = mPointerGesture.currentGestureCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002783 mPointerGesture.lastGestureIdToIndex[id] = index;
2784 }
2785 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002786 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002787}
2788
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002789std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2790 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002791 const MotionClassification classification =
2792 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2793 ? MotionClassification::TWO_FINGER_SWIPE
2794 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002795 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002796 // Cancel previously dispatches pointers.
2797 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2798 int32_t metaState = getContext()->getGlobalMetaState();
2799 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002800 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002801 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2802 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002803 mPointerGesture.lastGestureProperties,
2804 mPointerGesture.lastGestureCoords,
2805 mPointerGesture.lastGestureIdToIndex,
2806 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2807 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002808 }
2809
2810 // Reset the current pointer gesture.
2811 mPointerGesture.reset();
2812 mPointerVelocityControl.reset();
2813
2814 // Remove any current spots.
2815 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002816 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002817 mPointerController->clearSpots();
2818 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002819 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002820}
2821
2822bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2823 bool* outFinishPreviousGesture, bool isTimeout) {
2824 *outCancelPreviousGesture = false;
2825 *outFinishPreviousGesture = false;
2826
2827 // Handle TAP timeout.
2828 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002829 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830
Michael Wright227c5542020-07-02 18:30:52 +01002831 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002832 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2833 // The tap/drag timeout has not yet expired.
2834 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2835 mConfig.pointerGestureTapDragInterval);
2836 } else {
2837 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002838 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002839 *outFinishPreviousGesture = true;
2840
2841 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002842 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002843 mPointerGesture.currentGestureIdBits.clear();
2844
2845 mPointerVelocityControl.reset();
2846 return true;
2847 }
2848 }
2849
2850 // We did not handle this timeout.
2851 return false;
2852 }
2853
2854 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2855 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2856
2857 // Update the velocity tracker.
2858 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002859 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002860 uint32_t id = idBits.clearFirstMarkedBit();
2861 const RawPointerData::Pointer& pointer =
2862 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002863 const float x = pointer.x * mPointerXMovementScale;
2864 const float y = pointer.y * mPointerYMovementScale;
2865 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2866 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002867 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002868 }
2869
2870 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2871 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002872 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2873 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2874 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 mPointerGesture.resetTap();
2876 }
2877
2878 // Pick a new active touch id if needed.
2879 // Choose an arbitrary pointer that just went down, if there is one.
2880 // Otherwise choose an arbitrary remaining pointer.
2881 // This guarantees we always have an active touch id when there is at least one pointer.
2882 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002883 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002885 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002886 mPointerGesture.firstTouchTime = when;
2887 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002888 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2889 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2890 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2891 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002893 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002894
2895 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002896 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002897 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002898 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2899 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2900 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002901 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002902 *outFinishPreviousGesture = true;
2903 }
2904
2905 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002906 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907 mPointerGesture.currentGestureIdBits.clear();
2908
2909 mPointerVelocityControl.reset();
2910 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2911 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2912 // The pointer follows the active touch point.
2913 // Emit DOWN, MOVE, UP events at the pointer location.
2914 //
2915 // Only the active touch matters; other fingers are ignored. This policy helps
2916 // to handle the case where the user places a second finger on the touch pad
2917 // to apply the necessary force to depress an integrated button below the surface.
2918 // We don't want the second finger to be delivered to applications.
2919 //
2920 // For this to work well, we need to make sure to track the pointer that is really
2921 // active. If the user first puts one finger down to click then adds another
2922 // finger to drag then the active pointer should switch to the finger that is
2923 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002924 ALOGD_IF(DEBUG_GESTURES,
2925 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2926 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002927 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002928 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002929 *outFinishPreviousGesture = true;
2930 mPointerGesture.activeGestureId = 0;
2931 }
2932
2933 // Switch pointers if needed.
2934 // Find the fastest pointer and follow it.
2935 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002936 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002937 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002938 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002939 ALOGD_IF(DEBUG_GESTURES,
2940 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2941 "bestSpeed=%0.3f",
2942 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002943 }
2944 }
2945
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002946 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002947 // When using spots, the click will occur at the position of the anchor
2948 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002949 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002950 } else {
2951 mPointerVelocityControl.reset();
2952 }
2953
Prabir Pradhan2719e822023-02-28 17:39:36 +00002954 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002955
Michael Wright227c5542020-07-02 18:30:52 +01002956 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002957 mPointerGesture.currentGestureIdBits.clear();
2958 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2959 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2960 mPointerGesture.currentGestureProperties[0].clear();
2961 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002962 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002963 mPointerGesture.currentGestureCoords[0].clear();
2964 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2965 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2966 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2967 } else if (currentFingerCount == 0) {
2968 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002969 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002970 *outFinishPreviousGesture = true;
2971 }
2972
2973 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2974 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2975 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002976 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2977 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002978 lastFingerCount == 1) {
2979 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002980 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2982 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002983 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002984
2985 mPointerGesture.tapUpTime = when;
2986 getContext()->requestTimeoutAtTime(when +
2987 mConfig.pointerGestureTapDragInterval);
2988
2989 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002990 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002991 mPointerGesture.currentGestureIdBits.clear();
2992 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2993 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2994 mPointerGesture.currentGestureProperties[0].clear();
2995 mPointerGesture.currentGestureProperties[0].id =
2996 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002997 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002998 mPointerGesture.currentGestureCoords[0].clear();
2999 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3000 mPointerGesture.tapX);
3001 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3002 mPointerGesture.tapY);
3003 mPointerGesture.currentGestureCoords[0]
3004 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3005
3006 tapped = true;
3007 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003008 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
3009 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003010 }
3011 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003012 if (DEBUG_GESTURES) {
3013 if (mPointerGesture.tapDownTime != LLONG_MIN) {
3014 ALOGD("Gestures: Not a TAP, %0.3fms since down",
3015 (when - mPointerGesture.tapDownTime) * 0.000001f);
3016 } else {
3017 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
3018 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003019 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003020 }
3021 }
3022
3023 mPointerVelocityControl.reset();
3024
3025 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00003026 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003027 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01003028 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003029 mPointerGesture.currentGestureIdBits.clear();
3030 }
3031 } else if (currentFingerCount == 1) {
3032 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3033 // The pointer follows the active touch point.
3034 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3035 // When in TAP_DRAG, emit MOVE events at the pointer location.
3036 ALOG_ASSERT(activeTouchId >= 0);
3037
Michael Wright227c5542020-07-02 18:30:52 +01003038 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3039 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003040 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003041 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003042 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3043 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003044 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003045 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003046 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3047 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003048 }
3049 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003050 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3051 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003052 }
Michael Wright227c5542020-07-02 18:30:52 +01003053 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3054 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003055 }
3056
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003057 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003058 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003059 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003060 } else {
3061 mPointerVelocityControl.reset();
3062 }
3063
3064 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003065 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003066 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003067 down = true;
3068 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003069 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003070 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003071 *outFinishPreviousGesture = true;
3072 }
3073 mPointerGesture.activeGestureId = 0;
3074 down = false;
3075 }
3076
Prabir Pradhan2719e822023-02-28 17:39:36 +00003077 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003078
3079 mPointerGesture.currentGestureIdBits.clear();
3080 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3081 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3082 mPointerGesture.currentGestureProperties[0].clear();
3083 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003084 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003085 mPointerGesture.currentGestureCoords[0].clear();
3086 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3087 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3088 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3089 down ? 1.0f : 0.0f);
3090
3091 if (lastFingerCount == 0 && currentFingerCount != 0) {
3092 mPointerGesture.resetTap();
3093 mPointerGesture.tapDownTime = when;
3094 mPointerGesture.tapX = x;
3095 mPointerGesture.tapY = y;
3096 }
3097 } else {
3098 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003099 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003100 }
3101
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003102 if (DEBUG_GESTURES) {
3103 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00003104 "currentGestureMode=%s, currentGestureIdBits=0x%08x, "
3105 "lastGestureMode=%s, lastGestureIdBits=0x%08x",
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003106 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
Harry Cuttsc57cd3c2024-04-24 13:52:55 +00003107 ftl::enum_string(mPointerGesture.currentGestureMode).c_str(),
3108 mPointerGesture.currentGestureIdBits.value,
3109 ftl::enum_string(mPointerGesture.lastGestureMode).c_str(),
3110 mPointerGesture.lastGestureIdBits.value);
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003111 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3112 uint32_t id = idBits.clearFirstMarkedBit();
3113 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3114 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3115 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003116 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003117 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003118 id, index, ftl::enum_string(properties.toolType).c_str(),
3119 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003120 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3121 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3122 }
3123 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3124 uint32_t id = idBits.clearFirstMarkedBit();
3125 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3126 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3127 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003128 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003129 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003130 id, index, ftl::enum_string(properties.toolType).c_str(),
3131 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003132 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3133 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3134 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003135 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003136 return true;
3137}
3138
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003139bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3140 if (mPointerGesture.activeTouchId < 0) {
3141 mPointerGesture.resetQuietTime();
3142 return false;
3143 }
3144
3145 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3146 return true;
3147 }
3148
3149 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3150 bool isQuietTime = false;
3151 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3152 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3153 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3154 currentFingerCount < 2) {
3155 // Enter quiet time when exiting swipe or freeform state.
3156 // This is to prevent accidentally entering the hover state and flinging the
3157 // pointer when finishing a swipe and there is still one pointer left onscreen.
3158 isQuietTime = true;
3159 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3160 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3161 // Enter quiet time when releasing the button and there are still two or more
3162 // fingers down. This may indicate that one finger was used to press the button
3163 // but it has not gone up yet.
3164 isQuietTime = true;
3165 }
3166 if (isQuietTime) {
3167 mPointerGesture.quietTime = when;
3168 }
3169 return isQuietTime;
3170}
3171
3172std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3173 int32_t bestId = -1;
3174 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3175 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3176 uint32_t id = idBits.clearFirstMarkedBit();
3177 std::optional<float> vx =
3178 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3179 std::optional<float> vy =
3180 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3181 if (vx && vy) {
3182 float speed = hypotf(*vx, *vy);
3183 if (speed > bestSpeed) {
3184 bestId = id;
3185 bestSpeed = speed;
3186 }
3187 }
3188 }
3189 return std::make_pair(bestId, bestSpeed);
3190}
3191
3192void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3193 bool* finishPreviousGesture) {
3194 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3195 // to move before deciding what to do.
3196 //
3197 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3198 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3199 // just a press or long-press at the pointer location.
3200 //
3201 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3202 // pointer location.
3203 //
3204 // When the two fingers move enough or when additional fingers are added, we make a decision to
3205 // transition into SWIPE or FREEFORM mode accordingly.
3206 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3207 ALOG_ASSERT(activeTouchId >= 0);
3208
3209 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3210 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3211 bool settled =
3212 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3213 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3214 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3215 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3216 *finishPreviousGesture = true;
3217 } else if (!settled && currentFingerCount > lastFingerCount) {
3218 // Additional pointers have gone down but not yet settled.
3219 // Reset the gesture.
3220 ALOGD_IF(DEBUG_GESTURES,
3221 "Gestures: Resetting gesture since additional pointers went down for "
3222 "MULTITOUCH, settle time remaining %0.3fms",
3223 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3224 when) * 0.000001f);
3225 *cancelPreviousGesture = true;
3226 } else {
3227 // Continue previous gesture.
3228 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3229 }
3230
3231 if (*finishPreviousGesture || *cancelPreviousGesture) {
3232 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3233 mPointerGesture.activeGestureId = 0;
3234 mPointerGesture.referenceIdBits.clear();
3235 mPointerVelocityControl.reset();
3236
3237 // Use the centroid and pointer location as the reference points for the gesture.
3238 ALOGD_IF(DEBUG_GESTURES,
3239 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3240 "%0.3fms",
3241 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3242 when) * 0.000001f);
3243 mCurrentRawState.rawPointerData
3244 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3245 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003246 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3247 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003248 }
3249
3250 // Clear the reference deltas for fingers not yet included in the reference calculation.
3251 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3252 ~mPointerGesture.referenceIdBits.value);
3253 !idBits.isEmpty();) {
3254 uint32_t id = idBits.clearFirstMarkedBit();
3255 mPointerGesture.referenceDeltas[id].dx = 0;
3256 mPointerGesture.referenceDeltas[id].dy = 0;
3257 }
3258 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3259
3260 // Add delta for all fingers and calculate a common movement delta.
3261 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3262 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3263 mCurrentCookedState.fingerIdBits.value);
3264 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3265 bool first = (idBits == commonIdBits);
3266 uint32_t id = idBits.clearFirstMarkedBit();
3267 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3268 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3269 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3270 delta.dx += cpd.x - lpd.x;
3271 delta.dy += cpd.y - lpd.y;
3272
3273 if (first) {
3274 commonDeltaRawX = delta.dx;
3275 commonDeltaRawY = delta.dy;
3276 } else {
3277 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3278 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3279 }
3280 }
3281
3282 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3283 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3284 float dist[MAX_POINTER_ID + 1];
3285 int32_t distOverThreshold = 0;
3286 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3287 uint32_t id = idBits.clearFirstMarkedBit();
3288 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3289 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3290 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3291 distOverThreshold += 1;
3292 }
3293 }
3294
3295 // Only transition when at least two pointers have moved further than
3296 // the minimum distance threshold.
3297 if (distOverThreshold >= 2) {
3298 if (currentFingerCount > 2) {
3299 // There are more than two pointers, switch to FREEFORM.
3300 ALOGD_IF(DEBUG_GESTURES,
3301 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3302 currentFingerCount);
3303 *cancelPreviousGesture = true;
3304 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3305 } else {
3306 // There are exactly two pointers.
3307 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3308 uint32_t id1 = idBits.clearFirstMarkedBit();
3309 uint32_t id2 = idBits.firstMarkedBit();
3310 const RawPointerData::Pointer& p1 =
3311 mCurrentRawState.rawPointerData.pointerForId(id1);
3312 const RawPointerData::Pointer& p2 =
3313 mCurrentRawState.rawPointerData.pointerForId(id2);
3314 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3315 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3316 // There are two pointers but they are too far apart for a SWIPE,
3317 // switch to FREEFORM.
3318 ALOGD_IF(DEBUG_GESTURES,
3319 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3320 mutualDistance, mPointerGestureMaxSwipeWidth);
3321 *cancelPreviousGesture = true;
3322 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3323 } else {
3324 // There are two pointers. Wait for both pointers to start moving
3325 // before deciding whether this is a SWIPE or FREEFORM gesture.
3326 float dist1 = dist[id1];
3327 float dist2 = dist[id2];
3328 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3329 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3330 // Calculate the dot product of the displacement vectors.
3331 // When the vectors are oriented in approximately the same direction,
3332 // the angle betweeen them is near zero and the cosine of the angle
3333 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3334 // mag(v2).
3335 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3336 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3337 float dx1 = delta1.dx * mPointerXZoomScale;
3338 float dy1 = delta1.dy * mPointerYZoomScale;
3339 float dx2 = delta2.dx * mPointerXZoomScale;
3340 float dy2 = delta2.dy * mPointerYZoomScale;
3341 float dot = dx1 * dx2 + dy1 * dy2;
3342 float cosine = dot / (dist1 * dist2); // denominator always > 0
3343 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3344 // Pointers are moving in the same direction. Switch to SWIPE.
3345 ALOGD_IF(DEBUG_GESTURES,
3346 "Gestures: PRESS transitioned to SWIPE, "
3347 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3348 "cosine %0.3f >= %0.3f",
3349 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3350 mConfig.pointerGestureMultitouchMinDistance, cosine,
3351 mConfig.pointerGestureSwipeTransitionAngleCosine);
3352 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3353 } else {
3354 // Pointers are moving in different directions. Switch to FREEFORM.
3355 ALOGD_IF(DEBUG_GESTURES,
3356 "Gestures: PRESS transitioned to FREEFORM, "
3357 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3358 "cosine %0.3f < %0.3f",
3359 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3360 mConfig.pointerGestureMultitouchMinDistance, cosine,
3361 mConfig.pointerGestureSwipeTransitionAngleCosine);
3362 *cancelPreviousGesture = true;
3363 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3364 }
3365 }
3366 }
3367 }
3368 }
3369 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3370 // Switch from SWIPE to FREEFORM if additional pointers go down.
3371 // Cancel previous gesture.
3372 if (currentFingerCount > 2) {
3373 ALOGD_IF(DEBUG_GESTURES,
3374 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3375 currentFingerCount);
3376 *cancelPreviousGesture = true;
3377 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3378 }
3379 }
3380
3381 // Move the reference points based on the overall group motion of the fingers
3382 // except in PRESS mode while waiting for a transition to occur.
3383 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3384 (commonDeltaRawX || commonDeltaRawY)) {
3385 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3386 uint32_t id = idBits.clearFirstMarkedBit();
3387 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3388 delta.dx = 0;
3389 delta.dy = 0;
3390 }
3391
3392 mPointerGesture.referenceTouchX += commonDeltaRawX;
3393 mPointerGesture.referenceTouchY += commonDeltaRawY;
3394
3395 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3396 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3397
3398 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3399 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3400
3401 mPointerGesture.referenceGestureX += commonDeltaX;
3402 mPointerGesture.referenceGestureY += commonDeltaY;
3403 }
3404
3405 // Report gestures.
3406 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3407 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3408 // PRESS or SWIPE mode.
3409 ALOGD_IF(DEBUG_GESTURES,
3410 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3411 "currentTouchPointerCount=%d",
3412 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3413 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3414
3415 mPointerGesture.currentGestureIdBits.clear();
3416 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3417 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3418 mPointerGesture.currentGestureProperties[0].clear();
3419 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003420 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003421 mPointerGesture.currentGestureCoords[0].clear();
3422 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3423 mPointerGesture.referenceGestureX);
3424 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3425 mPointerGesture.referenceGestureY);
3426 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3427 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3428 float xOffset = static_cast<float>(commonDeltaRawX) /
3429 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3430 float yOffset = static_cast<float>(commonDeltaRawY) /
3431 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3432 mPointerGesture.currentGestureCoords[0]
3433 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3434 mPointerGesture.currentGestureCoords[0]
3435 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3436 }
3437 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3438 // FREEFORM mode.
3439 ALOGD_IF(DEBUG_GESTURES,
3440 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3441 "currentTouchPointerCount=%d",
3442 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3443 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3444
3445 mPointerGesture.currentGestureIdBits.clear();
3446
3447 BitSet32 mappedTouchIdBits;
3448 BitSet32 usedGestureIdBits;
3449 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3450 // Initially, assign the active gesture id to the active touch point
3451 // if there is one. No other touch id bits are mapped yet.
3452 if (!*cancelPreviousGesture) {
3453 mappedTouchIdBits.markBit(activeTouchId);
3454 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3455 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3456 mPointerGesture.activeGestureId;
3457 } else {
3458 mPointerGesture.activeGestureId = -1;
3459 }
3460 } else {
3461 // Otherwise, assume we mapped all touches from the previous frame.
3462 // Reuse all mappings that are still applicable.
3463 mappedTouchIdBits.value =
3464 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3465 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3466
3467 // Check whether we need to choose a new active gesture id because the
3468 // current went went up.
3469 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3470 ~mCurrentCookedState.fingerIdBits.value);
3471 !upTouchIdBits.isEmpty();) {
3472 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3473 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3474 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3475 mPointerGesture.activeGestureId = -1;
3476 break;
3477 }
3478 }
3479 }
3480
3481 ALOGD_IF(DEBUG_GESTURES,
3482 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3483 "activeGestureId=%d",
3484 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3485
3486 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3487 for (uint32_t i = 0; i < currentFingerCount; i++) {
3488 uint32_t touchId = idBits.clearFirstMarkedBit();
3489 uint32_t gestureId;
3490 if (!mappedTouchIdBits.hasBit(touchId)) {
3491 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3492 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3493 ALOGD_IF(DEBUG_GESTURES,
3494 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3495 gestureId);
3496 } else {
3497 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3498 ALOGD_IF(DEBUG_GESTURES,
3499 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3500 touchId, gestureId);
3501 }
3502 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3503 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3504
3505 const RawPointerData::Pointer& pointer =
3506 mCurrentRawState.rawPointerData.pointerForId(touchId);
3507 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3508 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3509 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3510
3511 mPointerGesture.currentGestureProperties[i].clear();
3512 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003513 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003514 mPointerGesture.currentGestureCoords[i].clear();
3515 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3516 mPointerGesture.referenceGestureX +
3517 deltaX);
3518 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3519 mPointerGesture.referenceGestureY +
3520 deltaY);
3521 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3522 }
3523
3524 if (mPointerGesture.activeGestureId < 0) {
3525 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3526 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3527 mPointerGesture.activeGestureId);
3528 }
3529 }
3530}
3531
Harry Cutts714d1ad2022-08-24 16:36:43 +00003532void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3533 const RawPointerData::Pointer& currentPointer =
3534 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3535 const RawPointerData::Pointer& lastPointer =
3536 mLastRawState.rawPointerData.pointerForId(pointerId);
3537 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3538 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3539
3540 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3541 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3542
3543 mPointerController->move(deltaX, deltaY);
3544}
3545
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003546std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3547 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003548 mPointerSimple.currentCoords.clear();
3549 mPointerSimple.currentProperties.clear();
3550
3551 bool down, hovering;
3552 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3553 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3554 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003555 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3556 down = !hovering;
3557
Prabir Pradhane71e5702023-03-29 14:51:38 +00003558 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3559 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3560 // Styluses are configured specifically for one display. We only update the
3561 // PointerController for this stylus if the PointerController is configured for
3562 // the same display as this stylus,
3563 if (getAssociatedDisplayId() == mViewport.displayId) {
3564 mPointerController->setPosition(x, y);
3565 std::tie(x, y) = mPointerController->getPosition();
3566 }
3567
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003568 mPointerSimple.currentCoords = mCurrentCookedState.cookedPointerData.pointerCoords[index];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003569 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3570 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3571 mPointerSimple.currentProperties.id = 0;
3572 mPointerSimple.currentProperties.toolType =
3573 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3574 } else {
3575 down = false;
3576 hovering = false;
3577 }
3578
Prabir Pradhane71e5702023-03-29 14:51:38 +00003579 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003580}
3581
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003582std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3583 uint32_t policyFlags) {
3584 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003585}
3586
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003587std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3588 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003589 mPointerSimple.currentCoords.clear();
3590 mPointerSimple.currentProperties.clear();
3591
3592 bool down, hovering;
3593 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3594 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003595 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003596 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003597 } else {
3598 mPointerVelocityControl.reset();
3599 }
3600
3601 down = isPointerDown(mCurrentRawState.buttonState);
3602 hovering = !down;
3603
Prabir Pradhan2719e822023-02-28 17:39:36 +00003604 const auto [x, y] = mPointerController->getPosition();
3605 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003606 mPointerSimple.currentCoords =
3607 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003608 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3609 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3610 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3611 hovering ? 0.0f : 1.0f);
3612 mPointerSimple.currentProperties.id = 0;
3613 mPointerSimple.currentProperties.toolType =
3614 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3615 } else {
3616 mPointerVelocityControl.reset();
3617
3618 down = false;
3619 hovering = false;
3620 }
3621
Prabir Pradhane71e5702023-03-29 14:51:38 +00003622 const int32_t displayId = mPointerController->getDisplayId();
3623 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003624}
3625
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003626std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3627 uint32_t policyFlags) {
3628 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003629
3630 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003631
3632 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003633}
3634
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003635std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3636 uint32_t policyFlags, bool down,
Prabir Pradhane71e5702023-03-29 14:51:38 +00003637 bool hovering, int32_t displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003638 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3639 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003640 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003641 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003642 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003643
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003644 if (displayId == mPointerController->getDisplayId()) {
3645 std::tie(cursorPosition.x, cursorPosition.y) = mPointerController->getPosition();
3646 if (down || hovering) {
3647 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
3648 mPointerController->clearSpots();
3649 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3650 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
3651 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3652 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003653 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003654
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003655 if (mPointerSimple.down && !down) {
3656 mPointerSimple.down = false;
3657
3658 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003659 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3660 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3661 0, metaState, mLastRawState.buttonState,
3662 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3663 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003664 mOrientedXPrecision, mOrientedYPrecision,
3665 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3666 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003667 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003668 }
3669
3670 if (mPointerSimple.hovering && !hovering) {
3671 mPointerSimple.hovering = false;
3672
3673 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003674 out.push_back(
3675 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3676 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3677 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3678 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3679 &mPointerSimple.lastCoords, mOrientedXPrecision,
3680 mOrientedYPrecision, mPointerSimple.lastCursorX,
3681 mPointerSimple.lastCursorY, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003682 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003683 }
3684
3685 if (down) {
3686 if (!mPointerSimple.down) {
3687 mPointerSimple.down = true;
3688 mPointerSimple.downTime = when;
3689
3690 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003691 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3692 mSource, displayId, policyFlags,
3693 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3694 mCurrentRawState.buttonState, MotionClassification::NONE,
3695 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3696 &mPointerSimple.currentProperties,
3697 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003698 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003699 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003700 }
3701
3702 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003703 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3704 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3705 0, 0, metaState, mCurrentRawState.buttonState,
3706 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3707 &mPointerSimple.currentProperties,
3708 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003709 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003710 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003711 }
3712
3713 if (hovering) {
3714 if (!mPointerSimple.hovering) {
3715 mPointerSimple.hovering = true;
3716
3717 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003718 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3719 mSource, displayId, policyFlags,
3720 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3721 mCurrentRawState.buttonState, MotionClassification::NONE,
3722 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3723 &mPointerSimple.currentProperties,
3724 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003725 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003726 mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003727 }
3728
3729 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003730 out.push_back(
3731 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3732 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3733 metaState, mCurrentRawState.buttonState,
3734 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3735 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003736 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003737 cursorPosition.y, mPointerSimple.downTime, /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003738 }
3739
3740 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3741 float vscroll = mCurrentRawState.rawVScroll;
3742 float hscroll = mCurrentRawState.rawHScroll;
3743 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3744 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3745
3746 // Send scroll.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003747 PointerCoords pointerCoords = mPointerSimple.currentCoords;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003748 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3749 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3750
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003751 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3752 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3753 0, 0, metaState, mCurrentRawState.buttonState,
3754 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3755 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003756 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3757 cursorPosition.y, mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003758 /*videoFrames=*/{}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003759 }
3760
3761 // Save state.
3762 if (down || hovering) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07003763 mPointerSimple.lastCoords = mPointerSimple.currentCoords;
3764 mPointerSimple.lastProperties = mPointerSimple.currentProperties;
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003765 mPointerSimple.displayId = displayId;
3766 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003767 mPointerSimple.lastCursorX = cursorPosition.x;
3768 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003769 } else {
3770 mPointerSimple.reset();
3771 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003772 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003773}
3774
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003775std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3776 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003777 std::list<NotifyArgs> out;
3778 if (mPointerSimple.down || mPointerSimple.hovering) {
3779 int32_t metaState = getContext()->getGlobalMetaState();
3780 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3781 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3782 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3783 metaState, mLastRawState.buttonState,
3784 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3785 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3786 mOrientedXPrecision, mOrientedYPrecision,
3787 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3788 mPointerSimple.downTime,
Harry Cutts101ee9b2023-07-06 18:04:14 +00003789 /*videoFrames=*/{}));
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003790 if (mPointerController != nullptr) {
3791 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3792 }
3793 }
3794 mPointerSimple.reset();
3795 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003796}
3797
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003798NotifyMotionArgs TouchInputMapper::dispatchMotion(
3799 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3800 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003801 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3802 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003803 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003804 std::vector<PointerCoords> pointerCoords;
3805 std::vector<PointerProperties> pointerProperties;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003806 uint32_t pointerCount = 0;
3807 while (!idBits.isEmpty()) {
3808 uint32_t id = idBits.clearFirstMarkedBit();
3809 uint32_t index = idToIndex[id];
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003810 pointerProperties.push_back(properties[index]);
3811 pointerCoords.push_back(coords[index]);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003812
3813 if (changedId >= 0 && id == uint32_t(changedId)) {
3814 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3815 }
3816
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003817 pointerCount++;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003818 }
3819
3820 ALOG_ASSERT(pointerCount != 0);
3821
3822 if (changedId >= 0 && pointerCount == 1) {
3823 // Replace initial down and final up action.
3824 // We can compare the action without masking off the changed pointer index
3825 // because we know the index is 0.
3826 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3827 action = AMOTION_EVENT_ACTION_DOWN;
3828 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003829 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3830 action = AMOTION_EVENT_ACTION_CANCEL;
3831 } else {
3832 action = AMOTION_EVENT_ACTION_UP;
3833 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003834 } else {
3835 // Can't happen.
3836 ALOG_ASSERT(false);
3837 }
3838 }
Prabir Pradhanb08a0e82023-09-14 22:28:32 +00003839 if (mCurrentStreamModifiedByExternalStylus) {
3840 source |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3841 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003842
3843 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3844 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003845 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003846 mPointerController && displayId != ADISPLAY_ID_NONE &&
3847 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003848 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003849 switch (action & AMOTION_EVENT_ACTION_MASK) {
3850 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3851 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3852 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003853 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003854 mPointerController
3855 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3856 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3857 .getY());
3858 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3859 break;
3860 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3861 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3862 break;
3863 }
3864 }
3865
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003866 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3867 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003868 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003869 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003870 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003871 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003872 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003873 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003874 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003875 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3876 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakoudcc6e6e2023-10-18 09:20:07 -07003877 classification, edgeFlags, pointerCount, pointerProperties.data(),
3878 pointerCoords.data(), xPrecision, yPrecision, xCursorPosition,
3879 yCursorPosition, downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003880}
3881
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003882std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3883 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003884 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3885 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003886 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003887}
3888
Prabir Pradhan1728b212021-10-19 16:00:03 -07003889bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003890 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003891 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003892 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003893}
3894
3895const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3896 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003897 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3898 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3899 "left=%d, top=%d, right=%d, bottom=%d",
3900 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3901 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003902
3903 if (virtualKey.isHit(x, y)) {
3904 return &virtualKey;
3905 }
3906 }
3907
3908 return nullptr;
3909}
3910
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003911void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3912 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3913 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003914
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003915 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003916
3917 if (currentPointerCount == 0) {
3918 // No pointers to assign.
3919 return;
3920 }
3921
3922 if (lastPointerCount == 0) {
3923 // All pointers are new.
3924 for (uint32_t i = 0; i < currentPointerCount; i++) {
3925 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003926 current.rawPointerData.pointers[i].id = id;
3927 current.rawPointerData.idToIndex[id] = i;
3928 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003929 }
3930 return;
3931 }
3932
3933 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003934 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003935 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003936 uint32_t id = last.rawPointerData.pointers[0].id;
3937 current.rawPointerData.pointers[0].id = id;
3938 current.rawPointerData.idToIndex[id] = 0;
3939 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003940 return;
3941 }
3942
3943 // General case.
3944 // We build a heap of squared euclidean distances between current and last pointers
3945 // associated with the current and last pointer indices. Then, we find the best
3946 // match (by distance) for each current pointer.
3947 // The pointers must have the same tool type but it is possible for them to
3948 // transition from hovering to touching or vice-versa while retaining the same id.
3949 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3950
3951 uint32_t heapSize = 0;
3952 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3953 currentPointerIndex++) {
3954 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3955 lastPointerIndex++) {
3956 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003957 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003958 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003959 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003960 if (currentPointer.toolType == lastPointer.toolType) {
3961 int64_t deltaX = currentPointer.x - lastPointer.x;
3962 int64_t deltaY = currentPointer.y - lastPointer.y;
3963
3964 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3965
3966 // Insert new element into the heap (sift up).
3967 heap[heapSize].currentPointerIndex = currentPointerIndex;
3968 heap[heapSize].lastPointerIndex = lastPointerIndex;
3969 heap[heapSize].distance = distance;
3970 heapSize += 1;
3971 }
3972 }
3973 }
3974
3975 // Heapify
3976 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3977 startIndex -= 1;
3978 for (uint32_t parentIndex = startIndex;;) {
3979 uint32_t childIndex = parentIndex * 2 + 1;
3980 if (childIndex >= heapSize) {
3981 break;
3982 }
3983
3984 if (childIndex + 1 < heapSize &&
3985 heap[childIndex + 1].distance < heap[childIndex].distance) {
3986 childIndex += 1;
3987 }
3988
3989 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3990 break;
3991 }
3992
3993 swap(heap[parentIndex], heap[childIndex]);
3994 parentIndex = childIndex;
3995 }
3996 }
3997
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003998 if (DEBUG_POINTER_ASSIGNMENT) {
3999 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
4000 for (size_t i = 0; i < heapSize; i++) {
4001 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
4002 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
4003 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004004 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004005
4006 // Pull matches out by increasing order of distance.
4007 // To avoid reassigning pointers that have already been matched, the loop keeps track
4008 // of which last and current pointers have been matched using the matchedXXXBits variables.
4009 // It also tracks the used pointer id bits.
4010 BitSet32 matchedLastBits(0);
4011 BitSet32 matchedCurrentBits(0);
4012 BitSet32 usedIdBits(0);
4013 bool first = true;
4014 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
4015 while (heapSize > 0) {
4016 if (first) {
4017 // The first time through the loop, we just consume the root element of
4018 // the heap (the one with smallest distance).
4019 first = false;
4020 } else {
4021 // Previous iterations consumed the root element of the heap.
4022 // Pop root element off of the heap (sift down).
4023 heap[0] = heap[heapSize];
4024 for (uint32_t parentIndex = 0;;) {
4025 uint32_t childIndex = parentIndex * 2 + 1;
4026 if (childIndex >= heapSize) {
4027 break;
4028 }
4029
4030 if (childIndex + 1 < heapSize &&
4031 heap[childIndex + 1].distance < heap[childIndex].distance) {
4032 childIndex += 1;
4033 }
4034
4035 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4036 break;
4037 }
4038
4039 swap(heap[parentIndex], heap[childIndex]);
4040 parentIndex = childIndex;
4041 }
4042
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004043 if (DEBUG_POINTER_ASSIGNMENT) {
4044 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4045 for (size_t j = 0; j < heapSize; j++) {
4046 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4047 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4048 heap[j].distance);
4049 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004050 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004051 }
4052
4053 heapSize -= 1;
4054
4055 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4056 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4057
4058 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4059 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4060
4061 matchedCurrentBits.markBit(currentPointerIndex);
4062 matchedLastBits.markBit(lastPointerIndex);
4063
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004064 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4065 current.rawPointerData.pointers[currentPointerIndex].id = id;
4066 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4067 current.rawPointerData.markIdBit(id,
4068 current.rawPointerData.isHovering(
4069 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004070 usedIdBits.markBit(id);
4071
Harry Cutts45483602022-08-24 14:36:48 +00004072 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4073 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4074 ", distance=%" PRIu64,
4075 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004076 break;
4077 }
4078 }
4079
4080 // Assign fresh ids to pointers that were not matched in the process.
4081 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4082 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4083 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4084
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004085 current.rawPointerData.pointers[currentPointerIndex].id = id;
4086 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4087 current.rawPointerData.markIdBit(id,
4088 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004089
Harry Cutts45483602022-08-24 14:36:48 +00004090 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4091 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4092 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004093 }
4094}
4095
4096int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4097 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4098 return AKEY_STATE_VIRTUAL;
4099 }
4100
4101 for (const VirtualKey& virtualKey : mVirtualKeys) {
4102 if (virtualKey.keyCode == keyCode) {
4103 return AKEY_STATE_UP;
4104 }
4105 }
4106
4107 return AKEY_STATE_UNKNOWN;
4108}
4109
4110int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4111 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4112 return AKEY_STATE_VIRTUAL;
4113 }
4114
4115 for (const VirtualKey& virtualKey : mVirtualKeys) {
4116 if (virtualKey.scanCode == scanCode) {
4117 return AKEY_STATE_UP;
4118 }
4119 }
4120
4121 return AKEY_STATE_UNKNOWN;
4122}
4123
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004124bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4125 const std::vector<int32_t>& keyCodes,
4126 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004127 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004128 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004129 if (virtualKey.keyCode == keyCodes[i]) {
4130 outFlags[i] = 1;
4131 }
4132 }
4133 }
4134
4135 return true;
4136}
4137
4138std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4139 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004140 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004141 return std::make_optional(mPointerController->getDisplayId());
4142 } else {
4143 return std::make_optional(mViewport.displayId);
4144 }
4145 }
4146 return std::nullopt;
4147}
4148
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004149} // namespace android