blob: cbdb1d02f72bdd4bd2442a8c99f7edb8b89609bd [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 Wrightaff169e2020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wrightaff169e2020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
23#include "CursorButtonAccumulator.h"
24#include "CursorScrollAccumulator.h"
25#include "TouchButtonAccumulator.h"
26#include "TouchCursorInputMapperCommon.h"
27
28namespace android {
29
30// --- Constants ---
31
32// Maximum amount of latency to add to touch events while waiting for data from an
33// external stylus.
34static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
35
36// Maximum amount of time to wait on touch data before pushing out new pressure data.
37static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
38
39// Artificial latency on synthetic events created from stylus data without corresponding touch
40// data.
41static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
42
43// --- Static Definitions ---
44
45template <typename T>
46inline static void swap(T& a, T& b) {
47 T temp = a;
48 a = b;
49 b = temp;
50}
51
52static float calculateCommonVector(float a, float b) {
53 if (a > 0 && b > 0) {
54 return a < b ? a : b;
55 } else if (a < 0 && b < 0) {
56 return a > b ? a : b;
57 } else {
58 return 0;
59 }
60}
61
62inline static float distance(float x1, float y1, float x2, float y2) {
63 return hypotf(x1 - x2, y1 - y2);
64}
65
66inline static int32_t signExtendNybble(int32_t value) {
67 return value >= 8 ? value - 16 : value;
68}
69
70// --- RawPointerAxes ---
71
72RawPointerAxes::RawPointerAxes() {
73 clear();
74}
75
76void RawPointerAxes::clear() {
77 x.clear();
78 y.clear();
79 pressure.clear();
80 touchMajor.clear();
81 touchMinor.clear();
82 toolMajor.clear();
83 toolMinor.clear();
84 orientation.clear();
85 distance.clear();
86 tiltX.clear();
87 tiltY.clear();
88 trackingId.clear();
89 slot.clear();
90}
91
92// --- RawPointerData ---
93
94RawPointerData::RawPointerData() {
95 clear();
96}
97
98void RawPointerData::clear() {
99 pointerCount = 0;
100 clearIdBits();
101}
102
103void RawPointerData::copyFrom(const RawPointerData& other) {
104 pointerCount = other.pointerCount;
105 hoveringIdBits = other.hoveringIdBits;
106 touchingIdBits = other.touchingIdBits;
arthurhung65600042020-04-30 17:55:40 +0800107 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700108
109 for (uint32_t i = 0; i < pointerCount; i++) {
110 pointers[i] = other.pointers[i];
111
112 int id = pointers[i].id;
113 idToIndex[id] = other.idToIndex[id];
114 }
115}
116
117void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
118 float x = 0, y = 0;
119 uint32_t count = touchingIdBits.count();
120 if (count) {
121 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
122 uint32_t id = idBits.clearFirstMarkedBit();
123 const Pointer& pointer = pointerForId(id);
124 x += pointer.x;
125 y += pointer.y;
126 }
127 x /= count;
128 y /= count;
129 }
130 *outX = x;
131 *outY = y;
132}
133
134// --- CookedPointerData ---
135
136CookedPointerData::CookedPointerData() {
137 clear();
138}
139
140void CookedPointerData::clear() {
141 pointerCount = 0;
142 hoveringIdBits.clear();
143 touchingIdBits.clear();
arthurhung65600042020-04-30 17:55:40 +0800144 canceledIdBits.clear();
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +0000145 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700146}
147
148void CookedPointerData::copyFrom(const CookedPointerData& other) {
149 pointerCount = other.pointerCount;
150 hoveringIdBits = other.hoveringIdBits;
151 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +0000152 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700153
154 for (uint32_t i = 0; i < pointerCount; i++) {
155 pointerProperties[i].copyFrom(other.pointerProperties[i]);
156 pointerCoords[i].copyFrom(other.pointerCoords[i]);
157
158 int id = pointerProperties[i].id;
159 idToIndex[id] = other.idToIndex[id];
160 }
161}
162
163// --- TouchInputMapper ---
164
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800165TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
166 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700167 mSource(0),
Michael Wrightaff169e2020-07-02 18:30:52 +0100168 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800169 mRawSurfaceWidth(-1),
170 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700171 mSurfaceLeft(0),
172 mSurfaceTop(0),
173 mPhysicalWidth(-1),
174 mPhysicalHeight(-1),
175 mPhysicalLeft(0),
176 mPhysicalTop(0),
177 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
178
179TouchInputMapper::~TouchInputMapper() {}
180
181uint32_t TouchInputMapper::getSources() {
182 return mSource;
183}
184
185void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
186 InputMapper::populateDeviceInfo(info);
187
Michael Wrightaff169e2020-07-02 18:30:52 +0100188 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700189 info->addMotionRange(mOrientedRanges.x);
190 info->addMotionRange(mOrientedRanges.y);
191 info->addMotionRange(mOrientedRanges.pressure);
192
Chris Ye1fb45302020-09-02 22:41:50 -0700193 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye4b2268c2020-09-15 17:17:34 -0700194 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
195 //
196 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
197 // motion, i.e. the hardware dimensions, as the finger could move completely across the
198 // touchpad in one sample cycle.
Chris Ye1fb45302020-09-02 22:41:50 -0700199 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
200 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
201 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
202 x.fuzz, x.resolution);
203 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
204 y.fuzz, y.resolution);
205 }
206
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700207 if (mOrientedRanges.haveSize) {
208 info->addMotionRange(mOrientedRanges.size);
209 }
210
211 if (mOrientedRanges.haveTouchSize) {
212 info->addMotionRange(mOrientedRanges.touchMajor);
213 info->addMotionRange(mOrientedRanges.touchMinor);
214 }
215
216 if (mOrientedRanges.haveToolSize) {
217 info->addMotionRange(mOrientedRanges.toolMajor);
218 info->addMotionRange(mOrientedRanges.toolMinor);
219 }
220
221 if (mOrientedRanges.haveOrientation) {
222 info->addMotionRange(mOrientedRanges.orientation);
223 }
224
225 if (mOrientedRanges.haveDistance) {
226 info->addMotionRange(mOrientedRanges.distance);
227 }
228
229 if (mOrientedRanges.haveTilt) {
230 info->addMotionRange(mOrientedRanges.tilt);
231 }
232
233 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
234 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
235 0.0f);
236 }
237 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
238 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
239 0.0f);
240 }
Michael Wrightaff169e2020-07-02 18:30:52 +0100241 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700242 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
243 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
244 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
245 x.fuzz, x.resolution);
246 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
247 y.fuzz, y.resolution);
248 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
249 x.fuzz, x.resolution);
250 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
251 y.fuzz, y.resolution);
252 }
253 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
254 }
255}
256
257void TouchInputMapper::dump(std::string& dump) {
258 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
259 dumpParameters(dump);
260 dumpVirtualKeys(dump);
261 dumpRawPointerAxes(dump);
262 dumpCalibration(dump);
263 dumpAffineTransformation(dump);
264 dumpSurface(dump);
265
266 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
267 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
268 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
269 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
270 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
271 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
272 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
273 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
274 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
275 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
276 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
277 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
278 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
279 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
280 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
281 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
282 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
283
284 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
285 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
286 mLastRawState.rawPointerData.pointerCount);
287 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
288 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
289 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
290 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
291 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
292 "toolType=%d, isHovering=%s\n",
293 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
294 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
295 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
296 pointer.distance, pointer.toolType, toString(pointer.isHovering));
297 }
298
299 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
300 mLastCookedState.buttonState);
301 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
302 mLastCookedState.cookedPointerData.pointerCount);
303 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
304 const PointerProperties& pointerProperties =
305 mLastCookedState.cookedPointerData.pointerProperties[i];
306 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +0000307 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
308 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
309 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700310 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
311 "toolType=%d, isHovering=%s\n",
312 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +0000313 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
314 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700315 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
316 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
323 pointerProperties.toolType,
324 toString(mLastCookedState.cookedPointerData.isHovering(i)));
325 }
326
327 dump += INDENT3 "Stylus Fusion:\n";
328 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
329 toString(mExternalStylusConnected));
330 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
331 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
332 mExternalStylusFusionTimeout);
333 dump += INDENT3 "External Stylus State:\n";
334 dumpStylusState(dump, mExternalStylusState);
335
Michael Wrightaff169e2020-07-02 18:30:52 +0100336 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
338 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
339 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
340 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
341 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
342 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
343 }
344}
345
346const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
347 switch (deviceMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100348 case DeviceMode::DISABLED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700349 return "disabled";
Michael Wrightaff169e2020-07-02 18:30:52 +0100350 case DeviceMode::DIRECT:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351 return "direct";
Michael Wrightaff169e2020-07-02 18:30:52 +0100352 case DeviceMode::UNSCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700353 return "unscaled";
Michael Wrightaff169e2020-07-02 18:30:52 +0100354 case DeviceMode::NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700355 return "navigation";
Michael Wrightaff169e2020-07-02 18:30:52 +0100356 case DeviceMode::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700357 return "pointer";
358 }
359 return "unknown";
360}
361
362void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
363 uint32_t changes) {
364 InputMapper::configure(when, config, changes);
365
366 mConfig = *config;
367
368 if (!changes) { // first time only
369 // Configure basic parameters.
370 configureParameters();
371
372 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800373 mCursorScrollAccumulator.configure(getDeviceContext());
374 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700375
376 // Configure absolute axis information.
377 configureRawPointerAxes();
378
379 // Prepare input device calibration.
380 parseCalibration();
381 resolveCalibration();
382 }
383
384 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
385 // Update location calibration to reflect current settings
386 updateAffineTransformation();
387 }
388
389 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
390 // Update pointer speed.
391 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
392 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
393 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
394 }
395
396 bool resetNeeded = false;
397 if (!changes ||
398 (changes &
399 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewiseba157b2018-02-22 13:31:42 -0800400 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700401 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
402 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
403 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
404 // Configure device sources, surface dimensions, orientation and
405 // scaling factors.
406 configureSurface(when, &resetNeeded);
407 }
408
409 if (changes && resetNeeded) {
410 // Send reset, unless this is the first time the device has been configured,
411 // in which case the reader will call reset itself after all mappers are ready.
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800412 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800413 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700414 }
415}
416
417void TouchInputMapper::resolveExternalStylusPresence() {
418 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700420 mExternalStylusConnected = !devices.empty();
421
422 if (!mExternalStylusConnected) {
423 resetExternalStylus();
424 }
425}
426
427void TouchInputMapper::configureParameters() {
428 // Use the pointer presentation mode for devices that do not support distinct
429 // multitouch. The spot-based presentation relies on being able to accurately
430 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800431 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wrightaff169e2020-07-02 18:30:52 +0100432 ? Parameters::GestureMode::SINGLE_TOUCH
433 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700434
435 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800436 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
437 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700438 if (gestureModeString == "single-touch") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100439 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700440 } else if (gestureModeString == "multi-touch") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100441 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700442 } else if (gestureModeString != "default") {
443 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
444 }
445 }
446
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800447 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700448 // The device is a touch screen.
Michael Wrightaff169e2020-07-02 18:30:52 +0100449 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800450 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700451 // The device is a pointing device like a track pad.
Michael Wrightaff169e2020-07-02 18:30:52 +0100452 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800453 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
454 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700455 // The device is a cursor device with a touch pad attached.
456 // By default don't use the touch pad to move the pointer.
Michael Wrightaff169e2020-07-02 18:30:52 +0100457 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 } else {
459 // The device is a touch pad of unknown purpose.
Michael Wrightaff169e2020-07-02 18:30:52 +0100460 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700461 }
462
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800463 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700464
465 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800466 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
467 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700468 if (deviceTypeString == "touchScreen") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100469 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700470 } else if (deviceTypeString == "touchPad") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100471 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472 } else if (deviceTypeString == "touchNavigation") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100473 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700474 } else if (deviceTypeString == "pointer") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100475 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700476 } else if (deviceTypeString != "default") {
477 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
478 }
479 }
480
Michael Wrightaff169e2020-07-02 18:30:52 +0100481 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800482 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
483 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484
485 mParameters.hasAssociatedDisplay = false;
486 mParameters.associatedDisplayIsExternal = false;
487 if (mParameters.orientationAware ||
Michael Wrightaff169e2020-07-02 18:30:52 +0100488 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
489 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700490 mParameters.hasAssociatedDisplay = true;
Michael Wrightaff169e2020-07-02 18:30:52 +0100491 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800492 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700493 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
495 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
497 }
498 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800499 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700500 mParameters.hasAssociatedDisplay = true;
501 }
502
503 // Initial downs on external touch devices should wake the device.
504 // Normally we don't do this for internal touch screens to prevent them from waking
505 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800506 mParameters.wake = getDeviceContext().isExternal();
507 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700508}
509
510void TouchInputMapper::dumpParameters(std::string& dump) {
511 dump += INDENT3 "Parameters:\n";
512
513 switch (mParameters.gestureMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100514 case Parameters::GestureMode::SINGLE_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700515 dump += INDENT4 "GestureMode: single-touch\n";
516 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100517 case Parameters::GestureMode::MULTI_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700518 dump += INDENT4 "GestureMode: multi-touch\n";
519 break;
520 default:
521 assert(false);
522 }
523
524 switch (mParameters.deviceType) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100525 case Parameters::DeviceType::TOUCH_SCREEN:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700526 dump += INDENT4 "DeviceType: touchScreen\n";
527 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100528 case Parameters::DeviceType::TOUCH_PAD:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700529 dump += INDENT4 "DeviceType: touchPad\n";
530 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100531 case Parameters::DeviceType::TOUCH_NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700532 dump += INDENT4 "DeviceType: touchNavigation\n";
533 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100534 case Parameters::DeviceType::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700535 dump += INDENT4 "DeviceType: pointer\n";
536 break;
537 default:
538 ALOG_ASSERT(false);
539 }
540
541 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
542 "displayId='%s'\n",
543 toString(mParameters.hasAssociatedDisplay),
544 toString(mParameters.associatedDisplayIsExternal),
545 mParameters.uniqueDisplayId.c_str());
546 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
547}
548
549void TouchInputMapper::configureRawPointerAxes() {
550 mRawPointerAxes.clear();
551}
552
553void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
554 dump += INDENT3 "Raw Touch Axes:\n";
555 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
556 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
557 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
558 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
559 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
560 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
561 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
562 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
563 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
564 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
565 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
566 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
567 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
568}
569
570bool TouchInputMapper::hasExternalStylus() const {
571 return mExternalStylusConnected;
572}
573
574/**
575 * Determine which DisplayViewport to use.
576 * 1. If display port is specified, return the matching viewport. If matching viewport not
577 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800578 * 2. Always use the suggested viewport from WindowManagerService for pointers.
579 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700580 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800581 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700582 */
583std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewiseba157b2018-02-22 13:31:42 -0800584 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800585 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700586 if (displayPort) {
587 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800588 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700589 }
590
Michael Wrightaff169e2020-07-02 18:30:52 +0100591 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800592 std::optional<DisplayViewport> viewport =
593 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
594 if (viewport) {
595 return viewport;
596 } else {
597 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
598 mConfig.defaultPointerDisplayId);
599 }
600 }
601
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700602 // Check if uniqueDisplayId is specified in idc file.
603 if (!mParameters.uniqueDisplayId.empty()) {
604 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
605 }
606
607 ViewportType viewportTypeToUse;
608 if (mParameters.associatedDisplayIsExternal) {
609 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
610 } else {
611 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
612 }
613
614 std::optional<DisplayViewport> viewport =
615 mConfig.getDisplayViewportByType(viewportTypeToUse);
616 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
617 ALOGW("Input device %s should be associated with external display, "
618 "fallback to internal one for the external viewport is not found.",
619 getDeviceName().c_str());
620 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
621 }
622
623 return viewport;
624 }
625
626 // No associated display, return a non-display viewport.
627 DisplayViewport newViewport;
628 // Raw width and height in the natural orientation.
629 int32_t rawWidth = mRawPointerAxes.getRawWidth();
630 int32_t rawHeight = mRawPointerAxes.getRawHeight();
631 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
632 return std::make_optional(newViewport);
633}
634
635void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100636 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700637
638 resolveExternalStylusPresence();
639
640 // Determine device mode.
Michael Wrightaff169e2020-07-02 18:30:52 +0100641 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewiseba157b2018-02-22 13:31:42 -0800642 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700643 mSource = AINPUT_SOURCE_MOUSE;
Michael Wrightaff169e2020-07-02 18:30:52 +0100644 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700645 if (hasStylus()) {
646 mSource |= AINPUT_SOURCE_STYLUS;
647 }
Michael Wrightaff169e2020-07-02 18:30:52 +0100648 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700649 mParameters.hasAssociatedDisplay) {
650 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wrightaff169e2020-07-02 18:30:52 +0100651 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700652 if (hasStylus()) {
653 mSource |= AINPUT_SOURCE_STYLUS;
654 }
655 if (hasExternalStylus()) {
656 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
657 }
Michael Wrightaff169e2020-07-02 18:30:52 +0100658 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700659 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wrightaff169e2020-07-02 18:30:52 +0100660 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700661 } else {
662 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wrightaff169e2020-07-02 18:30:52 +0100663 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700664 }
665
666 // Ensure we have valid X and Y axes.
667 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
668 ALOGW("Touch device '%s' did not report support for X or Y axis! "
669 "The device will be inoperable.",
670 getDeviceName().c_str());
Michael Wrightaff169e2020-07-02 18:30:52 +0100671 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700672 return;
673 }
674
675 // Get associated display dimensions.
676 std::optional<DisplayViewport> newViewport = findViewport();
677 if (!newViewport) {
678 ALOGI("Touch device '%s' could not query the properties of its associated "
679 "display. The device will be inoperable until the display size "
680 "becomes available.",
681 getDeviceName().c_str());
Michael Wrightaff169e2020-07-02 18:30:52 +0100682 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700683 return;
684 }
685
686 // Raw width and height in the natural orientation.
687 int32_t rawWidth = mRawPointerAxes.getRawWidth();
688 int32_t rawHeight = mRawPointerAxes.getRawHeight();
689
690 bool viewportChanged = mViewport != *newViewport;
691 if (viewportChanged) {
692 mViewport = *newViewport;
693
Michael Wrightaff169e2020-07-02 18:30:52 +0100694 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700695 // Convert rotated viewport to natural surface coordinates.
696 int32_t naturalLogicalWidth, naturalLogicalHeight;
697 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
698 int32_t naturalPhysicalLeft, naturalPhysicalTop;
699 int32_t naturalDeviceWidth, naturalDeviceHeight;
700 switch (mViewport.orientation) {
701 case DISPLAY_ORIENTATION_90:
702 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
703 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
704 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
705 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800706 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700707 naturalPhysicalTop = mViewport.physicalLeft;
708 naturalDeviceWidth = mViewport.deviceHeight;
709 naturalDeviceHeight = mViewport.deviceWidth;
710 break;
711 case DISPLAY_ORIENTATION_180:
712 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
713 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
714 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
715 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
716 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
717 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
718 naturalDeviceWidth = mViewport.deviceWidth;
719 naturalDeviceHeight = mViewport.deviceHeight;
720 break;
721 case DISPLAY_ORIENTATION_270:
722 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
723 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
724 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
725 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
726 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800727 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700728 naturalDeviceWidth = mViewport.deviceHeight;
729 naturalDeviceHeight = mViewport.deviceWidth;
730 break;
731 case DISPLAY_ORIENTATION_0:
732 default:
733 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
734 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
735 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
736 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
737 naturalPhysicalLeft = mViewport.physicalLeft;
738 naturalPhysicalTop = mViewport.physicalTop;
739 naturalDeviceWidth = mViewport.deviceWidth;
740 naturalDeviceHeight = mViewport.deviceHeight;
741 break;
742 }
743
744 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
745 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
746 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
747 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
748 }
749
750 mPhysicalWidth = naturalPhysicalWidth;
751 mPhysicalHeight = naturalPhysicalHeight;
752 mPhysicalLeft = naturalPhysicalLeft;
753 mPhysicalTop = naturalPhysicalTop;
754
Arthur Hung4197f6b2020-03-16 15:39:59 +0800755 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
756 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700757 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
758 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800759 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
760 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700761
762 mSurfaceOrientation =
763 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
764 } else {
765 mPhysicalWidth = rawWidth;
766 mPhysicalHeight = rawHeight;
767 mPhysicalLeft = 0;
768 mPhysicalTop = 0;
769
Arthur Hung4197f6b2020-03-16 15:39:59 +0800770 mRawSurfaceWidth = rawWidth;
771 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700772 mSurfaceLeft = 0;
773 mSurfaceTop = 0;
774 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
775 }
776 }
777
778 // If moving between pointer modes, need to reset some state.
779 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
780 if (deviceModeChanged) {
781 mOrientedRanges.clear();
782 }
783
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800784 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
785 // preserve the cursor position.
Michael Wrightaff169e2020-07-02 18:30:52 +0100786 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800787 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
788 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800789 if (mPointerController == nullptr) {
790 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700791 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800792 if (mConfig.pointerCapture) {
793 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
794 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700795 } else {
Michael Wright7a376672020-06-26 20:51:44 +0100796 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700797 }
798
799 if (viewportChanged || deviceModeChanged) {
800 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
801 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800802 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700803 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
804
805 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800806 mXScale = float(mRawSurfaceWidth) / rawWidth;
807 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700808 mXTranslate = -mSurfaceLeft;
809 mYTranslate = -mSurfaceTop;
810 mXPrecision = 1.0f / mXScale;
811 mYPrecision = 1.0f / mYScale;
812
813 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
814 mOrientedRanges.x.source = mSource;
815 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
816 mOrientedRanges.y.source = mSource;
817
818 configureVirtualKeys();
819
820 // Scale factor for terms that are not oriented in a particular axis.
821 // If the pixels are square then xScale == yScale otherwise we fake it
822 // by choosing an average.
823 mGeometricScale = avg(mXScale, mYScale);
824
825 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800826 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700827
828 // Size factors.
Michael Wrightaff169e2020-07-02 18:30:52 +0100829 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700830 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
831 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
832 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
833 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
834 } else {
835 mSizeScale = 0.0f;
836 }
837
838 mOrientedRanges.haveTouchSize = true;
839 mOrientedRanges.haveToolSize = true;
840 mOrientedRanges.haveSize = true;
841
842 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
843 mOrientedRanges.touchMajor.source = mSource;
844 mOrientedRanges.touchMajor.min = 0;
845 mOrientedRanges.touchMajor.max = diagonalSize;
846 mOrientedRanges.touchMajor.flat = 0;
847 mOrientedRanges.touchMajor.fuzz = 0;
848 mOrientedRanges.touchMajor.resolution = 0;
849
850 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
851 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
852
853 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
854 mOrientedRanges.toolMajor.source = mSource;
855 mOrientedRanges.toolMajor.min = 0;
856 mOrientedRanges.toolMajor.max = diagonalSize;
857 mOrientedRanges.toolMajor.flat = 0;
858 mOrientedRanges.toolMajor.fuzz = 0;
859 mOrientedRanges.toolMajor.resolution = 0;
860
861 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
862 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
863
864 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
865 mOrientedRanges.size.source = mSource;
866 mOrientedRanges.size.min = 0;
867 mOrientedRanges.size.max = 1.0;
868 mOrientedRanges.size.flat = 0;
869 mOrientedRanges.size.fuzz = 0;
870 mOrientedRanges.size.resolution = 0;
871 } else {
872 mSizeScale = 0.0f;
873 }
874
875 // Pressure factors.
876 mPressureScale = 0;
877 float pressureMax = 1.0;
Michael Wrightaff169e2020-07-02 18:30:52 +0100878 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
879 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700880 if (mCalibration.havePressureScale) {
881 mPressureScale = mCalibration.pressureScale;
882 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
883 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
884 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
885 }
886 }
887
888 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
889 mOrientedRanges.pressure.source = mSource;
890 mOrientedRanges.pressure.min = 0;
891 mOrientedRanges.pressure.max = pressureMax;
892 mOrientedRanges.pressure.flat = 0;
893 mOrientedRanges.pressure.fuzz = 0;
894 mOrientedRanges.pressure.resolution = 0;
895
896 // Tilt
897 mTiltXCenter = 0;
898 mTiltXScale = 0;
899 mTiltYCenter = 0;
900 mTiltYScale = 0;
901 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
902 if (mHaveTilt) {
903 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
904 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
905 mTiltXScale = M_PI / 180;
906 mTiltYScale = M_PI / 180;
907
908 mOrientedRanges.haveTilt = true;
909
910 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
911 mOrientedRanges.tilt.source = mSource;
912 mOrientedRanges.tilt.min = 0;
913 mOrientedRanges.tilt.max = M_PI_2;
914 mOrientedRanges.tilt.flat = 0;
915 mOrientedRanges.tilt.fuzz = 0;
916 mOrientedRanges.tilt.resolution = 0;
917 }
918
919 // Orientation
920 mOrientationScale = 0;
921 if (mHaveTilt) {
922 mOrientedRanges.haveOrientation = true;
923
924 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
925 mOrientedRanges.orientation.source = mSource;
926 mOrientedRanges.orientation.min = -M_PI;
927 mOrientedRanges.orientation.max = M_PI;
928 mOrientedRanges.orientation.flat = 0;
929 mOrientedRanges.orientation.fuzz = 0;
930 mOrientedRanges.orientation.resolution = 0;
931 } else if (mCalibration.orientationCalibration !=
Michael Wrightaff169e2020-07-02 18:30:52 +0100932 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700933 if (mCalibration.orientationCalibration ==
Michael Wrightaff169e2020-07-02 18:30:52 +0100934 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700935 if (mRawPointerAxes.orientation.valid) {
936 if (mRawPointerAxes.orientation.maxValue > 0) {
937 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
938 } else if (mRawPointerAxes.orientation.minValue < 0) {
939 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
940 } else {
941 mOrientationScale = 0;
942 }
943 }
944 }
945
946 mOrientedRanges.haveOrientation = true;
947
948 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
949 mOrientedRanges.orientation.source = mSource;
950 mOrientedRanges.orientation.min = -M_PI_2;
951 mOrientedRanges.orientation.max = M_PI_2;
952 mOrientedRanges.orientation.flat = 0;
953 mOrientedRanges.orientation.fuzz = 0;
954 mOrientedRanges.orientation.resolution = 0;
955 }
956
957 // Distance
958 mDistanceScale = 0;
Michael Wrightaff169e2020-07-02 18:30:52 +0100959 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
960 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700961 if (mCalibration.haveDistanceScale) {
962 mDistanceScale = mCalibration.distanceScale;
963 } else {
964 mDistanceScale = 1.0f;
965 }
966 }
967
968 mOrientedRanges.haveDistance = true;
969
970 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
971 mOrientedRanges.distance.source = mSource;
972 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
973 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
974 mOrientedRanges.distance.flat = 0;
975 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
976 mOrientedRanges.distance.resolution = 0;
977 }
978
979 // Compute oriented precision, scales and ranges.
980 // Note that the maximum value reported is an inclusive maximum value so it is one
981 // unit less than the total width or height of surface.
982 switch (mSurfaceOrientation) {
983 case DISPLAY_ORIENTATION_90:
984 case DISPLAY_ORIENTATION_270:
985 mOrientedXPrecision = mYPrecision;
986 mOrientedYPrecision = mXPrecision;
987
988 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800989 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700990 mOrientedRanges.x.flat = 0;
991 mOrientedRanges.x.fuzz = 0;
992 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
993
994 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800995 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700996 mOrientedRanges.y.flat = 0;
997 mOrientedRanges.y.fuzz = 0;
998 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
999 break;
1000
1001 default:
1002 mOrientedXPrecision = mXPrecision;
1003 mOrientedYPrecision = mYPrecision;
1004
1005 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001006 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001007 mOrientedRanges.x.flat = 0;
1008 mOrientedRanges.x.fuzz = 0;
1009 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1010
1011 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001012 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001013 mOrientedRanges.y.flat = 0;
1014 mOrientedRanges.y.fuzz = 0;
1015 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1016 break;
1017 }
1018
1019 // Location
1020 updateAffineTransformation();
1021
Michael Wrightaff169e2020-07-02 18:30:52 +01001022 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001023 // Compute pointer gesture detection parameters.
1024 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001025 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001026
1027 // Scale movements such that one whole swipe of the touch pad covers a
1028 // given area relative to the diagonal size of the display when no acceleration
1029 // is applied.
1030 // Assume that the touch pad has a square aspect ratio such that movements in
1031 // X and Y of the same number of raw units cover the same physical distance.
1032 mPointerXMovementScale =
1033 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1034 mPointerYMovementScale = mPointerXMovementScale;
1035
1036 // Scale zooms to cover a smaller range of the display than movements do.
1037 // This value determines the area around the pointer that is affected by freeform
1038 // pointer gestures.
1039 mPointerXZoomScale =
1040 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1041 mPointerYZoomScale = mPointerXZoomScale;
1042
1043 // Max width between pointers to detect a swipe gesture is more than some fraction
1044 // of the diagonal axis of the touch pad. Touches that are wider than this are
1045 // translated into freeform gestures.
1046 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1047
1048 // Abort current pointer usages because the state has changed.
1049 abortPointerUsage(when, 0 /*policyFlags*/);
1050 }
1051
1052 // Inform the dispatcher about the changes.
1053 *outResetNeeded = true;
1054 bumpGeneration();
1055 }
1056}
1057
1058void TouchInputMapper::dumpSurface(std::string& dump) {
1059 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001060 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1061 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001062 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1063 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001064 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1065 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001066 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1067 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1068 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1069 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1070 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1071}
1072
1073void TouchInputMapper::configureVirtualKeys() {
1074 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001075 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001076
1077 mVirtualKeys.clear();
1078
1079 if (virtualKeyDefinitions.size() == 0) {
1080 return;
1081 }
1082
1083 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1084 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1085 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1086 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1087
1088 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1089 VirtualKey virtualKey;
1090
1091 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1092 int32_t keyCode;
1093 int32_t dummyKeyMetaState;
1094 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001095 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1096 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001097 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1098 continue; // drop the key
1099 }
1100
1101 virtualKey.keyCode = keyCode;
1102 virtualKey.flags = flags;
1103
1104 // convert the key definition's display coordinates into touch coordinates for a hit box
1105 int32_t halfWidth = virtualKeyDefinition.width / 2;
1106 int32_t halfHeight = virtualKeyDefinition.height / 2;
1107
1108 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001109 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001110 touchScreenLeft;
1111 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001112 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001114 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1115 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001116 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001117 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1118 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001119 touchScreenTop;
1120 mVirtualKeys.push_back(virtualKey);
1121 }
1122}
1123
1124void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1125 if (!mVirtualKeys.empty()) {
1126 dump += INDENT3 "Virtual Keys:\n";
1127
1128 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1129 const VirtualKey& virtualKey = mVirtualKeys[i];
1130 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1131 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1132 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1133 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1134 }
1135 }
1136}
1137
1138void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001139 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001140 Calibration& out = mCalibration;
1141
1142 // Size
Michael Wrightaff169e2020-07-02 18:30:52 +01001143 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 String8 sizeCalibrationString;
1145 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1146 if (sizeCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001147 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 } else if (sizeCalibrationString == "geometric") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001149 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 } else if (sizeCalibrationString == "diameter") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001151 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001152 } else if (sizeCalibrationString == "box") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001153 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001154 } else if (sizeCalibrationString == "area") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001155 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001156 } else if (sizeCalibrationString != "default") {
1157 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1158 }
1159 }
1160
1161 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1162 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1163 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1164
1165 // Pressure
Michael Wrightaff169e2020-07-02 18:30:52 +01001166 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 String8 pressureCalibrationString;
1168 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1169 if (pressureCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001170 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 } else if (pressureCalibrationString == "physical") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001172 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001173 } else if (pressureCalibrationString == "amplitude") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001174 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 } else if (pressureCalibrationString != "default") {
1176 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1177 pressureCalibrationString.string());
1178 }
1179 }
1180
1181 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1182
1183 // Orientation
Michael Wrightaff169e2020-07-02 18:30:52 +01001184 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001185 String8 orientationCalibrationString;
1186 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1187 if (orientationCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001188 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001189 } else if (orientationCalibrationString == "interpolated") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001190 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 } else if (orientationCalibrationString == "vector") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001192 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 } else if (orientationCalibrationString != "default") {
1194 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1195 orientationCalibrationString.string());
1196 }
1197 }
1198
1199 // Distance
Michael Wrightaff169e2020-07-02 18:30:52 +01001200 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 String8 distanceCalibrationString;
1202 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1203 if (distanceCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001204 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 } else if (distanceCalibrationString == "scaled") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001206 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 } else if (distanceCalibrationString != "default") {
1208 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1209 distanceCalibrationString.string());
1210 }
1211 }
1212
1213 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1214
Michael Wrightaff169e2020-07-02 18:30:52 +01001215 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 String8 coverageCalibrationString;
1217 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1218 if (coverageCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001219 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220 } else if (coverageCalibrationString == "box") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001221 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222 } else if (coverageCalibrationString != "default") {
1223 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1224 coverageCalibrationString.string());
1225 }
1226 }
1227}
1228
1229void TouchInputMapper::resolveCalibration() {
1230 // Size
1231 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001232 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1233 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001234 }
1235 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001236 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 }
1238
1239 // Pressure
1240 if (mRawPointerAxes.pressure.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001241 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1242 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243 }
1244 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001245 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 }
1247
1248 // Orientation
1249 if (mRawPointerAxes.orientation.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001250 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1251 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252 }
1253 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001254 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256
1257 // Distance
1258 if (mRawPointerAxes.distance.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001259 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1260 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 }
1262 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001263 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265
1266 // Coverage
Michael Wrightaff169e2020-07-02 18:30:52 +01001267 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1268 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
1270}
1271
1272void TouchInputMapper::dumpCalibration(std::string& dump) {
1273 dump += INDENT3 "Calibration:\n";
1274
1275 // Size
1276 switch (mCalibration.sizeCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001277 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 dump += INDENT4 "touch.size.calibration: none\n";
1279 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001280 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 dump += INDENT4 "touch.size.calibration: geometric\n";
1282 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001283 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 dump += INDENT4 "touch.size.calibration: diameter\n";
1285 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001286 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 dump += INDENT4 "touch.size.calibration: box\n";
1288 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001289 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290 dump += INDENT4 "touch.size.calibration: area\n";
1291 break;
1292 default:
1293 ALOG_ASSERT(false);
1294 }
1295
1296 if (mCalibration.haveSizeScale) {
1297 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1298 }
1299
1300 if (mCalibration.haveSizeBias) {
1301 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1302 }
1303
1304 if (mCalibration.haveSizeIsSummed) {
1305 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1306 toString(mCalibration.sizeIsSummed));
1307 }
1308
1309 // Pressure
1310 switch (mCalibration.pressureCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001311 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 dump += INDENT4 "touch.pressure.calibration: none\n";
1313 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001314 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 dump += INDENT4 "touch.pressure.calibration: physical\n";
1316 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001317 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1319 break;
1320 default:
1321 ALOG_ASSERT(false);
1322 }
1323
1324 if (mCalibration.havePressureScale) {
1325 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1326 }
1327
1328 // Orientation
1329 switch (mCalibration.orientationCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001330 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.orientation.calibration: none\n";
1332 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001333 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1335 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001336 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001337 dump += INDENT4 "touch.orientation.calibration: vector\n";
1338 break;
1339 default:
1340 ALOG_ASSERT(false);
1341 }
1342
1343 // Distance
1344 switch (mCalibration.distanceCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001345 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001346 dump += INDENT4 "touch.distance.calibration: none\n";
1347 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001348 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001349 dump += INDENT4 "touch.distance.calibration: scaled\n";
1350 break;
1351 default:
1352 ALOG_ASSERT(false);
1353 }
1354
1355 if (mCalibration.haveDistanceScale) {
1356 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1357 }
1358
1359 switch (mCalibration.coverageCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001360 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001361 dump += INDENT4 "touch.coverage.calibration: none\n";
1362 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001363 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001364 dump += INDENT4 "touch.coverage.calibration: box\n";
1365 break;
1366 default:
1367 ALOG_ASSERT(false);
1368 }
1369}
1370
1371void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1372 dump += INDENT3 "Affine Transformation:\n";
1373
1374 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1375 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1376 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1377 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1378 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1379 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1380}
1381
1382void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001383 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001384 mSurfaceOrientation);
1385}
1386
1387void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001388 mCursorButtonAccumulator.reset(getDeviceContext());
1389 mCursorScrollAccumulator.reset(getDeviceContext());
1390 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001391
1392 mPointerVelocityControl.reset();
1393 mWheelXVelocityControl.reset();
1394 mWheelYVelocityControl.reset();
1395
1396 mRawStatesPending.clear();
1397 mCurrentRawState.clear();
1398 mCurrentCookedState.clear();
1399 mLastRawState.clear();
1400 mLastCookedState.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001401 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001402 mSentHoverEnter = false;
1403 mHavePointerIds = false;
1404 mCurrentMotionAborted = false;
1405 mDownTime = 0;
1406
1407 mCurrentVirtualKey.down = false;
1408
1409 mPointerGesture.reset();
1410 mPointerSimple.reset();
1411 resetExternalStylus();
1412
1413 if (mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01001414 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001415 mPointerController->clearSpots();
1416 }
1417
1418 InputMapper::reset(when);
1419}
1420
1421void TouchInputMapper::resetExternalStylus() {
1422 mExternalStylusState.clear();
1423 mExternalStylusId = -1;
1424 mExternalStylusFusionTimeout = LLONG_MAX;
1425 mExternalStylusDataPending = false;
1426}
1427
1428void TouchInputMapper::clearStylusDataPendingFlags() {
1429 mExternalStylusDataPending = false;
1430 mExternalStylusFusionTimeout = LLONG_MAX;
1431}
1432
1433void TouchInputMapper::process(const RawEvent* rawEvent) {
1434 mCursorButtonAccumulator.process(rawEvent);
1435 mCursorScrollAccumulator.process(rawEvent);
1436 mTouchButtonAccumulator.process(rawEvent);
1437
1438 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1439 sync(rawEvent->when);
1440 }
1441}
1442
1443void TouchInputMapper::sync(nsecs_t when) {
1444 const RawState* last =
1445 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1446
1447 // Push a new state.
1448 mRawStatesPending.emplace_back();
1449
1450 RawState* next = &mRawStatesPending.back();
1451 next->clear();
1452 next->when = when;
1453
1454 // Sync button state.
1455 next->buttonState =
1456 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1457
1458 // Sync scroll
1459 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1460 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1461 mCursorScrollAccumulator.finishSync();
1462
1463 // Sync touch
1464 syncTouch(when, next);
1465
1466 // Assign pointer ids.
1467 if (!mHavePointerIds) {
1468 assignPointerIds(last, next);
1469 }
1470
1471#if DEBUG_RAW_EVENTS
1472 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhung65600042020-04-30 17:55:40 +08001473 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001474 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1475 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhung65600042020-04-30 17:55:40 +08001476 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1477 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001478#endif
1479
1480 processRawTouches(false /*timeout*/);
1481}
1482
1483void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001484 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001485 // Drop all input if the device is disabled.
1486 mCurrentRawState.clear();
1487 mRawStatesPending.clear();
1488 return;
1489 }
1490
1491 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1492 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1493 // touching the current state will only observe the events that have been dispatched to the
1494 // rest of the pipeline.
1495 const size_t N = mRawStatesPending.size();
1496 size_t count;
1497 for (count = 0; count < N; count++) {
1498 const RawState& next = mRawStatesPending[count];
1499
1500 // A failure to assign the stylus id means that we're waiting on stylus data
1501 // and so should defer the rest of the pipeline.
1502 if (assignExternalStylusId(next, timeout)) {
1503 break;
1504 }
1505
1506 // All ready to go.
1507 clearStylusDataPendingFlags();
1508 mCurrentRawState.copyFrom(next);
1509 if (mCurrentRawState.when < mLastRawState.when) {
1510 mCurrentRawState.when = mLastRawState.when;
1511 }
1512 cookAndDispatch(mCurrentRawState.when);
1513 }
1514 if (count != 0) {
1515 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1516 }
1517
1518 if (mExternalStylusDataPending) {
1519 if (timeout) {
1520 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1521 clearStylusDataPendingFlags();
1522 mCurrentRawState.copyFrom(mLastRawState);
1523#if DEBUG_STYLUS_FUSION
1524 ALOGD("Timeout expired, synthesizing event with new stylus data");
1525#endif
1526 cookAndDispatch(when);
1527 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1528 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1529 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1530 }
1531 }
1532}
1533
1534void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1535 // Always start with a clean state.
1536 mCurrentCookedState.clear();
1537
1538 // Apply stylus buttons to current raw state.
1539 applyExternalStylusButtonState(when);
1540
1541 // Handle policy on initial down or hover events.
1542 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1543 mCurrentRawState.rawPointerData.pointerCount != 0;
1544
1545 uint32_t policyFlags = 0;
1546 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1547 if (initialDown || buttonsPressed) {
1548 // If this is a touch screen, hide the pointer on an initial down.
Michael Wrightaff169e2020-07-02 18:30:52 +01001549 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550 getContext()->fadePointer();
1551 }
1552
1553 if (mParameters.wake) {
1554 policyFlags |= POLICY_FLAG_WAKE;
1555 }
1556 }
1557
1558 // Consume raw off-screen touches before cooking pointer data.
1559 // If touches are consumed, subsequent code will not receive any pointer data.
1560 if (consumeRawTouches(when, policyFlags)) {
1561 mCurrentRawState.rawPointerData.clear();
1562 }
1563
1564 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1565 // with cooked pointer data that has the same ids and indices as the raw data.
1566 // The following code can use either the raw or cooked data, as needed.
1567 cookPointerData();
1568
1569 // Apply stylus pressure to current cooked state.
1570 applyExternalStylusTouchState(when);
1571
1572 // Synthesize key down from raw buttons if needed.
1573 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1574 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1575 mCurrentCookedState.buttonState);
1576
1577 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wrightaff169e2020-07-02 18:30:52 +01001578 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001579 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1580 uint32_t id = idBits.clearFirstMarkedBit();
1581 const RawPointerData::Pointer& pointer =
1582 mCurrentRawState.rawPointerData.pointerForId(id);
1583 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1584 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1585 mCurrentCookedState.stylusIdBits.markBit(id);
1586 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1587 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1588 mCurrentCookedState.fingerIdBits.markBit(id);
1589 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1590 mCurrentCookedState.mouseIdBits.markBit(id);
1591 }
1592 }
1593 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1594 uint32_t id = idBits.clearFirstMarkedBit();
1595 const RawPointerData::Pointer& pointer =
1596 mCurrentRawState.rawPointerData.pointerForId(id);
1597 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1598 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1599 mCurrentCookedState.stylusIdBits.markBit(id);
1600 }
1601 }
1602
1603 // Stylus takes precedence over all tools, then mouse, then finger.
1604 PointerUsage pointerUsage = mPointerUsage;
1605 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1606 mCurrentCookedState.mouseIdBits.clear();
1607 mCurrentCookedState.fingerIdBits.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001608 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001609 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1610 mCurrentCookedState.fingerIdBits.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001611 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001612 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1613 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001614 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001615 }
1616
1617 dispatchPointerUsage(when, policyFlags, pointerUsage);
1618 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001619 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001620 mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01001621 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1622 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001623
1624 mPointerController->setButtonState(mCurrentRawState.buttonState);
1625 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1626 mCurrentCookedState.cookedPointerData.idToIndex,
1627 mCurrentCookedState.cookedPointerData.touchingIdBits,
1628 mViewport.displayId);
1629 }
1630
1631 if (!mCurrentMotionAborted) {
1632 dispatchButtonRelease(when, policyFlags);
1633 dispatchHoverExit(when, policyFlags);
1634 dispatchTouches(when, policyFlags);
1635 dispatchHoverEnterAndMove(when, policyFlags);
1636 dispatchButtonPress(when, policyFlags);
1637 }
1638
1639 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1640 mCurrentMotionAborted = false;
1641 }
1642 }
1643
1644 // Synthesize key up from raw buttons if needed.
1645 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1646 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1647 mCurrentCookedState.buttonState);
1648
1649 // Clear some transient state.
1650 mCurrentRawState.rawVScroll = 0;
1651 mCurrentRawState.rawHScroll = 0;
1652
1653 // Copy current touch to last touch in preparation for the next cycle.
1654 mLastRawState.copyFrom(mCurrentRawState);
1655 mLastCookedState.copyFrom(mCurrentCookedState);
1656}
1657
1658void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001659 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001660 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1661 }
1662}
1663
1664void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1665 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1666 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1667
1668 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1669 float pressure = mExternalStylusState.pressure;
1670 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1671 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1672 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1673 }
1674 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1675 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1676
1677 PointerProperties& properties =
1678 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1679 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1680 properties.toolType = mExternalStylusState.toolType;
1681 }
1682 }
1683}
1684
1685bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001686 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001687 return false;
1688 }
1689
1690 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1691 state.rawPointerData.pointerCount != 0;
1692 if (initialDown) {
1693 if (mExternalStylusState.pressure != 0.0f) {
1694#if DEBUG_STYLUS_FUSION
1695 ALOGD("Have both stylus and touch data, beginning fusion");
1696#endif
1697 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1698 } else if (timeout) {
1699#if DEBUG_STYLUS_FUSION
1700 ALOGD("Timeout expired, assuming touch is not a stylus.");
1701#endif
1702 resetExternalStylus();
1703 } else {
1704 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1705 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1706 }
1707#if DEBUG_STYLUS_FUSION
1708 ALOGD("No stylus data but stylus is connected, requesting timeout "
1709 "(%" PRId64 "ms)",
1710 mExternalStylusFusionTimeout);
1711#endif
1712 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1713 return true;
1714 }
1715 }
1716
1717 // Check if the stylus pointer has gone up.
1718 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1719#if DEBUG_STYLUS_FUSION
1720 ALOGD("Stylus pointer is going up");
1721#endif
1722 mExternalStylusId = -1;
1723 }
1724
1725 return false;
1726}
1727
1728void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001729 if (mDeviceMode == DeviceMode::POINTER) {
1730 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001731 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1732 }
Michael Wrightaff169e2020-07-02 18:30:52 +01001733 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001734 if (mExternalStylusFusionTimeout < when) {
1735 processRawTouches(true /*timeout*/);
1736 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1737 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1738 }
1739 }
1740}
1741
1742void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1743 mExternalStylusState.copyFrom(state);
1744 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1745 // We're either in the middle of a fused stream of data or we're waiting on data before
1746 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1747 // data.
1748 mExternalStylusDataPending = true;
1749 processRawTouches(false /*timeout*/);
1750 }
1751}
1752
1753bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1754 // Check for release of a virtual key.
1755 if (mCurrentVirtualKey.down) {
1756 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1757 // Pointer went up while virtual key was down.
1758 mCurrentVirtualKey.down = false;
1759 if (!mCurrentVirtualKey.ignored) {
1760#if DEBUG_VIRTUAL_KEYS
1761 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1762 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1763#endif
1764 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1765 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1766 }
1767 return true;
1768 }
1769
1770 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1771 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1772 const RawPointerData::Pointer& pointer =
1773 mCurrentRawState.rawPointerData.pointerForId(id);
1774 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1775 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1776 // Pointer is still within the space of the virtual key.
1777 return true;
1778 }
1779 }
1780
1781 // Pointer left virtual key area or another pointer also went down.
1782 // Send key cancellation but do not consume the touch yet.
1783 // This is useful when the user swipes through from the virtual key area
1784 // into the main display surface.
1785 mCurrentVirtualKey.down = false;
1786 if (!mCurrentVirtualKey.ignored) {
1787#if DEBUG_VIRTUAL_KEYS
1788 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1789 mCurrentVirtualKey.scanCode);
1790#endif
1791 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1792 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1793 AKEY_EVENT_FLAG_CANCELED);
1794 }
1795 }
1796
1797 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1798 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1799 // Pointer just went down. Check for virtual key press or off-screen touches.
1800 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1801 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Yedca44af2020-08-05 15:07:56 -07001802 // Exclude unscaled device for inside surface checking.
1803 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001804 // If exactly one pointer went down, check for virtual key hit.
1805 // Otherwise we will drop the entire stroke.
1806 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1807 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1808 if (virtualKey) {
1809 mCurrentVirtualKey.down = true;
1810 mCurrentVirtualKey.downTime = when;
1811 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1812 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1813 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001814 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1815 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001816
1817 if (!mCurrentVirtualKey.ignored) {
1818#if DEBUG_VIRTUAL_KEYS
1819 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1820 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1821#endif
1822 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1823 AKEY_EVENT_FLAG_FROM_SYSTEM |
1824 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1825 }
1826 }
1827 }
1828 return true;
1829 }
1830 }
1831
1832 // Disable all virtual key touches that happen within a short time interval of the
1833 // most recent touch within the screen area. The idea is to filter out stray
1834 // virtual key presses when interacting with the touch screen.
1835 //
1836 // Problems we're trying to solve:
1837 //
1838 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1839 // virtual key area that is implemented by a separate touch panel and accidentally
1840 // triggers a virtual key.
1841 //
1842 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1843 // area and accidentally triggers a virtual key. This often happens when virtual keys
1844 // are layed out below the screen near to where the on screen keyboard's space bar
1845 // is displayed.
1846 if (mConfig.virtualKeyQuietTime > 0 &&
1847 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001848 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001849 }
1850 return false;
1851}
1852
1853void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1854 int32_t keyEventAction, int32_t keyEventFlags) {
1855 int32_t keyCode = mCurrentVirtualKey.keyCode;
1856 int32_t scanCode = mCurrentVirtualKey.scanCode;
1857 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001858 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001859 policyFlags |= POLICY_FLAG_VIRTUAL;
1860
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001861 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1862 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1863 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001864 getListener()->notifyKey(&args);
1865}
1866
1867void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1868 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1869 if (!currentIdBits.isEmpty()) {
1870 int32_t metaState = getContext()->getGlobalMetaState();
1871 int32_t buttonState = mCurrentCookedState.buttonState;
1872 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1873 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1874 mCurrentCookedState.cookedPointerData.pointerProperties,
1875 mCurrentCookedState.cookedPointerData.pointerCoords,
1876 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1877 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1878 mCurrentMotionAborted = true;
1879 }
1880}
1881
1882void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1883 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1884 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1885 int32_t metaState = getContext()->getGlobalMetaState();
1886 int32_t buttonState = mCurrentCookedState.buttonState;
1887
1888 if (currentIdBits == lastIdBits) {
1889 if (!currentIdBits.isEmpty()) {
1890 // No pointer id changes so this is a move event.
1891 // The listener takes care of batching moves so we don't have to deal with that here.
1892 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1893 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1894 mCurrentCookedState.cookedPointerData.pointerProperties,
1895 mCurrentCookedState.cookedPointerData.pointerCoords,
1896 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1897 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1898 }
1899 } else {
1900 // There may be pointers going up and pointers going down and pointers moving
1901 // all at the same time.
1902 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1903 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1904 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1905 BitSet32 dispatchedIdBits(lastIdBits.value);
1906
1907 // Update last coordinates of pointers that have moved so that we observe the new
1908 // pointer positions at the same time as other pointers that have just gone up.
1909 bool moveNeeded =
1910 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1911 mCurrentCookedState.cookedPointerData.pointerCoords,
1912 mCurrentCookedState.cookedPointerData.idToIndex,
1913 mLastCookedState.cookedPointerData.pointerProperties,
1914 mLastCookedState.cookedPointerData.pointerCoords,
1915 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1916 if (buttonState != mLastCookedState.buttonState) {
1917 moveNeeded = true;
1918 }
1919
1920 // Dispatch pointer up events.
1921 while (!upIdBits.isEmpty()) {
1922 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhung65600042020-04-30 17:55:40 +08001923 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1924 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1925 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001926 mLastCookedState.cookedPointerData.pointerProperties,
1927 mLastCookedState.cookedPointerData.pointerCoords,
1928 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1929 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1930 dispatchedIdBits.clearBit(upId);
arthurhung65600042020-04-30 17:55:40 +08001931 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001932 }
1933
1934 // Dispatch move events if any of the remaining pointers moved from their old locations.
1935 // Although applications receive new locations as part of individual pointer up
1936 // events, they do not generally handle them except when presented in a move event.
1937 if (moveNeeded && !moveIdBits.isEmpty()) {
1938 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1939 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1940 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1941 mCurrentCookedState.cookedPointerData.pointerCoords,
1942 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1943 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1944 }
1945
1946 // Dispatch pointer down events using the new pointer locations.
1947 while (!downIdBits.isEmpty()) {
1948 uint32_t downId = downIdBits.clearFirstMarkedBit();
1949 dispatchedIdBits.markBit(downId);
1950
1951 if (dispatchedIdBits.count() == 1) {
1952 // First pointer is going down. Set down time.
1953 mDownTime = when;
1954 }
1955
1956 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1957 metaState, buttonState, 0,
1958 mCurrentCookedState.cookedPointerData.pointerProperties,
1959 mCurrentCookedState.cookedPointerData.pointerCoords,
1960 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1961 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1962 }
1963 }
1964}
1965
1966void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1967 if (mSentHoverEnter &&
1968 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1969 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1970 int32_t metaState = getContext()->getGlobalMetaState();
1971 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1972 mLastCookedState.buttonState, 0,
1973 mLastCookedState.cookedPointerData.pointerProperties,
1974 mLastCookedState.cookedPointerData.pointerCoords,
1975 mLastCookedState.cookedPointerData.idToIndex,
1976 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1977 mOrientedYPrecision, mDownTime);
1978 mSentHoverEnter = false;
1979 }
1980}
1981
1982void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1983 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1984 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1985 int32_t metaState = getContext()->getGlobalMetaState();
1986 if (!mSentHoverEnter) {
1987 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1988 metaState, mCurrentRawState.buttonState, 0,
1989 mCurrentCookedState.cookedPointerData.pointerProperties,
1990 mCurrentCookedState.cookedPointerData.pointerCoords,
1991 mCurrentCookedState.cookedPointerData.idToIndex,
1992 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1993 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1994 mSentHoverEnter = true;
1995 }
1996
1997 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1998 mCurrentRawState.buttonState, 0,
1999 mCurrentCookedState.cookedPointerData.pointerProperties,
2000 mCurrentCookedState.cookedPointerData.pointerCoords,
2001 mCurrentCookedState.cookedPointerData.idToIndex,
2002 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2003 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2004 }
2005}
2006
2007void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
2008 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2009 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2010 const int32_t metaState = getContext()->getGlobalMetaState();
2011 int32_t buttonState = mLastCookedState.buttonState;
2012 while (!releasedButtons.isEmpty()) {
2013 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2014 buttonState &= ~actionButton;
2015 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2016 actionButton, 0, metaState, buttonState, 0,
2017 mCurrentCookedState.cookedPointerData.pointerProperties,
2018 mCurrentCookedState.cookedPointerData.pointerCoords,
2019 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2020 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2021 }
2022}
2023
2024void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2025 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2026 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2027 const int32_t metaState = getContext()->getGlobalMetaState();
2028 int32_t buttonState = mLastCookedState.buttonState;
2029 while (!pressedButtons.isEmpty()) {
2030 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2031 buttonState |= actionButton;
2032 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2033 0, metaState, buttonState, 0,
2034 mCurrentCookedState.cookedPointerData.pointerProperties,
2035 mCurrentCookedState.cookedPointerData.pointerCoords,
2036 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2037 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2038 }
2039}
2040
2041const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2042 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2043 return cookedPointerData.touchingIdBits;
2044 }
2045 return cookedPointerData.hoveringIdBits;
2046}
2047
2048void TouchInputMapper::cookPointerData() {
2049 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2050
2051 mCurrentCookedState.cookedPointerData.clear();
2052 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2053 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2054 mCurrentRawState.rawPointerData.hoveringIdBits;
2055 mCurrentCookedState.cookedPointerData.touchingIdBits =
2056 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhung65600042020-04-30 17:55:40 +08002057 mCurrentCookedState.cookedPointerData.canceledIdBits =
2058 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002059
2060 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2061 mCurrentCookedState.buttonState = 0;
2062 } else {
2063 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2064 }
2065
2066 // Walk through the the active pointers and map device coordinates onto
2067 // surface coordinates and adjust for display orientation.
2068 for (uint32_t i = 0; i < currentPointerCount; i++) {
2069 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2070
2071 // Size
2072 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2073 switch (mCalibration.sizeCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002074 case Calibration::SizeCalibration::GEOMETRIC:
2075 case Calibration::SizeCalibration::DIAMETER:
2076 case Calibration::SizeCalibration::BOX:
2077 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002078 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2079 touchMajor = in.touchMajor;
2080 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2081 toolMajor = in.toolMajor;
2082 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2083 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2084 : in.touchMajor;
2085 } else if (mRawPointerAxes.touchMajor.valid) {
2086 toolMajor = touchMajor = in.touchMajor;
2087 toolMinor = touchMinor =
2088 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2089 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2090 : in.touchMajor;
2091 } else if (mRawPointerAxes.toolMajor.valid) {
2092 touchMajor = toolMajor = in.toolMajor;
2093 touchMinor = toolMinor =
2094 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2095 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2096 : in.toolMajor;
2097 } else {
2098 ALOG_ASSERT(false,
2099 "No touch or tool axes. "
2100 "Size calibration should have been resolved to NONE.");
2101 touchMajor = 0;
2102 touchMinor = 0;
2103 toolMajor = 0;
2104 toolMinor = 0;
2105 size = 0;
2106 }
2107
2108 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2109 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2110 if (touchingCount > 1) {
2111 touchMajor /= touchingCount;
2112 touchMinor /= touchingCount;
2113 toolMajor /= touchingCount;
2114 toolMinor /= touchingCount;
2115 size /= touchingCount;
2116 }
2117 }
2118
Michael Wrightaff169e2020-07-02 18:30:52 +01002119 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002120 touchMajor *= mGeometricScale;
2121 touchMinor *= mGeometricScale;
2122 toolMajor *= mGeometricScale;
2123 toolMinor *= mGeometricScale;
Michael Wrightaff169e2020-07-02 18:30:52 +01002124 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002125 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2126 touchMinor = touchMajor;
2127 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2128 toolMinor = toolMajor;
Michael Wrightaff169e2020-07-02 18:30:52 +01002129 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002130 touchMinor = touchMajor;
2131 toolMinor = toolMajor;
2132 }
2133
2134 mCalibration.applySizeScaleAndBias(&touchMajor);
2135 mCalibration.applySizeScaleAndBias(&touchMinor);
2136 mCalibration.applySizeScaleAndBias(&toolMajor);
2137 mCalibration.applySizeScaleAndBias(&toolMinor);
2138 size *= mSizeScale;
2139 break;
2140 default:
2141 touchMajor = 0;
2142 touchMinor = 0;
2143 toolMajor = 0;
2144 toolMinor = 0;
2145 size = 0;
2146 break;
2147 }
2148
2149 // Pressure
2150 float pressure;
2151 switch (mCalibration.pressureCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002152 case Calibration::PressureCalibration::PHYSICAL:
2153 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002154 pressure = in.pressure * mPressureScale;
2155 break;
2156 default:
2157 pressure = in.isHovering ? 0 : 1;
2158 break;
2159 }
2160
2161 // Tilt and Orientation
2162 float tilt;
2163 float orientation;
2164 if (mHaveTilt) {
2165 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2166 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2167 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2168 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2169 } else {
2170 tilt = 0;
2171
2172 switch (mCalibration.orientationCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002173 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002174 orientation = in.orientation * mOrientationScale;
2175 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002176 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002177 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2178 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2179 if (c1 != 0 || c2 != 0) {
2180 orientation = atan2f(c1, c2) * 0.5f;
2181 float confidence = hypotf(c1, c2);
2182 float scale = 1.0f + confidence / 16.0f;
2183 touchMajor *= scale;
2184 touchMinor /= scale;
2185 toolMajor *= scale;
2186 toolMinor /= scale;
2187 } else {
2188 orientation = 0;
2189 }
2190 break;
2191 }
2192 default:
2193 orientation = 0;
2194 }
2195 }
2196
2197 // Distance
2198 float distance;
2199 switch (mCalibration.distanceCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002200 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002201 distance = in.distance * mDistanceScale;
2202 break;
2203 default:
2204 distance = 0;
2205 }
2206
2207 // Coverage
2208 int32_t rawLeft, rawTop, rawRight, rawBottom;
2209 switch (mCalibration.coverageCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002210 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002211 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2212 rawRight = in.toolMinor & 0x0000ffff;
2213 rawBottom = in.toolMajor & 0x0000ffff;
2214 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2215 break;
2216 default:
2217 rawLeft = rawTop = rawRight = rawBottom = 0;
2218 break;
2219 }
2220
2221 // Adjust X,Y coords for device calibration
2222 // TODO: Adjust coverage coords?
2223 float xTransformed = in.x, yTransformed = in.y;
2224 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002225 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002226
2227 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002228 float left, top, right, bottom;
2229
2230 switch (mSurfaceOrientation) {
2231 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002232 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2233 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2234 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2235 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2236 orientation -= M_PI_2;
2237 if (mOrientedRanges.haveOrientation &&
2238 orientation < mOrientedRanges.orientation.min) {
2239 orientation +=
2240 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2241 }
2242 break;
2243 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002244 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2245 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2246 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2247 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2248 orientation -= M_PI;
2249 if (mOrientedRanges.haveOrientation &&
2250 orientation < mOrientedRanges.orientation.min) {
2251 orientation +=
2252 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2253 }
2254 break;
2255 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002256 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2257 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2258 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2259 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2260 orientation += M_PI_2;
2261 if (mOrientedRanges.haveOrientation &&
2262 orientation > mOrientedRanges.orientation.max) {
2263 orientation -=
2264 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2265 }
2266 break;
2267 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002268 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2269 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2270 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2271 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2272 break;
2273 }
2274
2275 // Write output coords.
2276 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2277 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002278 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2279 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002280 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2281 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2282 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2283 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2284 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2285 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2286 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wrightaff169e2020-07-02 18:30:52 +01002287 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002288 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2289 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2290 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2291 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2292 } else {
2293 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2294 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2295 }
2296
Chris Yedca44af2020-08-05 15:07:56 -07002297 // Write output relative fields if applicable.
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +00002298 uint32_t id = in.id;
2299 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2300 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2301 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2302 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2303 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2304 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2305 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2306 }
2307
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002308 // Write output properties.
2309 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002310 properties.clear();
2311 properties.id = id;
2312 properties.toolType = in.toolType;
2313
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +00002314 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +00002316 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002317 }
2318}
2319
2320void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2321 PointerUsage pointerUsage) {
2322 if (pointerUsage != mPointerUsage) {
2323 abortPointerUsage(when, policyFlags);
2324 mPointerUsage = pointerUsage;
2325 }
2326
2327 switch (mPointerUsage) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002328 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002329 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2330 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002331 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002332 dispatchPointerStylus(when, policyFlags);
2333 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002334 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002335 dispatchPointerMouse(when, policyFlags);
2336 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002337 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002338 break;
2339 }
2340}
2341
2342void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2343 switch (mPointerUsage) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002344 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002345 abortPointerGestures(when, policyFlags);
2346 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002347 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002348 abortPointerStylus(when, policyFlags);
2349 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002350 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 abortPointerMouse(when, policyFlags);
2352 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002353 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354 break;
2355 }
2356
Michael Wrightaff169e2020-07-02 18:30:52 +01002357 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358}
2359
2360void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2361 // Update current gesture coordinates.
2362 bool cancelPreviousGesture, finishPreviousGesture;
2363 bool sendEvents =
2364 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2365 if (!sendEvents) {
2366 return;
2367 }
2368 if (finishPreviousGesture) {
2369 cancelPreviousGesture = false;
2370 }
2371
2372 // Update the pointer presentation and spots.
Michael Wrightaff169e2020-07-02 18:30:52 +01002373 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wright976db0c2020-07-02 00:00:29 +01002374 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 if (finishPreviousGesture || cancelPreviousGesture) {
2376 mPointerController->clearSpots();
2377 }
2378
Michael Wrightaff169e2020-07-02 18:30:52 +01002379 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2381 mPointerGesture.currentGestureIdToIndex,
2382 mPointerGesture.currentGestureIdBits,
2383 mPointerController->getDisplayId());
2384 }
2385 } else {
Michael Wright976db0c2020-07-02 00:00:29 +01002386 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 }
2388
2389 // Show or hide the pointer if needed.
2390 switch (mPointerGesture.currentGestureMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002391 case PointerGesture::Mode::NEUTRAL:
2392 case PointerGesture::Mode::QUIET:
2393 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2394 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002395 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wright976db0c2020-07-02 00:00:29 +01002396 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 }
2398 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002399 case PointerGesture::Mode::TAP:
2400 case PointerGesture::Mode::TAP_DRAG:
2401 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2402 case PointerGesture::Mode::HOVER:
2403 case PointerGesture::Mode::PRESS:
2404 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405 // Unfade the pointer when the current gesture manipulates the
2406 // area directly under the pointer.
Michael Wright976db0c2020-07-02 00:00:29 +01002407 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002408 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002409 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 // Fade the pointer when the current gesture manipulates a different
2411 // area and there are spots to guide the user experience.
Michael Wrightaff169e2020-07-02 18:30:52 +01002412 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wright976db0c2020-07-02 00:00:29 +01002413 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002414 } else {
Michael Wright976db0c2020-07-02 00:00:29 +01002415 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002416 }
2417 break;
2418 }
2419
2420 // Send events!
2421 int32_t metaState = getContext()->getGlobalMetaState();
2422 int32_t buttonState = mCurrentCookedState.buttonState;
2423
2424 // Update last coordinates of pointers that have moved so that we observe the new
2425 // pointer positions at the same time as other pointers that have just gone up.
Michael Wrightaff169e2020-07-02 18:30:52 +01002426 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2427 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2428 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2429 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2430 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2431 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002432 bool moveNeeded = false;
2433 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2434 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2435 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2436 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2437 mPointerGesture.lastGestureIdBits.value);
2438 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2439 mPointerGesture.currentGestureCoords,
2440 mPointerGesture.currentGestureIdToIndex,
2441 mPointerGesture.lastGestureProperties,
2442 mPointerGesture.lastGestureCoords,
2443 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2444 if (buttonState != mLastCookedState.buttonState) {
2445 moveNeeded = true;
2446 }
2447 }
2448
2449 // Send motion events for all pointers that went up or were canceled.
2450 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2451 if (!dispatchedGestureIdBits.isEmpty()) {
2452 if (cancelPreviousGesture) {
2453 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2454 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2455 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2456 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2457 mPointerGesture.downTime);
2458
2459 dispatchedGestureIdBits.clear();
2460 } else {
2461 BitSet32 upGestureIdBits;
2462 if (finishPreviousGesture) {
2463 upGestureIdBits = dispatchedGestureIdBits;
2464 } else {
2465 upGestureIdBits.value =
2466 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2467 }
2468 while (!upGestureIdBits.isEmpty()) {
2469 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2470
2471 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2472 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2473 mPointerGesture.lastGestureProperties,
2474 mPointerGesture.lastGestureCoords,
2475 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2476 0, mPointerGesture.downTime);
2477
2478 dispatchedGestureIdBits.clearBit(id);
2479 }
2480 }
2481 }
2482
2483 // Send motion events for all pointers that moved.
2484 if (moveNeeded) {
2485 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2486 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2487 mPointerGesture.currentGestureProperties,
2488 mPointerGesture.currentGestureCoords,
2489 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2490 mPointerGesture.downTime);
2491 }
2492
2493 // Send motion events for all pointers that went down.
2494 if (down) {
2495 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2496 ~dispatchedGestureIdBits.value);
2497 while (!downGestureIdBits.isEmpty()) {
2498 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2499 dispatchedGestureIdBits.markBit(id);
2500
2501 if (dispatchedGestureIdBits.count() == 1) {
2502 mPointerGesture.downTime = when;
2503 }
2504
2505 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2506 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2507 mPointerGesture.currentGestureCoords,
2508 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2509 0, mPointerGesture.downTime);
2510 }
2511 }
2512
2513 // Send motion events for hover.
Michael Wrightaff169e2020-07-02 18:30:52 +01002514 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002515 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2516 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2517 mPointerGesture.currentGestureProperties,
2518 mPointerGesture.currentGestureCoords,
2519 mPointerGesture.currentGestureIdToIndex,
2520 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2521 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2522 // Synthesize a hover move event after all pointers go up to indicate that
2523 // the pointer is hovering again even if the user is not currently touching
2524 // the touch pad. This ensures that a view will receive a fresh hover enter
2525 // event after a tap.
2526 float x, y;
2527 mPointerController->getPosition(&x, &y);
2528
2529 PointerProperties pointerProperties;
2530 pointerProperties.clear();
2531 pointerProperties.id = 0;
2532 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2533
2534 PointerCoords pointerCoords;
2535 pointerCoords.clear();
2536 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2537 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2538
2539 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002540 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2541 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2542 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2543 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2544 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002545 getListener()->notifyMotion(&args);
2546 }
2547
2548 // Update state.
2549 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2550 if (!down) {
2551 mPointerGesture.lastGestureIdBits.clear();
2552 } else {
2553 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2554 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2555 uint32_t id = idBits.clearFirstMarkedBit();
2556 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2557 mPointerGesture.lastGestureProperties[index].copyFrom(
2558 mPointerGesture.currentGestureProperties[index]);
2559 mPointerGesture.lastGestureCoords[index].copyFrom(
2560 mPointerGesture.currentGestureCoords[index]);
2561 mPointerGesture.lastGestureIdToIndex[id] = index;
2562 }
2563 }
2564}
2565
2566void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2567 // Cancel previously dispatches pointers.
2568 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2569 int32_t metaState = getContext()->getGlobalMetaState();
2570 int32_t buttonState = mCurrentRawState.buttonState;
2571 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2572 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2573 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2574 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2575 0, 0, mPointerGesture.downTime);
2576 }
2577
2578 // Reset the current pointer gesture.
2579 mPointerGesture.reset();
2580 mPointerVelocityControl.reset();
2581
2582 // Remove any current spots.
2583 if (mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01002584 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002585 mPointerController->clearSpots();
2586 }
2587}
2588
2589bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2590 bool* outFinishPreviousGesture, bool isTimeout) {
2591 *outCancelPreviousGesture = false;
2592 *outFinishPreviousGesture = false;
2593
2594 // Handle TAP timeout.
2595 if (isTimeout) {
2596#if DEBUG_GESTURES
2597 ALOGD("Gestures: Processing timeout");
2598#endif
2599
Michael Wrightaff169e2020-07-02 18:30:52 +01002600 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002601 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2602 // The tap/drag timeout has not yet expired.
2603 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2604 mConfig.pointerGestureTapDragInterval);
2605 } else {
2606 // The tap is finished.
2607#if DEBUG_GESTURES
2608 ALOGD("Gestures: TAP finished");
2609#endif
2610 *outFinishPreviousGesture = true;
2611
2612 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002613 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002614 mPointerGesture.currentGestureIdBits.clear();
2615
2616 mPointerVelocityControl.reset();
2617 return true;
2618 }
2619 }
2620
2621 // We did not handle this timeout.
2622 return false;
2623 }
2624
2625 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2626 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2627
2628 // Update the velocity tracker.
2629 {
2630 VelocityTracker::Position positions[MAX_POINTERS];
2631 uint32_t count = 0;
2632 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
2633 uint32_t id = idBits.clearFirstMarkedBit();
2634 const RawPointerData::Pointer& pointer =
2635 mCurrentRawState.rawPointerData.pointerForId(id);
2636 positions[count].x = pointer.x * mPointerXMovementScale;
2637 positions[count].y = pointer.y * mPointerYMovementScale;
2638 }
2639 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2640 positions);
2641 }
2642
2643 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2644 // to NEUTRAL, then we should not generate tap event.
Michael Wrightaff169e2020-07-02 18:30:52 +01002645 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2646 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2647 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002648 mPointerGesture.resetTap();
2649 }
2650
2651 // Pick a new active touch id if needed.
2652 // Choose an arbitrary pointer that just went down, if there is one.
2653 // Otherwise choose an arbitrary remaining pointer.
2654 // This guarantees we always have an active touch id when there is at least one pointer.
2655 // We keep the same active touch id for as long as possible.
2656 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2657 int32_t activeTouchId = lastActiveTouchId;
2658 if (activeTouchId < 0) {
2659 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2660 activeTouchId = mPointerGesture.activeTouchId =
2661 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2662 mPointerGesture.firstTouchTime = when;
2663 }
2664 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2665 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2666 activeTouchId = mPointerGesture.activeTouchId =
2667 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2668 } else {
2669 activeTouchId = mPointerGesture.activeTouchId = -1;
2670 }
2671 }
2672
2673 // Determine whether we are in quiet time.
2674 bool isQuietTime = false;
2675 if (activeTouchId < 0) {
2676 mPointerGesture.resetQuietTime();
2677 } else {
2678 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2679 if (!isQuietTime) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002680 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2681 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2682 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002683 currentFingerCount < 2) {
2684 // Enter quiet time when exiting swipe or freeform state.
2685 // This is to prevent accidentally entering the hover state and flinging the
2686 // pointer when finishing a swipe and there is still one pointer left onscreen.
2687 isQuietTime = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01002688 } else if (mPointerGesture.lastGestureMode ==
2689 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002690 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2691 // Enter quiet time when releasing the button and there are still two or more
2692 // fingers down. This may indicate that one finger was used to press the button
2693 // but it has not gone up yet.
2694 isQuietTime = true;
2695 }
2696 if (isQuietTime) {
2697 mPointerGesture.quietTime = when;
2698 }
2699 }
2700 }
2701
2702 // Switch states based on button and pointer state.
2703 if (isQuietTime) {
2704 // Case 1: Quiet time. (QUIET)
2705#if DEBUG_GESTURES
2706 ALOGD("Gestures: QUIET for next %0.3fms",
2707 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2708#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01002709 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002710 *outFinishPreviousGesture = true;
2711 }
2712
2713 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002714 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002715 mPointerGesture.currentGestureIdBits.clear();
2716
2717 mPointerVelocityControl.reset();
2718 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2719 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2720 // The pointer follows the active touch point.
2721 // Emit DOWN, MOVE, UP events at the pointer location.
2722 //
2723 // Only the active touch matters; other fingers are ignored. This policy helps
2724 // to handle the case where the user places a second finger on the touch pad
2725 // to apply the necessary force to depress an integrated button below the surface.
2726 // We don't want the second finger to be delivered to applications.
2727 //
2728 // For this to work well, we need to make sure to track the pointer that is really
2729 // active. If the user first puts one finger down to click then adds another
2730 // finger to drag then the active pointer should switch to the finger that is
2731 // being dragged.
2732#if DEBUG_GESTURES
2733 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2734 "currentFingerCount=%d",
2735 activeTouchId, currentFingerCount);
2736#endif
2737 // Reset state when just starting.
Michael Wrightaff169e2020-07-02 18:30:52 +01002738 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002739 *outFinishPreviousGesture = true;
2740 mPointerGesture.activeGestureId = 0;
2741 }
2742
2743 // Switch pointers if needed.
2744 // Find the fastest pointer and follow it.
2745 if (activeTouchId >= 0 && currentFingerCount > 1) {
2746 int32_t bestId = -1;
2747 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2748 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2749 uint32_t id = idBits.clearFirstMarkedBit();
2750 float vx, vy;
2751 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2752 float speed = hypotf(vx, vy);
2753 if (speed > bestSpeed) {
2754 bestId = id;
2755 bestSpeed = speed;
2756 }
2757 }
2758 }
2759 if (bestId >= 0 && bestId != activeTouchId) {
2760 mPointerGesture.activeTouchId = activeTouchId = bestId;
2761#if DEBUG_GESTURES
2762 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2763 "bestId=%d, bestSpeed=%0.3f",
2764 bestId, bestSpeed);
2765#endif
2766 }
2767 }
2768
2769 float deltaX = 0, deltaY = 0;
2770 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2771 const RawPointerData::Pointer& currentPointer =
2772 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2773 const RawPointerData::Pointer& lastPointer =
2774 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2775 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2776 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2777
2778 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2779 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2780
2781 // Move the pointer using a relative motion.
2782 // When using spots, the click will occur at the position of the anchor
2783 // spot and all other spots will move there.
2784 mPointerController->move(deltaX, deltaY);
2785 } else {
2786 mPointerVelocityControl.reset();
2787 }
2788
2789 float x, y;
2790 mPointerController->getPosition(&x, &y);
2791
Michael Wrightaff169e2020-07-02 18:30:52 +01002792 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002793 mPointerGesture.currentGestureIdBits.clear();
2794 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2795 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2796 mPointerGesture.currentGestureProperties[0].clear();
2797 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2798 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2799 mPointerGesture.currentGestureCoords[0].clear();
2800 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2801 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2802 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2803 } else if (currentFingerCount == 0) {
2804 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wrightaff169e2020-07-02 18:30:52 +01002805 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806 *outFinishPreviousGesture = true;
2807 }
2808
2809 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2810 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2811 bool tapped = false;
Michael Wrightaff169e2020-07-02 18:30:52 +01002812 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2813 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002814 lastFingerCount == 1) {
2815 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2816 float x, y;
2817 mPointerController->getPosition(&x, &y);
2818 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2819 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2820#if DEBUG_GESTURES
2821 ALOGD("Gestures: TAP");
2822#endif
2823
2824 mPointerGesture.tapUpTime = when;
2825 getContext()->requestTimeoutAtTime(when +
2826 mConfig.pointerGestureTapDragInterval);
2827
2828 mPointerGesture.activeGestureId = 0;
Michael Wrightaff169e2020-07-02 18:30:52 +01002829 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 mPointerGesture.currentGestureIdBits.clear();
2831 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2832 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2833 mPointerGesture.currentGestureProperties[0].clear();
2834 mPointerGesture.currentGestureProperties[0].id =
2835 mPointerGesture.activeGestureId;
2836 mPointerGesture.currentGestureProperties[0].toolType =
2837 AMOTION_EVENT_TOOL_TYPE_FINGER;
2838 mPointerGesture.currentGestureCoords[0].clear();
2839 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2840 mPointerGesture.tapX);
2841 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2842 mPointerGesture.tapY);
2843 mPointerGesture.currentGestureCoords[0]
2844 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2845
2846 tapped = true;
2847 } else {
2848#if DEBUG_GESTURES
2849 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2850 y - mPointerGesture.tapY);
2851#endif
2852 }
2853 } else {
2854#if DEBUG_GESTURES
2855 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2856 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2857 (when - mPointerGesture.tapDownTime) * 0.000001f);
2858 } else {
2859 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2860 }
2861#endif
2862 }
2863 }
2864
2865 mPointerVelocityControl.reset();
2866
2867 if (!tapped) {
2868#if DEBUG_GESTURES
2869 ALOGD("Gestures: NEUTRAL");
2870#endif
2871 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002872 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002873 mPointerGesture.currentGestureIdBits.clear();
2874 }
2875 } else if (currentFingerCount == 1) {
2876 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2877 // The pointer follows the active touch point.
2878 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2879 // When in TAP_DRAG, emit MOVE events at the pointer location.
2880 ALOG_ASSERT(activeTouchId >= 0);
2881
Michael Wrightaff169e2020-07-02 18:30:52 +01002882 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2883 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2885 float x, y;
2886 mPointerController->getPosition(&x, &y);
2887 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2888 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002889 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002890 } else {
2891#if DEBUG_GESTURES
2892 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2893 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2894#endif
2895 }
2896 } else {
2897#if DEBUG_GESTURES
2898 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2899 (when - mPointerGesture.tapUpTime) * 0.000001f);
2900#endif
2901 }
Michael Wrightaff169e2020-07-02 18:30:52 +01002902 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2903 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002904 }
2905
2906 float deltaX = 0, deltaY = 0;
2907 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2908 const RawPointerData::Pointer& currentPointer =
2909 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2910 const RawPointerData::Pointer& lastPointer =
2911 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2912 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2913 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2914
2915 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2916 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2917
2918 // Move the pointer using a relative motion.
2919 // When using spots, the hover or drag will occur at the position of the anchor spot.
2920 mPointerController->move(deltaX, deltaY);
2921 } else {
2922 mPointerVelocityControl.reset();
2923 }
2924
2925 bool down;
Michael Wrightaff169e2020-07-02 18:30:52 +01002926 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002927#if DEBUG_GESTURES
2928 ALOGD("Gestures: TAP_DRAG");
2929#endif
2930 down = true;
2931 } else {
2932#if DEBUG_GESTURES
2933 ALOGD("Gestures: HOVER");
2934#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01002935 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002936 *outFinishPreviousGesture = true;
2937 }
2938 mPointerGesture.activeGestureId = 0;
2939 down = false;
2940 }
2941
2942 float x, y;
2943 mPointerController->getPosition(&x, &y);
2944
2945 mPointerGesture.currentGestureIdBits.clear();
2946 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2947 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2948 mPointerGesture.currentGestureProperties[0].clear();
2949 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2950 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2951 mPointerGesture.currentGestureCoords[0].clear();
2952 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2953 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2954 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2955 down ? 1.0f : 0.0f);
2956
2957 if (lastFingerCount == 0 && currentFingerCount != 0) {
2958 mPointerGesture.resetTap();
2959 mPointerGesture.tapDownTime = when;
2960 mPointerGesture.tapX = x;
2961 mPointerGesture.tapY = y;
2962 }
2963 } else {
2964 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2965 // We need to provide feedback for each finger that goes down so we cannot wait
2966 // for the fingers to move before deciding what to do.
2967 //
2968 // The ambiguous case is deciding what to do when there are two fingers down but they
2969 // have not moved enough to determine whether they are part of a drag or part of a
2970 // freeform gesture, or just a press or long-press at the pointer location.
2971 //
2972 // When there are two fingers we start with the PRESS hypothesis and we generate a
2973 // down at the pointer location.
2974 //
2975 // When the two fingers move enough or when additional fingers are added, we make
2976 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2977 ALOG_ASSERT(activeTouchId >= 0);
2978
2979 bool settled = when >=
2980 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wrightaff169e2020-07-02 18:30:52 +01002981 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2982 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2983 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002984 *outFinishPreviousGesture = true;
2985 } else if (!settled && currentFingerCount > lastFingerCount) {
2986 // Additional pointers have gone down but not yet settled.
2987 // Reset the gesture.
2988#if DEBUG_GESTURES
2989 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2990 "settle time remaining %0.3fms",
2991 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2992 when) * 0.000001f);
2993#endif
2994 *outCancelPreviousGesture = true;
2995 } else {
2996 // Continue previous gesture.
2997 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2998 }
2999
3000 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wrightaff169e2020-07-02 18:30:52 +01003001 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003002 mPointerGesture.activeGestureId = 0;
3003 mPointerGesture.referenceIdBits.clear();
3004 mPointerVelocityControl.reset();
3005
3006 // Use the centroid and pointer location as the reference points for the gesture.
3007#if DEBUG_GESTURES
3008 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3009 "settle time remaining %0.3fms",
3010 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3011 when) * 0.000001f);
3012#endif
3013 mCurrentRawState.rawPointerData
3014 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3015 &mPointerGesture.referenceTouchY);
3016 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3017 &mPointerGesture.referenceGestureY);
3018 }
3019
3020 // Clear the reference deltas for fingers not yet included in the reference calculation.
3021 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3022 ~mPointerGesture.referenceIdBits.value);
3023 !idBits.isEmpty();) {
3024 uint32_t id = idBits.clearFirstMarkedBit();
3025 mPointerGesture.referenceDeltas[id].dx = 0;
3026 mPointerGesture.referenceDeltas[id].dy = 0;
3027 }
3028 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3029
3030 // Add delta for all fingers and calculate a common movement delta.
3031 float commonDeltaX = 0, commonDeltaY = 0;
3032 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3033 mCurrentCookedState.fingerIdBits.value);
3034 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3035 bool first = (idBits == commonIdBits);
3036 uint32_t id = idBits.clearFirstMarkedBit();
3037 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3038 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3039 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3040 delta.dx += cpd.x - lpd.x;
3041 delta.dy += cpd.y - lpd.y;
3042
3043 if (first) {
3044 commonDeltaX = delta.dx;
3045 commonDeltaY = delta.dy;
3046 } else {
3047 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3048 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3049 }
3050 }
3051
3052 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wrightaff169e2020-07-02 18:30:52 +01003053 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003054 float dist[MAX_POINTER_ID + 1];
3055 int32_t distOverThreshold = 0;
3056 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3057 uint32_t id = idBits.clearFirstMarkedBit();
3058 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3059 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3060 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3061 distOverThreshold += 1;
3062 }
3063 }
3064
3065 // Only transition when at least two pointers have moved further than
3066 // the minimum distance threshold.
3067 if (distOverThreshold >= 2) {
3068 if (currentFingerCount > 2) {
3069 // There are more than two pointers, switch to FREEFORM.
3070#if DEBUG_GESTURES
3071 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3072 currentFingerCount);
3073#endif
3074 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003075 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003076 } else {
3077 // There are exactly two pointers.
3078 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3079 uint32_t id1 = idBits.clearFirstMarkedBit();
3080 uint32_t id2 = idBits.firstMarkedBit();
3081 const RawPointerData::Pointer& p1 =
3082 mCurrentRawState.rawPointerData.pointerForId(id1);
3083 const RawPointerData::Pointer& p2 =
3084 mCurrentRawState.rawPointerData.pointerForId(id2);
3085 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3086 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3087 // There are two pointers but they are too far apart for a SWIPE,
3088 // switch to FREEFORM.
3089#if DEBUG_GESTURES
3090 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3091 mutualDistance, mPointerGestureMaxSwipeWidth);
3092#endif
3093 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003094 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003095 } else {
3096 // There are two pointers. Wait for both pointers to start moving
3097 // before deciding whether this is a SWIPE or FREEFORM gesture.
3098 float dist1 = dist[id1];
3099 float dist2 = dist[id2];
3100 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3101 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3102 // Calculate the dot product of the displacement vectors.
3103 // When the vectors are oriented in approximately the same direction,
3104 // the angle betweeen them is near zero and the cosine of the angle
3105 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3106 // mag(v2).
3107 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3108 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3109 float dx1 = delta1.dx * mPointerXZoomScale;
3110 float dy1 = delta1.dy * mPointerYZoomScale;
3111 float dx2 = delta2.dx * mPointerXZoomScale;
3112 float dy2 = delta2.dy * mPointerYZoomScale;
3113 float dot = dx1 * dx2 + dy1 * dy2;
3114 float cosine = dot / (dist1 * dist2); // denominator always > 0
3115 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3116 // Pointers are moving in the same direction. Switch to SWIPE.
3117#if DEBUG_GESTURES
3118 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3119 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3120 "cosine %0.3f >= %0.3f",
3121 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3122 mConfig.pointerGestureMultitouchMinDistance, cosine,
3123 mConfig.pointerGestureSwipeTransitionAngleCosine);
3124#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01003125 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003126 } else {
3127 // Pointers are moving in different directions. Switch to FREEFORM.
3128#if DEBUG_GESTURES
3129 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3130 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3131 "cosine %0.3f < %0.3f",
3132 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3133 mConfig.pointerGestureMultitouchMinDistance, cosine,
3134 mConfig.pointerGestureSwipeTransitionAngleCosine);
3135#endif
3136 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003137 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003138 }
3139 }
3140 }
3141 }
3142 }
Michael Wrightaff169e2020-07-02 18:30:52 +01003143 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003144 // Switch from SWIPE to FREEFORM if additional pointers go down.
3145 // Cancel previous gesture.
3146 if (currentFingerCount > 2) {
3147#if DEBUG_GESTURES
3148 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3149 currentFingerCount);
3150#endif
3151 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003152 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003153 }
3154 }
3155
3156 // Move the reference points based on the overall group motion of the fingers
3157 // except in PRESS mode while waiting for a transition to occur.
Michael Wrightaff169e2020-07-02 18:30:52 +01003158 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003159 (commonDeltaX || commonDeltaY)) {
3160 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3161 uint32_t id = idBits.clearFirstMarkedBit();
3162 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3163 delta.dx = 0;
3164 delta.dy = 0;
3165 }
3166
3167 mPointerGesture.referenceTouchX += commonDeltaX;
3168 mPointerGesture.referenceTouchY += commonDeltaY;
3169
3170 commonDeltaX *= mPointerXMovementScale;
3171 commonDeltaY *= mPointerYMovementScale;
3172
3173 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3174 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3175
3176 mPointerGesture.referenceGestureX += commonDeltaX;
3177 mPointerGesture.referenceGestureY += commonDeltaY;
3178 }
3179
3180 // Report gestures.
Michael Wrightaff169e2020-07-02 18:30:52 +01003181 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3182 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003183 // PRESS or SWIPE mode.
3184#if DEBUG_GESTURES
3185 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3186 "activeGestureId=%d, currentTouchPointerCount=%d",
3187 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3188#endif
3189 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3190
3191 mPointerGesture.currentGestureIdBits.clear();
3192 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3193 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3194 mPointerGesture.currentGestureProperties[0].clear();
3195 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3196 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3197 mPointerGesture.currentGestureCoords[0].clear();
3198 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3199 mPointerGesture.referenceGestureX);
3200 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3201 mPointerGesture.referenceGestureY);
3202 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wrightaff169e2020-07-02 18:30:52 +01003203 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003204 // FREEFORM mode.
3205#if DEBUG_GESTURES
3206 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3207 "activeGestureId=%d, currentTouchPointerCount=%d",
3208 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3209#endif
3210 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3211
3212 mPointerGesture.currentGestureIdBits.clear();
3213
3214 BitSet32 mappedTouchIdBits;
3215 BitSet32 usedGestureIdBits;
Michael Wrightaff169e2020-07-02 18:30:52 +01003216 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003217 // Initially, assign the active gesture id to the active touch point
3218 // if there is one. No other touch id bits are mapped yet.
3219 if (!*outCancelPreviousGesture) {
3220 mappedTouchIdBits.markBit(activeTouchId);
3221 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3222 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3223 mPointerGesture.activeGestureId;
3224 } else {
3225 mPointerGesture.activeGestureId = -1;
3226 }
3227 } else {
3228 // Otherwise, assume we mapped all touches from the previous frame.
3229 // Reuse all mappings that are still applicable.
3230 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3231 mCurrentCookedState.fingerIdBits.value;
3232 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3233
3234 // Check whether we need to choose a new active gesture id because the
3235 // current went went up.
3236 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3237 ~mCurrentCookedState.fingerIdBits.value);
3238 !upTouchIdBits.isEmpty();) {
3239 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3240 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3241 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3242 mPointerGesture.activeGestureId = -1;
3243 break;
3244 }
3245 }
3246 }
3247
3248#if DEBUG_GESTURES
3249 ALOGD("Gestures: FREEFORM follow up "
3250 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3251 "activeGestureId=%d",
3252 mappedTouchIdBits.value, usedGestureIdBits.value,
3253 mPointerGesture.activeGestureId);
3254#endif
3255
3256 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3257 for (uint32_t i = 0; i < currentFingerCount; i++) {
3258 uint32_t touchId = idBits.clearFirstMarkedBit();
3259 uint32_t gestureId;
3260 if (!mappedTouchIdBits.hasBit(touchId)) {
3261 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3262 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3263#if DEBUG_GESTURES
3264 ALOGD("Gestures: FREEFORM "
3265 "new mapping for touch id %d -> gesture id %d",
3266 touchId, gestureId);
3267#endif
3268 } else {
3269 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3270#if DEBUG_GESTURES
3271 ALOGD("Gestures: FREEFORM "
3272 "existing mapping for touch id %d -> gesture id %d",
3273 touchId, gestureId);
3274#endif
3275 }
3276 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3277 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3278
3279 const RawPointerData::Pointer& pointer =
3280 mCurrentRawState.rawPointerData.pointerForId(touchId);
3281 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3282 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3283 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3284
3285 mPointerGesture.currentGestureProperties[i].clear();
3286 mPointerGesture.currentGestureProperties[i].id = gestureId;
3287 mPointerGesture.currentGestureProperties[i].toolType =
3288 AMOTION_EVENT_TOOL_TYPE_FINGER;
3289 mPointerGesture.currentGestureCoords[i].clear();
3290 mPointerGesture.currentGestureCoords[i]
3291 .setAxisValue(AMOTION_EVENT_AXIS_X,
3292 mPointerGesture.referenceGestureX + deltaX);
3293 mPointerGesture.currentGestureCoords[i]
3294 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3295 mPointerGesture.referenceGestureY + deltaY);
3296 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3297 1.0f);
3298 }
3299
3300 if (mPointerGesture.activeGestureId < 0) {
3301 mPointerGesture.activeGestureId =
3302 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3303#if DEBUG_GESTURES
3304 ALOGD("Gestures: FREEFORM new "
3305 "activeGestureId=%d",
3306 mPointerGesture.activeGestureId);
3307#endif
3308 }
3309 }
3310 }
3311
3312 mPointerController->setButtonState(mCurrentRawState.buttonState);
3313
3314#if DEBUG_GESTURES
3315 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3316 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3317 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3318 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3319 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3320 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3321 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3322 uint32_t id = idBits.clearFirstMarkedBit();
3323 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3324 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3325 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3326 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3327 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3328 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3329 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3330 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3331 }
3332 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3333 uint32_t id = idBits.clearFirstMarkedBit();
3334 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3335 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3336 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3337 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3338 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3339 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3340 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3341 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3342 }
3343#endif
3344 return true;
3345}
3346
3347void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3348 mPointerSimple.currentCoords.clear();
3349 mPointerSimple.currentProperties.clear();
3350
3351 bool down, hovering;
3352 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3353 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3354 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3355 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3356 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3357 mPointerController->setPosition(x, y);
3358
3359 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3360 down = !hovering;
3361
3362 mPointerController->getPosition(&x, &y);
3363 mPointerSimple.currentCoords.copyFrom(
3364 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3365 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3366 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3367 mPointerSimple.currentProperties.id = 0;
3368 mPointerSimple.currentProperties.toolType =
3369 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3370 } else {
3371 down = false;
3372 hovering = false;
3373 }
3374
3375 dispatchPointerSimple(when, policyFlags, down, hovering);
3376}
3377
3378void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3379 abortPointerSimple(when, policyFlags);
3380}
3381
3382void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3383 mPointerSimple.currentCoords.clear();
3384 mPointerSimple.currentProperties.clear();
3385
3386 bool down, hovering;
3387 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3388 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3389 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3390 float deltaX = 0, deltaY = 0;
3391 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3392 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3393 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3394 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3395 mPointerXMovementScale;
3396 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3397 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3398 mPointerYMovementScale;
3399
3400 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3401 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3402
3403 mPointerController->move(deltaX, deltaY);
3404 } else {
3405 mPointerVelocityControl.reset();
3406 }
3407
3408 down = isPointerDown(mCurrentRawState.buttonState);
3409 hovering = !down;
3410
3411 float x, y;
3412 mPointerController->getPosition(&x, &y);
3413 mPointerSimple.currentCoords.copyFrom(
3414 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3415 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3416 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3417 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3418 hovering ? 0.0f : 1.0f);
3419 mPointerSimple.currentProperties.id = 0;
3420 mPointerSimple.currentProperties.toolType =
3421 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3422 } else {
3423 mPointerVelocityControl.reset();
3424
3425 down = false;
3426 hovering = false;
3427 }
3428
3429 dispatchPointerSimple(when, policyFlags, down, hovering);
3430}
3431
3432void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3433 abortPointerSimple(when, policyFlags);
3434
3435 mPointerVelocityControl.reset();
3436}
3437
3438void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3439 bool hovering) {
3440 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003441
3442 if (down || hovering) {
Michael Wright976db0c2020-07-02 00:00:29 +01003443 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003444 mPointerController->clearSpots();
3445 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wright976db0c2020-07-02 00:00:29 +01003446 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003447 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wright976db0c2020-07-02 00:00:29 +01003448 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003449 }
Garfield Tan9514d782020-11-10 16:37:23 -08003450 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003451
3452 float xCursorPosition;
3453 float yCursorPosition;
3454 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3455
3456 if (mPointerSimple.down && !down) {
3457 mPointerSimple.down = false;
3458
3459 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003460 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3461 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003462 mLastRawState.buttonState, MotionClassification::NONE,
3463 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3464 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3465 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3466 /* videoFrames */ {});
3467 getListener()->notifyMotion(&args);
3468 }
3469
3470 if (mPointerSimple.hovering && !hovering) {
3471 mPointerSimple.hovering = false;
3472
3473 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003474 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3475 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3476 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003477 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3478 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3479 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3480 /* videoFrames */ {});
3481 getListener()->notifyMotion(&args);
3482 }
3483
3484 if (down) {
3485 if (!mPointerSimple.down) {
3486 mPointerSimple.down = true;
3487 mPointerSimple.downTime = when;
3488
3489 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003490 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003491 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3492 metaState, mCurrentRawState.buttonState,
3493 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3494 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3495 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3496 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3497 getListener()->notifyMotion(&args);
3498 }
3499
3500 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003501 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3502 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003503 mCurrentRawState.buttonState, MotionClassification::NONE,
3504 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3505 &mPointerSimple.currentCoords, mOrientedXPrecision,
3506 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3507 mPointerSimple.downTime, /* videoFrames */ {});
3508 getListener()->notifyMotion(&args);
3509 }
3510
3511 if (hovering) {
3512 if (!mPointerSimple.hovering) {
3513 mPointerSimple.hovering = true;
3514
3515 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003516 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003517 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3518 metaState, mCurrentRawState.buttonState,
3519 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3520 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3521 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3522 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3523 getListener()->notifyMotion(&args);
3524 }
3525
3526 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003527 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3528 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3529 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003530 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3531 &mPointerSimple.currentCoords, mOrientedXPrecision,
3532 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3533 mPointerSimple.downTime, /* videoFrames */ {});
3534 getListener()->notifyMotion(&args);
3535 }
3536
3537 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3538 float vscroll = mCurrentRawState.rawVScroll;
3539 float hscroll = mCurrentRawState.rawHScroll;
3540 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3541 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3542
3543 // Send scroll.
3544 PointerCoords pointerCoords;
3545 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3546 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3547 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3548
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003549 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3550 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003551 mCurrentRawState.buttonState, MotionClassification::NONE,
3552 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3553 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3554 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3555 /* videoFrames */ {});
3556 getListener()->notifyMotion(&args);
3557 }
3558
3559 // Save state.
3560 if (down || hovering) {
3561 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3562 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3563 } else {
3564 mPointerSimple.reset();
3565 }
3566}
3567
3568void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3569 mPointerSimple.currentCoords.clear();
3570 mPointerSimple.currentProperties.clear();
3571
3572 dispatchPointerSimple(when, policyFlags, false, false);
3573}
3574
3575void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3576 int32_t action, int32_t actionButton, int32_t flags,
3577 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3578 const PointerProperties* properties,
3579 const PointerCoords* coords, const uint32_t* idToIndex,
3580 BitSet32 idBits, int32_t changedId, float xPrecision,
3581 float yPrecision, nsecs_t downTime) {
3582 PointerCoords pointerCoords[MAX_POINTERS];
3583 PointerProperties pointerProperties[MAX_POINTERS];
3584 uint32_t pointerCount = 0;
3585 while (!idBits.isEmpty()) {
3586 uint32_t id = idBits.clearFirstMarkedBit();
3587 uint32_t index = idToIndex[id];
3588 pointerProperties[pointerCount].copyFrom(properties[index]);
3589 pointerCoords[pointerCount].copyFrom(coords[index]);
3590
3591 if (changedId >= 0 && id == uint32_t(changedId)) {
3592 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3593 }
3594
3595 pointerCount += 1;
3596 }
3597
3598 ALOG_ASSERT(pointerCount != 0);
3599
3600 if (changedId >= 0 && pointerCount == 1) {
3601 // Replace initial down and final up action.
3602 // We can compare the action without masking off the changed pointer index
3603 // because we know the index is 0.
3604 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3605 action = AMOTION_EVENT_ACTION_DOWN;
3606 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhung65600042020-04-30 17:55:40 +08003607 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3608 action = AMOTION_EVENT_ACTION_CANCEL;
3609 } else {
3610 action = AMOTION_EVENT_ACTION_UP;
3611 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003612 } else {
3613 // Can't happen.
3614 ALOG_ASSERT(false);
3615 }
3616 }
3617 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3618 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wrightaff169e2020-07-02 18:30:52 +01003619 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003620 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3621 }
3622 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3623 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003624 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003625 std::for_each(frames.begin(), frames.end(),
3626 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003627 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3628 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003629 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3630 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3631 downTime, std::move(frames));
3632 getListener()->notifyMotion(&args);
3633}
3634
3635bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3636 const PointerCoords* inCoords,
3637 const uint32_t* inIdToIndex,
3638 PointerProperties* outProperties,
3639 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3640 BitSet32 idBits) const {
3641 bool changed = false;
3642 while (!idBits.isEmpty()) {
3643 uint32_t id = idBits.clearFirstMarkedBit();
3644 uint32_t inIndex = inIdToIndex[id];
3645 uint32_t outIndex = outIdToIndex[id];
3646
3647 const PointerProperties& curInProperties = inProperties[inIndex];
3648 const PointerCoords& curInCoords = inCoords[inIndex];
3649 PointerProperties& curOutProperties = outProperties[outIndex];
3650 PointerCoords& curOutCoords = outCoords[outIndex];
3651
3652 if (curInProperties != curOutProperties) {
3653 curOutProperties.copyFrom(curInProperties);
3654 changed = true;
3655 }
3656
3657 if (curInCoords != curOutCoords) {
3658 curOutCoords.copyFrom(curInCoords);
3659 changed = true;
3660 }
3661 }
3662 return changed;
3663}
3664
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003665void TouchInputMapper::cancelTouch(nsecs_t when) {
3666 abortPointerUsage(when, 0 /*policyFlags*/);
3667 abortTouches(when, 0 /* policyFlags*/);
3668}
3669
Arthur Hung4197f6b2020-03-16 15:39:59 +08003670// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003671void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003672 // Scale to surface coordinate.
3673 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3674 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3675
arthurhung10052f62020-12-29 20:28:15 +08003676 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3677 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3678
Arthur Hung4197f6b2020-03-16 15:39:59 +08003679 // Rotate to surface coordinate.
3680 // 0 - no swap and reverse.
3681 // 90 - swap x/y and reverse y.
3682 // 180 - reverse x, y.
3683 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003684 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003685 case DISPLAY_ORIENTATION_0:
3686 x = xScaled + mXTranslate;
3687 y = yScaled + mYTranslate;
3688 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003689 case DISPLAY_ORIENTATION_90:
arthurhung10052f62020-12-29 20:28:15 +08003690 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003691 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003692 break;
3693 case DISPLAY_ORIENTATION_180:
arthurhung10052f62020-12-29 20:28:15 +08003694 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3695 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003696 break;
3697 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003698 y = xScaled + mXTranslate;
arthurhung10052f62020-12-29 20:28:15 +08003699 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003700 break;
3701 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003702 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003703 }
3704}
3705
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003706bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003707 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3708 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3709
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003710 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003711 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003712 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003713 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003714}
3715
3716const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3717 for (const VirtualKey& virtualKey : mVirtualKeys) {
3718#if DEBUG_VIRTUAL_KEYS
3719 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3720 "left=%d, top=%d, right=%d, bottom=%d",
3721 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3722 virtualKey.hitRight, virtualKey.hitBottom);
3723#endif
3724
3725 if (virtualKey.isHit(x, y)) {
3726 return &virtualKey;
3727 }
3728 }
3729
3730 return nullptr;
3731}
3732
3733void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3734 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3735 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3736
3737 current->rawPointerData.clearIdBits();
3738
3739 if (currentPointerCount == 0) {
3740 // No pointers to assign.
3741 return;
3742 }
3743
3744 if (lastPointerCount == 0) {
3745 // All pointers are new.
3746 for (uint32_t i = 0; i < currentPointerCount; i++) {
3747 uint32_t id = i;
3748 current->rawPointerData.pointers[i].id = id;
3749 current->rawPointerData.idToIndex[id] = i;
3750 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3751 }
3752 return;
3753 }
3754
3755 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3756 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3757 // Only one pointer and no change in count so it must have the same id as before.
3758 uint32_t id = last->rawPointerData.pointers[0].id;
3759 current->rawPointerData.pointers[0].id = id;
3760 current->rawPointerData.idToIndex[id] = 0;
3761 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3762 return;
3763 }
3764
3765 // General case.
3766 // We build a heap of squared euclidean distances between current and last pointers
3767 // associated with the current and last pointer indices. Then, we find the best
3768 // match (by distance) for each current pointer.
3769 // The pointers must have the same tool type but it is possible for them to
3770 // transition from hovering to touching or vice-versa while retaining the same id.
3771 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3772
3773 uint32_t heapSize = 0;
3774 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3775 currentPointerIndex++) {
3776 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3777 lastPointerIndex++) {
3778 const RawPointerData::Pointer& currentPointer =
3779 current->rawPointerData.pointers[currentPointerIndex];
3780 const RawPointerData::Pointer& lastPointer =
3781 last->rawPointerData.pointers[lastPointerIndex];
3782 if (currentPointer.toolType == lastPointer.toolType) {
3783 int64_t deltaX = currentPointer.x - lastPointer.x;
3784 int64_t deltaY = currentPointer.y - lastPointer.y;
3785
3786 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3787
3788 // Insert new element into the heap (sift up).
3789 heap[heapSize].currentPointerIndex = currentPointerIndex;
3790 heap[heapSize].lastPointerIndex = lastPointerIndex;
3791 heap[heapSize].distance = distance;
3792 heapSize += 1;
3793 }
3794 }
3795 }
3796
3797 // Heapify
3798 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3799 startIndex -= 1;
3800 for (uint32_t parentIndex = startIndex;;) {
3801 uint32_t childIndex = parentIndex * 2 + 1;
3802 if (childIndex >= heapSize) {
3803 break;
3804 }
3805
3806 if (childIndex + 1 < heapSize &&
3807 heap[childIndex + 1].distance < heap[childIndex].distance) {
3808 childIndex += 1;
3809 }
3810
3811 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3812 break;
3813 }
3814
3815 swap(heap[parentIndex], heap[childIndex]);
3816 parentIndex = childIndex;
3817 }
3818 }
3819
3820#if DEBUG_POINTER_ASSIGNMENT
3821 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3822 for (size_t i = 0; i < heapSize; i++) {
3823 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3824 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3825 }
3826#endif
3827
3828 // Pull matches out by increasing order of distance.
3829 // To avoid reassigning pointers that have already been matched, the loop keeps track
3830 // of which last and current pointers have been matched using the matchedXXXBits variables.
3831 // It also tracks the used pointer id bits.
3832 BitSet32 matchedLastBits(0);
3833 BitSet32 matchedCurrentBits(0);
3834 BitSet32 usedIdBits(0);
3835 bool first = true;
3836 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3837 while (heapSize > 0) {
3838 if (first) {
3839 // The first time through the loop, we just consume the root element of
3840 // the heap (the one with smallest distance).
3841 first = false;
3842 } else {
3843 // Previous iterations consumed the root element of the heap.
3844 // Pop root element off of the heap (sift down).
3845 heap[0] = heap[heapSize];
3846 for (uint32_t parentIndex = 0;;) {
3847 uint32_t childIndex = parentIndex * 2 + 1;
3848 if (childIndex >= heapSize) {
3849 break;
3850 }
3851
3852 if (childIndex + 1 < heapSize &&
3853 heap[childIndex + 1].distance < heap[childIndex].distance) {
3854 childIndex += 1;
3855 }
3856
3857 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3858 break;
3859 }
3860
3861 swap(heap[parentIndex], heap[childIndex]);
3862 parentIndex = childIndex;
3863 }
3864
3865#if DEBUG_POINTER_ASSIGNMENT
3866 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3867 for (size_t i = 0; i < heapSize; i++) {
3868 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3869 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3870 }
3871#endif
3872 }
3873
3874 heapSize -= 1;
3875
3876 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3877 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3878
3879 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3880 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3881
3882 matchedCurrentBits.markBit(currentPointerIndex);
3883 matchedLastBits.markBit(lastPointerIndex);
3884
3885 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3886 current->rawPointerData.pointers[currentPointerIndex].id = id;
3887 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3888 current->rawPointerData.markIdBit(id,
3889 current->rawPointerData.isHovering(
3890 currentPointerIndex));
3891 usedIdBits.markBit(id);
3892
3893#if DEBUG_POINTER_ASSIGNMENT
3894 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3895 ", distance=%" PRIu64,
3896 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3897#endif
3898 break;
3899 }
3900 }
3901
3902 // Assign fresh ids to pointers that were not matched in the process.
3903 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3904 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3905 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3906
3907 current->rawPointerData.pointers[currentPointerIndex].id = id;
3908 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3909 current->rawPointerData.markIdBit(id,
3910 current->rawPointerData.isHovering(currentPointerIndex));
3911
3912#if DEBUG_POINTER_ASSIGNMENT
3913 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3914#endif
3915 }
3916}
3917
3918int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3919 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3920 return AKEY_STATE_VIRTUAL;
3921 }
3922
3923 for (const VirtualKey& virtualKey : mVirtualKeys) {
3924 if (virtualKey.keyCode == keyCode) {
3925 return AKEY_STATE_UP;
3926 }
3927 }
3928
3929 return AKEY_STATE_UNKNOWN;
3930}
3931
3932int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3933 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3934 return AKEY_STATE_VIRTUAL;
3935 }
3936
3937 for (const VirtualKey& virtualKey : mVirtualKeys) {
3938 if (virtualKey.scanCode == scanCode) {
3939 return AKEY_STATE_UP;
3940 }
3941 }
3942
3943 return AKEY_STATE_UNKNOWN;
3944}
3945
3946bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3947 const int32_t* keyCodes, uint8_t* outFlags) {
3948 for (const VirtualKey& virtualKey : mVirtualKeys) {
3949 for (size_t i = 0; i < numCodes; i++) {
3950 if (virtualKey.keyCode == keyCodes[i]) {
3951 outFlags[i] = 1;
3952 }
3953 }
3954 }
3955
3956 return true;
3957}
3958
3959std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3960 if (mParameters.hasAssociatedDisplay) {
Michael Wrightaff169e2020-07-02 18:30:52 +01003961 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003962 return std::make_optional(mPointerController->getDisplayId());
3963 } else {
3964 return std::make_optional(mViewport.displayId);
3965 }
3966 }
3967 return std::nullopt;
3968}
3969
3970} // namespace android