blob: f2b0a4b0a7d74511bc980299848186753f1f0729 [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 Singh56adebc2023-04-25 13:56:05 +0000128 mConfig(readerConfig) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700129
130TouchInputMapper::~TouchInputMapper() {}
131
Philip Junker4af3b3d2021-12-14 10:36:55 +0100132uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700133 return mSource;
134}
135
Harry Cuttsd02ea102023-03-17 18:21:30 +0000136void TouchInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700137 InputMapper::populateDeviceInfo(info);
138
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000139 if (mDeviceMode == DeviceMode::DISABLED) {
140 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700141 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000142
Harry Cuttsd02ea102023-03-17 18:21:30 +0000143 info.addMotionRange(mOrientedRanges.x);
144 info.addMotionRange(mOrientedRanges.y);
145 info.addMotionRange(mOrientedRanges.pressure);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000146
147 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
148 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
149 //
150 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
151 // motion, i.e. the hardware dimensions, as the finger could move completely across the
152 // touchpad in one sample cycle.
153 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
154 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
Harry Cuttsd02ea102023-03-17 18:21:30 +0000155 info.addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
156 x.resolution);
157 info.addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
158 y.resolution);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000159 }
160
161 if (mOrientedRanges.size) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000162 info.addMotionRange(*mOrientedRanges.size);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000163 }
164
165 if (mOrientedRanges.touchMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000166 info.addMotionRange(*mOrientedRanges.touchMajor);
167 info.addMotionRange(*mOrientedRanges.touchMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000168 }
169
170 if (mOrientedRanges.toolMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000171 info.addMotionRange(*mOrientedRanges.toolMajor);
172 info.addMotionRange(*mOrientedRanges.toolMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000173 }
174
175 if (mOrientedRanges.orientation) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000176 info.addMotionRange(*mOrientedRanges.orientation);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000177 }
178
179 if (mOrientedRanges.distance) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000180 info.addMotionRange(*mOrientedRanges.distance);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000181 }
182
183 if (mOrientedRanges.tilt) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000184 info.addMotionRange(*mOrientedRanges.tilt);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000185 }
186
187 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000188 info.addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000189 }
190 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000191 info.addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000192 }
Harry Cuttsd02ea102023-03-17 18:21:30 +0000193 info.setButtonUnderPad(mParameters.hasButtonUnderPad);
194 info.setUsiVersion(mParameters.usiVersion);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700195}
196
197void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700198 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800199 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700200 dumpParameters(dump);
201 dumpVirtualKeys(dump);
202 dumpRawPointerAxes(dump);
203 dumpCalibration(dump);
204 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700205 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700206
207 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000208 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000209 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
210 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
211 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700212 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
213 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
214 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
215 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
216 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
217 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
218 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
219 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
220 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
221 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
222
223 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
224 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
225 mLastRawState.rawPointerData.pointerCount);
226 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
227 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
228 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
229 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
230 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700231 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700232 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
233 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
234 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700235 pointer.distance, ftl::enum_string(pointer.toolType).c_str(),
236 toString(pointer.isHovering));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700237 }
238
239 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
240 mLastCookedState.buttonState);
241 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
242 mLastCookedState.cookedPointerData.pointerCount);
243 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
244 const PointerProperties& pointerProperties =
245 mLastCookedState.cookedPointerData.pointerProperties[i];
246 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000247 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
248 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
249 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700250 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700251 "toolType=%s, isHovering=%s\n",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700252 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000253 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
254 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700255 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
256 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
257 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
258 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
259 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
260 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
261 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
262 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700263 ftl::enum_string(pointerProperties.toolType).c_str(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700264 toString(mLastCookedState.cookedPointerData.isHovering(i)));
265 }
266
267 dump += INDENT3 "Stylus Fusion:\n";
268 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
269 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000270 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
271 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700272 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
273 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000274 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
275 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700276 dump += INDENT3 "External Stylus State:\n";
277 dumpStylusState(dump, mExternalStylusState);
278
Michael Wright227c5542020-07-02 18:30:52 +0100279 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700280 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
281 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
282 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
283 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
284 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
285 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
286 }
287}
288
Arpit Singh4be4eef2023-03-28 14:26:01 +0000289std::list<NotifyArgs> TouchInputMapper::reconfigure(nsecs_t when,
Arpit Singhed6c3de2023-04-05 19:24:37 +0000290 const InputReaderConfiguration& config,
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000291 ConfigurationChanges changes) {
Arpit Singh4be4eef2023-03-28 14:26:01 +0000292 std::list<NotifyArgs> out = InputMapper::reconfigure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700293
Arpit Singhed6c3de2023-04-05 19:24:37 +0000294 mConfig = config;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700295
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000296 // Full configuration should happen the first time configure is called and
297 // when the device type is changed. Changing a device type can affect
298 // various other parameters so should result in a reconfiguration.
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000299 if (!changes.any() || changes.test(InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700300 // Configure basic parameters.
Arpit Singh403e53c2023-04-18 11:46:56 +0000301 mParameters = computeParameters(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700302
303 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800304 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000305 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700306
307 // Configure absolute axis information.
308 configureRawPointerAxes();
309
310 // Prepare input device calibration.
311 parseCalibration();
312 resolveCalibration();
313 }
314
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000315 if (!changes.any() ||
316 changes.test(InputReaderConfiguration::Change::TOUCH_AFFINE_TRANSFORMATION)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700317 // Update location calibration to reflect current settings
318 updateAffineTransformation();
319 }
320
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000321 if (!changes.any() || changes.test(InputReaderConfiguration::Change::POINTER_SPEED)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700322 // Update pointer speed.
323 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
324 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
325 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
326 }
327
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000328 using namespace ftl::flag_operators;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700329 bool resetNeeded = false;
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000330 if (!changes.any() ||
331 changes.any(InputReaderConfiguration::Change::DISPLAY_INFO |
332 InputReaderConfiguration::Change::POINTER_CAPTURE |
333 InputReaderConfiguration::Change::POINTER_GESTURE_ENABLEMENT |
334 InputReaderConfiguration::Change::SHOW_TOUCHES |
335 InputReaderConfiguration::Change::EXTERNAL_STYLUS_PRESENCE |
336 InputReaderConfiguration::Change::DEVICE_TYPE)) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700337 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700338 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700339 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700340 }
341
Prabir Pradhan4bf6d452023-04-18 21:26:56 +0000342 if (changes.any() && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700343 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000344
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700345 // Send reset, unless this is the first time the device has been configured,
346 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000347 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700348 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700349 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350}
351
352void TouchInputMapper::resolveExternalStylusPresence() {
353 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800354 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700355 mExternalStylusConnected = !devices.empty();
356
357 if (!mExternalStylusConnected) {
358 resetExternalStylus();
359 }
360}
361
Arpit Singh403e53c2023-04-18 11:46:56 +0000362TouchInputMapper::Parameters TouchInputMapper::computeParameters(
363 const InputDeviceContext& deviceContext) {
364 Parameters parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700365 // Use the pointer presentation mode for devices that do not support distinct
366 // multitouch. The spot-based presentation relies on being able to accurately
367 // locate two or more fingers on the touch pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000368 parameters.gestureMode = deviceContext.hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100369 ? Parameters::GestureMode::SINGLE_TOUCH
370 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700371
Arpit Singh403e53c2023-04-18 11:46:56 +0000372 const PropertyMap& config = deviceContext.getConfiguration();
Harry Cuttsf13161a2023-03-08 14:15:49 +0000373 std::optional<std::string> gestureModeString = config.getString("touch.gestureMode");
374 if (gestureModeString.has_value()) {
375 if (*gestureModeString == "single-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000376 parameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000377 } else if (*gestureModeString == "multi-touch") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000378 parameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000379 } else if (*gestureModeString != "default") {
380 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700381 }
382 }
383
Arpit Singh403e53c2023-04-18 11:46:56 +0000384 parameters.deviceType = computeDeviceType(deviceContext);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700385
Arpit Singh403e53c2023-04-18 11:46:56 +0000386 parameters.hasButtonUnderPad = deviceContext.hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700387
Arpit Singh403e53c2023-04-18 11:46:56 +0000388 parameters.orientationAware =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000389 config.getBool("touch.orientationAware")
Arpit Singh403e53c2023-04-18 11:46:56 +0000390 .value_or(parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700391
Arpit Singh403e53c2023-04-18 11:46:56 +0000392 parameters.orientation = ui::ROTATION_0;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000393 std::optional<std::string> orientationString = config.getString("touch.orientation");
394 if (orientationString.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000395 if (parameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700396 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
Harry Cuttsf13161a2023-03-08 14:15:49 +0000397 } else if (*orientationString == "ORIENTATION_90") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000398 parameters.orientation = ui::ROTATION_90;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000399 } else if (*orientationString == "ORIENTATION_180") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000400 parameters.orientation = ui::ROTATION_180;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000401 } else if (*orientationString == "ORIENTATION_270") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000402 parameters.orientation = ui::ROTATION_270;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000403 } else if (*orientationString != "ORIENTATION_0") {
404 ALOGW("Invalid value for touch.orientation: '%s'", orientationString->c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700405 }
406 }
407
Arpit Singh403e53c2023-04-18 11:46:56 +0000408 parameters.hasAssociatedDisplay = false;
409 parameters.associatedDisplayIsExternal = false;
410 if (parameters.orientationAware ||
411 parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
412 parameters.deviceType == Parameters::DeviceType::POINTER ||
413 (parameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
414 deviceContext.getAssociatedViewport())) {
415 parameters.hasAssociatedDisplay = true;
416 if (parameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
417 parameters.associatedDisplayIsExternal = deviceContext.isExternal();
418 parameters.uniqueDisplayId = config.getString("touch.displayId").value_or("").c_str();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700419 }
420 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000421 if (deviceContext.getAssociatedDisplayPort()) {
422 parameters.hasAssociatedDisplay = true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700423 }
424
425 // Initial downs on external touch devices should wake the device.
426 // Normally we don't do this for internal touch screens to prevent them from waking
427 // up in your pocket but you can enable it using the input device configuration.
Arpit Singh403e53c2023-04-18 11:46:56 +0000428 parameters.wake = config.getBool("touch.wake").value_or(deviceContext.isExternal());
Prabir Pradhan167c2702022-09-14 00:37:24 +0000429
Harry Cuttsf13161a2023-03-08 14:15:49 +0000430 std::optional<int32_t> usiVersionMajor = config.getInt("touch.usiVersionMajor");
431 std::optional<int32_t> usiVersionMinor = config.getInt("touch.usiVersionMinor");
432 if (usiVersionMajor.has_value() && usiVersionMinor.has_value()) {
Arpit Singh403e53c2023-04-18 11:46:56 +0000433 parameters.usiVersion = {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000434 .majorVersion = *usiVersionMajor,
435 .minorVersion = *usiVersionMinor,
436 };
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000437 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700438
Arpit Singh403e53c2023-04-18 11:46:56 +0000439 parameters.enableForInactiveViewport =
Harry Cuttsf13161a2023-03-08 14:15:49 +0000440 config.getBool("touch.enableForInactiveViewport").value_or(false);
Arpit Singh403e53c2023-04-18 11:46:56 +0000441
442 return parameters;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443}
444
Arpit Singh403e53c2023-04-18 11:46:56 +0000445TouchInputMapper::Parameters::DeviceType TouchInputMapper::computeDeviceType(
446 const InputDeviceContext& deviceContext) {
447 Parameters::DeviceType deviceType;
448 if (deviceContext.hasInputProperty(INPUT_PROP_DIRECT)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000449 // The device is a touch screen.
Arpit Singh403e53c2023-04-18 11:46:56 +0000450 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
451 } else if (deviceContext.hasInputProperty(INPUT_PROP_POINTER)) {
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000452 // The device is a pointing device like a track pad.
Arpit Singh403e53c2023-04-18 11:46:56 +0000453 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000454 } else {
455 // The device is a touch pad of unknown purpose.
Arpit Singh403e53c2023-04-18 11:46:56 +0000456 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000457 }
458
459 // Type association takes precedence over the device type found in the idc file.
Arpit Singh403e53c2023-04-18 11:46:56 +0000460 std::string deviceTypeString = deviceContext.getDeviceTypeAssociation().value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000461 if (deviceTypeString.empty()) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000462 deviceTypeString =
Arpit Singh403e53c2023-04-18 11:46:56 +0000463 deviceContext.getConfiguration().getString("touch.deviceType").value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000464 }
465 if (deviceTypeString == "touchScreen") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000466 deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000467 } else if (deviceTypeString == "touchNavigation") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000468 deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000469 } else if (deviceTypeString == "pointer") {
Arpit Singh403e53c2023-04-18 11:46:56 +0000470 deviceType = Parameters::DeviceType::POINTER;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000471 } else if (deviceTypeString != "default" && deviceTypeString != "") {
472 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
473 }
Arpit Singh403e53c2023-04-18 11:46:56 +0000474 return deviceType;
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000475}
476
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700477void TouchInputMapper::dumpParameters(std::string& dump) {
478 dump += INDENT3 "Parameters:\n";
479
Dominik Laskowski75788452021-02-09 18:51:25 -0800480 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700481
Dominik Laskowski75788452021-02-09 18:51:25 -0800482 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700483
484 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
485 "displayId='%s'\n",
486 toString(mParameters.hasAssociatedDisplay),
487 toString(mParameters.associatedDisplayIsExternal),
488 mParameters.uniqueDisplayId.c_str());
489 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800490 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000491 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
492 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700493 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
494 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700495}
496
497void TouchInputMapper::configureRawPointerAxes() {
498 mRawPointerAxes.clear();
499}
500
501void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
502 dump += INDENT3 "Raw Touch Axes:\n";
503 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
504 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
505 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
506 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
507 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
508 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
509 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
510 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
511 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
512 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
513 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
514 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
515 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
516}
517
518bool TouchInputMapper::hasExternalStylus() const {
519 return mExternalStylusConnected;
520}
521
522/**
523 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000524 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800525 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000526 * 3. Get the matching viewport by either unique id in idc file or by the display type
527 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800528 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700529 */
530std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800531 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000532 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800533 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700534 }
535
Christine Franks2a2293c2022-01-18 11:51:16 -0800536 const std::optional<std::string> associatedDisplayUniqueId =
537 getDeviceContext().getAssociatedDisplayUniqueId();
538 if (associatedDisplayUniqueId) {
539 return getDeviceContext().getAssociatedViewport();
540 }
541
Michael Wright227c5542020-07-02 18:30:52 +0100542 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800543 std::optional<DisplayViewport> viewport =
544 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
545 if (viewport) {
546 return viewport;
547 } else {
548 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
549 mConfig.defaultPointerDisplayId);
550 }
551 }
552
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700553 // Check if uniqueDisplayId is specified in idc file.
554 if (!mParameters.uniqueDisplayId.empty()) {
555 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
556 }
557
558 ViewportType viewportTypeToUse;
559 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100560 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700561 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100562 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700563 }
564
565 std::optional<DisplayViewport> viewport =
566 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100567 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700568 ALOGW("Input device %s should be associated with external display, "
569 "fallback to internal one for the external viewport is not found.",
570 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100571 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700572 }
573
574 return viewport;
575 }
576
577 // No associated display, return a non-display viewport.
578 DisplayViewport newViewport;
579 // Raw width and height in the natural orientation.
580 int32_t rawWidth = mRawPointerAxes.getRawWidth();
581 int32_t rawHeight = mRawPointerAxes.getRawHeight();
582 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
583 return std::make_optional(newViewport);
584}
585
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800586int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
587 if (resolution < 0) {
588 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
589 getDeviceName().c_str());
590 return 0;
591 }
592 return resolution;
593}
594
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800595void TouchInputMapper::initializeSizeRanges() {
596 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
597 mSizeScale = 0.0f;
598 return;
599 }
600
601 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000602 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800603
604 // Size factors.
605 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
606 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
607 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
608 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
609 } else {
610 mSizeScale = 0.0f;
611 }
612
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700613 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
614 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
615 .source = mSource,
616 .min = 0,
617 .max = diagonalSize,
618 .flat = 0,
619 .fuzz = 0,
620 .resolution = 0,
621 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800622
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800623 if (mRawPointerAxes.touchMajor.valid) {
624 mRawPointerAxes.touchMajor.resolution =
625 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700626 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800627 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800628
629 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700630 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800631 if (mRawPointerAxes.touchMinor.valid) {
632 mRawPointerAxes.touchMinor.resolution =
633 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700634 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800635 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800636
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700637 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
638 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
639 .source = mSource,
640 .min = 0,
641 .max = diagonalSize,
642 .flat = 0,
643 .fuzz = 0,
644 .resolution = 0,
645 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800646 if (mRawPointerAxes.toolMajor.valid) {
647 mRawPointerAxes.toolMajor.resolution =
648 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700649 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800650 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800651
652 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700653 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800654 if (mRawPointerAxes.toolMinor.valid) {
655 mRawPointerAxes.toolMinor.resolution =
656 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700657 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800658 }
659
660 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700661 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
662 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
663 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
664 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800665 } else {
666 // Support for other calibrations can be added here.
667 ALOGW("%s calibration is not supported for size ranges at the moment. "
668 "Using raw resolution instead",
669 ftl::enum_string(mCalibration.sizeCalibration).c_str());
670 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800671
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700672 mOrientedRanges.size = InputDeviceInfo::MotionRange{
673 .axis = AMOTION_EVENT_AXIS_SIZE,
674 .source = mSource,
675 .min = 0,
676 .max = 1.0,
677 .flat = 0,
678 .fuzz = 0,
679 .resolution = 0,
680 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800681}
682
683void TouchInputMapper::initializeOrientedRanges() {
684 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000685 const float orientedScaleX = mRawToDisplay.getScaleX();
686 const float orientedScaleY = mRawToDisplay.getScaleY();
687 mOrientedXPrecision = 1.0f / orientedScaleX;
688 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800689
690 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
691 mOrientedRanges.x.source = mSource;
692 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
693 mOrientedRanges.y.source = mSource;
694
695 // Scale factor for terms that are not oriented in a particular axis.
696 // If the pixels are square then xScale == yScale otherwise we fake it
697 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000698 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800699
700 initializeSizeRanges();
701
702 // Pressure factors.
703 mPressureScale = 0;
704 float pressureMax = 1.0;
705 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
706 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700707 if (mCalibration.pressureScale) {
708 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800709 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
710 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
711 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
712 }
713 }
714
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700715 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
716 .axis = AMOTION_EVENT_AXIS_PRESSURE,
717 .source = mSource,
718 .min = 0,
719 .max = pressureMax,
720 .flat = 0,
721 .fuzz = 0,
722 .resolution = 0,
723 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800724
725 // Tilt
726 mTiltXCenter = 0;
727 mTiltXScale = 0;
728 mTiltYCenter = 0;
729 mTiltYScale = 0;
730 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
731 if (mHaveTilt) {
732 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
733 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
734 mTiltXScale = M_PI / 180;
735 mTiltYScale = M_PI / 180;
736
737 if (mRawPointerAxes.tiltX.resolution) {
738 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
739 }
740 if (mRawPointerAxes.tiltY.resolution) {
741 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
742 }
743
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700744 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
745 .axis = AMOTION_EVENT_AXIS_TILT,
746 .source = mSource,
747 .min = 0,
748 .max = M_PI_2,
749 .flat = 0,
750 .fuzz = 0,
751 .resolution = 0,
752 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800753 }
754
755 // Orientation
756 mOrientationScale = 0;
757 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700758 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
759 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
760 .source = mSource,
761 .min = -M_PI,
762 .max = M_PI,
763 .flat = 0,
764 .fuzz = 0,
765 .resolution = 0,
766 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800767
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800768 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
769 if (mCalibration.orientationCalibration ==
770 Calibration::OrientationCalibration::INTERPOLATED) {
771 if (mRawPointerAxes.orientation.valid) {
772 if (mRawPointerAxes.orientation.maxValue > 0) {
773 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
774 } else if (mRawPointerAxes.orientation.minValue < 0) {
775 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
776 } else {
777 mOrientationScale = 0;
778 }
779 }
780 }
781
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700782 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
783 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
784 .source = mSource,
785 .min = -M_PI_2,
786 .max = M_PI_2,
787 .flat = 0,
788 .fuzz = 0,
789 .resolution = 0,
790 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800791 }
792
793 // Distance
794 mDistanceScale = 0;
795 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
796 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700797 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800798 }
799
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700800 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800801
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700802 .axis = AMOTION_EVENT_AXIS_DISTANCE,
803 .source = mSource,
804 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
805 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
806 .flat = 0,
807 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
808 .resolution = 0,
809 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800810 }
811
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000812 // Oriented X/Y range (in the rotated display's orientation)
813 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
814 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
815 .toFloatRect();
816 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
817 mOrientedRanges.x.min = orientedRangeRect.left;
818 mOrientedRanges.y.min = orientedRangeRect.top;
819 mOrientedRanges.x.max = orientedRangeRect.right;
820 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800821
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000822 // Oriented flat (in the rotated display's orientation)
823 const auto orientedFlat =
824 transformWithoutTranslation(mRawToRotatedDisplay,
825 {static_cast<float>(mRawPointerAxes.x.flat),
826 static_cast<float>(mRawPointerAxes.y.flat)});
827 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
828 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800829
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000830 // Oriented fuzz (in the rotated display's orientation)
831 const auto orientedFuzz =
832 transformWithoutTranslation(mRawToRotatedDisplay,
833 {static_cast<float>(mRawPointerAxes.x.fuzz),
834 static_cast<float>(mRawPointerAxes.y.fuzz)});
835 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
836 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800837
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000838 // Oriented resolution (in the rotated display's orientation)
839 const auto orientedRes =
840 transformWithoutTranslation(mRawToRotatedDisplay,
841 {static_cast<float>(mRawPointerAxes.x.resolution),
842 static_cast<float>(mRawPointerAxes.y.resolution)});
843 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
844 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800845}
846
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000847void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000848 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
849 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
850 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000851
Prabir Pradhan3e798762022-12-02 21:02:11 +0000852 // See notes about input coordinates in the inputflinger docs:
853 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000854
855 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000856 ui::Transform undoOffsetInRaw;
857 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000858
Prabir Pradhan3e798762022-12-02 21:02:11 +0000859 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
860 // will now be in the same orientation as the display in ROTATION_0.
861 // Note: Negating an ui::Rotation value will give its inverse rotation.
862 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
863 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
864 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
865 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
866 // When rotating raw values, account for the extra unit added when calculating the raw range.
867 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
868 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000869
Prabir Pradhan3e798762022-12-02 21:02:11 +0000870 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
871 // now be in the same orientation as the rotated display. There is no need to rotate the
872 // coordinates to the display rotation if the device is not orientation-aware.
873 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
874 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
875 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
876 : orientedRawSize;
877 // When rotating raw values, account for the extra unit added when calculating the raw range.
878 const auto rotateInRaw = mParameters.orientationAware
879 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
880 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000881
Prabir Pradhan3e798762022-12-02 21:02:11 +0000882 // Step 4: Scale the raw coordinates to the display space.
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000883 // - In DIRECT mode, we assume that the raw surface of the touch device maps perfectly to
884 // the surface of the display panel. This is usually true for touchscreens.
885 // - In POINTER mode, we cannot assume that the display and the touch device have the same
886 // aspect ratio, since it is likely to be untrue for devices like external drawing tablets.
887 // In this case, we used a fixed scale so that 1) we use the same scale across both the x and
888 // y axes to ensure the mapping does not stretch gestures, and 2) the entire region of the
889 // display can be reached by the touch device.
Prabir Pradhan3e798762022-12-02 21:02:11 +0000890 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
891 // are in the continuous space of the logical display.
892 ui::Transform scaleRawToDisplay;
893 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
894 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
Prabir Pradhan7d9cb5a2023-03-14 21:18:07 +0000895 if (mDeviceMode == DeviceMode::DIRECT) {
896 scaleRawToDisplay.set(xScale, 0, 0, yScale);
897 } else if (mDeviceMode == DeviceMode::POINTER) {
898 const float fixedScale = std::max(xScale, yScale);
899 scaleRawToDisplay.set(fixedScale, 0, 0, fixedScale);
900 } else {
901 LOG_ALWAYS_FATAL("computeInputTransform can only be used for DIRECT and POINTER modes");
902 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000903
Prabir Pradhan3e798762022-12-02 21:02:11 +0000904 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
905 // that InputReader uses.
906 const auto undoRotateInDisplay =
907 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
908 .inverse();
909
910 // Now put it all together!
911 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
912 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
913 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000914}
915
Prabir Pradhan1728b212021-10-19 16:00:03 -0700916void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000917 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700918
919 resolveExternalStylusPresence();
920
921 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100922 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000923 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700924 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100925 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700926 if (hasStylus()) {
927 mSource |= AINPUT_SOURCE_STYLUS;
928 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800929 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700930 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100931 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700932 if (hasStylus()) {
933 mSource |= AINPUT_SOURCE_STYLUS;
934 }
935 if (hasExternalStylus()) {
936 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
937 }
Michael Wright227c5542020-07-02 18:30:52 +0100938 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700939 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100940 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700941 } else {
942 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100943 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700944 }
945
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000946 const std::optional<DisplayViewport> newViewportOpt = findViewport();
947
948 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700949 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
950 ALOGW("Touch device '%s' did not report support for X or Y axis! "
951 "The device will be inoperable.",
952 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100953 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000954 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700955 ALOGI("Touch device '%s' could not query the properties of its associated "
956 "display. The device will be inoperable until the display size "
957 "becomes available.",
958 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100959 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700960 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000961 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
962 getDeviceName().c_str(), getDeviceId());
963 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000964 }
965
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000967 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000968 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
969 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
970 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
971 const float rawMeanResolution =
972 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700973
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000974 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
975 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700976 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700977 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000978 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
979 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
980 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700981
Michael Wright227c5542020-07-02 18:30:52 +0100982 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000983 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700984
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000985 mDisplayBounds = getNaturalDisplaySize(mViewport);
986 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
987 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700988
Prabir Pradhan3e798762022-12-02 21:02:11 +0000989 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
990 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
991 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000992 // InputReader works in the un-rotated display coordinate space, so we don't need to do
993 // anything if the device is already orientation-aware. If the device is not
994 // orientation-aware, then we need to apply the inverse rotation of the display so that
995 // when the display rotation is applied later as a part of the per-window transform, we
996 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700997 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000998 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000999 : getInverseRotation(mViewport.orientation);
1000 // For orientation-aware devices that work in the un-rotated coordinate space, the
1001 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +00001002 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001003 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -07001004
1005 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +00001006 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001007 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001008 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001009 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001010 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +00001011 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00001012 mRawToDisplay.reset();
1013 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001014 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001015 }
1016 }
1017
1018 // If moving between pointer modes, need to reset some state.
1019 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1020 if (deviceModeChanged) {
1021 mOrientedRanges.clear();
1022 }
1023
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001024 // Create and preserve the pointer controller in the following cases:
1025 const bool isPointerControllerNeeded =
1026 // - when the device is in pointer mode, to show the mouse cursor;
1027 (mDeviceMode == DeviceMode::POINTER) ||
1028 // - when pointer capture is enabled, to preserve the mouse cursor position;
1029 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1030 mConfig.pointerCaptureRequest.enable) ||
1031 // - when we should be showing touches;
1032 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1033 // - when we should be showing a pointer icon for direct styluses.
1034 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1035 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001036 if (mPointerController == nullptr) {
1037 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001038 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001039 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001040 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1041 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001042 } else {
lilinnandef700b2022-06-17 19:32:01 +08001043 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1044 !mConfig.showTouches) {
1045 mPointerController->clearSpots();
1046 }
Michael Wright17db18e2020-06-26 20:51:44 +01001047 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001048 }
1049
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001050 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001051 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001052 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001053 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001054 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001055
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001056 configureVirtualKeys();
1057
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001058 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001059
1060 // Location
1061 updateAffineTransformation();
1062
Michael Wright227c5542020-07-02 18:30:52 +01001063 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001064 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001065 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1066 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001067
1068 // Scale movements such that one whole swipe of the touch pad covers a
1069 // given area relative to the diagonal size of the display when no acceleration
1070 // is applied.
1071 // Assume that the touch pad has a square aspect ratio such that movements in
1072 // X and Y of the same number of raw units cover the same physical distance.
1073 mPointerXMovementScale =
1074 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1075 mPointerYMovementScale = mPointerXMovementScale;
1076
1077 // Scale zooms to cover a smaller range of the display than movements do.
1078 // This value determines the area around the pointer that is affected by freeform
1079 // pointer gestures.
1080 mPointerXZoomScale =
1081 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1082 mPointerYZoomScale = mPointerXZoomScale;
1083
HQ Liue6983c72022-04-19 22:14:56 +00001084 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1085 // axis is non positive value.
1086 const float minFreeformGestureWidth =
1087 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1088
1089 mPointerGestureMaxSwipeWidth =
1090 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1091 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001092 }
1093
1094 // Inform the dispatcher about the changes.
1095 *outResetNeeded = true;
1096 bumpGeneration();
1097 }
1098}
1099
Prabir Pradhan1728b212021-10-19 16:00:03 -07001100void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001101 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001102 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001103 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1104 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001105 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001106}
1107
1108void TouchInputMapper::configureVirtualKeys() {
1109 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001110 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001111
1112 mVirtualKeys.clear();
1113
1114 if (virtualKeyDefinitions.size() == 0) {
1115 return;
1116 }
1117
1118 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1119 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1120 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1121 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1122
1123 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1124 VirtualKey virtualKey;
1125
1126 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1127 int32_t keyCode;
1128 int32_t dummyKeyMetaState;
1129 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001130 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1131 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001132 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1133 continue; // drop the key
1134 }
1135
1136 virtualKey.keyCode = keyCode;
1137 virtualKey.flags = flags;
1138
1139 // convert the key definition's display coordinates into touch coordinates for a hit box
1140 int32_t halfWidth = virtualKeyDefinition.width / 2;
1141 int32_t halfHeight = virtualKeyDefinition.height / 2;
1142
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001143 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1144 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001146 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1147 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001149 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1150 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001152 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1153 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001154 touchScreenTop;
1155 mVirtualKeys.push_back(virtualKey);
1156 }
1157}
1158
1159void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1160 if (!mVirtualKeys.empty()) {
1161 dump += INDENT3 "Virtual Keys:\n";
1162
1163 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1164 const VirtualKey& virtualKey = mVirtualKeys[i];
1165 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1166 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1167 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1168 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1169 }
1170 }
1171}
1172
1173void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001174 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 Calibration& out = mCalibration;
1176
1177 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001178 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001179 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1180 if (sizeCalibrationString.has_value()) {
1181 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001182 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001183 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001185 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001186 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001187 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001189 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001191 } else if (*sizeCalibrationString != "default") {
1192 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 }
1194 }
1195
Harry Cuttsf13161a2023-03-08 14:15:49 +00001196 out.sizeScale = in.getFloat("touch.size.scale");
1197 out.sizeBias = in.getFloat("touch.size.bias");
1198 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199
1200 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001202 std::optional<std::string> pressureCalibrationString =
1203 in.getString("touch.pressure.calibration");
1204 if (pressureCalibrationString.has_value()) {
1205 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001207 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001209 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001210 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001211 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001213 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 }
1215 }
1216
Harry Cuttsf13161a2023-03-08 14:15:49 +00001217 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001218
1219 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001220 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001221 std::optional<std::string> orientationCalibrationString =
1222 in.getString("touch.orientation.calibration");
1223 if (orientationCalibrationString.has_value()) {
1224 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001225 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001226 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001227 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001228 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001229 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001230 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001232 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 }
1234 }
1235
1236 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001237 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001238 std::optional<std::string> distanceCalibrationString =
1239 in.getString("touch.distance.calibration");
1240 if (distanceCalibrationString.has_value()) {
1241 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001242 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001243 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001244 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001245 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001247 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 }
1249 }
1250
Harry Cuttsf13161a2023-03-08 14:15:49 +00001251 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252}
1253
1254void TouchInputMapper::resolveCalibration() {
1255 // Size
1256 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001257 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1258 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001261 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 }
1263
1264 // Pressure
1265 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001266 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1267 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 }
1269 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001270 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 }
1272
1273 // Orientation
1274 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001275 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1276 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277 }
1278 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001279 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 }
1281
1282 // Distance
1283 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001284 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1285 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001286 }
1287 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001288 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290}
1291
1292void TouchInputMapper::dumpCalibration(std::string& dump) {
1293 dump += INDENT3 "Calibration:\n";
1294
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001295 dump += INDENT4 "touch.size.calibration: ";
1296 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001298 if (mCalibration.sizeScale) {
1299 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 }
1301
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001302 if (mCalibration.sizeBias) {
1303 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 }
1305
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001306 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001308 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001309 }
1310
1311 // Pressure
1312 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001313 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001314 dump += INDENT4 "touch.pressure.calibration: none\n";
1315 break;
Michael Wright227c5542020-07-02 18:30:52 +01001316 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317 dump += INDENT4 "touch.pressure.calibration: physical\n";
1318 break;
Michael Wright227c5542020-07-02 18:30:52 +01001319 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1321 break;
1322 default:
1323 ALOG_ASSERT(false);
1324 }
1325
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001326 if (mCalibration.pressureScale) {
1327 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 }
1329
1330 // Orientation
1331 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001332 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001333 dump += INDENT4 "touch.orientation.calibration: none\n";
1334 break;
Michael Wright227c5542020-07-02 18:30:52 +01001335 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001336 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1337 break;
Michael Wright227c5542020-07-02 18:30:52 +01001338 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001339 dump += INDENT4 "touch.orientation.calibration: vector\n";
1340 break;
1341 default:
1342 ALOG_ASSERT(false);
1343 }
1344
1345 // Distance
1346 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001347 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001348 dump += INDENT4 "touch.distance.calibration: none\n";
1349 break;
Michael Wright227c5542020-07-02 18:30:52 +01001350 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001351 dump += INDENT4 "touch.distance.calibration: scaled\n";
1352 break;
1353 default:
1354 ALOG_ASSERT(false);
1355 }
1356
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001357 if (mCalibration.distanceScale) {
1358 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001359 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360}
1361
1362void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1363 dump += INDENT3 "Affine Transformation:\n";
1364
1365 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1366 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1367 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1368 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1369 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1370 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1371}
1372
1373void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001374 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001375 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001376}
1377
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001378std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001379 std::list<NotifyArgs> out = cancelTouch(when, when);
1380 updateTouchSpots();
1381
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001382 mCursorButtonAccumulator.reset(getDeviceContext());
1383 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001384 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001385
1386 mPointerVelocityControl.reset();
1387 mWheelXVelocityControl.reset();
1388 mWheelYVelocityControl.reset();
1389
1390 mRawStatesPending.clear();
1391 mCurrentRawState.clear();
1392 mCurrentCookedState.clear();
1393 mLastRawState.clear();
1394 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001395 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001396 mSentHoverEnter = false;
1397 mHavePointerIds = false;
1398 mCurrentMotionAborted = false;
1399 mDownTime = 0;
1400
1401 mCurrentVirtualKey.down = false;
1402
1403 mPointerGesture.reset();
1404 mPointerSimple.reset();
1405 resetExternalStylus();
1406
1407 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001408 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001409 mPointerController->clearSpots();
1410 }
1411
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001412 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001413}
1414
1415void TouchInputMapper::resetExternalStylus() {
1416 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001417 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001418 mExternalStylusFusionTimeout = LLONG_MAX;
1419 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001420 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001421}
1422
1423void TouchInputMapper::clearStylusDataPendingFlags() {
1424 mExternalStylusDataPending = false;
1425 mExternalStylusFusionTimeout = LLONG_MAX;
1426}
1427
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001428std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001429 mCursorButtonAccumulator.process(rawEvent);
1430 mCursorScrollAccumulator.process(rawEvent);
1431 mTouchButtonAccumulator.process(rawEvent);
1432
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001433 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001434 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001435 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001437 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001438}
1439
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001440std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1441 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001442 if (mDeviceMode == DeviceMode::DISABLED) {
1443 // Only save the last pending state when the device is disabled.
1444 mRawStatesPending.clear();
1445 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001446 // Push a new state.
1447 mRawStatesPending.emplace_back();
1448
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001449 RawState& next = mRawStatesPending.back();
1450 next.clear();
1451 next.when = when;
1452 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001453
1454 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001455 next.buttonState = filterButtonState(mConfig,
1456 mTouchButtonAccumulator.getButtonState() |
1457 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001458
1459 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001460 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1461 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001462 mCursorScrollAccumulator.finishSync();
1463
1464 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001465 syncTouch(when, &next);
1466
1467 // The last RawState is the actually second to last, since we just added a new state
1468 const RawState& last =
1469 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001470
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001471 std::tie(next.when, next.readTime) =
1472 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1473 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001474
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001475 // Assign pointer ids.
1476 if (!mHavePointerIds) {
1477 assignPointerIds(last, next);
1478 }
1479
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001480 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001481 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1482 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1483 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1484 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1485 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1486 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001487
Arthur Hung9ad18942021-06-19 02:04:46 +00001488 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1489 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1490 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1491 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1492 next.rawPointerData.hoveringIdBits.value);
1493 }
1494
Harry Cutts33476232023-01-30 19:57:29 +00001495 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001496 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001497}
1498
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001499std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1500 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001501 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001502 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001503 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001504 }
1505
1506 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1507 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1508 // touching the current state will only observe the events that have been dispatched to the
1509 // rest of the pipeline.
1510 const size_t N = mRawStatesPending.size();
1511 size_t count;
1512 for (count = 0; count < N; count++) {
1513 const RawState& next = mRawStatesPending[count];
1514
1515 // A failure to assign the stylus id means that we're waiting on stylus data
1516 // and so should defer the rest of the pipeline.
1517 if (assignExternalStylusId(next, timeout)) {
1518 break;
1519 }
1520
1521 // All ready to go.
1522 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001523 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 if (mCurrentRawState.when < mLastRawState.when) {
1525 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001526 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001527 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001528 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001529 }
1530 if (count != 0) {
1531 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1532 }
1533
1534 if (mExternalStylusDataPending) {
1535 if (timeout) {
1536 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1537 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001538 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001539 ALOGD_IF(DEBUG_STYLUS_FUSION,
1540 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001541 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001542 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001543 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1544 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1545 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1546 }
1547 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001548 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001549}
1550
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001551std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1552 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001553 // Always start with a clean state.
1554 mCurrentCookedState.clear();
1555
1556 // Apply stylus buttons to current raw state.
1557 applyExternalStylusButtonState(when);
1558
1559 // Handle policy on initial down or hover events.
1560 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1561 mCurrentRawState.rawPointerData.pointerCount != 0;
1562
1563 uint32_t policyFlags = 0;
1564 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1565 if (initialDown || buttonsPressed) {
1566 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001567 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001568 getContext()->fadePointer();
1569 }
1570
1571 if (mParameters.wake) {
1572 policyFlags |= POLICY_FLAG_WAKE;
1573 }
1574 }
1575
1576 // Consume raw off-screen touches before cooking pointer data.
1577 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001578 bool consumed;
1579 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1580 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001581 mCurrentRawState.rawPointerData.clear();
1582 }
1583
1584 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1585 // with cooked pointer data that has the same ids and indices as the raw data.
1586 // The following code can use either the raw or cooked data, as needed.
1587 cookPointerData();
1588
1589 // Apply stylus pressure to current cooked state.
1590 applyExternalStylusTouchState(when);
1591
1592 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001593 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1594 mSource, mViewport.displayId, policyFlags,
1595 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596
1597 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001598 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001599 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1600 uint32_t id = idBits.clearFirstMarkedBit();
1601 const RawPointerData::Pointer& pointer =
1602 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001603 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001604 mCurrentCookedState.stylusIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001605 } else if (pointer.toolType == ToolType::FINGER ||
1606 pointer.toolType == ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001607 mCurrentCookedState.fingerIdBits.markBit(id);
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001608 } else if (pointer.toolType == ToolType::MOUSE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001609 mCurrentCookedState.mouseIdBits.markBit(id);
1610 }
1611 }
1612 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1613 uint32_t id = idBits.clearFirstMarkedBit();
1614 const RawPointerData::Pointer& pointer =
1615 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001616 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617 mCurrentCookedState.stylusIdBits.markBit(id);
1618 }
1619 }
1620
1621 // Stylus takes precedence over all tools, then mouse, then finger.
1622 PointerUsage pointerUsage = mPointerUsage;
1623 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1624 mCurrentCookedState.mouseIdBits.clear();
1625 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001626 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001627 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1628 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001629 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1631 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001632 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001633 }
1634
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001635 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001636 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001637 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001638 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001639 out += dispatchButtonRelease(when, readTime, policyFlags);
1640 out += dispatchHoverExit(when, readTime, policyFlags);
1641 out += dispatchTouches(when, readTime, policyFlags);
1642 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1643 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001644 }
1645
1646 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1647 mCurrentMotionAborted = false;
1648 }
1649 }
1650
1651 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001652 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1653 mSource, mViewport.displayId, policyFlags,
1654 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001655
1656 // Clear some transient state.
1657 mCurrentRawState.rawVScroll = 0;
1658 mCurrentRawState.rawHScroll = 0;
1659
1660 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001661 mLastRawState = mCurrentRawState;
1662 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001663 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001664}
1665
Garfield Tanc734e4f2021-01-15 20:01:39 -08001666void TouchInputMapper::updateTouchSpots() {
1667 if (!mConfig.showTouches || mPointerController == nullptr) {
1668 return;
1669 }
1670
1671 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1672 // clear touch spots.
1673 if (mDeviceMode != DeviceMode::DIRECT &&
1674 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1675 return;
1676 }
1677
1678 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1679 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1680
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001681 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1682 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001683 mCurrentCookedState.cookedPointerData.touchingIdBits |
1684 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001685 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001686}
1687
1688bool TouchInputMapper::isTouchScreen() {
1689 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1690 mParameters.hasAssociatedDisplay;
1691}
1692
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001693void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001694 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1695 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001696 const int32_t pressedButtons =
1697 filterButtonState(mConfig,
1698 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001699 const int32_t releasedButtons =
1700 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1701
1702 mCurrentRawState.buttonState |= pressedButtons;
1703 mCurrentRawState.buttonState &= ~releasedButtons;
1704
1705 mExternalStylusButtonsApplied |= pressedButtons;
1706 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001707 }
1708}
1709
1710void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1711 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1712 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001713 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1714 return;
1715 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001716
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001717 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1718 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1719 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1720 : 0.f;
1721 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1722 pressure = *mExternalStylusState.pressure;
1723 }
1724 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1725 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001726
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001727 if (mExternalStylusState.toolType != ToolType::UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001728 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001729 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001730 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001731 }
1732}
1733
1734bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001735 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001736 return false;
1737 }
1738
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001739 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001740 if (mFusedStylusPointerId &&
1741 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001742 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001743 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001744 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001745 }
1746
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001747 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1748 state.rawPointerData.pointerCount != 0;
1749 if (!initialDown) {
1750 return false;
1751 }
1752
1753 if (!mExternalStylusState.pressure) {
1754 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1755 return false;
1756 }
1757
1758 if (*mExternalStylusState.pressure != 0.0f) {
1759 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1760 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1761 return false;
1762 }
1763
1764 if (timeout) {
1765 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1766 mFusedStylusPointerId.reset();
1767 mExternalStylusFusionTimeout = LLONG_MAX;
1768 return false;
1769 }
1770
1771 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1772 // being processed until we either get pressure data or timeout.
1773 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1774 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1775 }
1776 ALOGD_IF(DEBUG_STYLUS_FUSION,
1777 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1778 mExternalStylusFusionTimeout);
1779 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1780 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001781}
1782
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001783std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1784 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001785 if (mDeviceMode == DeviceMode::POINTER) {
1786 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001787 // Since this is a synthetic event, we can consider its latency to be zero
1788 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001789 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001790 }
Michael Wright227c5542020-07-02 18:30:52 +01001791 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001792 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001793 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001794 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1795 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1796 }
1797 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001798 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001799}
1800
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001801std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1802 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001803 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001804 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001805 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001806 // The following three cases are handled here:
1807 // - We're in the middle of a fused stream of data;
1808 // - We're waiting on external stylus data before dispatching the initial down; or
1809 // - Only the button state, which is not reported through a specific pointer, has changed.
1810 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001811 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001812 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001813 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001814 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001815}
1816
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001817std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1818 uint32_t policyFlags, bool& outConsumed) {
1819 outConsumed = false;
1820 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001821 // Check for release of a virtual key.
1822 if (mCurrentVirtualKey.down) {
1823 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1824 // Pointer went up while virtual key was down.
1825 mCurrentVirtualKey.down = false;
1826 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001827 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1828 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1829 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001830 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1831 AKEY_EVENT_FLAG_FROM_SYSTEM |
1832 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001833 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001834 outConsumed = true;
1835 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001836 }
1837
1838 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1839 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1840 const RawPointerData::Pointer& pointer =
1841 mCurrentRawState.rawPointerData.pointerForId(id);
1842 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1843 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1844 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001845 outConsumed = true;
1846 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001847 }
1848 }
1849
1850 // Pointer left virtual key area or another pointer also went down.
1851 // Send key cancellation but do not consume the touch yet.
1852 // This is useful when the user swipes through from the virtual key area
1853 // into the main display surface.
1854 mCurrentVirtualKey.down = false;
1855 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001856 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1857 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001858 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1859 AKEY_EVENT_FLAG_FROM_SYSTEM |
1860 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1861 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001862 }
1863 }
1864
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001865 if (!mCurrentRawState.rawPointerData.hoveringIdBits.isEmpty() &&
1866 mCurrentRawState.rawPointerData.touchingIdBits.isEmpty() &&
1867 mDeviceMode != DeviceMode::UNSCALED) {
1868 // We have hovering pointers, and there are no touching pointers.
1869 bool hoveringPointersInFrame = false;
1870 auto hoveringIds = mCurrentRawState.rawPointerData.hoveringIdBits;
1871 while (!hoveringIds.isEmpty()) {
1872 uint32_t id = hoveringIds.clearFirstMarkedBit();
1873 const auto& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1874 if (isPointInsidePhysicalFrame(pointer.x, pointer.y)) {
1875 hoveringPointersInFrame = true;
1876 break;
1877 }
1878 }
1879 if (!hoveringPointersInFrame) {
1880 // All hovering pointers are outside the physical frame.
1881 outConsumed = true;
1882 return out;
1883 }
1884 }
1885
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001886 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1887 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1888 // Pointer just went down. Check for virtual key press or off-screen touches.
1889 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1890 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001891 // Skip checking whether the pointer is inside the physical frame if the device is in
Harry Cutts1db43992023-06-19 17:05:07 +00001892 // unscaled or pointer mode.
Prabir Pradhan1728b212021-10-19 16:00:03 -07001893 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
Harry Cutts1db43992023-06-19 17:05:07 +00001894 mDeviceMode != DeviceMode::UNSCALED && mDeviceMode != DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001895 // If exactly one pointer went down, check for virtual key hit.
Prabir Pradhane1e309a2022-11-29 02:54:27 +00001896 // Otherwise, we will drop the entire stroke.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001897 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1898 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1899 if (virtualKey) {
1900 mCurrentVirtualKey.down = true;
1901 mCurrentVirtualKey.downTime = when;
1902 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1903 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1904 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001905 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1906 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001907
1908 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001909 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1910 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1911 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001912 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1913 AKEY_EVENT_ACTION_DOWN,
1914 AKEY_EVENT_FLAG_FROM_SYSTEM |
1915 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001916 }
1917 }
1918 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001919 outConsumed = true;
1920 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921 }
1922 }
1923
1924 // Disable all virtual key touches that happen within a short time interval of the
1925 // most recent touch within the screen area. The idea is to filter out stray
1926 // virtual key presses when interacting with the touch screen.
1927 //
1928 // Problems we're trying to solve:
1929 //
1930 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1931 // virtual key area that is implemented by a separate touch panel and accidentally
1932 // triggers a virtual key.
1933 //
1934 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1935 // area and accidentally triggers a virtual key. This often happens when virtual keys
1936 // are layed out below the screen near to where the on screen keyboard's space bar
1937 // is displayed.
1938 if (mConfig.virtualKeyQuietTime > 0 &&
1939 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001940 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001941 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001942 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001943}
1944
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001945NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1946 uint32_t policyFlags, int32_t keyEventAction,
1947 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001948 int32_t keyCode = mCurrentVirtualKey.keyCode;
1949 int32_t scanCode = mCurrentVirtualKey.scanCode;
1950 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001951 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001952 policyFlags |= POLICY_FLAG_VIRTUAL;
1953
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001954 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1955 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1956 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001957}
1958
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001959std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1960 uint32_t policyFlags) {
1961 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001962 if (mCurrentMotionAborted) {
1963 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001964 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001965 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001966 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1967 if (!currentIdBits.isEmpty()) {
1968 int32_t metaState = getContext()->getGlobalMetaState();
1969 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001970 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001971 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1972 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001973 mCurrentCookedState.cookedPointerData.pointerProperties,
1974 mCurrentCookedState.cookedPointerData.pointerCoords,
1975 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1976 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1977 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001978 mCurrentMotionAborted = true;
1979 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001980 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001981}
1982
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001983// Updates pointer coords and properties for pointers with specified ids that have moved.
1984// Returns true if any of them changed.
1985static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1986 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1987 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1988 BitSet32 idBits) {
1989 bool changed = false;
1990 while (!idBits.isEmpty()) {
1991 uint32_t id = idBits.clearFirstMarkedBit();
1992 uint32_t inIndex = inIdToIndex[id];
1993 uint32_t outIndex = outIdToIndex[id];
1994
1995 const PointerProperties& curInProperties = inProperties[inIndex];
1996 const PointerCoords& curInCoords = inCoords[inIndex];
1997 PointerProperties& curOutProperties = outProperties[outIndex];
1998 PointerCoords& curOutCoords = outCoords[outIndex];
1999
2000 if (curInProperties != curOutProperties) {
2001 curOutProperties.copyFrom(curInProperties);
2002 changed = true;
2003 }
2004
2005 if (curInCoords != curOutCoords) {
2006 curOutCoords.copyFrom(curInCoords);
2007 changed = true;
2008 }
2009 }
2010 return changed;
2011}
2012
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002013std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
2014 uint32_t policyFlags) {
2015 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002016 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
2017 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
2018 int32_t metaState = getContext()->getGlobalMetaState();
2019 int32_t buttonState = mCurrentCookedState.buttonState;
2020
2021 if (currentIdBits == lastIdBits) {
2022 if (!currentIdBits.isEmpty()) {
2023 // No pointer id changes so this is a move event.
2024 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002025 out.push_back(
2026 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2027 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2028 mCurrentCookedState.cookedPointerData.pointerProperties,
2029 mCurrentCookedState.cookedPointerData.pointerCoords,
2030 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2031 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2032 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002033 }
2034 } else {
2035 // There may be pointers going up and pointers going down and pointers moving
2036 // all at the same time.
2037 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2038 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2039 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2040 BitSet32 dispatchedIdBits(lastIdBits.value);
2041
2042 // Update last coordinates of pointers that have moved so that we observe the new
2043 // pointer positions at the same time as other pointers that have just gone up.
2044 bool moveNeeded =
2045 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2046 mCurrentCookedState.cookedPointerData.pointerCoords,
2047 mCurrentCookedState.cookedPointerData.idToIndex,
2048 mLastCookedState.cookedPointerData.pointerProperties,
2049 mLastCookedState.cookedPointerData.pointerCoords,
2050 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2051 if (buttonState != mLastCookedState.buttonState) {
2052 moveNeeded = true;
2053 }
2054
2055 // Dispatch pointer up events.
2056 while (!upIdBits.isEmpty()) {
2057 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002058 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002059 if (isCanceled) {
2060 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2061 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002062 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2063 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2064 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2065 buttonState, 0,
2066 mLastCookedState.cookedPointerData.pointerProperties,
2067 mLastCookedState.cookedPointerData.pointerCoords,
2068 mLastCookedState.cookedPointerData.idToIndex,
2069 dispatchedIdBits, upId, mOrientedXPrecision,
2070 mOrientedYPrecision, mDownTime,
2071 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002072 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002073 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002074 }
2075
2076 // Dispatch move events if any of the remaining pointers moved from their old locations.
2077 // Although applications receive new locations as part of individual pointer up
2078 // events, they do not generally handle them except when presented in a move event.
2079 if (moveNeeded && !moveIdBits.isEmpty()) {
2080 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002081 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2082 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2083 mCurrentCookedState.cookedPointerData.pointerProperties,
2084 mCurrentCookedState.cookedPointerData.pointerCoords,
2085 mCurrentCookedState.cookedPointerData.idToIndex,
2086 dispatchedIdBits, -1, mOrientedXPrecision,
2087 mOrientedYPrecision, mDownTime,
2088 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089 }
2090
2091 // Dispatch pointer down events using the new pointer locations.
2092 while (!downIdBits.isEmpty()) {
2093 uint32_t downId = downIdBits.clearFirstMarkedBit();
2094 dispatchedIdBits.markBit(downId);
2095
2096 if (dispatchedIdBits.count() == 1) {
2097 // First pointer is going down. Set down time.
2098 mDownTime = when;
2099 }
2100
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002101 out.push_back(
2102 dispatchMotion(when, readTime, policyFlags, mSource,
2103 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2104 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2105 mCurrentCookedState.cookedPointerData.pointerCoords,
2106 mCurrentCookedState.cookedPointerData.idToIndex,
2107 dispatchedIdBits, downId, mOrientedXPrecision,
2108 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002109 }
2110 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002111 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002112}
2113
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002114std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2115 uint32_t policyFlags) {
2116 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002117 if (mSentHoverEnter &&
2118 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2119 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2120 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002121 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2122 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2123 mLastCookedState.buttonState, 0,
2124 mLastCookedState.cookedPointerData.pointerProperties,
2125 mLastCookedState.cookedPointerData.pointerCoords,
2126 mLastCookedState.cookedPointerData.idToIndex,
2127 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2128 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2129 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002130 mSentHoverEnter = false;
2131 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002132 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002133}
2134
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002135std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2136 uint32_t policyFlags) {
2137 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002138 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2139 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2140 int32_t metaState = getContext()->getGlobalMetaState();
2141 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002142 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2143 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2144 mCurrentRawState.buttonState, 0,
2145 mCurrentCookedState.cookedPointerData.pointerProperties,
2146 mCurrentCookedState.cookedPointerData.pointerCoords,
2147 mCurrentCookedState.cookedPointerData.idToIndex,
2148 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2149 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2150 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002151 mSentHoverEnter = true;
2152 }
2153
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002154 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2155 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2156 mCurrentRawState.buttonState, 0,
2157 mCurrentCookedState.cookedPointerData.pointerProperties,
2158 mCurrentCookedState.cookedPointerData.pointerCoords,
2159 mCurrentCookedState.cookedPointerData.idToIndex,
2160 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2161 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2162 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002163 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002164 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002165}
2166
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002167std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2168 uint32_t policyFlags) {
2169 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002170 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2171 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2172 const int32_t metaState = getContext()->getGlobalMetaState();
2173 int32_t buttonState = mLastCookedState.buttonState;
2174 while (!releasedButtons.isEmpty()) {
2175 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2176 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002177 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2178 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2179 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002180 mLastCookedState.cookedPointerData.pointerProperties,
2181 mLastCookedState.cookedPointerData.pointerCoords,
2182 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002183 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2184 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002185 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002186 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002187}
2188
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002189std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2190 uint32_t policyFlags) {
2191 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002192 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2193 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2194 const int32_t metaState = getContext()->getGlobalMetaState();
2195 int32_t buttonState = mLastCookedState.buttonState;
2196 while (!pressedButtons.isEmpty()) {
2197 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2198 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002199 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2200 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2201 buttonState, 0,
2202 mCurrentCookedState.cookedPointerData.pointerProperties,
2203 mCurrentCookedState.cookedPointerData.pointerCoords,
2204 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2205 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2206 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002207 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002208 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002209}
2210
LiZhihong758eb562022-11-03 15:28:29 +08002211std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2212 uint32_t policyFlags,
2213 BitSet32 idBits,
2214 nsecs_t readTime) {
2215 std::list<NotifyArgs> out;
2216 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2217 const int32_t metaState = getContext()->getGlobalMetaState();
2218 int32_t buttonState = mLastCookedState.buttonState;
2219
2220 while (!releasedButtons.isEmpty()) {
2221 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2222 buttonState &= ~actionButton;
2223 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2224 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2225 metaState, buttonState, 0,
2226 mPointerGesture.lastGestureProperties,
2227 mPointerGesture.lastGestureCoords,
2228 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2229 mOrientedXPrecision, mOrientedYPrecision,
2230 mPointerGesture.downTime, MotionClassification::NONE));
2231 }
2232 return out;
2233}
2234
2235std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2236 uint32_t policyFlags,
2237 BitSet32 idBits,
2238 nsecs_t readTime) {
2239 std::list<NotifyArgs> out;
2240 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2241 const int32_t metaState = getContext()->getGlobalMetaState();
2242 int32_t buttonState = mLastCookedState.buttonState;
2243
2244 while (!pressedButtons.isEmpty()) {
2245 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2246 buttonState |= actionButton;
2247 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2248 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2249 buttonState, 0, mPointerGesture.currentGestureProperties,
2250 mPointerGesture.currentGestureCoords,
2251 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2252 mOrientedXPrecision, mOrientedYPrecision,
2253 mPointerGesture.downTime, MotionClassification::NONE));
2254 }
2255 return out;
2256}
2257
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002258const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2259 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2260 return cookedPointerData.touchingIdBits;
2261 }
2262 return cookedPointerData.hoveringIdBits;
2263}
2264
2265void TouchInputMapper::cookPointerData() {
2266 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2267
2268 mCurrentCookedState.cookedPointerData.clear();
2269 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2270 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2271 mCurrentRawState.rawPointerData.hoveringIdBits;
2272 mCurrentCookedState.cookedPointerData.touchingIdBits =
2273 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002274 mCurrentCookedState.cookedPointerData.canceledIdBits =
2275 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002276
2277 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2278 mCurrentCookedState.buttonState = 0;
2279 } else {
2280 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2281 }
2282
2283 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002284 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002285 for (uint32_t i = 0; i < currentPointerCount; i++) {
2286 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2287
2288 // Size
2289 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2290 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002291 case Calibration::SizeCalibration::GEOMETRIC:
2292 case Calibration::SizeCalibration::DIAMETER:
2293 case Calibration::SizeCalibration::BOX:
2294 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002295 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2296 touchMajor = in.touchMajor;
2297 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2298 toolMajor = in.toolMajor;
2299 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2300 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2301 : in.touchMajor;
2302 } else if (mRawPointerAxes.touchMajor.valid) {
2303 toolMajor = touchMajor = in.touchMajor;
2304 toolMinor = touchMinor =
2305 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2306 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2307 : in.touchMajor;
2308 } else if (mRawPointerAxes.toolMajor.valid) {
2309 touchMajor = toolMajor = in.toolMajor;
2310 touchMinor = toolMinor =
2311 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2312 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2313 : in.toolMajor;
2314 } else {
2315 ALOG_ASSERT(false,
2316 "No touch or tool axes. "
2317 "Size calibration should have been resolved to NONE.");
2318 touchMajor = 0;
2319 touchMinor = 0;
2320 toolMajor = 0;
2321 toolMinor = 0;
2322 size = 0;
2323 }
2324
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002325 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002326 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2327 if (touchingCount > 1) {
2328 touchMajor /= touchingCount;
2329 touchMinor /= touchingCount;
2330 toolMajor /= touchingCount;
2331 toolMinor /= touchingCount;
2332 size /= touchingCount;
2333 }
2334 }
2335
Michael Wright227c5542020-07-02 18:30:52 +01002336 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002337 touchMajor *= mGeometricScale;
2338 touchMinor *= mGeometricScale;
2339 toolMajor *= mGeometricScale;
2340 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002341 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002342 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2343 touchMinor = touchMajor;
2344 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2345 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002346 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347 touchMinor = touchMajor;
2348 toolMinor = toolMajor;
2349 }
2350
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002351 mCalibration.applySizeScaleAndBias(touchMajor);
2352 mCalibration.applySizeScaleAndBias(touchMinor);
2353 mCalibration.applySizeScaleAndBias(toolMajor);
2354 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 size *= mSizeScale;
2356 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002357 case Calibration::SizeCalibration::DEFAULT:
2358 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2359 break;
2360 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 touchMajor = 0;
2362 touchMinor = 0;
2363 toolMajor = 0;
2364 toolMinor = 0;
2365 size = 0;
2366 break;
2367 }
2368
2369 // Pressure
2370 float pressure;
2371 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002372 case Calibration::PressureCalibration::PHYSICAL:
2373 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 pressure = in.pressure * mPressureScale;
2375 break;
2376 default:
2377 pressure = in.isHovering ? 0 : 1;
2378 break;
2379 }
2380
2381 // Tilt and Orientation
2382 float tilt;
2383 float orientation;
2384 if (mHaveTilt) {
2385 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2386 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002387 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2389 } else {
2390 tilt = 0;
2391
2392 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002393 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002394 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002395 break;
Michael Wright227c5542020-07-02 18:30:52 +01002396 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2398 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2399 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002400 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002401 float confidence = hypotf(c1, c2);
2402 float scale = 1.0f + confidence / 16.0f;
2403 touchMajor *= scale;
2404 touchMinor /= scale;
2405 toolMajor *= scale;
2406 toolMinor /= scale;
2407 } else {
2408 orientation = 0;
2409 }
2410 break;
2411 }
2412 default:
2413 orientation = 0;
2414 }
2415 }
2416
2417 // Distance
2418 float distance;
2419 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002420 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002421 distance = in.distance * mDistanceScale;
2422 break;
2423 default:
2424 distance = 0;
2425 }
2426
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002427 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2428 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002429 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2430 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002431
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002432 // Write output coords.
2433 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2434 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002435 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2436 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002437 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2438 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2439 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2440 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2441 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2442 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2443 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002444 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2445 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002446
Chris Ye364fdb52020-08-05 15:07:56 -07002447 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002448 uint32_t id = in.id;
2449 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2450 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2451 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002452 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2453 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002454 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2455 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2456 }
2457
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 // Write output properties.
2459 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 properties.clear();
2461 properties.id = id;
2462 properties.toolType = in.toolType;
2463
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002464 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002465 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002466 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 }
2468}
2469
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002470std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2471 uint32_t policyFlags,
2472 PointerUsage pointerUsage) {
2473 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002475 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002476 mPointerUsage = pointerUsage;
2477 }
2478
2479 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002480 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002481 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002482 break;
Michael Wright227c5542020-07-02 18:30:52 +01002483 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002484 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002485 break;
Michael Wright227c5542020-07-02 18:30:52 +01002486 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002487 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002488 break;
Michael Wright227c5542020-07-02 18:30:52 +01002489 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002490 break;
2491 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002492 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002493}
2494
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002495std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2496 uint32_t policyFlags) {
2497 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002498 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002499 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002500 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002501 break;
Michael Wright227c5542020-07-02 18:30:52 +01002502 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002503 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504 break;
Michael Wright227c5542020-07-02 18:30:52 +01002505 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002506 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002507 break;
Michael Wright227c5542020-07-02 18:30:52 +01002508 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 break;
2510 }
2511
Michael Wright227c5542020-07-02 18:30:52 +01002512 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002513 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514}
2515
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002516std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2517 uint32_t policyFlags,
2518 bool isTimeout) {
2519 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002520 // Update current gesture coordinates.
2521 bool cancelPreviousGesture, finishPreviousGesture;
2522 bool sendEvents =
2523 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2524 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002525 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002526 }
2527 if (finishPreviousGesture) {
2528 cancelPreviousGesture = false;
2529 }
2530
2531 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002532 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002533 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 if (finishPreviousGesture || cancelPreviousGesture) {
2535 mPointerController->clearSpots();
2536 }
2537
Michael Wright227c5542020-07-02 18:30:52 +01002538 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002539 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2540 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002541 mPointerGesture.currentGestureIdBits,
2542 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002543 }
2544 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002545 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002546 }
2547
2548 // Show or hide the pointer if needed.
2549 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002550 case PointerGesture::Mode::NEUTRAL:
2551 case PointerGesture::Mode::QUIET:
2552 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2553 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002554 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002555 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002556 }
2557 break;
Michael Wright227c5542020-07-02 18:30:52 +01002558 case PointerGesture::Mode::TAP:
2559 case PointerGesture::Mode::TAP_DRAG:
2560 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2561 case PointerGesture::Mode::HOVER:
2562 case PointerGesture::Mode::PRESS:
2563 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002564 // Unfade the pointer when the current gesture manipulates the
2565 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002566 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002567 break;
Michael Wright227c5542020-07-02 18:30:52 +01002568 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002569 // Fade the pointer when the current gesture manipulates a different
2570 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002571 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002572 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002573 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002574 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002575 }
2576 break;
2577 }
2578
2579 // Send events!
2580 int32_t metaState = getContext()->getGlobalMetaState();
2581 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002582 const MotionClassification classification =
2583 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2584 ? MotionClassification::TWO_FINGER_SWIPE
2585 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002586
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002587 uint32_t flags = 0;
2588
2589 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2590 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2591 }
2592
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002593 // Update last coordinates of pointers that have moved so that we observe the new
2594 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002595 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2596 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2597 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2598 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2599 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2600 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002601 bool moveNeeded = false;
2602 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2603 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2604 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2605 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2606 mPointerGesture.lastGestureIdBits.value);
2607 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2608 mPointerGesture.currentGestureCoords,
2609 mPointerGesture.currentGestureIdToIndex,
2610 mPointerGesture.lastGestureProperties,
2611 mPointerGesture.lastGestureCoords,
2612 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2613 if (buttonState != mLastCookedState.buttonState) {
2614 moveNeeded = true;
2615 }
2616 }
2617
2618 // Send motion events for all pointers that went up or were canceled.
2619 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2620 if (!dispatchedGestureIdBits.isEmpty()) {
2621 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002622 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002623 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002624 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002625 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2626 mPointerGesture.lastGestureProperties,
2627 mPointerGesture.lastGestureCoords,
2628 mPointerGesture.lastGestureIdToIndex,
2629 dispatchedGestureIdBits, -1, 0, 0,
2630 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002631
2632 dispatchedGestureIdBits.clear();
2633 } else {
2634 BitSet32 upGestureIdBits;
2635 if (finishPreviousGesture) {
2636 upGestureIdBits = dispatchedGestureIdBits;
2637 } else {
2638 upGestureIdBits.value =
2639 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2640 }
2641 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002642 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2643 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2644 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2645 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2646 readTime);
2647 }
2648 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002649 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2650 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2651 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2652 mPointerGesture.lastGestureProperties,
2653 mPointerGesture.lastGestureCoords,
2654 mPointerGesture.lastGestureIdToIndex,
2655 dispatchedGestureIdBits, id, 0, 0,
2656 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002657
2658 dispatchedGestureIdBits.clearBit(id);
2659 }
2660 }
2661 }
2662
2663 // Send motion events for all pointers that moved.
2664 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002665 out.push_back(
2666 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2667 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2668 mPointerGesture.currentGestureProperties,
2669 mPointerGesture.currentGestureCoords,
2670 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2671 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002672 }
2673
2674 // Send motion events for all pointers that went down.
2675 if (down) {
2676 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2677 ~dispatchedGestureIdBits.value);
2678 while (!downGestureIdBits.isEmpty()) {
2679 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2680 dispatchedGestureIdBits.markBit(id);
2681
2682 if (dispatchedGestureIdBits.count() == 1) {
2683 mPointerGesture.downTime = when;
2684 }
2685
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002686 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2687 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2688 buttonState, 0, mPointerGesture.currentGestureProperties,
2689 mPointerGesture.currentGestureCoords,
2690 mPointerGesture.currentGestureIdToIndex,
2691 dispatchedGestureIdBits, id, 0, 0,
2692 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002693 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2694 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2695 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2696 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2697 readTime);
2698 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002699 }
2700 }
2701
2702 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002703 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002704 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2705 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2706 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2707 mPointerGesture.currentGestureProperties,
2708 mPointerGesture.currentGestureCoords,
2709 mPointerGesture.currentGestureIdToIndex,
2710 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2711 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002712 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2713 // Synthesize a hover move event after all pointers go up to indicate that
2714 // the pointer is hovering again even if the user is not currently touching
2715 // the touch pad. This ensures that a view will receive a fresh hover enter
2716 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002717 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002718
2719 PointerProperties pointerProperties;
2720 pointerProperties.clear();
2721 pointerProperties.id = 0;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002722 pointerProperties.toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002723
2724 PointerCoords pointerCoords;
2725 pointerCoords.clear();
2726 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2727 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2728
2729 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002730 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2731 mSource, displayId, policyFlags,
2732 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2733 buttonState, MotionClassification::NONE,
2734 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2735 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2736 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002737 }
2738
2739 // Update state.
2740 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2741 if (!down) {
2742 mPointerGesture.lastGestureIdBits.clear();
2743 } else {
2744 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2745 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2746 uint32_t id = idBits.clearFirstMarkedBit();
2747 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2748 mPointerGesture.lastGestureProperties[index].copyFrom(
2749 mPointerGesture.currentGestureProperties[index]);
2750 mPointerGesture.lastGestureCoords[index].copyFrom(
2751 mPointerGesture.currentGestureCoords[index]);
2752 mPointerGesture.lastGestureIdToIndex[id] = index;
2753 }
2754 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002755 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002756}
2757
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002758std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2759 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002760 const MotionClassification classification =
2761 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2762 ? MotionClassification::TWO_FINGER_SWIPE
2763 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002764 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002765 // Cancel previously dispatches pointers.
2766 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2767 int32_t metaState = getContext()->getGlobalMetaState();
2768 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002769 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002770 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2771 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002772 mPointerGesture.lastGestureProperties,
2773 mPointerGesture.lastGestureCoords,
2774 mPointerGesture.lastGestureIdToIndex,
2775 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2776 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002777 }
2778
2779 // Reset the current pointer gesture.
2780 mPointerGesture.reset();
2781 mPointerVelocityControl.reset();
2782
2783 // Remove any current spots.
2784 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002785 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002786 mPointerController->clearSpots();
2787 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002788 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002789}
2790
2791bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2792 bool* outFinishPreviousGesture, bool isTimeout) {
2793 *outCancelPreviousGesture = false;
2794 *outFinishPreviousGesture = false;
2795
2796 // Handle TAP timeout.
2797 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002798 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002799
Michael Wright227c5542020-07-02 18:30:52 +01002800 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002801 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2802 // The tap/drag timeout has not yet expired.
2803 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2804 mConfig.pointerGestureTapDragInterval);
2805 } else {
2806 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002807 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002808 *outFinishPreviousGesture = true;
2809
2810 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002811 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002812 mPointerGesture.currentGestureIdBits.clear();
2813
2814 mPointerVelocityControl.reset();
2815 return true;
2816 }
2817 }
2818
2819 // We did not handle this timeout.
2820 return false;
2821 }
2822
2823 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2824 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2825
2826 // Update the velocity tracker.
2827 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002828 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002829 uint32_t id = idBits.clearFirstMarkedBit();
2830 const RawPointerData::Pointer& pointer =
2831 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002832 const float x = pointer.x * mPointerXMovementScale;
2833 const float y = pointer.y * mPointerYMovementScale;
2834 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2835 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002836 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002837 }
2838
2839 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2840 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002841 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2842 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2843 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002844 mPointerGesture.resetTap();
2845 }
2846
2847 // Pick a new active touch id if needed.
2848 // Choose an arbitrary pointer that just went down, if there is one.
2849 // Otherwise choose an arbitrary remaining pointer.
2850 // This guarantees we always have an active touch id when there is at least one pointer.
2851 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002852 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002853 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002854 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002855 mPointerGesture.firstTouchTime = when;
2856 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002857 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2858 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2859 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2860 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002861 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002862 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002863
2864 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002865 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002866 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002867 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2868 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2869 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002870 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002871 *outFinishPreviousGesture = true;
2872 }
2873
2874 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002875 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002876 mPointerGesture.currentGestureIdBits.clear();
2877
2878 mPointerVelocityControl.reset();
2879 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2880 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2881 // The pointer follows the active touch point.
2882 // Emit DOWN, MOVE, UP events at the pointer location.
2883 //
2884 // Only the active touch matters; other fingers are ignored. This policy helps
2885 // to handle the case where the user places a second finger on the touch pad
2886 // to apply the necessary force to depress an integrated button below the surface.
2887 // We don't want the second finger to be delivered to applications.
2888 //
2889 // For this to work well, we need to make sure to track the pointer that is really
2890 // active. If the user first puts one finger down to click then adds another
2891 // finger to drag then the active pointer should switch to the finger that is
2892 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002893 ALOGD_IF(DEBUG_GESTURES,
2894 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2895 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002896 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002897 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002898 *outFinishPreviousGesture = true;
2899 mPointerGesture.activeGestureId = 0;
2900 }
2901
2902 // Switch pointers if needed.
2903 // Find the fastest pointer and follow it.
2904 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002905 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002906 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002907 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002908 ALOGD_IF(DEBUG_GESTURES,
2909 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2910 "bestSpeed=%0.3f",
2911 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002912 }
2913 }
2914
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002915 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002916 // When using spots, the click will occur at the position of the anchor
2917 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002918 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 } else {
2920 mPointerVelocityControl.reset();
2921 }
2922
Prabir Pradhan2719e822023-02-28 17:39:36 +00002923 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002924
Michael Wright227c5542020-07-02 18:30:52 +01002925 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002926 mPointerGesture.currentGestureIdBits.clear();
2927 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2928 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2929 mPointerGesture.currentGestureProperties[0].clear();
2930 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002931 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002932 mPointerGesture.currentGestureCoords[0].clear();
2933 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2934 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2935 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2936 } else if (currentFingerCount == 0) {
2937 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002938 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002939 *outFinishPreviousGesture = true;
2940 }
2941
2942 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2943 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2944 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002945 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2946 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002947 lastFingerCount == 1) {
2948 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002949 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002950 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2951 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002952 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002953
2954 mPointerGesture.tapUpTime = when;
2955 getContext()->requestTimeoutAtTime(when +
2956 mConfig.pointerGestureTapDragInterval);
2957
2958 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002959 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002960 mPointerGesture.currentGestureIdBits.clear();
2961 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2962 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2963 mPointerGesture.currentGestureProperties[0].clear();
2964 mPointerGesture.currentGestureProperties[0].id =
2965 mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07002966 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002967 mPointerGesture.currentGestureCoords[0].clear();
2968 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2969 mPointerGesture.tapX);
2970 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2971 mPointerGesture.tapY);
2972 mPointerGesture.currentGestureCoords[0]
2973 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2974
2975 tapped = true;
2976 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002977 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2978 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002979 }
2980 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002981 if (DEBUG_GESTURES) {
2982 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2983 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2984 (when - mPointerGesture.tapDownTime) * 0.000001f);
2985 } else {
2986 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2987 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002988 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002989 }
2990 }
2991
2992 mPointerVelocityControl.reset();
2993
2994 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002995 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002996 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002997 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002998 mPointerGesture.currentGestureIdBits.clear();
2999 }
3000 } else if (currentFingerCount == 1) {
3001 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
3002 // The pointer follows the active touch point.
3003 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3004 // When in TAP_DRAG, emit MOVE events at the pointer location.
3005 ALOG_ASSERT(activeTouchId >= 0);
3006
Michael Wright227c5542020-07-02 18:30:52 +01003007 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3008 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003009 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003010 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003011 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3012 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003013 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003014 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003015 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3016 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003017 }
3018 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003019 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3020 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003021 }
Michael Wright227c5542020-07-02 18:30:52 +01003022 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3023 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003024 }
3025
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003026 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003027 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003028 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003029 } else {
3030 mPointerVelocityControl.reset();
3031 }
3032
3033 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003034 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003035 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003036 down = true;
3037 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003038 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003039 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003040 *outFinishPreviousGesture = true;
3041 }
3042 mPointerGesture.activeGestureId = 0;
3043 down = false;
3044 }
3045
Prabir Pradhan2719e822023-02-28 17:39:36 +00003046 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003047
3048 mPointerGesture.currentGestureIdBits.clear();
3049 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3050 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3051 mPointerGesture.currentGestureProperties[0].clear();
3052 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003053 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003054 mPointerGesture.currentGestureCoords[0].clear();
3055 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3056 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3057 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3058 down ? 1.0f : 0.0f);
3059
3060 if (lastFingerCount == 0 && currentFingerCount != 0) {
3061 mPointerGesture.resetTap();
3062 mPointerGesture.tapDownTime = when;
3063 mPointerGesture.tapX = x;
3064 mPointerGesture.tapY = y;
3065 }
3066 } else {
3067 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003068 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003069 }
3070
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003071 if (DEBUG_GESTURES) {
3072 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3073 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3074 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3075 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3076 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3077 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3078 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3079 uint32_t id = idBits.clearFirstMarkedBit();
3080 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3081 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3082 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003083 ALOGD(" currentGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003084 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003085 id, index, ftl::enum_string(properties.toolType).c_str(),
3086 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003087 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3088 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3089 }
3090 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3091 uint32_t id = idBits.clearFirstMarkedBit();
3092 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3093 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3094 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003095 ALOGD(" lastGesture[%d]: index=%d, toolType=%s, "
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003096 "x=%0.3f, y=%0.3f, pressure=%0.3f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003097 id, index, ftl::enum_string(properties.toolType).c_str(),
3098 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003099 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3100 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3101 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003102 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003103 return true;
3104}
3105
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003106bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3107 if (mPointerGesture.activeTouchId < 0) {
3108 mPointerGesture.resetQuietTime();
3109 return false;
3110 }
3111
3112 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3113 return true;
3114 }
3115
3116 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3117 bool isQuietTime = false;
3118 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3119 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3120 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3121 currentFingerCount < 2) {
3122 // Enter quiet time when exiting swipe or freeform state.
3123 // This is to prevent accidentally entering the hover state and flinging the
3124 // pointer when finishing a swipe and there is still one pointer left onscreen.
3125 isQuietTime = true;
3126 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3127 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3128 // Enter quiet time when releasing the button and there are still two or more
3129 // fingers down. This may indicate that one finger was used to press the button
3130 // but it has not gone up yet.
3131 isQuietTime = true;
3132 }
3133 if (isQuietTime) {
3134 mPointerGesture.quietTime = when;
3135 }
3136 return isQuietTime;
3137}
3138
3139std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3140 int32_t bestId = -1;
3141 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3142 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3143 uint32_t id = idBits.clearFirstMarkedBit();
3144 std::optional<float> vx =
3145 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3146 std::optional<float> vy =
3147 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3148 if (vx && vy) {
3149 float speed = hypotf(*vx, *vy);
3150 if (speed > bestSpeed) {
3151 bestId = id;
3152 bestSpeed = speed;
3153 }
3154 }
3155 }
3156 return std::make_pair(bestId, bestSpeed);
3157}
3158
3159void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3160 bool* finishPreviousGesture) {
3161 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3162 // to move before deciding what to do.
3163 //
3164 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3165 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3166 // just a press or long-press at the pointer location.
3167 //
3168 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3169 // pointer location.
3170 //
3171 // When the two fingers move enough or when additional fingers are added, we make a decision to
3172 // transition into SWIPE or FREEFORM mode accordingly.
3173 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3174 ALOG_ASSERT(activeTouchId >= 0);
3175
3176 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3177 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3178 bool settled =
3179 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3180 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3181 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3182 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3183 *finishPreviousGesture = true;
3184 } else if (!settled && currentFingerCount > lastFingerCount) {
3185 // Additional pointers have gone down but not yet settled.
3186 // Reset the gesture.
3187 ALOGD_IF(DEBUG_GESTURES,
3188 "Gestures: Resetting gesture since additional pointers went down for "
3189 "MULTITOUCH, settle time remaining %0.3fms",
3190 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3191 when) * 0.000001f);
3192 *cancelPreviousGesture = true;
3193 } else {
3194 // Continue previous gesture.
3195 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3196 }
3197
3198 if (*finishPreviousGesture || *cancelPreviousGesture) {
3199 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3200 mPointerGesture.activeGestureId = 0;
3201 mPointerGesture.referenceIdBits.clear();
3202 mPointerVelocityControl.reset();
3203
3204 // Use the centroid and pointer location as the reference points for the gesture.
3205 ALOGD_IF(DEBUG_GESTURES,
3206 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3207 "%0.3fms",
3208 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3209 when) * 0.000001f);
3210 mCurrentRawState.rawPointerData
3211 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3212 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003213 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3214 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003215 }
3216
3217 // Clear the reference deltas for fingers not yet included in the reference calculation.
3218 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3219 ~mPointerGesture.referenceIdBits.value);
3220 !idBits.isEmpty();) {
3221 uint32_t id = idBits.clearFirstMarkedBit();
3222 mPointerGesture.referenceDeltas[id].dx = 0;
3223 mPointerGesture.referenceDeltas[id].dy = 0;
3224 }
3225 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3226
3227 // Add delta for all fingers and calculate a common movement delta.
3228 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3229 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3230 mCurrentCookedState.fingerIdBits.value);
3231 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3232 bool first = (idBits == commonIdBits);
3233 uint32_t id = idBits.clearFirstMarkedBit();
3234 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3235 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3236 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3237 delta.dx += cpd.x - lpd.x;
3238 delta.dy += cpd.y - lpd.y;
3239
3240 if (first) {
3241 commonDeltaRawX = delta.dx;
3242 commonDeltaRawY = delta.dy;
3243 } else {
3244 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3245 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3246 }
3247 }
3248
3249 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3250 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3251 float dist[MAX_POINTER_ID + 1];
3252 int32_t distOverThreshold = 0;
3253 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3254 uint32_t id = idBits.clearFirstMarkedBit();
3255 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3256 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3257 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3258 distOverThreshold += 1;
3259 }
3260 }
3261
3262 // Only transition when at least two pointers have moved further than
3263 // the minimum distance threshold.
3264 if (distOverThreshold >= 2) {
3265 if (currentFingerCount > 2) {
3266 // There are more than two pointers, switch to FREEFORM.
3267 ALOGD_IF(DEBUG_GESTURES,
3268 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3269 currentFingerCount);
3270 *cancelPreviousGesture = true;
3271 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3272 } else {
3273 // There are exactly two pointers.
3274 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3275 uint32_t id1 = idBits.clearFirstMarkedBit();
3276 uint32_t id2 = idBits.firstMarkedBit();
3277 const RawPointerData::Pointer& p1 =
3278 mCurrentRawState.rawPointerData.pointerForId(id1);
3279 const RawPointerData::Pointer& p2 =
3280 mCurrentRawState.rawPointerData.pointerForId(id2);
3281 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3282 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3283 // There are two pointers but they are too far apart for a SWIPE,
3284 // switch to FREEFORM.
3285 ALOGD_IF(DEBUG_GESTURES,
3286 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3287 mutualDistance, mPointerGestureMaxSwipeWidth);
3288 *cancelPreviousGesture = true;
3289 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3290 } else {
3291 // There are two pointers. Wait for both pointers to start moving
3292 // before deciding whether this is a SWIPE or FREEFORM gesture.
3293 float dist1 = dist[id1];
3294 float dist2 = dist[id2];
3295 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3296 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3297 // Calculate the dot product of the displacement vectors.
3298 // When the vectors are oriented in approximately the same direction,
3299 // the angle betweeen them is near zero and the cosine of the angle
3300 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3301 // mag(v2).
3302 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3303 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3304 float dx1 = delta1.dx * mPointerXZoomScale;
3305 float dy1 = delta1.dy * mPointerYZoomScale;
3306 float dx2 = delta2.dx * mPointerXZoomScale;
3307 float dy2 = delta2.dy * mPointerYZoomScale;
3308 float dot = dx1 * dx2 + dy1 * dy2;
3309 float cosine = dot / (dist1 * dist2); // denominator always > 0
3310 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3311 // Pointers are moving in the same direction. Switch to SWIPE.
3312 ALOGD_IF(DEBUG_GESTURES,
3313 "Gestures: PRESS transitioned to SWIPE, "
3314 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3315 "cosine %0.3f >= %0.3f",
3316 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3317 mConfig.pointerGestureMultitouchMinDistance, cosine,
3318 mConfig.pointerGestureSwipeTransitionAngleCosine);
3319 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3320 } else {
3321 // Pointers are moving in different directions. Switch to FREEFORM.
3322 ALOGD_IF(DEBUG_GESTURES,
3323 "Gestures: PRESS transitioned to FREEFORM, "
3324 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3325 "cosine %0.3f < %0.3f",
3326 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3327 mConfig.pointerGestureMultitouchMinDistance, cosine,
3328 mConfig.pointerGestureSwipeTransitionAngleCosine);
3329 *cancelPreviousGesture = true;
3330 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3331 }
3332 }
3333 }
3334 }
3335 }
3336 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3337 // Switch from SWIPE to FREEFORM if additional pointers go down.
3338 // Cancel previous gesture.
3339 if (currentFingerCount > 2) {
3340 ALOGD_IF(DEBUG_GESTURES,
3341 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3342 currentFingerCount);
3343 *cancelPreviousGesture = true;
3344 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3345 }
3346 }
3347
3348 // Move the reference points based on the overall group motion of the fingers
3349 // except in PRESS mode while waiting for a transition to occur.
3350 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3351 (commonDeltaRawX || commonDeltaRawY)) {
3352 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3353 uint32_t id = idBits.clearFirstMarkedBit();
3354 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3355 delta.dx = 0;
3356 delta.dy = 0;
3357 }
3358
3359 mPointerGesture.referenceTouchX += commonDeltaRawX;
3360 mPointerGesture.referenceTouchY += commonDeltaRawY;
3361
3362 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3363 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3364
3365 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3366 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3367
3368 mPointerGesture.referenceGestureX += commonDeltaX;
3369 mPointerGesture.referenceGestureY += commonDeltaY;
3370 }
3371
3372 // Report gestures.
3373 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3374 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3375 // PRESS or SWIPE mode.
3376 ALOGD_IF(DEBUG_GESTURES,
3377 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3378 "currentTouchPointerCount=%d",
3379 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3380 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3381
3382 mPointerGesture.currentGestureIdBits.clear();
3383 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3384 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3385 mPointerGesture.currentGestureProperties[0].clear();
3386 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003387 mPointerGesture.currentGestureProperties[0].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003388 mPointerGesture.currentGestureCoords[0].clear();
3389 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3390 mPointerGesture.referenceGestureX);
3391 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3392 mPointerGesture.referenceGestureY);
3393 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3394 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3395 float xOffset = static_cast<float>(commonDeltaRawX) /
3396 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3397 float yOffset = static_cast<float>(commonDeltaRawY) /
3398 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3399 mPointerGesture.currentGestureCoords[0]
3400 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3401 mPointerGesture.currentGestureCoords[0]
3402 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3403 }
3404 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3405 // FREEFORM mode.
3406 ALOGD_IF(DEBUG_GESTURES,
3407 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3408 "currentTouchPointerCount=%d",
3409 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3410 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3411
3412 mPointerGesture.currentGestureIdBits.clear();
3413
3414 BitSet32 mappedTouchIdBits;
3415 BitSet32 usedGestureIdBits;
3416 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3417 // Initially, assign the active gesture id to the active touch point
3418 // if there is one. No other touch id bits are mapped yet.
3419 if (!*cancelPreviousGesture) {
3420 mappedTouchIdBits.markBit(activeTouchId);
3421 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3422 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3423 mPointerGesture.activeGestureId;
3424 } else {
3425 mPointerGesture.activeGestureId = -1;
3426 }
3427 } else {
3428 // Otherwise, assume we mapped all touches from the previous frame.
3429 // Reuse all mappings that are still applicable.
3430 mappedTouchIdBits.value =
3431 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3432 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3433
3434 // Check whether we need to choose a new active gesture id because the
3435 // current went went up.
3436 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3437 ~mCurrentCookedState.fingerIdBits.value);
3438 !upTouchIdBits.isEmpty();) {
3439 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3440 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3441 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3442 mPointerGesture.activeGestureId = -1;
3443 break;
3444 }
3445 }
3446 }
3447
3448 ALOGD_IF(DEBUG_GESTURES,
3449 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3450 "activeGestureId=%d",
3451 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3452
3453 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3454 for (uint32_t i = 0; i < currentFingerCount; i++) {
3455 uint32_t touchId = idBits.clearFirstMarkedBit();
3456 uint32_t gestureId;
3457 if (!mappedTouchIdBits.hasBit(touchId)) {
3458 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3459 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3460 ALOGD_IF(DEBUG_GESTURES,
3461 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3462 gestureId);
3463 } else {
3464 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3465 ALOGD_IF(DEBUG_GESTURES,
3466 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3467 touchId, gestureId);
3468 }
3469 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3470 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3471
3472 const RawPointerData::Pointer& pointer =
3473 mCurrentRawState.rawPointerData.pointerForId(touchId);
3474 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3475 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3476 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3477
3478 mPointerGesture.currentGestureProperties[i].clear();
3479 mPointerGesture.currentGestureProperties[i].id = gestureId;
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07003480 mPointerGesture.currentGestureProperties[i].toolType = ToolType::FINGER;
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003481 mPointerGesture.currentGestureCoords[i].clear();
3482 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3483 mPointerGesture.referenceGestureX +
3484 deltaX);
3485 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3486 mPointerGesture.referenceGestureY +
3487 deltaY);
3488 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3489 }
3490
3491 if (mPointerGesture.activeGestureId < 0) {
3492 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3493 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3494 mPointerGesture.activeGestureId);
3495 }
3496 }
3497}
3498
Harry Cutts714d1ad2022-08-24 16:36:43 +00003499void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3500 const RawPointerData::Pointer& currentPointer =
3501 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3502 const RawPointerData::Pointer& lastPointer =
3503 mLastRawState.rawPointerData.pointerForId(pointerId);
3504 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3505 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3506
3507 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3508 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3509
3510 mPointerController->move(deltaX, deltaY);
3511}
3512
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003513std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3514 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515 mPointerSimple.currentCoords.clear();
3516 mPointerSimple.currentProperties.clear();
3517
3518 bool down, hovering;
3519 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3520 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3521 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003522 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3523 down = !hovering;
3524
Prabir Pradhane71e5702023-03-29 14:51:38 +00003525 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3526 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3527 // Styluses are configured specifically for one display. We only update the
3528 // PointerController for this stylus if the PointerController is configured for
3529 // the same display as this stylus,
3530 if (getAssociatedDisplayId() == mViewport.displayId) {
3531 mPointerController->setPosition(x, y);
3532 std::tie(x, y) = mPointerController->getPosition();
3533 }
3534
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003535 mPointerSimple.currentCoords.copyFrom(
3536 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3537 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3538 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3539 mPointerSimple.currentProperties.id = 0;
3540 mPointerSimple.currentProperties.toolType =
3541 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3542 } else {
3543 down = false;
3544 hovering = false;
3545 }
3546
Prabir Pradhane71e5702023-03-29 14:51:38 +00003547 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003548}
3549
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003550std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3551 uint32_t policyFlags) {
3552 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003553}
3554
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003555std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3556 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003557 mPointerSimple.currentCoords.clear();
3558 mPointerSimple.currentProperties.clear();
3559
3560 bool down, hovering;
3561 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3562 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003563 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003564 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003565 } else {
3566 mPointerVelocityControl.reset();
3567 }
3568
3569 down = isPointerDown(mCurrentRawState.buttonState);
3570 hovering = !down;
3571
Prabir Pradhan2719e822023-02-28 17:39:36 +00003572 const auto [x, y] = mPointerController->getPosition();
3573 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003574 mPointerSimple.currentCoords.copyFrom(
3575 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3576 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3577 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3578 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3579 hovering ? 0.0f : 1.0f);
3580 mPointerSimple.currentProperties.id = 0;
3581 mPointerSimple.currentProperties.toolType =
3582 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3583 } else {
3584 mPointerVelocityControl.reset();
3585
3586 down = false;
3587 hovering = false;
3588 }
3589
Prabir Pradhane71e5702023-03-29 14:51:38 +00003590 const int32_t displayId = mPointerController->getDisplayId();
3591 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering, displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003592}
3593
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003594std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3595 uint32_t policyFlags) {
3596 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003597
3598 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003599
3600 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003601}
3602
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003603std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3604 uint32_t policyFlags, bool down,
Prabir Pradhane71e5702023-03-29 14:51:38 +00003605 bool hovering, int32_t displayId) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003606 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3607 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003608 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003609 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003610 auto cursorPosition = mPointerSimple.currentCoords.getXYValue();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003611
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003612 if (displayId == mPointerController->getDisplayId()) {
3613 std::tie(cursorPosition.x, cursorPosition.y) = mPointerController->getPosition();
3614 if (down || hovering) {
3615 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
3616 mPointerController->clearSpots();
3617 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3618 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
3619 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3620 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003621 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003622
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003623 if (mPointerSimple.down && !down) {
3624 mPointerSimple.down = false;
3625
3626 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003627 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3628 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3629 0, metaState, mLastRawState.buttonState,
3630 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3631 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003632 mOrientedXPrecision, mOrientedYPrecision,
3633 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3634 mPointerSimple.downTime,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003635 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003636 }
3637
3638 if (mPointerSimple.hovering && !hovering) {
3639 mPointerSimple.hovering = false;
3640
3641 // Send hover exit.
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003642 out.push_back(
3643 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3644 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3645 metaState, mLastRawState.buttonState, MotionClassification::NONE,
3646 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3647 &mPointerSimple.lastCoords, mOrientedXPrecision,
3648 mOrientedYPrecision, mPointerSimple.lastCursorX,
3649 mPointerSimple.lastCursorY, mPointerSimple.downTime,
3650 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003651 }
3652
3653 if (down) {
3654 if (!mPointerSimple.down) {
3655 mPointerSimple.down = true;
3656 mPointerSimple.downTime = when;
3657
3658 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003659 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3660 mSource, displayId, policyFlags,
3661 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3662 mCurrentRawState.buttonState, MotionClassification::NONE,
3663 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3664 &mPointerSimple.currentProperties,
3665 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003666 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003667 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003668 }
3669
3670 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003671 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3672 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3673 0, 0, metaState, mCurrentRawState.buttonState,
3674 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3675 &mPointerSimple.currentProperties,
3676 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003677 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003678 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003679 }
3680
3681 if (hovering) {
3682 if (!mPointerSimple.hovering) {
3683 mPointerSimple.hovering = true;
3684
3685 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003686 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3687 mSource, displayId, policyFlags,
3688 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3689 mCurrentRawState.buttonState, MotionClassification::NONE,
3690 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3691 &mPointerSimple.currentProperties,
3692 &mPointerSimple.currentCoords, mOrientedXPrecision,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003693 mOrientedYPrecision, cursorPosition.x, cursorPosition.y,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003694 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003695 }
3696
3697 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003698 out.push_back(
3699 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3700 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3701 metaState, mCurrentRawState.buttonState,
3702 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3703 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003704 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3705 cursorPosition.y, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003706 }
3707
3708 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3709 float vscroll = mCurrentRawState.rawVScroll;
3710 float hscroll = mCurrentRawState.rawHScroll;
3711 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3712 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3713
3714 // Send scroll.
3715 PointerCoords pointerCoords;
3716 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3717 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3718 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3719
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003720 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3721 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3722 0, 0, metaState, mCurrentRawState.buttonState,
3723 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3724 &mPointerSimple.currentProperties, &pointerCoords,
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003725 mOrientedXPrecision, mOrientedYPrecision, cursorPosition.x,
3726 cursorPosition.y, mPointerSimple.downTime,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003727 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003728 }
3729
3730 // Save state.
3731 if (down || hovering) {
3732 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3733 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003734 mPointerSimple.displayId = displayId;
3735 mPointerSimple.source = mSource;
Prabir Pradhan4ffa4d52023-04-12 19:38:34 +00003736 mPointerSimple.lastCursorX = cursorPosition.x;
3737 mPointerSimple.lastCursorY = cursorPosition.y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003738 } else {
3739 mPointerSimple.reset();
3740 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003741 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003742}
3743
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003744std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3745 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003746 std::list<NotifyArgs> out;
3747 if (mPointerSimple.down || mPointerSimple.hovering) {
3748 int32_t metaState = getContext()->getGlobalMetaState();
3749 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3750 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3751 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3752 metaState, mLastRawState.buttonState,
3753 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3754 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3755 mOrientedXPrecision, mOrientedYPrecision,
3756 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3757 mPointerSimple.downTime,
3758 /* videoFrames */ {}));
3759 if (mPointerController != nullptr) {
3760 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3761 }
3762 }
3763 mPointerSimple.reset();
3764 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003765}
3766
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003767static bool isStylusEvent(uint32_t source, int32_t action, const PointerProperties* properties) {
3768 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
3769 return false;
3770 }
3771 const auto actionIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3772 return isStylusToolType(properties[actionIndex].toolType);
3773}
3774
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003775NotifyMotionArgs TouchInputMapper::dispatchMotion(
3776 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3777 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003778 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3779 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003780 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003781 PointerCoords pointerCoords[MAX_POINTERS];
3782 PointerProperties pointerProperties[MAX_POINTERS];
3783 uint32_t pointerCount = 0;
3784 while (!idBits.isEmpty()) {
3785 uint32_t id = idBits.clearFirstMarkedBit();
3786 uint32_t index = idToIndex[id];
3787 pointerProperties[pointerCount].copyFrom(properties[index]);
3788 pointerCoords[pointerCount].copyFrom(coords[index]);
3789
3790 if (changedId >= 0 && id == uint32_t(changedId)) {
3791 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3792 }
3793
3794 pointerCount += 1;
3795 }
3796
3797 ALOG_ASSERT(pointerCount != 0);
3798
3799 if (changedId >= 0 && pointerCount == 1) {
3800 // Replace initial down and final up action.
3801 // We can compare the action without masking off the changed pointer index
3802 // because we know the index is 0.
3803 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3804 action = AMOTION_EVENT_ACTION_DOWN;
3805 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003806 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3807 action = AMOTION_EVENT_ACTION_CANCEL;
3808 } else {
3809 action = AMOTION_EVENT_ACTION_UP;
3810 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003811 } else {
3812 // Can't happen.
3813 ALOG_ASSERT(false);
3814 }
3815 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003816
3817 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3818 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
3819 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, action, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003820 mPointerController && displayId != ADISPLAY_ID_NONE &&
3821 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003822 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003823 switch (action & AMOTION_EVENT_ACTION_MASK) {
3824 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3825 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3826 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003827 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003828 mPointerController
3829 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3830 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3831 .getY());
3832 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3833 break;
3834 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3835 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3836 break;
3837 }
3838 }
3839
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003840 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3841 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003842 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003843 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003844 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003845 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003846 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003847 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003848 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003849 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3850 policyFlags, action, actionButton, flags, metaState, buttonState,
3851 classification, edgeFlags, pointerCount, pointerProperties,
3852 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3853 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003854}
3855
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003856std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3857 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003858 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3859 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003860 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003861}
3862
Prabir Pradhan1728b212021-10-19 16:00:03 -07003863bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003864 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003865 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003866 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003867}
3868
3869const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3870 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003871 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3872 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3873 "left=%d, top=%d, right=%d, bottom=%d",
3874 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3875 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003876
3877 if (virtualKey.isHit(x, y)) {
3878 return &virtualKey;
3879 }
3880 }
3881
3882 return nullptr;
3883}
3884
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003885void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3886 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3887 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003888
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003889 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003890
3891 if (currentPointerCount == 0) {
3892 // No pointers to assign.
3893 return;
3894 }
3895
3896 if (lastPointerCount == 0) {
3897 // All pointers are new.
3898 for (uint32_t i = 0; i < currentPointerCount; i++) {
3899 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003900 current.rawPointerData.pointers[i].id = id;
3901 current.rawPointerData.idToIndex[id] = i;
3902 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003903 }
3904 return;
3905 }
3906
3907 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003908 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003909 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003910 uint32_t id = last.rawPointerData.pointers[0].id;
3911 current.rawPointerData.pointers[0].id = id;
3912 current.rawPointerData.idToIndex[id] = 0;
3913 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003914 return;
3915 }
3916
3917 // General case.
3918 // We build a heap of squared euclidean distances between current and last pointers
3919 // associated with the current and last pointer indices. Then, we find the best
3920 // match (by distance) for each current pointer.
3921 // The pointers must have the same tool type but it is possible for them to
3922 // transition from hovering to touching or vice-versa while retaining the same id.
3923 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3924
3925 uint32_t heapSize = 0;
3926 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3927 currentPointerIndex++) {
3928 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3929 lastPointerIndex++) {
3930 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003931 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003932 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003933 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003934 if (currentPointer.toolType == lastPointer.toolType) {
3935 int64_t deltaX = currentPointer.x - lastPointer.x;
3936 int64_t deltaY = currentPointer.y - lastPointer.y;
3937
3938 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3939
3940 // Insert new element into the heap (sift up).
3941 heap[heapSize].currentPointerIndex = currentPointerIndex;
3942 heap[heapSize].lastPointerIndex = lastPointerIndex;
3943 heap[heapSize].distance = distance;
3944 heapSize += 1;
3945 }
3946 }
3947 }
3948
3949 // Heapify
3950 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3951 startIndex -= 1;
3952 for (uint32_t parentIndex = startIndex;;) {
3953 uint32_t childIndex = parentIndex * 2 + 1;
3954 if (childIndex >= heapSize) {
3955 break;
3956 }
3957
3958 if (childIndex + 1 < heapSize &&
3959 heap[childIndex + 1].distance < heap[childIndex].distance) {
3960 childIndex += 1;
3961 }
3962
3963 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3964 break;
3965 }
3966
3967 swap(heap[parentIndex], heap[childIndex]);
3968 parentIndex = childIndex;
3969 }
3970 }
3971
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003972 if (DEBUG_POINTER_ASSIGNMENT) {
3973 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3974 for (size_t i = 0; i < heapSize; i++) {
3975 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3976 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3977 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003978 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003979
3980 // Pull matches out by increasing order of distance.
3981 // To avoid reassigning pointers that have already been matched, the loop keeps track
3982 // of which last and current pointers have been matched using the matchedXXXBits variables.
3983 // It also tracks the used pointer id bits.
3984 BitSet32 matchedLastBits(0);
3985 BitSet32 matchedCurrentBits(0);
3986 BitSet32 usedIdBits(0);
3987 bool first = true;
3988 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3989 while (heapSize > 0) {
3990 if (first) {
3991 // The first time through the loop, we just consume the root element of
3992 // the heap (the one with smallest distance).
3993 first = false;
3994 } else {
3995 // Previous iterations consumed the root element of the heap.
3996 // Pop root element off of the heap (sift down).
3997 heap[0] = heap[heapSize];
3998 for (uint32_t parentIndex = 0;;) {
3999 uint32_t childIndex = parentIndex * 2 + 1;
4000 if (childIndex >= heapSize) {
4001 break;
4002 }
4003
4004 if (childIndex + 1 < heapSize &&
4005 heap[childIndex + 1].distance < heap[childIndex].distance) {
4006 childIndex += 1;
4007 }
4008
4009 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4010 break;
4011 }
4012
4013 swap(heap[parentIndex], heap[childIndex]);
4014 parentIndex = childIndex;
4015 }
4016
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08004017 if (DEBUG_POINTER_ASSIGNMENT) {
4018 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
4019 for (size_t j = 0; j < heapSize; j++) {
4020 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4021 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4022 heap[j].distance);
4023 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004024 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004025 }
4026
4027 heapSize -= 1;
4028
4029 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4030 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4031
4032 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4033 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4034
4035 matchedCurrentBits.markBit(currentPointerIndex);
4036 matchedLastBits.markBit(lastPointerIndex);
4037
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004038 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4039 current.rawPointerData.pointers[currentPointerIndex].id = id;
4040 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4041 current.rawPointerData.markIdBit(id,
4042 current.rawPointerData.isHovering(
4043 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004044 usedIdBits.markBit(id);
4045
Harry Cutts45483602022-08-24 14:36:48 +00004046 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4047 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4048 ", distance=%" PRIu64,
4049 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004050 break;
4051 }
4052 }
4053
4054 // Assign fresh ids to pointers that were not matched in the process.
4055 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4056 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4057 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4058
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004059 current.rawPointerData.pointers[currentPointerIndex].id = id;
4060 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4061 current.rawPointerData.markIdBit(id,
4062 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004063
Harry Cutts45483602022-08-24 14:36:48 +00004064 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4065 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4066 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004067 }
4068}
4069
4070int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4071 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4072 return AKEY_STATE_VIRTUAL;
4073 }
4074
4075 for (const VirtualKey& virtualKey : mVirtualKeys) {
4076 if (virtualKey.keyCode == keyCode) {
4077 return AKEY_STATE_UP;
4078 }
4079 }
4080
4081 return AKEY_STATE_UNKNOWN;
4082}
4083
4084int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4085 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4086 return AKEY_STATE_VIRTUAL;
4087 }
4088
4089 for (const VirtualKey& virtualKey : mVirtualKeys) {
4090 if (virtualKey.scanCode == scanCode) {
4091 return AKEY_STATE_UP;
4092 }
4093 }
4094
4095 return AKEY_STATE_UNKNOWN;
4096}
4097
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004098bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4099 const std::vector<int32_t>& keyCodes,
4100 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004101 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004102 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004103 if (virtualKey.keyCode == keyCodes[i]) {
4104 outFlags[i] = 1;
4105 }
4106 }
4107 }
4108
4109 return true;
4110}
4111
4112std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4113 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004114 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004115 return std::make_optional(mPointerController->getDisplayId());
4116 } else {
4117 return std::make_optional(mViewport.displayId);
4118 }
4119 }
4120 return std::nullopt;
4121}
4122
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004123} // namespace android