blob: c72a263dcd1f59f6d6b76a3a2282bd37d7feece4 [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
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
Prabir Pradhan8d9ba912022-11-11 22:26:33 +000024#include <input/PrintTools.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080025
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070026#include "CursorButtonAccumulator.h"
27#include "CursorScrollAccumulator.h"
28#include "TouchButtonAccumulator.h"
29#include "TouchCursorInputMapperCommon.h"
Michael Wrighta9cf4192022-12-01 23:46:39 +000030#include "ui/Rotation.h"
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070031
32namespace android {
33
34// --- Constants ---
35
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070036// Artificial latency on synthetic events created from stylus data without corresponding touch
37// data.
38static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
39
HQ Liue6983c72022-04-19 22:14:56 +000040// Minimum width between two pointers to determine a gesture as freeform gesture in mm
41static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070042// --- Static Definitions ---
43
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000044static const DisplayViewport kUninitializedViewport;
45
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000046static std::string toString(const Rect& rect) {
47 return base::StringPrintf("Rect{%d, %d, %d, %d}", rect.left, rect.top, rect.right, rect.bottom);
48}
49
50static std::string toString(const ui::Size& size) {
51 return base::StringPrintf("%dx%d", size.width, size.height);
52}
53
Prabir Pradhan675f25a2022-11-10 22:04:07 +000054static bool isPointInRect(const Rect& rect, vec2 p) {
55 return p.x >= rect.left && p.x < rect.right && p.y >= rect.top && p.y < rect.bottom;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000056}
57
Prabir Pradhane04ffaa2022-12-13 23:04:04 +000058static std::string toString(const InputDeviceUsiVersion& v) {
59 return base::StringPrintf("%d.%d", v.majorVersion, v.minorVersion);
60}
61
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070062template <typename T>
63inline static void swap(T& a, T& b) {
64 T temp = a;
65 a = b;
66 b = temp;
67}
68
69static float calculateCommonVector(float a, float b) {
70 if (a > 0 && b > 0) {
71 return a < b ? a : b;
72 } else if (a < 0 && b < 0) {
73 return a > b ? a : b;
74 } else {
75 return 0;
76 }
77}
78
79inline static float distance(float x1, float y1, float x2, float y2) {
80 return hypotf(x1 - x2, y1 - y2);
81}
82
83inline static int32_t signExtendNybble(int32_t value) {
84 return value >= 8 ? value - 16 : value;
85}
86
Prabir Pradhan675f25a2022-11-10 22:04:07 +000087static ui::Size getNaturalDisplaySize(const DisplayViewport& viewport) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000088 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +000089 if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000090 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
91 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +000092 return rotatedDisplaySize;
Prabir Pradhan2d613f42022-11-10 20:22:06 +000093}
94
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +000095static int32_t filterButtonState(InputReaderConfiguration& config, int32_t buttonState) {
96 if (!config.stylusButtonMotionEventsEnabled) {
97 buttonState &=
98 ~(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY | AMOTION_EVENT_BUTTON_STYLUS_SECONDARY);
99 }
100 return buttonState;
101}
102
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700103// --- RawPointerData ---
104
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700105void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
106 float x = 0, y = 0;
107 uint32_t count = touchingIdBits.count();
108 if (count) {
109 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
110 uint32_t id = idBits.clearFirstMarkedBit();
111 const Pointer& pointer = pointerForId(id);
112 x += pointer.x;
113 y += pointer.y;
114 }
115 x /= count;
116 y /= count;
117 }
118 *outX = x;
119 *outY = y;
120}
121
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700122// --- TouchInputMapper ---
123
Arpit Singh8e6fb252023-04-06 11:49:17 +0000124TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext,
125 const InputReaderConfiguration& readerConfig)
126 : InputMapper(deviceContext, readerConfig),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000127 mTouchButtonAccumulator(deviceContext),
Arpit Singh403e53c2023-04-18 11:46:56 +0000128 mConfig(readerConfig),
129 mParameters(computeParameters(deviceContext)) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700130
131TouchInputMapper::~TouchInputMapper() {}
132
Philip Junker4af3b3d2021-12-14 10:36:55 +0100133uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700134 return mSource;
135}
136
Harry Cuttsd02ea102023-03-17 18:21:30 +0000137void TouchInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700138 InputMapper::populateDeviceInfo(info);
139
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000140 if (mDeviceMode == DeviceMode::DISABLED) {
141 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700142 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000143
Harry Cuttsd02ea102023-03-17 18:21:30 +0000144 info.addMotionRange(mOrientedRanges.x);
145 info.addMotionRange(mOrientedRanges.y);
146 info.addMotionRange(mOrientedRanges.pressure);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000147
148 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
149 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
150 //
151 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
152 // motion, i.e. the hardware dimensions, as the finger could move completely across the
153 // touchpad in one sample cycle.
154 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
155 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
Harry Cuttsd02ea102023-03-17 18:21:30 +0000156 info.addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
157 x.resolution);
158 info.addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
159 y.resolution);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000160 }
161
162 if (mOrientedRanges.size) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000163 info.addMotionRange(*mOrientedRanges.size);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000164 }
165
166 if (mOrientedRanges.touchMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000167 info.addMotionRange(*mOrientedRanges.touchMajor);
168 info.addMotionRange(*mOrientedRanges.touchMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000169 }
170
171 if (mOrientedRanges.toolMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000172 info.addMotionRange(*mOrientedRanges.toolMajor);
173 info.addMotionRange(*mOrientedRanges.toolMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000174 }
175
176 if (mOrientedRanges.orientation) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000177 info.addMotionRange(*mOrientedRanges.orientation);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000178 }
179
180 if (mOrientedRanges.distance) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000181 info.addMotionRange(*mOrientedRanges.distance);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000182 }
183
184 if (mOrientedRanges.tilt) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000185 info.addMotionRange(*mOrientedRanges.tilt);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000186 }
187
188 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000189 info.addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000190 }
191 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000192 info.addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000193 }
Harry Cuttsd02ea102023-03-17 18:21:30 +0000194 info.setButtonUnderPad(mParameters.hasButtonUnderPad);
195 info.setUsiVersion(mParameters.usiVersion);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700196}
197
198void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700199 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800200 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700201 dumpParameters(dump);
202 dumpVirtualKeys(dump);
203 dumpRawPointerAxes(dump);
204 dumpCalibration(dump);
205 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700206 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700207
208 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000209 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000210 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
211 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
212 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700213 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
214 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
215 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
216 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
217 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
218 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
219 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
220 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
221 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
222 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
223
224 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
225 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
226 mLastRawState.rawPointerData.pointerCount);
227 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
228 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
229 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
230 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
231 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700232 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700233 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
234 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
235 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700236 pointer.distance, ftl::enum_string(pointer.toolType).c_str(),
237 toString(pointer.isHovering));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700238 }
239
240 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
241 mLastCookedState.buttonState);
242 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
243 mLastCookedState.cookedPointerData.pointerCount);
244 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
245 const PointerProperties& pointerProperties =
246 mLastCookedState.cookedPointerData.pointerProperties[i];
247 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000248 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
249 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
250 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700251 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700252 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700253 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000254 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
255 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700256 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
257 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
258 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
259 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
260 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
261 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
262 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
263 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700264 ftl::enum_string(pointerProperties.toolType).c_str(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700265 toString(mLastCookedState.cookedPointerData.isHovering(i)));
266 }
267
268 dump += INDENT3 "Stylus Fusion:\n";
269 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
270 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000271 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
272 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700273 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
274 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000275 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
276 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700277 dump += INDENT3 "External Stylus State:\n";
278 dumpStylusState(dump, mExternalStylusState);
279
Michael Wright227c5542020-07-02 18:30:52 +0100280 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700281 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
282 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
283 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
284 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
285 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
286 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
287 }
288}
289
Arpit Singh4be4eef2023-03-28 14:26:01 +0000290std::list<NotifyArgs> TouchInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000291 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000292 ConfigurationChanges changes) {
Arpit Singh4be4eef2023-03-28 14:26:01 +0000293 std::list<NotifyArgs> out = InputMapper::reconfigure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700294
Arpit Singhed6c3de2023-04-05 19:24:37 +0000295 mConfig = config;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700296
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000297 // Full configuration should happen the first time configure is called and
298 // when the device type is changed. Changing a device type can affect
299 // various other parameters so should result in a reconfiguration.
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000300 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700301 // Configure basic parameters.
Arpit Singh403e53c2023-04-18 11:46:56 +0000302 mParameters = computeParameters(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700303
304 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800305 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000306 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700307
308 // Configure absolute axis information.
309 configureRawPointerAxes();
310
311 // Prepare input device calibration.
312 parseCalibration();
313 resolveCalibration();
314 }
315
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000316 if (!changes.any() ||
317 changes.test(InputReaderConfiguration::Change::TOUCH_AFFINE_TRANSFORMATION)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700318 // Update location calibration to reflect current settings
319 updateAffineTransformation();
320 }
321
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000322 if (!changes.any() || changes.test(InputReaderConfiguration::Change::POINTER_SPEED)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700323 // Update pointer speed.
324 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
325 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
326 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
327 }
328
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000329 using namespace ftl::flag_operators;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700330 bool resetNeeded = false;
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000331 if (!changes.any() ||
332 changes.any(InputReaderConfiguration::Change::DISPLAY_INFO |
333 InputReaderConfiguration::Change::POINTER_CAPTURE |
334 InputReaderConfiguration::Change::POINTER_GESTURE_ENABLEMENT |
335 InputReaderConfiguration::Change::SHOW_TOUCHES |
336 InputReaderConfiguration::Change::EXTERNAL_STYLUS_PRESENCE |
337 InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700338 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700339 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700340 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 }
342
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000343 if (changes.any() && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700344 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000345
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700346 // Send reset, unless this is the first time the device has been configured,
347 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000348 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700349 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700350 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351}
352
353void TouchInputMapper::resolveExternalStylusPresence() {
354 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800355 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700356 mExternalStylusConnected = !devices.empty();
357
358 if (!mExternalStylusConnected) {
359 resetExternalStylus();
360 }
361}
362
Arpit Singh403e53c2023-04-18 11:46:56 +0000363TouchInputMapper::Parameters TouchInputMapper::computeParameters(
364 const InputDeviceContext& deviceContext) {
365 Parameters parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700366 // Use the pointer presentation mode for devices that do not support distinct
367 // multitouch. The spot-based presentation relies on being able to accurately
368 // locate two or more fingers on the touch pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000369 parameters.gestureMode = deviceContext.hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100370 ? Parameters::GestureMode::SINGLE_TOUCH
371 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700372
Arpit Singh403e53c2023-04-18 11:46:56 +0000373 const PropertyMap& config = deviceContext.getConfiguration();
Harry Cuttsf13161a2023-03-08 14:15:49 +0000374 std::optional<std::string> gestureModeString = config.getString("touch.gestureMode");
375 if (gestureModeString.has_value()) {
376 if (*gestureModeString == "single-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000377 parameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000378 } else if (*gestureModeString == "multi-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000379 parameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000380 } else if (*gestureModeString != "default") {
381 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700382 }
383 }
384
Arpit Singh403e53c2023-04-18 11:46:56 +0000385 parameters.deviceType = computeDeviceType(deviceContext);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700386
Arpit Singh403e53c2023-04-18 11:46:56 +0000387 parameters.hasButtonUnderPad = deviceContext.hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700388
Arpit Singh403e53c2023-04-18 11:46:56 +0000389 parameters.orientationAware =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000390 config.getBool("touch.orientationAware")
Arpit Singh403e53c2023-04-18 11:46:56 +0000391 .value_or(parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700392
Arpit Singh403e53c2023-04-18 11:46:56 +0000393 parameters.orientation = ui::ROTATION_0;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000394 std::optional<std::string> orientationString = config.getString("touch.orientation");
395 if (orientationString.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000396 if (parameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700397 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
Harry Cuttsf13161a2023-03-08 14:15:49 +0000398 } else if (*orientationString == "ORIENTATION_90") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000399 parameters.orientation = ui::ROTATION_90;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000400 } else if (*orientationString == "ORIENTATION_180") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000401 parameters.orientation = ui::ROTATION_180;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000402 } else if (*orientationString == "ORIENTATION_270") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000403 parameters.orientation = ui::ROTATION_270;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000404 } else if (*orientationString != "ORIENTATION_0") {
405 ALOGW("Invalid value for touch.orientation: '%s'", orientationString->c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700406 }
407 }
408
Arpit Singh403e53c2023-04-18 11:46:56 +0000409 parameters.hasAssociatedDisplay = false;
410 parameters.associatedDisplayIsExternal = false;
411 if (parameters.orientationAware ||
412 parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
413 parameters.deviceType == Parameters::DeviceType::POINTER ||
414 (parameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
415 deviceContext.getAssociatedViewport())) {
416 parameters.hasAssociatedDisplay = true;
417 if (parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
418 parameters.associatedDisplayIsExternal = deviceContext.isExternal();
419 parameters.uniqueDisplayId = config.getString("touch.displayId").value_or("").c_str();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700420 }
421 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000422 if (deviceContext.getAssociatedDisplayPort()) {
423 parameters.hasAssociatedDisplay = true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700424 }
425
426 // Initial downs on external touch devices should wake the device.
427 // Normally we don't do this for internal touch screens to prevent them from waking
428 // up in your pocket but you can enable it using the input device configuration.
Arpit Singh403e53c2023-04-18 11:46:56 +0000429 parameters.wake = config.getBool("touch.wake").value_or(deviceContext.isExternal());
Prabir Pradhan167c2702022-09-14 00:37:24 +0000430
Harry Cuttsf13161a2023-03-08 14:15:49 +0000431 std::optional<int32_t> usiVersionMajor = config.getInt("touch.usiVersionMajor");
432 std::optional<int32_t> usiVersionMinor = config.getInt("touch.usiVersionMinor");
433 if (usiVersionMajor.has_value() && usiVersionMinor.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000434 parameters.usiVersion = {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000435 .majorVersion = *usiVersionMajor,
436 .minorVersion = *usiVersionMinor,
437 };
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000438 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700439
Arpit Singh403e53c2023-04-18 11:46:56 +0000440 parameters.enableForInactiveViewport =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000441 config.getBool("touch.enableForInactiveViewport").value_or(false);
Arpit Singh403e53c2023-04-18 11:46:56 +0000442
443 return parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700444}
445
Arpit Singh403e53c2023-04-18 11:46:56 +0000446TouchInputMapper::Parameters::DeviceType TouchInputMapper::computeDeviceType(
447 const InputDeviceContext& deviceContext) {
448 Parameters::DeviceType deviceType;
449 if (deviceContext.hasInputProperty(INPUT_PROP_DIRECT)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000450 // The device is a touch screen.
Arpit Singh403e53c2023-04-18 11:46:56 +0000451 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
452 } else if (deviceContext.hasInputProperty(INPUT_PROP_POINTER)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000453 // The device is a pointing device like a track pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000454 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000455 } else {
456 // The device is a touch pad of unknown purpose.
Arpit Singh403e53c2023-04-18 11:46:56 +0000457 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000458 }
459
460 // Type association takes precedence over the device type found in the idc file.
Arpit Singh403e53c2023-04-18 11:46:56 +0000461 std::string deviceTypeString = deviceContext.getDeviceTypeAssociation().value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000462 if (deviceTypeString.empty()) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000463 deviceTypeString =
Arpit Singh403e53c2023-04-18 11:46:56 +0000464 deviceContext.getConfiguration().getString("touch.deviceType").value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000465 }
466 if (deviceTypeString == "touchScreen") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000467 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000468 } else if (deviceTypeString == "touchNavigation") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000469 deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000470 } else if (deviceTypeString == "pointer") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000471 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000472 } else if (deviceTypeString != "default" && deviceTypeString != "") {
473 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
474 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000475 return deviceType;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000476}
477
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700478void TouchInputMapper::dumpParameters(std::string& dump) {
479 dump += INDENT3 "Parameters:\n";
480
Dominik Laskowski75788452021-02-09 18:51:25 -0800481 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700482
Dominik Laskowski75788452021-02-09 18:51:25 -0800483 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484
485 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
486 "displayId='%s'\n",
487 toString(mParameters.hasAssociatedDisplay),
488 toString(mParameters.associatedDisplayIsExternal),
489 mParameters.uniqueDisplayId.c_str());
490 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800491 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000492 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
493 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700494 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
495 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496}
497
498void TouchInputMapper::configureRawPointerAxes() {
499 mRawPointerAxes.clear();
500}
501
502void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
503 dump += INDENT3 "Raw Touch Axes:\n";
504 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
505 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
506 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
507 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
508 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
509 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
510 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
511 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
512 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
513 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
514 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
515 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
516 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
517}
518
519bool TouchInputMapper::hasExternalStylus() const {
520 return mExternalStylusConnected;
521}
522
523/**
524 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000525 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800526 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000527 * 3. Get the matching viewport by either unique id in idc file or by the display type
528 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800529 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700530 */
531std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800532 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000533 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800534 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700535 }
536
Christine Franks2a2293c2022-01-18 11:51:16 -0800537 const std::optional<std::string> associatedDisplayUniqueId =
538 getDeviceContext().getAssociatedDisplayUniqueId();
539 if (associatedDisplayUniqueId) {
540 return getDeviceContext().getAssociatedViewport();
541 }
542
Michael Wright227c5542020-07-02 18:30:52 +0100543 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800544 std::optional<DisplayViewport> viewport =
545 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
546 if (viewport) {
547 return viewport;
548 } else {
549 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
550 mConfig.defaultPointerDisplayId);
551 }
552 }
553
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700554 // Check if uniqueDisplayId is specified in idc file.
555 if (!mParameters.uniqueDisplayId.empty()) {
556 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
557 }
558
559 ViewportType viewportTypeToUse;
560 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100561 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700562 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100563 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700564 }
565
566 std::optional<DisplayViewport> viewport =
567 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100568 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700569 ALOGW("Input device %s should be associated with external display, "
570 "fallback to internal one for the external viewport is not found.",
571 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100572 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700573 }
574
575 return viewport;
576 }
577
578 // No associated display, return a non-display viewport.
579 DisplayViewport newViewport;
580 // Raw width and height in the natural orientation.
581 int32_t rawWidth = mRawPointerAxes.getRawWidth();
582 int32_t rawHeight = mRawPointerAxes.getRawHeight();
583 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
584 return std::make_optional(newViewport);
585}
586
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800587int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
588 if (resolution < 0) {
589 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
590 getDeviceName().c_str());
591 return 0;
592 }
593 return resolution;
594}
595
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800596void TouchInputMapper::initializeSizeRanges() {
597 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
598 mSizeScale = 0.0f;
599 return;
600 }
601
602 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000603 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800604
605 // Size factors.
606 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
607 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
608 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
609 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
610 } else {
611 mSizeScale = 0.0f;
612 }
613
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700614 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
615 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
616 .source = mSource,
617 .min = 0,
618 .max = diagonalSize,
619 .flat = 0,
620 .fuzz = 0,
621 .resolution = 0,
622 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800623
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800624 if (mRawPointerAxes.touchMajor.valid) {
625 mRawPointerAxes.touchMajor.resolution =
626 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700627 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800628 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800629
630 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700631 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800632 if (mRawPointerAxes.touchMinor.valid) {
633 mRawPointerAxes.touchMinor.resolution =
634 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700635 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800636 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800637
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700638 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
639 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
640 .source = mSource,
641 .min = 0,
642 .max = diagonalSize,
643 .flat = 0,
644 .fuzz = 0,
645 .resolution = 0,
646 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800647 if (mRawPointerAxes.toolMajor.valid) {
648 mRawPointerAxes.toolMajor.resolution =
649 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700650 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800651 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800652
653 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700654 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800655 if (mRawPointerAxes.toolMinor.valid) {
656 mRawPointerAxes.toolMinor.resolution =
657 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700658 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800659 }
660
661 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700662 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
663 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
664 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
665 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800666 } else {
667 // Support for other calibrations can be added here.
668 ALOGW("%s calibration is not supported for size ranges at the moment. "
669 "Using raw resolution instead",
670 ftl::enum_string(mCalibration.sizeCalibration).c_str());
671 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800672
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700673 mOrientedRanges.size = InputDeviceInfo::MotionRange{
674 .axis = AMOTION_EVENT_AXIS_SIZE,
675 .source = mSource,
676 .min = 0,
677 .max = 1.0,
678 .flat = 0,
679 .fuzz = 0,
680 .resolution = 0,
681 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800682}
683
684void TouchInputMapper::initializeOrientedRanges() {
685 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000686 const float orientedScaleX = mRawToDisplay.getScaleX();
687 const float orientedScaleY = mRawToDisplay.getScaleY();
688 mOrientedXPrecision = 1.0f / orientedScaleX;
689 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800690
691 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
692 mOrientedRanges.x.source = mSource;
693 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
694 mOrientedRanges.y.source = mSource;
695
696 // Scale factor for terms that are not oriented in a particular axis.
697 // If the pixels are square then xScale == yScale otherwise we fake it
698 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000699 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800700
701 initializeSizeRanges();
702
703 // Pressure factors.
704 mPressureScale = 0;
705 float pressureMax = 1.0;
706 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
707 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700708 if (mCalibration.pressureScale) {
709 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800710 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
711 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
712 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
713 }
714 }
715
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700716 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
717 .axis = AMOTION_EVENT_AXIS_PRESSURE,
718 .source = mSource,
719 .min = 0,
720 .max = pressureMax,
721 .flat = 0,
722 .fuzz = 0,
723 .resolution = 0,
724 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800725
726 // Tilt
727 mTiltXCenter = 0;
728 mTiltXScale = 0;
729 mTiltYCenter = 0;
730 mTiltYScale = 0;
731 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
732 if (mHaveTilt) {
733 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
734 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
735 mTiltXScale = M_PI / 180;
736 mTiltYScale = M_PI / 180;
737
738 if (mRawPointerAxes.tiltX.resolution) {
739 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
740 }
741 if (mRawPointerAxes.tiltY.resolution) {
742 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
743 }
744
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700745 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
746 .axis = AMOTION_EVENT_AXIS_TILT,
747 .source = mSource,
748 .min = 0,
749 .max = M_PI_2,
750 .flat = 0,
751 .fuzz = 0,
752 .resolution = 0,
753 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800754 }
755
756 // Orientation
757 mOrientationScale = 0;
758 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700759 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
760 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
761 .source = mSource,
762 .min = -M_PI,
763 .max = M_PI,
764 .flat = 0,
765 .fuzz = 0,
766 .resolution = 0,
767 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800768
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800769 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
770 if (mCalibration.orientationCalibration ==
771 Calibration::OrientationCalibration::INTERPOLATED) {
772 if (mRawPointerAxes.orientation.valid) {
773 if (mRawPointerAxes.orientation.maxValue > 0) {
774 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
775 } else if (mRawPointerAxes.orientation.minValue < 0) {
776 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
777 } else {
778 mOrientationScale = 0;
779 }
780 }
781 }
782
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700783 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
784 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
785 .source = mSource,
786 .min = -M_PI_2,
787 .max = M_PI_2,
788 .flat = 0,
789 .fuzz = 0,
790 .resolution = 0,
791 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800792 }
793
794 // Distance
795 mDistanceScale = 0;
796 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
797 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700798 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800799 }
800
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700801 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800802
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700803 .axis = AMOTION_EVENT_AXIS_DISTANCE,
804 .source = mSource,
805 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
806 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
807 .flat = 0,
808 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
809 .resolution = 0,
810 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800811 }
812
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000813 // Oriented X/Y range (in the rotated display's orientation)
814 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
815 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
816 .toFloatRect();
817 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
818 mOrientedRanges.x.min = orientedRangeRect.left;
819 mOrientedRanges.y.min = orientedRangeRect.top;
820 mOrientedRanges.x.max = orientedRangeRect.right;
821 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800822
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000823 // Oriented flat (in the rotated display's orientation)
824 const auto orientedFlat =
825 transformWithoutTranslation(mRawToRotatedDisplay,
826 {static_cast<float>(mRawPointerAxes.x.flat),
827 static_cast<float>(mRawPointerAxes.y.flat)});
828 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
829 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800830
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000831 // Oriented fuzz (in the rotated display's orientation)
832 const auto orientedFuzz =
833 transformWithoutTranslation(mRawToRotatedDisplay,
834 {static_cast<float>(mRawPointerAxes.x.fuzz),
835 static_cast<float>(mRawPointerAxes.y.fuzz)});
836 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
837 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800838
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000839 // Oriented resolution (in the rotated display's orientation)
840 const auto orientedRes =
841 transformWithoutTranslation(mRawToRotatedDisplay,
842 {static_cast<float>(mRawPointerAxes.x.resolution),
843 static_cast<float>(mRawPointerAxes.y.resolution)});
844 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
845 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800846}
847
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000848void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000849 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
850 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
851 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000852
Prabir Pradhan3e798762022-12-02 21:02:11 +0000853 // See notes about input coordinates in the inputflinger docs:
854 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000855
856 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000857 ui::Transform undoOffsetInRaw;
858 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000859
Prabir Pradhan3e798762022-12-02 21:02:11 +0000860 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
861 // will now be in the same orientation as the display in ROTATION_0.
862 // Note: Negating an ui::Rotation value will give its inverse rotation.
863 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
864 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
865 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
866 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
867 // When rotating raw values, account for the extra unit added when calculating the raw range.
868 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
869 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000870
Prabir Pradhan3e798762022-12-02 21:02:11 +0000871 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
872 // now be in the same orientation as the rotated display. There is no need to rotate the
873 // coordinates to the display rotation if the device is not orientation-aware.
874 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
875 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
876 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
877 : orientedRawSize;
878 // When rotating raw values, account for the extra unit added when calculating the raw range.
879 const auto rotateInRaw = mParameters.orientationAware
880 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
881 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000882
Prabir Pradhan3e798762022-12-02 21:02:11 +0000883 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000884 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
885 // the surface of the display panel. This is usually true for touchscreens.
886 // - In POINTER mode, we cannot assume that the display and the touch device have the same
887 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
888 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
889 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
890 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000891 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
892 // are in the continuous space of the logical display.
893 ui::Transform scaleRawToDisplay;
894 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
895 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000896 if (mDeviceMode == DeviceMode::DIRECT) {
897 scaleRawToDisplay.set(xScale, 0, 0, yScale);
898 } else if (mDeviceMode == DeviceMode::POINTER) {
899 const float fixedScale = std::max(xScale, yScale);
900 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
901 } else {
902 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
903 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000904
Prabir Pradhan3e798762022-12-02 21:02:11 +0000905 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
906 // that InputReader uses.
907 const auto undoRotateInDisplay =
908 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
909 .inverse();
910
911 // Now put it all together!
912 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
913 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
914 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000915}
916
Prabir Pradhan1728b212021-10-19 16:00:03 -0700917void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000918 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700919
920 resolveExternalStylusPresence();
921
922 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100923 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000924 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700925 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100926 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700927 if (hasStylus()) {
928 mSource |= AINPUT_SOURCE_STYLUS;
929 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800930 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700931 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100932 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700933 if (hasStylus()) {
934 mSource |= AINPUT_SOURCE_STYLUS;
935 }
936 if (hasExternalStylus()) {
937 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
938 }
Michael Wright227c5542020-07-02 18:30:52 +0100939 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700940 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100941 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700942 } else {
943 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100944 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700945 }
946
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000947 const std::optional<DisplayViewport> newViewportOpt = findViewport();
948
949 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700950 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
951 ALOGW("Touch device '%s' did not report support for X or Y axis! "
952 "The device will be inoperable.",
953 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100954 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000955 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700956 ALOGI("Touch device '%s' could not query the properties of its associated "
957 "display. The device will be inoperable until the display size "
958 "becomes available.",
959 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100960 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700961 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000962 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
963 getDeviceName().c_str(), getDeviceId());
964 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000965 }
966
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700967 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000968 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000969 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
970 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
971 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
972 const float rawMeanResolution =
973 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700974
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000975 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
976 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700977 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700978 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000979 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
980 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
981 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700982
Michael Wright227c5542020-07-02 18:30:52 +0100983 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000984 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700985
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000986 mDisplayBounds = getNaturalDisplaySize(mViewport);
987 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
988 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700989
Prabir Pradhan3e798762022-12-02 21:02:11 +0000990 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
991 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
992 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000993 // InputReader works in the un-rotated display coordinate space, so we don't need to do
994 // anything if the device is already orientation-aware. If the device is not
995 // orientation-aware, then we need to apply the inverse rotation of the display so that
996 // when the display rotation is applied later as a part of the per-window transform, we
997 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700998 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000999 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00001000 : getInverseRotation(mViewport.orientation);
1001 // For orientation-aware devices that work in the un-rotated coordinate space, the
1002 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001003 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001004 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001005
1006 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001007 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001008 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001009 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001010 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001011 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001012 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001013 mRawToDisplay.reset();
1014 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001015 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001016 }
1017 }
1018
1019 // If moving between pointer modes, need to reset some state.
1020 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1021 if (deviceModeChanged) {
1022 mOrientedRanges.clear();
1023 }
1024
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001025 // Create and preserve the pointer controller in the following cases:
1026 const bool isPointerControllerNeeded =
1027 // - when the device is in pointer mode, to show the mouse cursor;
1028 (mDeviceMode == DeviceMode::POINTER) ||
1029 // - when pointer capture is enabled, to preserve the mouse cursor position;
1030 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1031 mConfig.pointerCaptureRequest.enable) ||
1032 // - when we should be showing touches;
1033 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1034 // - when we should be showing a pointer icon for direct styluses.
1035 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1036 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001037 if (mPointerController == nullptr) {
1038 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001039 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001040 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001041 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1042 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001043 } else {
lilinnandef700b2022-06-17 19:32:01 +08001044 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1045 !mConfig.showTouches) {
1046 mPointerController->clearSpots();
1047 }
Michael Wright17db18e2020-06-26 20:51:44 +01001048 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001049 }
1050
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001051 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001052 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001053 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001054 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001055 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001056
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057 configureVirtualKeys();
1058
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001059 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001060
1061 // Location
1062 updateAffineTransformation();
1063
Michael Wright227c5542020-07-02 18:30:52 +01001064 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001065 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001066 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1067 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001068
1069 // Scale movements such that one whole swipe of the touch pad covers a
1070 // given area relative to the diagonal size of the display when no acceleration
1071 // is applied.
1072 // Assume that the touch pad has a square aspect ratio such that movements in
1073 // X and Y of the same number of raw units cover the same physical distance.
1074 mPointerXMovementScale =
1075 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1076 mPointerYMovementScale = mPointerXMovementScale;
1077
1078 // Scale zooms to cover a smaller range of the display than movements do.
1079 // This value determines the area around the pointer that is affected by freeform
1080 // pointer gestures.
1081 mPointerXZoomScale =
1082 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1083 mPointerYZoomScale = mPointerXZoomScale;
1084
HQ Liue6983c72022-04-19 22:14:56 +00001085 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1086 // axis is non positive value.
1087 const float minFreeformGestureWidth =
1088 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1089
1090 mPointerGestureMaxSwipeWidth =
1091 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1092 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001093 }
1094
1095 // Inform the dispatcher about the changes.
1096 *outResetNeeded = true;
1097 bumpGeneration();
1098 }
1099}
1100
Prabir Pradhan1728b212021-10-19 16:00:03 -07001101void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001102 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001103 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001104 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1105 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001106 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001107}
1108
1109void TouchInputMapper::configureVirtualKeys() {
1110 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001111 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001112
1113 mVirtualKeys.clear();
1114
1115 if (virtualKeyDefinitions.size() == 0) {
1116 return;
1117 }
1118
1119 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1120 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1121 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1122 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1123
1124 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1125 VirtualKey virtualKey;
1126
1127 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1128 int32_t keyCode;
1129 int32_t dummyKeyMetaState;
1130 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001131 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1132 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1134 continue; // drop the key
1135 }
1136
1137 virtualKey.keyCode = keyCode;
1138 virtualKey.flags = flags;
1139
1140 // convert the key definition's display coordinates into touch coordinates for a hit box
1141 int32_t halfWidth = virtualKeyDefinition.width / 2;
1142 int32_t halfHeight = virtualKeyDefinition.height / 2;
1143
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001144 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1145 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001146 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001147 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1148 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001150 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1151 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001152 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001153 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1154 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001155 touchScreenTop;
1156 mVirtualKeys.push_back(virtualKey);
1157 }
1158}
1159
1160void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1161 if (!mVirtualKeys.empty()) {
1162 dump += INDENT3 "Virtual Keys:\n";
1163
1164 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1165 const VirtualKey& virtualKey = mVirtualKeys[i];
1166 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1167 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1168 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1169 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1170 }
1171 }
1172}
1173
1174void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001175 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 Calibration& out = mCalibration;
1177
1178 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001179 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001180 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1181 if (sizeCalibrationString.has_value()) {
1182 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001184 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001186 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001188 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001190 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001191 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001192 } else if (*sizeCalibrationString != "default") {
1193 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001194 }
1195 }
1196
Harry Cuttsf13161a2023-03-08 14:15:49 +00001197 out.sizeScale = in.getFloat("touch.size.scale");
1198 out.sizeBias = in.getFloat("touch.size.bias");
1199 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200
1201 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001202 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001203 std::optional<std::string> pressureCalibrationString =
1204 in.getString("touch.pressure.calibration");
1205 if (pressureCalibrationString.has_value()) {
1206 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001207 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001208 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001209 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001210 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001211 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001212 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001214 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 }
1216 }
1217
Harry Cuttsf13161a2023-03-08 14:15:49 +00001218 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219
1220 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001221 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001222 std::optional<std::string> orientationCalibrationString =
1223 in.getString("touch.orientation.calibration");
1224 if (orientationCalibrationString.has_value()) {
1225 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001226 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001227 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001228 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001229 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001230 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001231 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001233 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001234 }
1235 }
1236
1237 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001238 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001239 std::optional<std::string> distanceCalibrationString =
1240 in.getString("touch.distance.calibration");
1241 if (distanceCalibrationString.has_value()) {
1242 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001243 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001244 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001245 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001246 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001247 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001248 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 }
1250 }
1251
Harry Cuttsf13161a2023-03-08 14:15:49 +00001252 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253}
1254
1255void TouchInputMapper::resolveCalibration() {
1256 // Size
1257 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001258 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1259 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 }
1261 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001262 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 }
1264
1265 // Pressure
1266 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001267 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1268 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
1270 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001271 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001272 }
1273
1274 // Orientation
1275 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001276 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1277 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 }
1279 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001280 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 }
1282
1283 // Distance
1284 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001285 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1286 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 }
1288 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001289 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291}
1292
1293void TouchInputMapper::dumpCalibration(std::string& dump) {
1294 dump += INDENT3 "Calibration:\n";
1295
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001296 dump += INDENT4 "touch.size.calibration: ";
1297 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001299 if (mCalibration.sizeScale) {
1300 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 }
1302
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001303 if (mCalibration.sizeBias) {
1304 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001305 }
1306
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001307 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001309 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 }
1311
1312 // Pressure
1313 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001314 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 dump += INDENT4 "touch.pressure.calibration: none\n";
1316 break;
Michael Wright227c5542020-07-02 18:30:52 +01001317 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 dump += INDENT4 "touch.pressure.calibration: physical\n";
1319 break;
Michael Wright227c5542020-07-02 18:30:52 +01001320 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001321 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1322 break;
1323 default:
1324 ALOG_ASSERT(false);
1325 }
1326
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001327 if (mCalibration.pressureScale) {
1328 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329 }
1330
1331 // Orientation
1332 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001333 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.orientation.calibration: none\n";
1335 break;
Michael Wright227c5542020-07-02 18:30:52 +01001336 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001337 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1338 break;
Michael Wright227c5542020-07-02 18:30:52 +01001339 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001340 dump += INDENT4 "touch.orientation.calibration: vector\n";
1341 break;
1342 default:
1343 ALOG_ASSERT(false);
1344 }
1345
1346 // Distance
1347 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001348 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001349 dump += INDENT4 "touch.distance.calibration: none\n";
1350 break;
Michael Wright227c5542020-07-02 18:30:52 +01001351 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001352 dump += INDENT4 "touch.distance.calibration: scaled\n";
1353 break;
1354 default:
1355 ALOG_ASSERT(false);
1356 }
1357
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001358 if (mCalibration.distanceScale) {
1359 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001361}
1362
1363void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1364 dump += INDENT3 "Affine Transformation:\n";
1365
1366 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1367 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1368 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1369 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1370 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1371 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1372}
1373
1374void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001375 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001376 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001377}
1378
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001379std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001380 std::list<NotifyArgs> out = cancelTouch(when, when);
1381 updateTouchSpots();
1382
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001383 mCursorButtonAccumulator.reset(getDeviceContext());
1384 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001385 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001386
1387 mPointerVelocityControl.reset();
1388 mWheelXVelocityControl.reset();
1389 mWheelYVelocityControl.reset();
1390
1391 mRawStatesPending.clear();
1392 mCurrentRawState.clear();
1393 mCurrentCookedState.clear();
1394 mLastRawState.clear();
1395 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001396 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001397 mSentHoverEnter = false;
1398 mHavePointerIds = false;
1399 mCurrentMotionAborted = false;
1400 mDownTime = 0;
1401
1402 mCurrentVirtualKey.down = false;
1403
1404 mPointerGesture.reset();
1405 mPointerSimple.reset();
1406 resetExternalStylus();
1407
1408 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001409 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001410 mPointerController->clearSpots();
1411 }
1412
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001413 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001414}
1415
1416void TouchInputMapper::resetExternalStylus() {
1417 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001418 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001419 mExternalStylusFusionTimeout = LLONG_MAX;
1420 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001421 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001422}
1423
1424void TouchInputMapper::clearStylusDataPendingFlags() {
1425 mExternalStylusDataPending = false;
1426 mExternalStylusFusionTimeout = LLONG_MAX;
1427}
1428
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001429std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001430 mCursorButtonAccumulator.process(rawEvent);
1431 mCursorScrollAccumulator.process(rawEvent);
1432 mTouchButtonAccumulator.process(rawEvent);
1433
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001434 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001435 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001436 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001437 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001438 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001439}
1440
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001441std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1442 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001443 if (mDeviceMode == DeviceMode::DISABLED) {
1444 // Only save the last pending state when the device is disabled.
1445 mRawStatesPending.clear();
1446 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001447 // Push a new state.
1448 mRawStatesPending.emplace_back();
1449
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001450 RawState& next = mRawStatesPending.back();
1451 next.clear();
1452 next.when = when;
1453 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001454
1455 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001456 next.buttonState = filterButtonState(mConfig,
1457 mTouchButtonAccumulator.getButtonState() |
1458 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001459
1460 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001461 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1462 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001463 mCursorScrollAccumulator.finishSync();
1464
1465 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001466 syncTouch(when, &next);
1467
1468 // The last RawState is the actually second to last, since we just added a new state
1469 const RawState& last =
1470 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001471
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001472 std::tie(next.when, next.readTime) =
1473 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1474 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001475
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001476 // Assign pointer ids.
1477 if (!mHavePointerIds) {
1478 assignPointerIds(last, next);
1479 }
1480
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001481 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001482 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1483 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1484 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1485 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1486 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1487 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001488
Arthur Hung9ad18942021-06-19 02:04:46 +00001489 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1490 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1491 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1492 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1493 next.rawPointerData.hoveringIdBits.value);
1494 }
1495
Harry Cutts33476232023-01-30 19:57:29 +00001496 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001497 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498}
1499
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001500std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1501 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001502 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001503 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001504 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001505 }
1506
1507 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1508 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1509 // touching the current state will only observe the events that have been dispatched to the
1510 // rest of the pipeline.
1511 const size_t N = mRawStatesPending.size();
1512 size_t count;
1513 for (count = 0; count < N; count++) {
1514 const RawState& next = mRawStatesPending[count];
1515
1516 // A failure to assign the stylus id means that we're waiting on stylus data
1517 // and so should defer the rest of the pipeline.
1518 if (assignExternalStylusId(next, timeout)) {
1519 break;
1520 }
1521
1522 // All ready to go.
1523 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001524 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001525 if (mCurrentRawState.when < mLastRawState.when) {
1526 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001527 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001528 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001529 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001530 }
1531 if (count != 0) {
1532 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1533 }
1534
1535 if (mExternalStylusDataPending) {
1536 if (timeout) {
1537 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1538 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001539 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001540 ALOGD_IF(DEBUG_STYLUS_FUSION,
1541 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001542 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001543 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001544 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1545 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1546 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1547 }
1548 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001549 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550}
1551
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001552std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1553 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001554 // Always start with a clean state.
1555 mCurrentCookedState.clear();
1556
1557 // Apply stylus buttons to current raw state.
1558 applyExternalStylusButtonState(when);
1559
1560 // Handle policy on initial down or hover events.
1561 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1562 mCurrentRawState.rawPointerData.pointerCount != 0;
1563
1564 uint32_t policyFlags = 0;
1565 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1566 if (initialDown || buttonsPressed) {
1567 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001568 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001569 getContext()->fadePointer();
1570 }
1571
1572 if (mParameters.wake) {
1573 policyFlags |= POLICY_FLAG_WAKE;
1574 }
1575 }
1576
1577 // Consume raw off-screen touches before cooking pointer data.
1578 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001579 bool consumed;
1580 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1581 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001582 mCurrentRawState.rawPointerData.clear();
1583 }
1584
1585 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1586 // with cooked pointer data that has the same ids and indices as the raw data.
1587 // The following code can use either the raw or cooked data, as needed.
1588 cookPointerData();
1589
1590 // Apply stylus pressure to current cooked state.
1591 applyExternalStylusTouchState(when);
1592
1593 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001594 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1595 mSource, mViewport.displayId, policyFlags,
1596 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001597
1598 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001599 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001600 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1601 uint32_t id = idBits.clearFirstMarkedBit();
1602 const RawPointerData::Pointer& pointer =
1603 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001604 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001605 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001606 } else if (pointer.toolType == ToolType::FINGER ||
1607 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001608 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001609 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001610 mCurrentCookedState.mouseIdBits.markBit(id);
1611 }
1612 }
1613 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1614 uint32_t id = idBits.clearFirstMarkedBit();
1615 const RawPointerData::Pointer& pointer =
1616 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001617 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001618 mCurrentCookedState.stylusIdBits.markBit(id);
1619 }
1620 }
1621
1622 // Stylus takes precedence over all tools, then mouse, then finger.
1623 PointerUsage pointerUsage = mPointerUsage;
1624 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1625 mCurrentCookedState.mouseIdBits.clear();
1626 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001627 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001628 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1629 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001630 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001631 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1632 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001633 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001634 }
1635
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001636 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001637 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001638 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001639 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001640 out += dispatchButtonRelease(when, readTime, policyFlags);
1641 out += dispatchHoverExit(when, readTime, policyFlags);
1642 out += dispatchTouches(when, readTime, policyFlags);
1643 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1644 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001645 }
1646
1647 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1648 mCurrentMotionAborted = false;
1649 }
1650 }
1651
1652 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001653 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1654 mSource, mViewport.displayId, policyFlags,
1655 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001656
1657 // Clear some transient state.
1658 mCurrentRawState.rawVScroll = 0;
1659 mCurrentRawState.rawHScroll = 0;
1660
1661 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001662 mLastRawState = mCurrentRawState;
1663 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001664 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001665}
1666
Garfield Tanc734e4f2021-01-15 20:01:39 -08001667void TouchInputMapper::updateTouchSpots() {
1668 if (!mConfig.showTouches || mPointerController == nullptr) {
1669 return;
1670 }
1671
1672 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1673 // clear touch spots.
1674 if (mDeviceMode != DeviceMode::DIRECT &&
1675 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1676 return;
1677 }
1678
1679 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1680 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1681
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001682 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1683 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001684 mCurrentCookedState.cookedPointerData.touchingIdBits |
1685 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001686 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001687}
1688
1689bool TouchInputMapper::isTouchScreen() {
1690 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1691 mParameters.hasAssociatedDisplay;
1692}
1693
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001694void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001695 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1696 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001697 const int32_t pressedButtons =
1698 filterButtonState(mConfig,
1699 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001700 const int32_t releasedButtons =
1701 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1702
1703 mCurrentRawState.buttonState |= pressedButtons;
1704 mCurrentRawState.buttonState &= ~releasedButtons;
1705
1706 mExternalStylusButtonsApplied |= pressedButtons;
1707 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001708 }
1709}
1710
1711void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1712 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1713 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001714 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1715 return;
1716 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001717
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001718 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1719 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1720 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1721 : 0.f;
1722 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1723 pressure = *mExternalStylusState.pressure;
1724 }
1725 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1726 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001727
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001728 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001729 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001730 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001731 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001732 }
1733}
1734
1735bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001736 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001737 return false;
1738 }
1739
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001740 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001741 if (mFusedStylusPointerId &&
1742 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001743 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001744 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001745 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001746 }
1747
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001748 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1749 state.rawPointerData.pointerCount != 0;
1750 if (!initialDown) {
1751 return false;
1752 }
1753
1754 if (!mExternalStylusState.pressure) {
1755 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1756 return false;
1757 }
1758
1759 if (*mExternalStylusState.pressure != 0.0f) {
1760 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1761 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1762 return false;
1763 }
1764
1765 if (timeout) {
1766 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1767 mFusedStylusPointerId.reset();
1768 mExternalStylusFusionTimeout = LLONG_MAX;
1769 return false;
1770 }
1771
1772 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1773 // being processed until we either get pressure data or timeout.
1774 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1775 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1776 }
1777 ALOGD_IF(DEBUG_STYLUS_FUSION,
1778 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1779 mExternalStylusFusionTimeout);
1780 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1781 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001782}
1783
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001784std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1785 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001786 if (mDeviceMode == DeviceMode::POINTER) {
1787 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001788 // Since this is a synthetic event, we can consider its latency to be zero
1789 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001790 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001791 }
Michael Wright227c5542020-07-02 18:30:52 +01001792 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001793 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001794 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001795 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1796 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1797 }
1798 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001799 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001800}
1801
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001802std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1803 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001804 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001805 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001806 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001807 // The following three cases are handled here:
1808 // - We're in the middle of a fused stream of data;
1809 // - We're waiting on external stylus data before dispatching the initial down; or
1810 // - Only the button state, which is not reported through a specific pointer, has changed.
1811 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001812 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001813 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001814 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001815 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001816}
1817
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001818std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1819 uint32_t policyFlags, bool& outConsumed) {
1820 outConsumed = false;
1821 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001822 // Check for release of a virtual key.
1823 if (mCurrentVirtualKey.down) {
1824 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1825 // Pointer went up while virtual key was down.
1826 mCurrentVirtualKey.down = false;
1827 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001828 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1829 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1830 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001831 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1832 AKEY_EVENT_FLAG_FROM_SYSTEM |
1833 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001834 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001835 outConsumed = true;
1836 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001837 }
1838
1839 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1840 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1841 const RawPointerData::Pointer& pointer =
1842 mCurrentRawState.rawPointerData.pointerForId(id);
1843 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1844 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1845 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001846 outConsumed = true;
1847 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001848 }
1849 }
1850
1851 // Pointer left virtual key area or another pointer also went down.
1852 // Send key cancellation but do not consume the touch yet.
1853 // This is useful when the user swipes through from the virtual key area
1854 // into the main display surface.
1855 mCurrentVirtualKey.down = false;
1856 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001857 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1858 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001859 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1860 AKEY_EVENT_FLAG_FROM_SYSTEM |
1861 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1862 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001863 }
1864 }
1865
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001866 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
1867 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty() &&
1868 mDeviceMode != DeviceMode::UNSCALED) {
1869 // We have hovering pointers, and there are no touching pointers.
1870 bool hoveringPointersInFrame = false;
1871 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1872 while (!hoveringIds.isEmpty()) {
1873 uint32_t id = hoveringIds.clearFirstMarkedBit();
1874 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1875 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1876 hoveringPointersInFrame = true;
1877 break;
1878 }
1879 }
1880 if (!hoveringPointersInFrame) {
1881 // All hovering pointers are outside the physical frame.
1882 outConsumed = true;
1883 return out;
1884 }
1885 }
1886
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001887 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1888 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1889 // Pointer just went down. Check for virtual key press or off-screen touches.
1890 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1891 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001892 // Skip checking whether the pointer is inside the physical frame if the device is in
1893 // unscaled mode.
1894 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1895 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001896 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001897 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001898 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1899 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1900 if (virtualKey) {
1901 mCurrentVirtualKey.down = true;
1902 mCurrentVirtualKey.downTime = when;
1903 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1904 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1905 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001906 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1907 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001908
1909 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001910 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1911 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1912 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001913 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1914 AKEY_EVENT_ACTION_DOWN,
1915 AKEY_EVENT_FLAG_FROM_SYSTEM |
1916 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001917 }
1918 }
1919 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001920 outConsumed = true;
1921 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001922 }
1923 }
1924
1925 // Disable all virtual key touches that happen within a short time interval of the
1926 // most recent touch within the screen area. The idea is to filter out stray
1927 // virtual key presses when interacting with the touch screen.
1928 //
1929 // Problems we're trying to solve:
1930 //
1931 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1932 // virtual key area that is implemented by a separate touch panel and accidentally
1933 // triggers a virtual key.
1934 //
1935 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1936 // area and accidentally triggers a virtual key. This often happens when virtual keys
1937 // are layed out below the screen near to where the on screen keyboard's space bar
1938 // is displayed.
1939 if (mConfig.virtualKeyQuietTime > 0 &&
1940 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001941 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001942 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001943 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001944}
1945
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001946NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1947 uint32_t policyFlags, int32_t keyEventAction,
1948 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001949 int32_t keyCode = mCurrentVirtualKey.keyCode;
1950 int32_t scanCode = mCurrentVirtualKey.scanCode;
1951 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001952 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001953 policyFlags |= POLICY_FLAG_VIRTUAL;
1954
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001955 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1956 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1957 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001958}
1959
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001960std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1961 uint32_t policyFlags) {
1962 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001963 if (mCurrentMotionAborted) {
1964 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001965 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001966 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001967 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1968 if (!currentIdBits.isEmpty()) {
1969 int32_t metaState = getContext()->getGlobalMetaState();
1970 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001971 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001972 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1973 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001974 mCurrentCookedState.cookedPointerData.pointerProperties,
1975 mCurrentCookedState.cookedPointerData.pointerCoords,
1976 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1977 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1978 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001979 mCurrentMotionAborted = true;
1980 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001981 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001982}
1983
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001984// Updates pointer coords and properties for pointers with specified ids that have moved.
1985// Returns true if any of them changed.
1986static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1987 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1988 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1989 BitSet32 idBits) {
1990 bool changed = false;
1991 while (!idBits.isEmpty()) {
1992 uint32_t id = idBits.clearFirstMarkedBit();
1993 uint32_t inIndex = inIdToIndex[id];
1994 uint32_t outIndex = outIdToIndex[id];
1995
1996 const PointerProperties& curInProperties = inProperties[inIndex];
1997 const PointerCoords& curInCoords = inCoords[inIndex];
1998 PointerProperties& curOutProperties = outProperties[outIndex];
1999 PointerCoords& curOutCoords = outCoords[outIndex];
2000
2001 if (curInProperties != curOutProperties) {
2002 curOutProperties.copyFrom(curInProperties);
2003 changed = true;
2004 }
2005
2006 if (curInCoords != curOutCoords) {
2007 curOutCoords.copyFrom(curInCoords);
2008 changed = true;
2009 }
2010 }
2011 return changed;
2012}
2013
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002014std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
2015 uint32_t policyFlags) {
2016 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002017 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2018 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2019 int32_t metaState = getContext()->getGlobalMetaState();
2020 int32_t buttonState = mCurrentCookedState.buttonState;
2021
2022 if (currentIdBits == lastIdBits) {
2023 if (!currentIdBits.isEmpty()) {
2024 // No pointer id changes so this is a move event.
2025 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002026 out.push_back(
2027 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2028 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2029 mCurrentCookedState.cookedPointerData.pointerProperties,
2030 mCurrentCookedState.cookedPointerData.pointerCoords,
2031 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2032 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2033 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002034 }
2035 } else {
2036 // There may be pointers going up and pointers going down and pointers moving
2037 // all at the same time.
2038 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2039 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2040 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2041 BitSet32 dispatchedIdBits(lastIdBits.value);
2042
2043 // Update last coordinates of pointers that have moved so that we observe the new
2044 // pointer positions at the same time as other pointers that have just gone up.
2045 bool moveNeeded =
2046 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2047 mCurrentCookedState.cookedPointerData.pointerCoords,
2048 mCurrentCookedState.cookedPointerData.idToIndex,
2049 mLastCookedState.cookedPointerData.pointerProperties,
2050 mLastCookedState.cookedPointerData.pointerCoords,
2051 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2052 if (buttonState != mLastCookedState.buttonState) {
2053 moveNeeded = true;
2054 }
2055
2056 // Dispatch pointer up events.
2057 while (!upIdBits.isEmpty()) {
2058 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002059 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002060 if (isCanceled) {
2061 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2062 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002063 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2064 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2065 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2066 buttonState, 0,
2067 mLastCookedState.cookedPointerData.pointerProperties,
2068 mLastCookedState.cookedPointerData.pointerCoords,
2069 mLastCookedState.cookedPointerData.idToIndex,
2070 dispatchedIdBits, upId, mOrientedXPrecision,
2071 mOrientedYPrecision, mDownTime,
2072 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002073 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002074 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002075 }
2076
2077 // Dispatch move events if any of the remaining pointers moved from their old locations.
2078 // Although applications receive new locations as part of individual pointer up
2079 // events, they do not generally handle them except when presented in a move event.
2080 if (moveNeeded && !moveIdBits.isEmpty()) {
2081 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002082 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2083 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2084 mCurrentCookedState.cookedPointerData.pointerProperties,
2085 mCurrentCookedState.cookedPointerData.pointerCoords,
2086 mCurrentCookedState.cookedPointerData.idToIndex,
2087 dispatchedIdBits, -1, mOrientedXPrecision,
2088 mOrientedYPrecision, mDownTime,
2089 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002090 }
2091
2092 // Dispatch pointer down events using the new pointer locations.
2093 while (!downIdBits.isEmpty()) {
2094 uint32_t downId = downIdBits.clearFirstMarkedBit();
2095 dispatchedIdBits.markBit(downId);
2096
2097 if (dispatchedIdBits.count() == 1) {
2098 // First pointer is going down. Set down time.
2099 mDownTime = when;
2100 }
2101
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002102 out.push_back(
2103 dispatchMotion(when, readTime, policyFlags, mSource,
2104 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2105 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2106 mCurrentCookedState.cookedPointerData.pointerCoords,
2107 mCurrentCookedState.cookedPointerData.idToIndex,
2108 dispatchedIdBits, downId, mOrientedXPrecision,
2109 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002110 }
2111 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002112 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002113}
2114
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002115std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2116 uint32_t policyFlags) {
2117 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002118 if (mSentHoverEnter &&
2119 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2120 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2121 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002122 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2123 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2124 mLastCookedState.buttonState, 0,
2125 mLastCookedState.cookedPointerData.pointerProperties,
2126 mLastCookedState.cookedPointerData.pointerCoords,
2127 mLastCookedState.cookedPointerData.idToIndex,
2128 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2129 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2130 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002131 mSentHoverEnter = false;
2132 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002133 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002134}
2135
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002136std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2137 uint32_t policyFlags) {
2138 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002139 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2140 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2141 int32_t metaState = getContext()->getGlobalMetaState();
2142 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002143 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2144 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2145 mCurrentRawState.buttonState, 0,
2146 mCurrentCookedState.cookedPointerData.pointerProperties,
2147 mCurrentCookedState.cookedPointerData.pointerCoords,
2148 mCurrentCookedState.cookedPointerData.idToIndex,
2149 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2150 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2151 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002152 mSentHoverEnter = true;
2153 }
2154
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002155 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2156 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2157 mCurrentRawState.buttonState, 0,
2158 mCurrentCookedState.cookedPointerData.pointerProperties,
2159 mCurrentCookedState.cookedPointerData.pointerCoords,
2160 mCurrentCookedState.cookedPointerData.idToIndex,
2161 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2162 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2163 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002164 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002165 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002166}
2167
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002168std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2169 uint32_t policyFlags) {
2170 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002171 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2172 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2173 const int32_t metaState = getContext()->getGlobalMetaState();
2174 int32_t buttonState = mLastCookedState.buttonState;
2175 while (!releasedButtons.isEmpty()) {
2176 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2177 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002178 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2179 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2180 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002181 mLastCookedState.cookedPointerData.pointerProperties,
2182 mLastCookedState.cookedPointerData.pointerCoords,
2183 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002184 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2185 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002186 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002187 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002188}
2189
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002190std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2191 uint32_t policyFlags) {
2192 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002193 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2194 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2195 const int32_t metaState = getContext()->getGlobalMetaState();
2196 int32_t buttonState = mLastCookedState.buttonState;
2197 while (!pressedButtons.isEmpty()) {
2198 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2199 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002200 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2201 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2202 buttonState, 0,
2203 mCurrentCookedState.cookedPointerData.pointerProperties,
2204 mCurrentCookedState.cookedPointerData.pointerCoords,
2205 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2206 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2207 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002208 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002209 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002210}
2211
LiZhihong758eb562022-11-03 15:28:29 +08002212std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2213 uint32_t policyFlags,
2214 BitSet32 idBits,
2215 nsecs_t readTime) {
2216 std::list<NotifyArgs> out;
2217 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2218 const int32_t metaState = getContext()->getGlobalMetaState();
2219 int32_t buttonState = mLastCookedState.buttonState;
2220
2221 while (!releasedButtons.isEmpty()) {
2222 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2223 buttonState &= ~actionButton;
2224 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2225 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2226 metaState, buttonState, 0,
2227 mPointerGesture.lastGestureProperties,
2228 mPointerGesture.lastGestureCoords,
2229 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2230 mOrientedXPrecision, mOrientedYPrecision,
2231 mPointerGesture.downTime, MotionClassification::NONE));
2232 }
2233 return out;
2234}
2235
2236std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2237 uint32_t policyFlags,
2238 BitSet32 idBits,
2239 nsecs_t readTime) {
2240 std::list<NotifyArgs> out;
2241 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2242 const int32_t metaState = getContext()->getGlobalMetaState();
2243 int32_t buttonState = mLastCookedState.buttonState;
2244
2245 while (!pressedButtons.isEmpty()) {
2246 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2247 buttonState |= actionButton;
2248 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2249 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2250 buttonState, 0, mPointerGesture.currentGestureProperties,
2251 mPointerGesture.currentGestureCoords,
2252 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2253 mOrientedXPrecision, mOrientedYPrecision,
2254 mPointerGesture.downTime, MotionClassification::NONE));
2255 }
2256 return out;
2257}
2258
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002259const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2260 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2261 return cookedPointerData.touchingIdBits;
2262 }
2263 return cookedPointerData.hoveringIdBits;
2264}
2265
2266void TouchInputMapper::cookPointerData() {
2267 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2268
2269 mCurrentCookedState.cookedPointerData.clear();
2270 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2271 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2272 mCurrentRawState.rawPointerData.hoveringIdBits;
2273 mCurrentCookedState.cookedPointerData.touchingIdBits =
2274 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002275 mCurrentCookedState.cookedPointerData.canceledIdBits =
2276 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002277
2278 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2279 mCurrentCookedState.buttonState = 0;
2280 } else {
2281 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2282 }
2283
2284 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002285 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002286 for (uint32_t i = 0; i < currentPointerCount; i++) {
2287 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2288
2289 // Size
2290 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2291 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002292 case Calibration::SizeCalibration::GEOMETRIC:
2293 case Calibration::SizeCalibration::DIAMETER:
2294 case Calibration::SizeCalibration::BOX:
2295 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2297 touchMajor = in.touchMajor;
2298 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2299 toolMajor = in.toolMajor;
2300 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2301 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2302 : in.touchMajor;
2303 } else if (mRawPointerAxes.touchMajor.valid) {
2304 toolMajor = touchMajor = in.touchMajor;
2305 toolMinor = touchMinor =
2306 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2307 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2308 : in.touchMajor;
2309 } else if (mRawPointerAxes.toolMajor.valid) {
2310 touchMajor = toolMajor = in.toolMajor;
2311 touchMinor = toolMinor =
2312 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2313 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2314 : in.toolMajor;
2315 } else {
2316 ALOG_ASSERT(false,
2317 "No touch or tool axes. "
2318 "Size calibration should have been resolved to NONE.");
2319 touchMajor = 0;
2320 touchMinor = 0;
2321 toolMajor = 0;
2322 toolMinor = 0;
2323 size = 0;
2324 }
2325
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002326 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002327 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2328 if (touchingCount > 1) {
2329 touchMajor /= touchingCount;
2330 touchMinor /= touchingCount;
2331 toolMajor /= touchingCount;
2332 toolMinor /= touchingCount;
2333 size /= touchingCount;
2334 }
2335 }
2336
Michael Wright227c5542020-07-02 18:30:52 +01002337 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002338 touchMajor *= mGeometricScale;
2339 touchMinor *= mGeometricScale;
2340 toolMajor *= mGeometricScale;
2341 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002342 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002343 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2344 touchMinor = touchMajor;
2345 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2346 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002347 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002348 touchMinor = touchMajor;
2349 toolMinor = toolMajor;
2350 }
2351
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002352 mCalibration.applySizeScaleAndBias(touchMajor);
2353 mCalibration.applySizeScaleAndBias(touchMinor);
2354 mCalibration.applySizeScaleAndBias(toolMajor);
2355 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 size *= mSizeScale;
2357 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002358 case Calibration::SizeCalibration::DEFAULT:
2359 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2360 break;
2361 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002362 touchMajor = 0;
2363 touchMinor = 0;
2364 toolMajor = 0;
2365 toolMinor = 0;
2366 size = 0;
2367 break;
2368 }
2369
2370 // Pressure
2371 float pressure;
2372 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002373 case Calibration::PressureCalibration::PHYSICAL:
2374 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 pressure = in.pressure * mPressureScale;
2376 break;
2377 default:
2378 pressure = in.isHovering ? 0 : 1;
2379 break;
2380 }
2381
2382 // Tilt and Orientation
2383 float tilt;
2384 float orientation;
2385 if (mHaveTilt) {
2386 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2387 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002388 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2390 } else {
2391 tilt = 0;
2392
2393 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002394 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002395 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 break;
Michael Wright227c5542020-07-02 18:30:52 +01002397 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2399 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2400 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002401 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402 float confidence = hypotf(c1, c2);
2403 float scale = 1.0f + confidence / 16.0f;
2404 touchMajor *= scale;
2405 touchMinor /= scale;
2406 toolMajor *= scale;
2407 toolMinor /= scale;
2408 } else {
2409 orientation = 0;
2410 }
2411 break;
2412 }
2413 default:
2414 orientation = 0;
2415 }
2416 }
2417
2418 // Distance
2419 float distance;
2420 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002421 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002422 distance = in.distance * mDistanceScale;
2423 break;
2424 default:
2425 distance = 0;
2426 }
2427
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002428 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2429 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002430 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2431 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002432
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002433 // Write output coords.
2434 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2435 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002436 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2437 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002438 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2439 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2440 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2441 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2442 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2443 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2444 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002445 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2446 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002447
Chris Ye364fdb52020-08-05 15:07:56 -07002448 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002449 uint32_t id = in.id;
2450 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2451 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2452 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002453 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2454 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002455 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2456 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2457 }
2458
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002459 // Write output properties.
2460 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 properties.clear();
2462 properties.id = id;
2463 properties.toolType = in.toolType;
2464
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002465 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002467 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 }
2469}
2470
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002471std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2472 uint32_t policyFlags,
2473 PointerUsage pointerUsage) {
2474 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002475 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002476 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002477 mPointerUsage = pointerUsage;
2478 }
2479
2480 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002481 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002482 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002483 break;
Michael Wright227c5542020-07-02 18:30:52 +01002484 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002485 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486 break;
Michael Wright227c5542020-07-02 18:30:52 +01002487 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002488 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002489 break;
Michael Wright227c5542020-07-02 18:30:52 +01002490 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002491 break;
2492 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002493 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002494}
2495
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002496std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2497 uint32_t policyFlags) {
2498 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002499 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002500 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002501 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002502 break;
Michael Wright227c5542020-07-02 18:30:52 +01002503 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002504 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002505 break;
Michael Wright227c5542020-07-02 18:30:52 +01002506 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002507 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002508 break;
Michael Wright227c5542020-07-02 18:30:52 +01002509 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002510 break;
2511 }
2512
Michael Wright227c5542020-07-02 18:30:52 +01002513 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002514 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002515}
2516
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002517std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2518 uint32_t policyFlags,
2519 bool isTimeout) {
2520 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002521 // Update current gesture coordinates.
2522 bool cancelPreviousGesture, finishPreviousGesture;
2523 bool sendEvents =
2524 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2525 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002526 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002527 }
2528 if (finishPreviousGesture) {
2529 cancelPreviousGesture = false;
2530 }
2531
2532 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002533 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002534 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002535 if (finishPreviousGesture || cancelPreviousGesture) {
2536 mPointerController->clearSpots();
2537 }
2538
Michael Wright227c5542020-07-02 18:30:52 +01002539 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002540 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2541 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002542 mPointerGesture.currentGestureIdBits,
2543 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544 }
2545 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002546 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002547 }
2548
2549 // Show or hide the pointer if needed.
2550 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002551 case PointerGesture::Mode::NEUTRAL:
2552 case PointerGesture::Mode::QUIET:
2553 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2554 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002555 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002556 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002557 }
2558 break;
Michael Wright227c5542020-07-02 18:30:52 +01002559 case PointerGesture::Mode::TAP:
2560 case PointerGesture::Mode::TAP_DRAG:
2561 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2562 case PointerGesture::Mode::HOVER:
2563 case PointerGesture::Mode::PRESS:
2564 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002565 // Unfade the pointer when the current gesture manipulates the
2566 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002567 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002568 break;
Michael Wright227c5542020-07-02 18:30:52 +01002569 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002570 // Fade the pointer when the current gesture manipulates a different
2571 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002572 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002573 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002574 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002575 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002576 }
2577 break;
2578 }
2579
2580 // Send events!
2581 int32_t metaState = getContext()->getGlobalMetaState();
2582 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002583 const MotionClassification classification =
2584 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2585 ? MotionClassification::TWO_FINGER_SWIPE
2586 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002587
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002588 uint32_t flags = 0;
2589
2590 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2591 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2592 }
2593
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002594 // Update last coordinates of pointers that have moved so that we observe the new
2595 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002596 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2597 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2598 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2599 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2600 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2601 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002602 bool moveNeeded = false;
2603 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2604 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2605 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2606 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2607 mPointerGesture.lastGestureIdBits.value);
2608 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2609 mPointerGesture.currentGestureCoords,
2610 mPointerGesture.currentGestureIdToIndex,
2611 mPointerGesture.lastGestureProperties,
2612 mPointerGesture.lastGestureCoords,
2613 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2614 if (buttonState != mLastCookedState.buttonState) {
2615 moveNeeded = true;
2616 }
2617 }
2618
2619 // Send motion events for all pointers that went up or were canceled.
2620 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2621 if (!dispatchedGestureIdBits.isEmpty()) {
2622 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002623 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002624 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002625 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002626 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2627 mPointerGesture.lastGestureProperties,
2628 mPointerGesture.lastGestureCoords,
2629 mPointerGesture.lastGestureIdToIndex,
2630 dispatchedGestureIdBits, -1, 0, 0,
2631 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002632
2633 dispatchedGestureIdBits.clear();
2634 } else {
2635 BitSet32 upGestureIdBits;
2636 if (finishPreviousGesture) {
2637 upGestureIdBits = dispatchedGestureIdBits;
2638 } else {
2639 upGestureIdBits.value =
2640 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2641 }
2642 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002643 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2644 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2645 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2646 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2647 readTime);
2648 }
2649 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002650 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2651 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2652 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2653 mPointerGesture.lastGestureProperties,
2654 mPointerGesture.lastGestureCoords,
2655 mPointerGesture.lastGestureIdToIndex,
2656 dispatchedGestureIdBits, id, 0, 0,
2657 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002658
2659 dispatchedGestureIdBits.clearBit(id);
2660 }
2661 }
2662 }
2663
2664 // Send motion events for all pointers that moved.
2665 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002666 out.push_back(
2667 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2668 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2669 mPointerGesture.currentGestureProperties,
2670 mPointerGesture.currentGestureCoords,
2671 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2672 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002673 }
2674
2675 // Send motion events for all pointers that went down.
2676 if (down) {
2677 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2678 ~dispatchedGestureIdBits.value);
2679 while (!downGestureIdBits.isEmpty()) {
2680 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2681 dispatchedGestureIdBits.markBit(id);
2682
2683 if (dispatchedGestureIdBits.count() == 1) {
2684 mPointerGesture.downTime = when;
2685 }
2686
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002687 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2688 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2689 buttonState, 0, mPointerGesture.currentGestureProperties,
2690 mPointerGesture.currentGestureCoords,
2691 mPointerGesture.currentGestureIdToIndex,
2692 dispatchedGestureIdBits, id, 0, 0,
2693 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002694 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2695 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2696 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2697 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2698 readTime);
2699 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002700 }
2701 }
2702
2703 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002704 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002705 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2706 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2707 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2708 mPointerGesture.currentGestureProperties,
2709 mPointerGesture.currentGestureCoords,
2710 mPointerGesture.currentGestureIdToIndex,
2711 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2712 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002713 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2714 // Synthesize a hover move event after all pointers go up to indicate that
2715 // the pointer is hovering again even if the user is not currently touching
2716 // the touch pad. This ensures that a view will receive a fresh hover enter
2717 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002718 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002719
2720 PointerProperties pointerProperties;
2721 pointerProperties.clear();
2722 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002723 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002724
2725 PointerCoords pointerCoords;
2726 pointerCoords.clear();
2727 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2728 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2729
2730 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002731 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2732 mSource, displayId, policyFlags,
2733 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2734 buttonState, MotionClassification::NONE,
2735 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2736 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2737 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002738 }
2739
2740 // Update state.
2741 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2742 if (!down) {
2743 mPointerGesture.lastGestureIdBits.clear();
2744 } else {
2745 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2746 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2747 uint32_t id = idBits.clearFirstMarkedBit();
2748 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2749 mPointerGesture.lastGestureProperties[index].copyFrom(
2750 mPointerGesture.currentGestureProperties[index]);
2751 mPointerGesture.lastGestureCoords[index].copyFrom(
2752 mPointerGesture.currentGestureCoords[index]);
2753 mPointerGesture.lastGestureIdToIndex[id] = index;
2754 }
2755 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002756 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002757}
2758
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002759std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2760 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002761 const MotionClassification classification =
2762 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2763 ? MotionClassification::TWO_FINGER_SWIPE
2764 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002765 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002766 // Cancel previously dispatches pointers.
2767 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2768 int32_t metaState = getContext()->getGlobalMetaState();
2769 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002770 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002771 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2772 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002773 mPointerGesture.lastGestureProperties,
2774 mPointerGesture.lastGestureCoords,
2775 mPointerGesture.lastGestureIdToIndex,
2776 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2777 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002778 }
2779
2780 // Reset the current pointer gesture.
2781 mPointerGesture.reset();
2782 mPointerVelocityControl.reset();
2783
2784 // Remove any current spots.
2785 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002786 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002787 mPointerController->clearSpots();
2788 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002789 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002790}
2791
2792bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2793 bool* outFinishPreviousGesture, bool isTimeout) {
2794 *outCancelPreviousGesture = false;
2795 *outFinishPreviousGesture = false;
2796
2797 // Handle TAP timeout.
2798 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002799 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002800
Michael Wright227c5542020-07-02 18:30:52 +01002801 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002802 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2803 // The tap/drag timeout has not yet expired.
2804 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2805 mConfig.pointerGestureTapDragInterval);
2806 } else {
2807 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002808 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002809 *outFinishPreviousGesture = true;
2810
2811 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002812 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002813 mPointerGesture.currentGestureIdBits.clear();
2814
2815 mPointerVelocityControl.reset();
2816 return true;
2817 }
2818 }
2819
2820 // We did not handle this timeout.
2821 return false;
2822 }
2823
2824 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2825 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2826
2827 // Update the velocity tracker.
2828 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002829 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 uint32_t id = idBits.clearFirstMarkedBit();
2831 const RawPointerData::Pointer& pointer =
2832 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002833 const float x = pointer.x * mPointerXMovementScale;
2834 const float y = pointer.y * mPointerYMovementScale;
2835 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2836 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002837 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002838 }
2839
2840 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2841 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002842 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2843 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2844 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002845 mPointerGesture.resetTap();
2846 }
2847
2848 // Pick a new active touch id if needed.
2849 // Choose an arbitrary pointer that just went down, if there is one.
2850 // Otherwise choose an arbitrary remaining pointer.
2851 // This guarantees we always have an active touch id when there is at least one pointer.
2852 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002853 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002855 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002856 mPointerGesture.firstTouchTime = when;
2857 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002858 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2859 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2860 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2861 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002862 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002863 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002864
2865 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002866 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002867 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002868 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2869 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2870 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002871 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 *outFinishPreviousGesture = true;
2873 }
2874
2875 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002876 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002877 mPointerGesture.currentGestureIdBits.clear();
2878
2879 mPointerVelocityControl.reset();
2880 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2881 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2882 // The pointer follows the active touch point.
2883 // Emit DOWN, MOVE, UP events at the pointer location.
2884 //
2885 // Only the active touch matters; other fingers are ignored. This policy helps
2886 // to handle the case where the user places a second finger on the touch pad
2887 // to apply the necessary force to depress an integrated button below the surface.
2888 // We don't want the second finger to be delivered to applications.
2889 //
2890 // For this to work well, we need to make sure to track the pointer that is really
2891 // active. If the user first puts one finger down to click then adds another
2892 // finger to drag then the active pointer should switch to the finger that is
2893 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002894 ALOGD_IF(DEBUG_GESTURES,
2895 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2896 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002897 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002898 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002899 *outFinishPreviousGesture = true;
2900 mPointerGesture.activeGestureId = 0;
2901 }
2902
2903 // Switch pointers if needed.
2904 // Find the fastest pointer and follow it.
2905 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002906 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002908 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002909 ALOGD_IF(DEBUG_GESTURES,
2910 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2911 "bestSpeed=%0.3f",
2912 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002913 }
2914 }
2915
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002916 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002917 // When using spots, the click will occur at the position of the anchor
2918 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002919 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002920 } else {
2921 mPointerVelocityControl.reset();
2922 }
2923
Prabir Pradhan2719e822023-02-28 17:39:36 +00002924 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002925
Michael Wright227c5542020-07-02 18:30:52 +01002926 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002927 mPointerGesture.currentGestureIdBits.clear();
2928 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2929 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2930 mPointerGesture.currentGestureProperties[0].clear();
2931 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002932 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002933 mPointerGesture.currentGestureCoords[0].clear();
2934 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2935 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2936 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2937 } else if (currentFingerCount == 0) {
2938 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002939 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002940 *outFinishPreviousGesture = true;
2941 }
2942
2943 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2944 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2945 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002946 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2947 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002948 lastFingerCount == 1) {
2949 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002950 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002951 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2952 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002953 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002954
2955 mPointerGesture.tapUpTime = when;
2956 getContext()->requestTimeoutAtTime(when +
2957 mConfig.pointerGestureTapDragInterval);
2958
2959 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002960 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002961 mPointerGesture.currentGestureIdBits.clear();
2962 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2963 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2964 mPointerGesture.currentGestureProperties[0].clear();
2965 mPointerGesture.currentGestureProperties[0].id =
2966 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002967 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002968 mPointerGesture.currentGestureCoords[0].clear();
2969 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2970 mPointerGesture.tapX);
2971 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2972 mPointerGesture.tapY);
2973 mPointerGesture.currentGestureCoords[0]
2974 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2975
2976 tapped = true;
2977 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002978 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2979 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002980 }
2981 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002982 if (DEBUG_GESTURES) {
2983 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2984 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2985 (when - mPointerGesture.tapDownTime) * 0.000001f);
2986 } else {
2987 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2988 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002989 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002990 }
2991 }
2992
2993 mPointerVelocityControl.reset();
2994
2995 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002996 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002997 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002998 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002999 mPointerGesture.currentGestureIdBits.clear();
3000 }
3001 } else if (currentFingerCount == 1) {
3002 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3003 // The pointer follows the active touch point.
3004 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3005 // When in TAP_DRAG, emit MOVE events at the pointer location.
3006 ALOG_ASSERT(activeTouchId >= 0);
3007
Michael Wright227c5542020-07-02 18:30:52 +01003008 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3009 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003010 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003011 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003012 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3013 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003014 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003015 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003016 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3017 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003018 }
3019 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003020 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3021 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003022 }
Michael Wright227c5542020-07-02 18:30:52 +01003023 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3024 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003025 }
3026
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003027 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003028 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003029 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003030 } else {
3031 mPointerVelocityControl.reset();
3032 }
3033
3034 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003035 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003036 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003037 down = true;
3038 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003039 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003040 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003041 *outFinishPreviousGesture = true;
3042 }
3043 mPointerGesture.activeGestureId = 0;
3044 down = false;
3045 }
3046
Prabir Pradhan2719e822023-02-28 17:39:36 +00003047 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003048
3049 mPointerGesture.currentGestureIdBits.clear();
3050 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3051 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3052 mPointerGesture.currentGestureProperties[0].clear();
3053 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003054 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003055 mPointerGesture.currentGestureCoords[0].clear();
3056 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3057 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3058 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3059 down ? 1.0f : 0.0f);
3060
3061 if (lastFingerCount == 0 && currentFingerCount != 0) {
3062 mPointerGesture.resetTap();
3063 mPointerGesture.tapDownTime = when;
3064 mPointerGesture.tapX = x;
3065 mPointerGesture.tapY = y;
3066 }
3067 } else {
3068 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003069 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003070 }
3071
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003072 if (DEBUG_GESTURES) {
3073 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3074 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3075 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3076 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3077 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3078 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3079 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3080 uint32_t id = idBits.clearFirstMarkedBit();
3081 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3082 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3083 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003084 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003085 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003086 id, index, ftl::enum_string(properties.toolType).c_str(),
3087 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003088 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3089 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3090 }
3091 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3092 uint32_t id = idBits.clearFirstMarkedBit();
3093 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3094 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3095 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003096 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003097 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003098 id, index, ftl::enum_string(properties.toolType).c_str(),
3099 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003100 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3101 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3102 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003103 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003104 return true;
3105}
3106
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003107bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3108 if (mPointerGesture.activeTouchId < 0) {
3109 mPointerGesture.resetQuietTime();
3110 return false;
3111 }
3112
3113 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3114 return true;
3115 }
3116
3117 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3118 bool isQuietTime = false;
3119 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3120 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3121 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3122 currentFingerCount < 2) {
3123 // Enter quiet time when exiting swipe or freeform state.
3124 // This is to prevent accidentally entering the hover state and flinging the
3125 // pointer when finishing a swipe and there is still one pointer left onscreen.
3126 isQuietTime = true;
3127 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3128 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3129 // Enter quiet time when releasing the button and there are still two or more
3130 // fingers down. This may indicate that one finger was used to press the button
3131 // but it has not gone up yet.
3132 isQuietTime = true;
3133 }
3134 if (isQuietTime) {
3135 mPointerGesture.quietTime = when;
3136 }
3137 return isQuietTime;
3138}
3139
3140std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3141 int32_t bestId = -1;
3142 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3143 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3144 uint32_t id = idBits.clearFirstMarkedBit();
3145 std::optional<float> vx =
3146 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3147 std::optional<float> vy =
3148 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3149 if (vx && vy) {
3150 float speed = hypotf(*vx, *vy);
3151 if (speed > bestSpeed) {
3152 bestId = id;
3153 bestSpeed = speed;
3154 }
3155 }
3156 }
3157 return std::make_pair(bestId, bestSpeed);
3158}
3159
3160void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3161 bool* finishPreviousGesture) {
3162 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3163 // to move before deciding what to do.
3164 //
3165 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3166 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3167 // just a press or long-press at the pointer location.
3168 //
3169 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3170 // pointer location.
3171 //
3172 // When the two fingers move enough or when additional fingers are added, we make a decision to
3173 // transition into SWIPE or FREEFORM mode accordingly.
3174 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3175 ALOG_ASSERT(activeTouchId >= 0);
3176
3177 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3178 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3179 bool settled =
3180 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3181 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3182 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3183 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3184 *finishPreviousGesture = true;
3185 } else if (!settled && currentFingerCount > lastFingerCount) {
3186 // Additional pointers have gone down but not yet settled.
3187 // Reset the gesture.
3188 ALOGD_IF(DEBUG_GESTURES,
3189 "Gestures: Resetting gesture since additional pointers went down for "
3190 "MULTITOUCH, settle time remaining %0.3fms",
3191 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3192 when) * 0.000001f);
3193 *cancelPreviousGesture = true;
3194 } else {
3195 // Continue previous gesture.
3196 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3197 }
3198
3199 if (*finishPreviousGesture || *cancelPreviousGesture) {
3200 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3201 mPointerGesture.activeGestureId = 0;
3202 mPointerGesture.referenceIdBits.clear();
3203 mPointerVelocityControl.reset();
3204
3205 // Use the centroid and pointer location as the reference points for the gesture.
3206 ALOGD_IF(DEBUG_GESTURES,
3207 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3208 "%0.3fms",
3209 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3210 when) * 0.000001f);
3211 mCurrentRawState.rawPointerData
3212 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3213 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003214 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3215 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003216 }
3217
3218 // Clear the reference deltas for fingers not yet included in the reference calculation.
3219 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3220 ~mPointerGesture.referenceIdBits.value);
3221 !idBits.isEmpty();) {
3222 uint32_t id = idBits.clearFirstMarkedBit();
3223 mPointerGesture.referenceDeltas[id].dx = 0;
3224 mPointerGesture.referenceDeltas[id].dy = 0;
3225 }
3226 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3227
3228 // Add delta for all fingers and calculate a common movement delta.
3229 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3230 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3231 mCurrentCookedState.fingerIdBits.value);
3232 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3233 bool first = (idBits == commonIdBits);
3234 uint32_t id = idBits.clearFirstMarkedBit();
3235 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3236 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3237 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3238 delta.dx += cpd.x - lpd.x;
3239 delta.dy += cpd.y - lpd.y;
3240
3241 if (first) {
3242 commonDeltaRawX = delta.dx;
3243 commonDeltaRawY = delta.dy;
3244 } else {
3245 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3246 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3247 }
3248 }
3249
3250 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3251 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3252 float dist[MAX_POINTER_ID + 1];
3253 int32_t distOverThreshold = 0;
3254 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3255 uint32_t id = idBits.clearFirstMarkedBit();
3256 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3257 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3258 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3259 distOverThreshold += 1;
3260 }
3261 }
3262
3263 // Only transition when at least two pointers have moved further than
3264 // the minimum distance threshold.
3265 if (distOverThreshold >= 2) {
3266 if (currentFingerCount > 2) {
3267 // There are more than two pointers, switch to FREEFORM.
3268 ALOGD_IF(DEBUG_GESTURES,
3269 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3270 currentFingerCount);
3271 *cancelPreviousGesture = true;
3272 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3273 } else {
3274 // There are exactly two pointers.
3275 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3276 uint32_t id1 = idBits.clearFirstMarkedBit();
3277 uint32_t id2 = idBits.firstMarkedBit();
3278 const RawPointerData::Pointer& p1 =
3279 mCurrentRawState.rawPointerData.pointerForId(id1);
3280 const RawPointerData::Pointer& p2 =
3281 mCurrentRawState.rawPointerData.pointerForId(id2);
3282 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3283 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3284 // There are two pointers but they are too far apart for a SWIPE,
3285 // switch to FREEFORM.
3286 ALOGD_IF(DEBUG_GESTURES,
3287 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3288 mutualDistance, mPointerGestureMaxSwipeWidth);
3289 *cancelPreviousGesture = true;
3290 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3291 } else {
3292 // There are two pointers. Wait for both pointers to start moving
3293 // before deciding whether this is a SWIPE or FREEFORM gesture.
3294 float dist1 = dist[id1];
3295 float dist2 = dist[id2];
3296 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3297 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3298 // Calculate the dot product of the displacement vectors.
3299 // When the vectors are oriented in approximately the same direction,
3300 // the angle betweeen them is near zero and the cosine of the angle
3301 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3302 // mag(v2).
3303 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3304 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3305 float dx1 = delta1.dx * mPointerXZoomScale;
3306 float dy1 = delta1.dy * mPointerYZoomScale;
3307 float dx2 = delta2.dx * mPointerXZoomScale;
3308 float dy2 = delta2.dy * mPointerYZoomScale;
3309 float dot = dx1 * dx2 + dy1 * dy2;
3310 float cosine = dot / (dist1 * dist2); // denominator always > 0
3311 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3312 // Pointers are moving in the same direction. Switch to SWIPE.
3313 ALOGD_IF(DEBUG_GESTURES,
3314 "Gestures: PRESS transitioned to SWIPE, "
3315 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3316 "cosine %0.3f >= %0.3f",
3317 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3318 mConfig.pointerGestureMultitouchMinDistance, cosine,
3319 mConfig.pointerGestureSwipeTransitionAngleCosine);
3320 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3321 } else {
3322 // Pointers are moving in different directions. Switch to FREEFORM.
3323 ALOGD_IF(DEBUG_GESTURES,
3324 "Gestures: PRESS transitioned to FREEFORM, "
3325 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3326 "cosine %0.3f < %0.3f",
3327 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3328 mConfig.pointerGestureMultitouchMinDistance, cosine,
3329 mConfig.pointerGestureSwipeTransitionAngleCosine);
3330 *cancelPreviousGesture = true;
3331 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3332 }
3333 }
3334 }
3335 }
3336 }
3337 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3338 // Switch from SWIPE to FREEFORM if additional pointers go down.
3339 // Cancel previous gesture.
3340 if (currentFingerCount > 2) {
3341 ALOGD_IF(DEBUG_GESTURES,
3342 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3343 currentFingerCount);
3344 *cancelPreviousGesture = true;
3345 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3346 }
3347 }
3348
3349 // Move the reference points based on the overall group motion of the fingers
3350 // except in PRESS mode while waiting for a transition to occur.
3351 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3352 (commonDeltaRawX || commonDeltaRawY)) {
3353 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3354 uint32_t id = idBits.clearFirstMarkedBit();
3355 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3356 delta.dx = 0;
3357 delta.dy = 0;
3358 }
3359
3360 mPointerGesture.referenceTouchX += commonDeltaRawX;
3361 mPointerGesture.referenceTouchY += commonDeltaRawY;
3362
3363 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3364 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3365
3366 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3367 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3368
3369 mPointerGesture.referenceGestureX += commonDeltaX;
3370 mPointerGesture.referenceGestureY += commonDeltaY;
3371 }
3372
3373 // Report gestures.
3374 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3375 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3376 // PRESS or SWIPE mode.
3377 ALOGD_IF(DEBUG_GESTURES,
3378 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3379 "currentTouchPointerCount=%d",
3380 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3381 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3382
3383 mPointerGesture.currentGestureIdBits.clear();
3384 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3385 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3386 mPointerGesture.currentGestureProperties[0].clear();
3387 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003388 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003389 mPointerGesture.currentGestureCoords[0].clear();
3390 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3391 mPointerGesture.referenceGestureX);
3392 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3393 mPointerGesture.referenceGestureY);
3394 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3395 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3396 float xOffset = static_cast<float>(commonDeltaRawX) /
3397 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3398 float yOffset = static_cast<float>(commonDeltaRawY) /
3399 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3400 mPointerGesture.currentGestureCoords[0]
3401 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3402 mPointerGesture.currentGestureCoords[0]
3403 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3404 }
3405 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3406 // FREEFORM mode.
3407 ALOGD_IF(DEBUG_GESTURES,
3408 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3409 "currentTouchPointerCount=%d",
3410 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3411 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3412
3413 mPointerGesture.currentGestureIdBits.clear();
3414
3415 BitSet32 mappedTouchIdBits;
3416 BitSet32 usedGestureIdBits;
3417 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3418 // Initially, assign the active gesture id to the active touch point
3419 // if there is one. No other touch id bits are mapped yet.
3420 if (!*cancelPreviousGesture) {
3421 mappedTouchIdBits.markBit(activeTouchId);
3422 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3423 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3424 mPointerGesture.activeGestureId;
3425 } else {
3426 mPointerGesture.activeGestureId = -1;
3427 }
3428 } else {
3429 // Otherwise, assume we mapped all touches from the previous frame.
3430 // Reuse all mappings that are still applicable.
3431 mappedTouchIdBits.value =
3432 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3433 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3434
3435 // Check whether we need to choose a new active gesture id because the
3436 // current went went up.
3437 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3438 ~mCurrentCookedState.fingerIdBits.value);
3439 !upTouchIdBits.isEmpty();) {
3440 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3441 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3442 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3443 mPointerGesture.activeGestureId = -1;
3444 break;
3445 }
3446 }
3447 }
3448
3449 ALOGD_IF(DEBUG_GESTURES,
3450 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3451 "activeGestureId=%d",
3452 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3453
3454 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3455 for (uint32_t i = 0; i < currentFingerCount; i++) {
3456 uint32_t touchId = idBits.clearFirstMarkedBit();
3457 uint32_t gestureId;
3458 if (!mappedTouchIdBits.hasBit(touchId)) {
3459 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3460 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3461 ALOGD_IF(DEBUG_GESTURES,
3462 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3463 gestureId);
3464 } else {
3465 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3466 ALOGD_IF(DEBUG_GESTURES,
3467 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3468 touchId, gestureId);
3469 }
3470 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3471 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3472
3473 const RawPointerData::Pointer& pointer =
3474 mCurrentRawState.rawPointerData.pointerForId(touchId);
3475 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3476 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3477 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3478
3479 mPointerGesture.currentGestureProperties[i].clear();
3480 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003481 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003482 mPointerGesture.currentGestureCoords[i].clear();
3483 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3484 mPointerGesture.referenceGestureX +
3485 deltaX);
3486 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3487 mPointerGesture.referenceGestureY +
3488 deltaY);
3489 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3490 }
3491
3492 if (mPointerGesture.activeGestureId < 0) {
3493 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3494 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3495 mPointerGesture.activeGestureId);
3496 }
3497 }
3498}
3499
Harry Cutts714d1ad2022-08-24 16:36:43 +00003500void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3501 const RawPointerData::Pointer& currentPointer =
3502 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3503 const RawPointerData::Pointer& lastPointer =
3504 mLastRawState.rawPointerData.pointerForId(pointerId);
3505 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3506 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3507
3508 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3509 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3510
3511 mPointerController->move(deltaX, deltaY);
3512}
3513
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003514std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3515 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003516 mPointerSimple.currentCoords.clear();
3517 mPointerSimple.currentProperties.clear();
3518
3519 bool down, hovering;
3520 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3521 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3522 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003523 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3524 down = !hovering;
3525
Prabir Pradhane71e5702023-03-29 14:51:38 +00003526 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3527 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3528 // Styluses are configured specifically for one display. We only update the
3529 // PointerController for this stylus if the PointerController is configured for
3530 // the same display as this stylus,
3531 if (getAssociatedDisplayId() == mViewport.displayId) {
3532 mPointerController->setPosition(x, y);
3533 std::tie(x, y) = mPointerController->getPosition();
3534 }
3535
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003536 mPointerSimple.currentCoords.copyFrom(
3537 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3538 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3539 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3540 mPointerSimple.currentProperties.id = 0;
3541 mPointerSimple.currentProperties.toolType =
3542 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3543 } else {
3544 down = false;
3545 hovering = false;
3546 }
3547
Prabir Pradhane71e5702023-03-29 14:51:38 +00003548 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003549}
3550
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003551std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3552 uint32_t policyFlags) {
3553 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003554}
3555
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003556std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3557 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003558 mPointerSimple.currentCoords.clear();
3559 mPointerSimple.currentProperties.clear();
3560
3561 bool down, hovering;
3562 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3563 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003564 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003565 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003566 } else {
3567 mPointerVelocityControl.reset();
3568 }
3569
3570 down = isPointerDown(mCurrentRawState.buttonState);
3571 hovering = !down;
3572
Prabir Pradhan2719e822023-02-28 17:39:36 +00003573 const auto [x, y] = mPointerController->getPosition();
3574 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003575 mPointerSimple.currentCoords.copyFrom(
3576 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3577 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3578 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3579 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3580 hovering ? 0.0f : 1.0f);
3581 mPointerSimple.currentProperties.id = 0;
3582 mPointerSimple.currentProperties.toolType =
3583 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3584 } else {
3585 mPointerVelocityControl.reset();
3586
3587 down = false;
3588 hovering = false;
3589 }
3590
Prabir Pradhane71e5702023-03-29 14:51:38 +00003591 const int32_t displayId = mPointerController->getDisplayId();
3592 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593}
3594
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003595std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3596 uint32_t policyFlags) {
3597 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598
3599 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003600
3601 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003602}
3603
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003604std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3605 uint32_t policyFlags, bool down,
Prabir Pradhane71e5702023-03-29 14:51:38 +00003606 bool hovering, int32_t displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003607 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3608 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003609 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003610 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003611 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003612
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003613 if (displayId == mPointerController->getDisplayId()) {
3614 std::tie(cursorPosition.x, cursorPosition.y) = mPointerController->getPosition();
3615 if (down || hovering) {
3616 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
3617 mPointerController->clearSpots();
3618 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3619 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
3620 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3621 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003622 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003623
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003624 if (mPointerSimple.down && !down) {
3625 mPointerSimple.down = false;
3626
3627 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003628 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3629 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3630 0, metaState, mLastRawState.buttonState,
3631 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3632 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003633 mOrientedXPrecision, mOrientedYPrecision,
3634 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3635 mPointerSimple.downTime,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003636 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003637 }
3638
3639 if (mPointerSimple.hovering && !hovering) {
3640 mPointerSimple.hovering = false;
3641
3642 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003643 out.push_back(
3644 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3645 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3646 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3647 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3648 &mPointerSimple.lastCoords, mOrientedXPrecision,
3649 mOrientedYPrecision, mPointerSimple.lastCursorX,
3650 mPointerSimple.lastCursorY, mPointerSimple.downTime,
3651 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003652 }
3653
3654 if (down) {
3655 if (!mPointerSimple.down) {
3656 mPointerSimple.down = true;
3657 mPointerSimple.downTime = when;
3658
3659 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003660 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3661 mSource, displayId, policyFlags,
3662 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3663 mCurrentRawState.buttonState, MotionClassification::NONE,
3664 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3665 &mPointerSimple.currentProperties,
3666 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003667 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003668 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003669 }
3670
3671 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003672 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3673 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3674 0, 0, metaState, mCurrentRawState.buttonState,
3675 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3676 &mPointerSimple.currentProperties,
3677 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003678 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003679 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003680 }
3681
3682 if (hovering) {
3683 if (!mPointerSimple.hovering) {
3684 mPointerSimple.hovering = true;
3685
3686 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003687 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3688 mSource, displayId, policyFlags,
3689 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3690 mCurrentRawState.buttonState, MotionClassification::NONE,
3691 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3692 &mPointerSimple.currentProperties,
3693 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003694 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003695 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003696 }
3697
3698 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003699 out.push_back(
3700 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3701 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3702 metaState, mCurrentRawState.buttonState,
3703 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3704 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003705 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3706 cursorPosition.y, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003707 }
3708
3709 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3710 float vscroll = mCurrentRawState.rawVScroll;
3711 float hscroll = mCurrentRawState.rawHScroll;
3712 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3713 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3714
3715 // Send scroll.
3716 PointerCoords pointerCoords;
3717 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3718 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3719 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3720
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003721 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3722 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3723 0, 0, metaState, mCurrentRawState.buttonState,
3724 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3725 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003726 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3727 cursorPosition.y, mPointerSimple.downTime,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003728 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003729 }
3730
3731 // Save state.
3732 if (down || hovering) {
3733 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3734 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003735 mPointerSimple.displayId = displayId;
3736 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003737 mPointerSimple.lastCursorX = cursorPosition.x;
3738 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003739 } else {
3740 mPointerSimple.reset();
3741 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003742 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003743}
3744
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003745std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3746 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003747 std::list<NotifyArgs> out;
3748 if (mPointerSimple.down || mPointerSimple.hovering) {
3749 int32_t metaState = getContext()->getGlobalMetaState();
3750 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3751 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3752 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3753 metaState, mLastRawState.buttonState,
3754 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3755 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3756 mOrientedXPrecision, mOrientedYPrecision,
3757 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3758 mPointerSimple.downTime,
3759 /* videoFrames */ {}));
3760 if (mPointerController != nullptr) {
3761 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3762 }
3763 }
3764 mPointerSimple.reset();
3765 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003766}
3767
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003768static bool isStylusEvent(uint32_t source, int32_t action, const PointerProperties* properties) {
3769 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
3770 return false;
3771 }
3772 const auto actionIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3773 return isStylusToolType(properties[actionIndex].toolType);
3774}
3775
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003776NotifyMotionArgs TouchInputMapper::dispatchMotion(
3777 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3778 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003779 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3780 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003781 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003782 PointerCoords pointerCoords[MAX_POINTERS];
3783 PointerProperties pointerProperties[MAX_POINTERS];
3784 uint32_t pointerCount = 0;
3785 while (!idBits.isEmpty()) {
3786 uint32_t id = idBits.clearFirstMarkedBit();
3787 uint32_t index = idToIndex[id];
3788 pointerProperties[pointerCount].copyFrom(properties[index]);
3789 pointerCoords[pointerCount].copyFrom(coords[index]);
3790
3791 if (changedId >= 0 && id == uint32_t(changedId)) {
3792 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3793 }
3794
3795 pointerCount += 1;
3796 }
3797
3798 ALOG_ASSERT(pointerCount != 0);
3799
3800 if (changedId >= 0 && pointerCount == 1) {
3801 // Replace initial down and final up action.
3802 // We can compare the action without masking off the changed pointer index
3803 // because we know the index is 0.
3804 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3805 action = AMOTION_EVENT_ACTION_DOWN;
3806 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003807 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3808 action = AMOTION_EVENT_ACTION_CANCEL;
3809 } else {
3810 action = AMOTION_EVENT_ACTION_UP;
3811 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003812 } else {
3813 // Can't happen.
3814 ALOG_ASSERT(false);
3815 }
3816 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003817
3818 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3819 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
3820 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, action, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003821 mPointerController && displayId != ADISPLAY_ID_NONE &&
3822 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003823 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003824 switch (action & AMOTION_EVENT_ACTION_MASK) {
3825 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3826 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3827 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003828 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003829 mPointerController
3830 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3831 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3832 .getY());
3833 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3834 break;
3835 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3836 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3837 break;
3838 }
3839 }
3840
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003841 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3842 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003843 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003844 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003845 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003846 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003847 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003848 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003849 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003850 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3851 policyFlags, action, actionButton, flags, metaState, buttonState,
3852 classification, edgeFlags, pointerCount, pointerProperties,
3853 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3854 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003855}
3856
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003857std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3858 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003859 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3860 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003861 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003862}
3863
Prabir Pradhan1728b212021-10-19 16:00:03 -07003864bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003865 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003866 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003867 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003868}
3869
3870const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3871 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003872 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3873 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3874 "left=%d, top=%d, right=%d, bottom=%d",
3875 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3876 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003877
3878 if (virtualKey.isHit(x, y)) {
3879 return &virtualKey;
3880 }
3881 }
3882
3883 return nullptr;
3884}
3885
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003886void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3887 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3888 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003889
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003890 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003891
3892 if (currentPointerCount == 0) {
3893 // No pointers to assign.
3894 return;
3895 }
3896
3897 if (lastPointerCount == 0) {
3898 // All pointers are new.
3899 for (uint32_t i = 0; i < currentPointerCount; i++) {
3900 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003901 current.rawPointerData.pointers[i].id = id;
3902 current.rawPointerData.idToIndex[id] = i;
3903 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003904 }
3905 return;
3906 }
3907
3908 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003909 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003910 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003911 uint32_t id = last.rawPointerData.pointers[0].id;
3912 current.rawPointerData.pointers[0].id = id;
3913 current.rawPointerData.idToIndex[id] = 0;
3914 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003915 return;
3916 }
3917
3918 // General case.
3919 // We build a heap of squared euclidean distances between current and last pointers
3920 // associated with the current and last pointer indices. Then, we find the best
3921 // match (by distance) for each current pointer.
3922 // The pointers must have the same tool type but it is possible for them to
3923 // transition from hovering to touching or vice-versa while retaining the same id.
3924 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3925
3926 uint32_t heapSize = 0;
3927 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3928 currentPointerIndex++) {
3929 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3930 lastPointerIndex++) {
3931 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003932 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003933 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003934 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003935 if (currentPointer.toolType == lastPointer.toolType) {
3936 int64_t deltaX = currentPointer.x - lastPointer.x;
3937 int64_t deltaY = currentPointer.y - lastPointer.y;
3938
3939 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3940
3941 // Insert new element into the heap (sift up).
3942 heap[heapSize].currentPointerIndex = currentPointerIndex;
3943 heap[heapSize].lastPointerIndex = lastPointerIndex;
3944 heap[heapSize].distance = distance;
3945 heapSize += 1;
3946 }
3947 }
3948 }
3949
3950 // Heapify
3951 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3952 startIndex -= 1;
3953 for (uint32_t parentIndex = startIndex;;) {
3954 uint32_t childIndex = parentIndex * 2 + 1;
3955 if (childIndex >= heapSize) {
3956 break;
3957 }
3958
3959 if (childIndex + 1 < heapSize &&
3960 heap[childIndex + 1].distance < heap[childIndex].distance) {
3961 childIndex += 1;
3962 }
3963
3964 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3965 break;
3966 }
3967
3968 swap(heap[parentIndex], heap[childIndex]);
3969 parentIndex = childIndex;
3970 }
3971 }
3972
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003973 if (DEBUG_POINTER_ASSIGNMENT) {
3974 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3975 for (size_t i = 0; i < heapSize; i++) {
3976 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3977 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3978 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003979 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003980
3981 // Pull matches out by increasing order of distance.
3982 // To avoid reassigning pointers that have already been matched, the loop keeps track
3983 // of which last and current pointers have been matched using the matchedXXXBits variables.
3984 // It also tracks the used pointer id bits.
3985 BitSet32 matchedLastBits(0);
3986 BitSet32 matchedCurrentBits(0);
3987 BitSet32 usedIdBits(0);
3988 bool first = true;
3989 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3990 while (heapSize > 0) {
3991 if (first) {
3992 // The first time through the loop, we just consume the root element of
3993 // the heap (the one with smallest distance).
3994 first = false;
3995 } else {
3996 // Previous iterations consumed the root element of the heap.
3997 // Pop root element off of the heap (sift down).
3998 heap[0] = heap[heapSize];
3999 for (uint32_t parentIndex = 0;;) {
4000 uint32_t childIndex = parentIndex * 2 + 1;
4001 if (childIndex >= heapSize) {
4002 break;
4003 }
4004
4005 if (childIndex + 1 < heapSize &&
4006 heap[childIndex + 1].distance < heap[childIndex].distance) {
4007 childIndex += 1;
4008 }
4009
4010 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4011 break;
4012 }
4013
4014 swap(heap[parentIndex], heap[childIndex]);
4015 parentIndex = childIndex;
4016 }
4017
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004018 if (DEBUG_POINTER_ASSIGNMENT) {
4019 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4020 for (size_t j = 0; j < heapSize; j++) {
4021 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4022 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4023 heap[j].distance);
4024 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004025 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004026 }
4027
4028 heapSize -= 1;
4029
4030 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4031 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4032
4033 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4034 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4035
4036 matchedCurrentBits.markBit(currentPointerIndex);
4037 matchedLastBits.markBit(lastPointerIndex);
4038
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004039 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4040 current.rawPointerData.pointers[currentPointerIndex].id = id;
4041 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4042 current.rawPointerData.markIdBit(id,
4043 current.rawPointerData.isHovering(
4044 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004045 usedIdBits.markBit(id);
4046
Harry Cutts45483602022-08-24 14:36:48 +00004047 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4048 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4049 ", distance=%" PRIu64,
4050 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004051 break;
4052 }
4053 }
4054
4055 // Assign fresh ids to pointers that were not matched in the process.
4056 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4057 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4058 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4059
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004060 current.rawPointerData.pointers[currentPointerIndex].id = id;
4061 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4062 current.rawPointerData.markIdBit(id,
4063 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004064
Harry Cutts45483602022-08-24 14:36:48 +00004065 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4066 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4067 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004068 }
4069}
4070
4071int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4072 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4073 return AKEY_STATE_VIRTUAL;
4074 }
4075
4076 for (const VirtualKey& virtualKey : mVirtualKeys) {
4077 if (virtualKey.keyCode == keyCode) {
4078 return AKEY_STATE_UP;
4079 }
4080 }
4081
4082 return AKEY_STATE_UNKNOWN;
4083}
4084
4085int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4086 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4087 return AKEY_STATE_VIRTUAL;
4088 }
4089
4090 for (const VirtualKey& virtualKey : mVirtualKeys) {
4091 if (virtualKey.scanCode == scanCode) {
4092 return AKEY_STATE_UP;
4093 }
4094 }
4095
4096 return AKEY_STATE_UNKNOWN;
4097}
4098
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004099bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4100 const std::vector<int32_t>& keyCodes,
4101 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004102 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004103 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004104 if (virtualKey.keyCode == keyCodes[i]) {
4105 outFlags[i] = 1;
4106 }
4107 }
4108 }
4109
4110 return true;
4111}
4112
4113std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4114 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004115 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004116 return std::make_optional(mPointerController->getDisplayId());
4117 } else {
4118 return std::make_optional(mViewport.displayId);
4119 }
4120 }
4121 return std::nullopt;
4122}
4123
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004124} // namespace android