blob: 80910360affad1b16e03c00b9531ff6753941e39 [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 Pradhanc7ef27e2020-02-03 19:19:15 -0800784 // Create pointer controller if needed.
Michael Wrightaff169e2020-07-02 18:30:52 +0100785 if (mDeviceMode == DeviceMode::POINTER ||
786 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800787 if (mPointerController == nullptr) {
788 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700789 }
790 } else {
Michael Wright7a376672020-06-26 20:51:44 +0100791 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700792 }
793
794 if (viewportChanged || deviceModeChanged) {
795 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
796 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800797 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700798 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
799
800 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800801 mXScale = float(mRawSurfaceWidth) / rawWidth;
802 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700803 mXTranslate = -mSurfaceLeft;
804 mYTranslate = -mSurfaceTop;
805 mXPrecision = 1.0f / mXScale;
806 mYPrecision = 1.0f / mYScale;
807
808 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
809 mOrientedRanges.x.source = mSource;
810 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
811 mOrientedRanges.y.source = mSource;
812
813 configureVirtualKeys();
814
815 // Scale factor for terms that are not oriented in a particular axis.
816 // If the pixels are square then xScale == yScale otherwise we fake it
817 // by choosing an average.
818 mGeometricScale = avg(mXScale, mYScale);
819
820 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800821 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700822
823 // Size factors.
Michael Wrightaff169e2020-07-02 18:30:52 +0100824 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700825 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
826 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
827 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
828 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
829 } else {
830 mSizeScale = 0.0f;
831 }
832
833 mOrientedRanges.haveTouchSize = true;
834 mOrientedRanges.haveToolSize = true;
835 mOrientedRanges.haveSize = true;
836
837 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
838 mOrientedRanges.touchMajor.source = mSource;
839 mOrientedRanges.touchMajor.min = 0;
840 mOrientedRanges.touchMajor.max = diagonalSize;
841 mOrientedRanges.touchMajor.flat = 0;
842 mOrientedRanges.touchMajor.fuzz = 0;
843 mOrientedRanges.touchMajor.resolution = 0;
844
845 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
846 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
847
848 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
849 mOrientedRanges.toolMajor.source = mSource;
850 mOrientedRanges.toolMajor.min = 0;
851 mOrientedRanges.toolMajor.max = diagonalSize;
852 mOrientedRanges.toolMajor.flat = 0;
853 mOrientedRanges.toolMajor.fuzz = 0;
854 mOrientedRanges.toolMajor.resolution = 0;
855
856 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
857 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
858
859 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
860 mOrientedRanges.size.source = mSource;
861 mOrientedRanges.size.min = 0;
862 mOrientedRanges.size.max = 1.0;
863 mOrientedRanges.size.flat = 0;
864 mOrientedRanges.size.fuzz = 0;
865 mOrientedRanges.size.resolution = 0;
866 } else {
867 mSizeScale = 0.0f;
868 }
869
870 // Pressure factors.
871 mPressureScale = 0;
872 float pressureMax = 1.0;
Michael Wrightaff169e2020-07-02 18:30:52 +0100873 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
874 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700875 if (mCalibration.havePressureScale) {
876 mPressureScale = mCalibration.pressureScale;
877 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
878 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
879 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
880 }
881 }
882
883 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
884 mOrientedRanges.pressure.source = mSource;
885 mOrientedRanges.pressure.min = 0;
886 mOrientedRanges.pressure.max = pressureMax;
887 mOrientedRanges.pressure.flat = 0;
888 mOrientedRanges.pressure.fuzz = 0;
889 mOrientedRanges.pressure.resolution = 0;
890
891 // Tilt
892 mTiltXCenter = 0;
893 mTiltXScale = 0;
894 mTiltYCenter = 0;
895 mTiltYScale = 0;
896 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
897 if (mHaveTilt) {
898 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
899 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
900 mTiltXScale = M_PI / 180;
901 mTiltYScale = M_PI / 180;
902
903 mOrientedRanges.haveTilt = true;
904
905 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
906 mOrientedRanges.tilt.source = mSource;
907 mOrientedRanges.tilt.min = 0;
908 mOrientedRanges.tilt.max = M_PI_2;
909 mOrientedRanges.tilt.flat = 0;
910 mOrientedRanges.tilt.fuzz = 0;
911 mOrientedRanges.tilt.resolution = 0;
912 }
913
914 // Orientation
915 mOrientationScale = 0;
916 if (mHaveTilt) {
917 mOrientedRanges.haveOrientation = true;
918
919 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
920 mOrientedRanges.orientation.source = mSource;
921 mOrientedRanges.orientation.min = -M_PI;
922 mOrientedRanges.orientation.max = M_PI;
923 mOrientedRanges.orientation.flat = 0;
924 mOrientedRanges.orientation.fuzz = 0;
925 mOrientedRanges.orientation.resolution = 0;
926 } else if (mCalibration.orientationCalibration !=
Michael Wrightaff169e2020-07-02 18:30:52 +0100927 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700928 if (mCalibration.orientationCalibration ==
Michael Wrightaff169e2020-07-02 18:30:52 +0100929 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700930 if (mRawPointerAxes.orientation.valid) {
931 if (mRawPointerAxes.orientation.maxValue > 0) {
932 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
933 } else if (mRawPointerAxes.orientation.minValue < 0) {
934 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
935 } else {
936 mOrientationScale = 0;
937 }
938 }
939 }
940
941 mOrientedRanges.haveOrientation = true;
942
943 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
944 mOrientedRanges.orientation.source = mSource;
945 mOrientedRanges.orientation.min = -M_PI_2;
946 mOrientedRanges.orientation.max = M_PI_2;
947 mOrientedRanges.orientation.flat = 0;
948 mOrientedRanges.orientation.fuzz = 0;
949 mOrientedRanges.orientation.resolution = 0;
950 }
951
952 // Distance
953 mDistanceScale = 0;
Michael Wrightaff169e2020-07-02 18:30:52 +0100954 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
955 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700956 if (mCalibration.haveDistanceScale) {
957 mDistanceScale = mCalibration.distanceScale;
958 } else {
959 mDistanceScale = 1.0f;
960 }
961 }
962
963 mOrientedRanges.haveDistance = true;
964
965 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
966 mOrientedRanges.distance.source = mSource;
967 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
968 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
969 mOrientedRanges.distance.flat = 0;
970 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
971 mOrientedRanges.distance.resolution = 0;
972 }
973
974 // Compute oriented precision, scales and ranges.
975 // Note that the maximum value reported is an inclusive maximum value so it is one
976 // unit less than the total width or height of surface.
977 switch (mSurfaceOrientation) {
978 case DISPLAY_ORIENTATION_90:
979 case DISPLAY_ORIENTATION_270:
980 mOrientedXPrecision = mYPrecision;
981 mOrientedYPrecision = mXPrecision;
982
983 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800984 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700985 mOrientedRanges.x.flat = 0;
986 mOrientedRanges.x.fuzz = 0;
987 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
988
989 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800990 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700991 mOrientedRanges.y.flat = 0;
992 mOrientedRanges.y.fuzz = 0;
993 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
994 break;
995
996 default:
997 mOrientedXPrecision = mXPrecision;
998 mOrientedYPrecision = mYPrecision;
999
1000 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001001 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001002 mOrientedRanges.x.flat = 0;
1003 mOrientedRanges.x.fuzz = 0;
1004 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1005
1006 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001007 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001008 mOrientedRanges.y.flat = 0;
1009 mOrientedRanges.y.fuzz = 0;
1010 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1011 break;
1012 }
1013
1014 // Location
1015 updateAffineTransformation();
1016
Michael Wrightaff169e2020-07-02 18:30:52 +01001017 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001018 // Compute pointer gesture detection parameters.
1019 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001020 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001021
1022 // Scale movements such that one whole swipe of the touch pad covers a
1023 // given area relative to the diagonal size of the display when no acceleration
1024 // is applied.
1025 // Assume that the touch pad has a square aspect ratio such that movements in
1026 // X and Y of the same number of raw units cover the same physical distance.
1027 mPointerXMovementScale =
1028 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1029 mPointerYMovementScale = mPointerXMovementScale;
1030
1031 // Scale zooms to cover a smaller range of the display than movements do.
1032 // This value determines the area around the pointer that is affected by freeform
1033 // pointer gestures.
1034 mPointerXZoomScale =
1035 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1036 mPointerYZoomScale = mPointerXZoomScale;
1037
1038 // Max width between pointers to detect a swipe gesture is more than some fraction
1039 // of the diagonal axis of the touch pad. Touches that are wider than this are
1040 // translated into freeform gestures.
1041 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1042
1043 // Abort current pointer usages because the state has changed.
1044 abortPointerUsage(when, 0 /*policyFlags*/);
1045 }
1046
1047 // Inform the dispatcher about the changes.
1048 *outResetNeeded = true;
1049 bumpGeneration();
1050 }
1051}
1052
1053void TouchInputMapper::dumpSurface(std::string& dump) {
1054 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001055 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1056 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1058 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001059 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1060 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001061 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1062 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1063 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1064 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1065 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1066}
1067
1068void TouchInputMapper::configureVirtualKeys() {
1069 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001070 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001071
1072 mVirtualKeys.clear();
1073
1074 if (virtualKeyDefinitions.size() == 0) {
1075 return;
1076 }
1077
1078 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1079 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1080 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1081 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1082
1083 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1084 VirtualKey virtualKey;
1085
1086 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1087 int32_t keyCode;
1088 int32_t dummyKeyMetaState;
1089 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001090 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1091 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001092 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1093 continue; // drop the key
1094 }
1095
1096 virtualKey.keyCode = keyCode;
1097 virtualKey.flags = flags;
1098
1099 // convert the key definition's display coordinates into touch coordinates for a hit box
1100 int32_t halfWidth = virtualKeyDefinition.width / 2;
1101 int32_t halfHeight = virtualKeyDefinition.height / 2;
1102
1103 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001104 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001105 touchScreenLeft;
1106 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001107 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001108 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001109 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1110 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001111 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001112 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1113 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001114 touchScreenTop;
1115 mVirtualKeys.push_back(virtualKey);
1116 }
1117}
1118
1119void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1120 if (!mVirtualKeys.empty()) {
1121 dump += INDENT3 "Virtual Keys:\n";
1122
1123 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1124 const VirtualKey& virtualKey = mVirtualKeys[i];
1125 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1126 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1127 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1128 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1129 }
1130 }
1131}
1132
1133void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001134 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 Calibration& out = mCalibration;
1136
1137 // Size
Michael Wrightaff169e2020-07-02 18:30:52 +01001138 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 String8 sizeCalibrationString;
1140 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1141 if (sizeCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (sizeCalibrationString == "geometric") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001144 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 } else if (sizeCalibrationString == "diameter") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001146 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 } else if (sizeCalibrationString == "box") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001148 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 } else if (sizeCalibrationString == "area") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001150 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 } else if (sizeCalibrationString != "default") {
1152 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1153 }
1154 }
1155
1156 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1157 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1158 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1159
1160 // Pressure
Michael Wrightaff169e2020-07-02 18:30:52 +01001161 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001162 String8 pressureCalibrationString;
1163 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1164 if (pressureCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001165 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 } else if (pressureCalibrationString == "physical") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001167 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 } else if (pressureCalibrationString == "amplitude") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001169 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (pressureCalibrationString != "default") {
1171 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1172 pressureCalibrationString.string());
1173 }
1174 }
1175
1176 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1177
1178 // Orientation
Michael Wrightaff169e2020-07-02 18:30:52 +01001179 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001180 String8 orientationCalibrationString;
1181 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1182 if (orientationCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001183 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 } else if (orientationCalibrationString == "interpolated") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001185 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 } else if (orientationCalibrationString == "vector") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001187 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 } else if (orientationCalibrationString != "default") {
1189 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1190 orientationCalibrationString.string());
1191 }
1192 }
1193
1194 // Distance
Michael Wrightaff169e2020-07-02 18:30:52 +01001195 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 String8 distanceCalibrationString;
1197 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1198 if (distanceCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001199 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 } else if (distanceCalibrationString == "scaled") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001201 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 } else if (distanceCalibrationString != "default") {
1203 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1204 distanceCalibrationString.string());
1205 }
1206 }
1207
1208 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1209
Michael Wrightaff169e2020-07-02 18:30:52 +01001210 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 String8 coverageCalibrationString;
1212 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1213 if (coverageCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001214 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 } else if (coverageCalibrationString == "box") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001216 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 } else if (coverageCalibrationString != "default") {
1218 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1219 coverageCalibrationString.string());
1220 }
1221 }
1222}
1223
1224void TouchInputMapper::resolveCalibration() {
1225 // Size
1226 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001227 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1228 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 }
1230 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001231 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 }
1233
1234 // Pressure
1235 if (mRawPointerAxes.pressure.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001236 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1237 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238 }
1239 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001240 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241 }
1242
1243 // Orientation
1244 if (mRawPointerAxes.orientation.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001245 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1246 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001247 }
1248 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001249 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251
1252 // Distance
1253 if (mRawPointerAxes.distance.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001254 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1255 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001256 }
1257 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001258 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260
1261 // Coverage
Michael Wrightaff169e2020-07-02 18:30:52 +01001262 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1263 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265}
1266
1267void TouchInputMapper::dumpCalibration(std::string& dump) {
1268 dump += INDENT3 "Calibration:\n";
1269
1270 // Size
1271 switch (mCalibration.sizeCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001272 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 dump += INDENT4 "touch.size.calibration: none\n";
1274 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001275 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 dump += INDENT4 "touch.size.calibration: geometric\n";
1277 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001278 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 dump += INDENT4 "touch.size.calibration: diameter\n";
1280 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001281 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 dump += INDENT4 "touch.size.calibration: box\n";
1283 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001284 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 dump += INDENT4 "touch.size.calibration: area\n";
1286 break;
1287 default:
1288 ALOG_ASSERT(false);
1289 }
1290
1291 if (mCalibration.haveSizeScale) {
1292 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1293 }
1294
1295 if (mCalibration.haveSizeBias) {
1296 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1297 }
1298
1299 if (mCalibration.haveSizeIsSummed) {
1300 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1301 toString(mCalibration.sizeIsSummed));
1302 }
1303
1304 // Pressure
1305 switch (mCalibration.pressureCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001306 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.pressure.calibration: none\n";
1308 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001309 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.pressure.calibration: physical\n";
1311 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001312 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1314 break;
1315 default:
1316 ALOG_ASSERT(false);
1317 }
1318
1319 if (mCalibration.havePressureScale) {
1320 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1321 }
1322
1323 // Orientation
1324 switch (mCalibration.orientationCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001325 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001326 dump += INDENT4 "touch.orientation.calibration: none\n";
1327 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001328 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1330 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001331 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 dump += INDENT4 "touch.orientation.calibration: vector\n";
1333 break;
1334 default:
1335 ALOG_ASSERT(false);
1336 }
1337
1338 // Distance
1339 switch (mCalibration.distanceCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001340 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.distance.calibration: none\n";
1342 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001343 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.distance.calibration: scaled\n";
1345 break;
1346 default:
1347 ALOG_ASSERT(false);
1348 }
1349
1350 if (mCalibration.haveDistanceScale) {
1351 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1352 }
1353
1354 switch (mCalibration.coverageCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001355 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356 dump += INDENT4 "touch.coverage.calibration: none\n";
1357 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001358 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001359 dump += INDENT4 "touch.coverage.calibration: box\n";
1360 break;
1361 default:
1362 ALOG_ASSERT(false);
1363 }
1364}
1365
1366void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1367 dump += INDENT3 "Affine Transformation:\n";
1368
1369 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1370 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1371 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1372 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1373 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1374 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1375}
1376
1377void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001378 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001379 mSurfaceOrientation);
1380}
1381
1382void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001383 mCursorButtonAccumulator.reset(getDeviceContext());
1384 mCursorScrollAccumulator.reset(getDeviceContext());
1385 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001386
1387 mPointerVelocityControl.reset();
1388 mWheelXVelocityControl.reset();
1389 mWheelYVelocityControl.reset();
1390
1391 mRawStatesPending.clear();
1392 mCurrentRawState.clear();
1393 mCurrentCookedState.clear();
1394 mLastRawState.clear();
1395 mLastCookedState.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001396 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001397 mSentHoverEnter = false;
1398 mHavePointerIds = false;
1399 mCurrentMotionAborted = false;
1400 mDownTime = 0;
1401
1402 mCurrentVirtualKey.down = false;
1403
1404 mPointerGesture.reset();
1405 mPointerSimple.reset();
1406 resetExternalStylus();
1407
1408 if (mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01001409 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001410 mPointerController->clearSpots();
1411 }
1412
1413 InputMapper::reset(when);
1414}
1415
1416void TouchInputMapper::resetExternalStylus() {
1417 mExternalStylusState.clear();
1418 mExternalStylusId = -1;
1419 mExternalStylusFusionTimeout = LLONG_MAX;
1420 mExternalStylusDataPending = false;
1421}
1422
1423void TouchInputMapper::clearStylusDataPendingFlags() {
1424 mExternalStylusDataPending = false;
1425 mExternalStylusFusionTimeout = LLONG_MAX;
1426}
1427
1428void TouchInputMapper::process(const RawEvent* rawEvent) {
1429 mCursorButtonAccumulator.process(rawEvent);
1430 mCursorScrollAccumulator.process(rawEvent);
1431 mTouchButtonAccumulator.process(rawEvent);
1432
1433 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1434 sync(rawEvent->when);
1435 }
1436}
1437
1438void TouchInputMapper::sync(nsecs_t when) {
1439 const RawState* last =
1440 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1441
1442 // Push a new state.
1443 mRawStatesPending.emplace_back();
1444
1445 RawState* next = &mRawStatesPending.back();
1446 next->clear();
1447 next->when = when;
1448
1449 // Sync button state.
1450 next->buttonState =
1451 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1452
1453 // Sync scroll
1454 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1455 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1456 mCursorScrollAccumulator.finishSync();
1457
1458 // Sync touch
1459 syncTouch(when, next);
1460
1461 // Assign pointer ids.
1462 if (!mHavePointerIds) {
1463 assignPointerIds(last, next);
1464 }
1465
1466#if DEBUG_RAW_EVENTS
1467 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhung65600042020-04-30 17:55:40 +08001468 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001469 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1470 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhung65600042020-04-30 17:55:40 +08001471 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1472 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001473#endif
1474
1475 processRawTouches(false /*timeout*/);
1476}
1477
1478void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001479 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001480 // Drop all input if the device is disabled.
1481 mCurrentRawState.clear();
1482 mRawStatesPending.clear();
1483 return;
1484 }
1485
1486 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1487 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1488 // touching the current state will only observe the events that have been dispatched to the
1489 // rest of the pipeline.
1490 const size_t N = mRawStatesPending.size();
1491 size_t count;
1492 for (count = 0; count < N; count++) {
1493 const RawState& next = mRawStatesPending[count];
1494
1495 // A failure to assign the stylus id means that we're waiting on stylus data
1496 // and so should defer the rest of the pipeline.
1497 if (assignExternalStylusId(next, timeout)) {
1498 break;
1499 }
1500
1501 // All ready to go.
1502 clearStylusDataPendingFlags();
1503 mCurrentRawState.copyFrom(next);
1504 if (mCurrentRawState.when < mLastRawState.when) {
1505 mCurrentRawState.when = mLastRawState.when;
1506 }
1507 cookAndDispatch(mCurrentRawState.when);
1508 }
1509 if (count != 0) {
1510 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1511 }
1512
1513 if (mExternalStylusDataPending) {
1514 if (timeout) {
1515 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1516 clearStylusDataPendingFlags();
1517 mCurrentRawState.copyFrom(mLastRawState);
1518#if DEBUG_STYLUS_FUSION
1519 ALOGD("Timeout expired, synthesizing event with new stylus data");
1520#endif
1521 cookAndDispatch(when);
1522 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1523 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1524 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1525 }
1526 }
1527}
1528
1529void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1530 // Always start with a clean state.
1531 mCurrentCookedState.clear();
1532
1533 // Apply stylus buttons to current raw state.
1534 applyExternalStylusButtonState(when);
1535
1536 // Handle policy on initial down or hover events.
1537 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1538 mCurrentRawState.rawPointerData.pointerCount != 0;
1539
1540 uint32_t policyFlags = 0;
1541 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1542 if (initialDown || buttonsPressed) {
1543 // If this is a touch screen, hide the pointer on an initial down.
Michael Wrightaff169e2020-07-02 18:30:52 +01001544 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001545 getContext()->fadePointer();
1546 }
1547
1548 if (mParameters.wake) {
1549 policyFlags |= POLICY_FLAG_WAKE;
1550 }
1551 }
1552
1553 // Consume raw off-screen touches before cooking pointer data.
1554 // If touches are consumed, subsequent code will not receive any pointer data.
1555 if (consumeRawTouches(when, policyFlags)) {
1556 mCurrentRawState.rawPointerData.clear();
1557 }
1558
1559 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1560 // with cooked pointer data that has the same ids and indices as the raw data.
1561 // The following code can use either the raw or cooked data, as needed.
1562 cookPointerData();
1563
1564 // Apply stylus pressure to current cooked state.
1565 applyExternalStylusTouchState(when);
1566
1567 // Synthesize key down from raw buttons if needed.
1568 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1569 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1570 mCurrentCookedState.buttonState);
1571
1572 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wrightaff169e2020-07-02 18:30:52 +01001573 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001574 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1575 uint32_t id = idBits.clearFirstMarkedBit();
1576 const RawPointerData::Pointer& pointer =
1577 mCurrentRawState.rawPointerData.pointerForId(id);
1578 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1579 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1580 mCurrentCookedState.stylusIdBits.markBit(id);
1581 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1582 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1583 mCurrentCookedState.fingerIdBits.markBit(id);
1584 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1585 mCurrentCookedState.mouseIdBits.markBit(id);
1586 }
1587 }
1588 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1589 uint32_t id = idBits.clearFirstMarkedBit();
1590 const RawPointerData::Pointer& pointer =
1591 mCurrentRawState.rawPointerData.pointerForId(id);
1592 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1593 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1594 mCurrentCookedState.stylusIdBits.markBit(id);
1595 }
1596 }
1597
1598 // Stylus takes precedence over all tools, then mouse, then finger.
1599 PointerUsage pointerUsage = mPointerUsage;
1600 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1601 mCurrentCookedState.mouseIdBits.clear();
1602 mCurrentCookedState.fingerIdBits.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001603 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001604 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1605 mCurrentCookedState.fingerIdBits.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001606 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001607 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1608 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001609 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001610 }
1611
1612 dispatchPointerUsage(when, policyFlags, pointerUsage);
1613 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001614 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001615 mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01001616 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1617 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001618
1619 mPointerController->setButtonState(mCurrentRawState.buttonState);
1620 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1621 mCurrentCookedState.cookedPointerData.idToIndex,
1622 mCurrentCookedState.cookedPointerData.touchingIdBits,
1623 mViewport.displayId);
1624 }
1625
1626 if (!mCurrentMotionAborted) {
1627 dispatchButtonRelease(when, policyFlags);
1628 dispatchHoverExit(when, policyFlags);
1629 dispatchTouches(when, policyFlags);
1630 dispatchHoverEnterAndMove(when, policyFlags);
1631 dispatchButtonPress(when, policyFlags);
1632 }
1633
1634 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1635 mCurrentMotionAborted = false;
1636 }
1637 }
1638
1639 // Synthesize key up from raw buttons if needed.
1640 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1641 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1642 mCurrentCookedState.buttonState);
1643
1644 // Clear some transient state.
1645 mCurrentRawState.rawVScroll = 0;
1646 mCurrentRawState.rawHScroll = 0;
1647
1648 // Copy current touch to last touch in preparation for the next cycle.
1649 mLastRawState.copyFrom(mCurrentRawState);
1650 mLastCookedState.copyFrom(mCurrentCookedState);
1651}
1652
1653void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001654 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001655 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1656 }
1657}
1658
1659void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1660 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1661 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1662
1663 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1664 float pressure = mExternalStylusState.pressure;
1665 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1666 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1667 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1668 }
1669 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1670 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1671
1672 PointerProperties& properties =
1673 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1674 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1675 properties.toolType = mExternalStylusState.toolType;
1676 }
1677 }
1678}
1679
1680bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001681 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001682 return false;
1683 }
1684
1685 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1686 state.rawPointerData.pointerCount != 0;
1687 if (initialDown) {
1688 if (mExternalStylusState.pressure != 0.0f) {
1689#if DEBUG_STYLUS_FUSION
1690 ALOGD("Have both stylus and touch data, beginning fusion");
1691#endif
1692 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1693 } else if (timeout) {
1694#if DEBUG_STYLUS_FUSION
1695 ALOGD("Timeout expired, assuming touch is not a stylus.");
1696#endif
1697 resetExternalStylus();
1698 } else {
1699 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1700 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1701 }
1702#if DEBUG_STYLUS_FUSION
1703 ALOGD("No stylus data but stylus is connected, requesting timeout "
1704 "(%" PRId64 "ms)",
1705 mExternalStylusFusionTimeout);
1706#endif
1707 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1708 return true;
1709 }
1710 }
1711
1712 // Check if the stylus pointer has gone up.
1713 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1714#if DEBUG_STYLUS_FUSION
1715 ALOGD("Stylus pointer is going up");
1716#endif
1717 mExternalStylusId = -1;
1718 }
1719
1720 return false;
1721}
1722
1723void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001724 if (mDeviceMode == DeviceMode::POINTER) {
1725 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001726 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1727 }
Michael Wrightaff169e2020-07-02 18:30:52 +01001728 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001729 if (mExternalStylusFusionTimeout < when) {
1730 processRawTouches(true /*timeout*/);
1731 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1732 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1733 }
1734 }
1735}
1736
1737void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1738 mExternalStylusState.copyFrom(state);
1739 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1740 // We're either in the middle of a fused stream of data or we're waiting on data before
1741 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1742 // data.
1743 mExternalStylusDataPending = true;
1744 processRawTouches(false /*timeout*/);
1745 }
1746}
1747
1748bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1749 // Check for release of a virtual key.
1750 if (mCurrentVirtualKey.down) {
1751 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1752 // Pointer went up while virtual key was down.
1753 mCurrentVirtualKey.down = false;
1754 if (!mCurrentVirtualKey.ignored) {
1755#if DEBUG_VIRTUAL_KEYS
1756 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1757 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1758#endif
1759 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1760 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1761 }
1762 return true;
1763 }
1764
1765 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1766 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1767 const RawPointerData::Pointer& pointer =
1768 mCurrentRawState.rawPointerData.pointerForId(id);
1769 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1770 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1771 // Pointer is still within the space of the virtual key.
1772 return true;
1773 }
1774 }
1775
1776 // Pointer left virtual key area or another pointer also went down.
1777 // Send key cancellation but do not consume the touch yet.
1778 // This is useful when the user swipes through from the virtual key area
1779 // into the main display surface.
1780 mCurrentVirtualKey.down = false;
1781 if (!mCurrentVirtualKey.ignored) {
1782#if DEBUG_VIRTUAL_KEYS
1783 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1784 mCurrentVirtualKey.scanCode);
1785#endif
1786 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1787 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1788 AKEY_EVENT_FLAG_CANCELED);
1789 }
1790 }
1791
1792 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1793 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1794 // Pointer just went down. Check for virtual key press or off-screen touches.
1795 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1796 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Yedca44af2020-08-05 15:07:56 -07001797 // Exclude unscaled device for inside surface checking.
1798 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001799 // If exactly one pointer went down, check for virtual key hit.
1800 // Otherwise we will drop the entire stroke.
1801 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1802 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1803 if (virtualKey) {
1804 mCurrentVirtualKey.down = true;
1805 mCurrentVirtualKey.downTime = when;
1806 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1807 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1808 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001809 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1810 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001811
1812 if (!mCurrentVirtualKey.ignored) {
1813#if DEBUG_VIRTUAL_KEYS
1814 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1815 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1816#endif
1817 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1818 AKEY_EVENT_FLAG_FROM_SYSTEM |
1819 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1820 }
1821 }
1822 }
1823 return true;
1824 }
1825 }
1826
1827 // Disable all virtual key touches that happen within a short time interval of the
1828 // most recent touch within the screen area. The idea is to filter out stray
1829 // virtual key presses when interacting with the touch screen.
1830 //
1831 // Problems we're trying to solve:
1832 //
1833 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1834 // virtual key area that is implemented by a separate touch panel and accidentally
1835 // triggers a virtual key.
1836 //
1837 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1838 // area and accidentally triggers a virtual key. This often happens when virtual keys
1839 // are layed out below the screen near to where the on screen keyboard's space bar
1840 // is displayed.
1841 if (mConfig.virtualKeyQuietTime > 0 &&
1842 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001843 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001844 }
1845 return false;
1846}
1847
1848void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1849 int32_t keyEventAction, int32_t keyEventFlags) {
1850 int32_t keyCode = mCurrentVirtualKey.keyCode;
1851 int32_t scanCode = mCurrentVirtualKey.scanCode;
1852 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001853 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001854 policyFlags |= POLICY_FLAG_VIRTUAL;
1855
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001856 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1857 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1858 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001859 getListener()->notifyKey(&args);
1860}
1861
1862void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1863 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1864 if (!currentIdBits.isEmpty()) {
1865 int32_t metaState = getContext()->getGlobalMetaState();
1866 int32_t buttonState = mCurrentCookedState.buttonState;
1867 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1868 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1869 mCurrentCookedState.cookedPointerData.pointerProperties,
1870 mCurrentCookedState.cookedPointerData.pointerCoords,
1871 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1872 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1873 mCurrentMotionAborted = true;
1874 }
1875}
1876
1877void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1878 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1879 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1880 int32_t metaState = getContext()->getGlobalMetaState();
1881 int32_t buttonState = mCurrentCookedState.buttonState;
1882
1883 if (currentIdBits == lastIdBits) {
1884 if (!currentIdBits.isEmpty()) {
1885 // No pointer id changes so this is a move event.
1886 // The listener takes care of batching moves so we don't have to deal with that here.
1887 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1888 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1889 mCurrentCookedState.cookedPointerData.pointerProperties,
1890 mCurrentCookedState.cookedPointerData.pointerCoords,
1891 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1892 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1893 }
1894 } else {
1895 // There may be pointers going up and pointers going down and pointers moving
1896 // all at the same time.
1897 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1898 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1899 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1900 BitSet32 dispatchedIdBits(lastIdBits.value);
1901
1902 // Update last coordinates of pointers that have moved so that we observe the new
1903 // pointer positions at the same time as other pointers that have just gone up.
1904 bool moveNeeded =
1905 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1906 mCurrentCookedState.cookedPointerData.pointerCoords,
1907 mCurrentCookedState.cookedPointerData.idToIndex,
1908 mLastCookedState.cookedPointerData.pointerProperties,
1909 mLastCookedState.cookedPointerData.pointerCoords,
1910 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1911 if (buttonState != mLastCookedState.buttonState) {
1912 moveNeeded = true;
1913 }
1914
1915 // Dispatch pointer up events.
1916 while (!upIdBits.isEmpty()) {
1917 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhung65600042020-04-30 17:55:40 +08001918 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1919 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1920 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921 mLastCookedState.cookedPointerData.pointerProperties,
1922 mLastCookedState.cookedPointerData.pointerCoords,
1923 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1924 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1925 dispatchedIdBits.clearBit(upId);
arthurhung65600042020-04-30 17:55:40 +08001926 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001927 }
1928
1929 // Dispatch move events if any of the remaining pointers moved from their old locations.
1930 // Although applications receive new locations as part of individual pointer up
1931 // events, they do not generally handle them except when presented in a move event.
1932 if (moveNeeded && !moveIdBits.isEmpty()) {
1933 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1934 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1935 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1936 mCurrentCookedState.cookedPointerData.pointerCoords,
1937 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1938 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1939 }
1940
1941 // Dispatch pointer down events using the new pointer locations.
1942 while (!downIdBits.isEmpty()) {
1943 uint32_t downId = downIdBits.clearFirstMarkedBit();
1944 dispatchedIdBits.markBit(downId);
1945
1946 if (dispatchedIdBits.count() == 1) {
1947 // First pointer is going down. Set down time.
1948 mDownTime = when;
1949 }
1950
1951 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1952 metaState, buttonState, 0,
1953 mCurrentCookedState.cookedPointerData.pointerProperties,
1954 mCurrentCookedState.cookedPointerData.pointerCoords,
1955 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1956 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1957 }
1958 }
1959}
1960
1961void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1962 if (mSentHoverEnter &&
1963 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1964 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1965 int32_t metaState = getContext()->getGlobalMetaState();
1966 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1967 mLastCookedState.buttonState, 0,
1968 mLastCookedState.cookedPointerData.pointerProperties,
1969 mLastCookedState.cookedPointerData.pointerCoords,
1970 mLastCookedState.cookedPointerData.idToIndex,
1971 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1972 mOrientedYPrecision, mDownTime);
1973 mSentHoverEnter = false;
1974 }
1975}
1976
1977void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1978 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1979 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1980 int32_t metaState = getContext()->getGlobalMetaState();
1981 if (!mSentHoverEnter) {
1982 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1983 metaState, mCurrentRawState.buttonState, 0,
1984 mCurrentCookedState.cookedPointerData.pointerProperties,
1985 mCurrentCookedState.cookedPointerData.pointerCoords,
1986 mCurrentCookedState.cookedPointerData.idToIndex,
1987 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1988 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1989 mSentHoverEnter = true;
1990 }
1991
1992 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1993 mCurrentRawState.buttonState, 0,
1994 mCurrentCookedState.cookedPointerData.pointerProperties,
1995 mCurrentCookedState.cookedPointerData.pointerCoords,
1996 mCurrentCookedState.cookedPointerData.idToIndex,
1997 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1998 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1999 }
2000}
2001
2002void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
2003 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2004 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2005 const int32_t metaState = getContext()->getGlobalMetaState();
2006 int32_t buttonState = mLastCookedState.buttonState;
2007 while (!releasedButtons.isEmpty()) {
2008 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2009 buttonState &= ~actionButton;
2010 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2011 actionButton, 0, metaState, buttonState, 0,
2012 mCurrentCookedState.cookedPointerData.pointerProperties,
2013 mCurrentCookedState.cookedPointerData.pointerCoords,
2014 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2015 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2016 }
2017}
2018
2019void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2020 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2021 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2022 const int32_t metaState = getContext()->getGlobalMetaState();
2023 int32_t buttonState = mLastCookedState.buttonState;
2024 while (!pressedButtons.isEmpty()) {
2025 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2026 buttonState |= actionButton;
2027 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2028 0, metaState, buttonState, 0,
2029 mCurrentCookedState.cookedPointerData.pointerProperties,
2030 mCurrentCookedState.cookedPointerData.pointerCoords,
2031 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2032 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2033 }
2034}
2035
2036const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2037 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2038 return cookedPointerData.touchingIdBits;
2039 }
2040 return cookedPointerData.hoveringIdBits;
2041}
2042
2043void TouchInputMapper::cookPointerData() {
2044 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2045
2046 mCurrentCookedState.cookedPointerData.clear();
2047 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2048 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2049 mCurrentRawState.rawPointerData.hoveringIdBits;
2050 mCurrentCookedState.cookedPointerData.touchingIdBits =
2051 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhung65600042020-04-30 17:55:40 +08002052 mCurrentCookedState.cookedPointerData.canceledIdBits =
2053 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002054
2055 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2056 mCurrentCookedState.buttonState = 0;
2057 } else {
2058 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2059 }
2060
2061 // Walk through the the active pointers and map device coordinates onto
2062 // surface coordinates and adjust for display orientation.
2063 for (uint32_t i = 0; i < currentPointerCount; i++) {
2064 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2065
2066 // Size
2067 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2068 switch (mCalibration.sizeCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002069 case Calibration::SizeCalibration::GEOMETRIC:
2070 case Calibration::SizeCalibration::DIAMETER:
2071 case Calibration::SizeCalibration::BOX:
2072 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002073 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2074 touchMajor = in.touchMajor;
2075 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2076 toolMajor = in.toolMajor;
2077 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2078 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2079 : in.touchMajor;
2080 } else if (mRawPointerAxes.touchMajor.valid) {
2081 toolMajor = touchMajor = in.touchMajor;
2082 toolMinor = touchMinor =
2083 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2084 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2085 : in.touchMajor;
2086 } else if (mRawPointerAxes.toolMajor.valid) {
2087 touchMajor = toolMajor = in.toolMajor;
2088 touchMinor = toolMinor =
2089 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2090 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2091 : in.toolMajor;
2092 } else {
2093 ALOG_ASSERT(false,
2094 "No touch or tool axes. "
2095 "Size calibration should have been resolved to NONE.");
2096 touchMajor = 0;
2097 touchMinor = 0;
2098 toolMajor = 0;
2099 toolMinor = 0;
2100 size = 0;
2101 }
2102
2103 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2104 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2105 if (touchingCount > 1) {
2106 touchMajor /= touchingCount;
2107 touchMinor /= touchingCount;
2108 toolMajor /= touchingCount;
2109 toolMinor /= touchingCount;
2110 size /= touchingCount;
2111 }
2112 }
2113
Michael Wrightaff169e2020-07-02 18:30:52 +01002114 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002115 touchMajor *= mGeometricScale;
2116 touchMinor *= mGeometricScale;
2117 toolMajor *= mGeometricScale;
2118 toolMinor *= mGeometricScale;
Michael Wrightaff169e2020-07-02 18:30:52 +01002119 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002120 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2121 touchMinor = touchMajor;
2122 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2123 toolMinor = toolMajor;
Michael Wrightaff169e2020-07-02 18:30:52 +01002124 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002125 touchMinor = touchMajor;
2126 toolMinor = toolMajor;
2127 }
2128
2129 mCalibration.applySizeScaleAndBias(&touchMajor);
2130 mCalibration.applySizeScaleAndBias(&touchMinor);
2131 mCalibration.applySizeScaleAndBias(&toolMajor);
2132 mCalibration.applySizeScaleAndBias(&toolMinor);
2133 size *= mSizeScale;
2134 break;
2135 default:
2136 touchMajor = 0;
2137 touchMinor = 0;
2138 toolMajor = 0;
2139 toolMinor = 0;
2140 size = 0;
2141 break;
2142 }
2143
2144 // Pressure
2145 float pressure;
2146 switch (mCalibration.pressureCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002147 case Calibration::PressureCalibration::PHYSICAL:
2148 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002149 pressure = in.pressure * mPressureScale;
2150 break;
2151 default:
2152 pressure = in.isHovering ? 0 : 1;
2153 break;
2154 }
2155
2156 // Tilt and Orientation
2157 float tilt;
2158 float orientation;
2159 if (mHaveTilt) {
2160 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2161 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2162 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2163 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2164 } else {
2165 tilt = 0;
2166
2167 switch (mCalibration.orientationCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002168 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002169 orientation = in.orientation * mOrientationScale;
2170 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002171 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002172 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2173 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2174 if (c1 != 0 || c2 != 0) {
2175 orientation = atan2f(c1, c2) * 0.5f;
2176 float confidence = hypotf(c1, c2);
2177 float scale = 1.0f + confidence / 16.0f;
2178 touchMajor *= scale;
2179 touchMinor /= scale;
2180 toolMajor *= scale;
2181 toolMinor /= scale;
2182 } else {
2183 orientation = 0;
2184 }
2185 break;
2186 }
2187 default:
2188 orientation = 0;
2189 }
2190 }
2191
2192 // Distance
2193 float distance;
2194 switch (mCalibration.distanceCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002195 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002196 distance = in.distance * mDistanceScale;
2197 break;
2198 default:
2199 distance = 0;
2200 }
2201
2202 // Coverage
2203 int32_t rawLeft, rawTop, rawRight, rawBottom;
2204 switch (mCalibration.coverageCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002205 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002206 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2207 rawRight = in.toolMinor & 0x0000ffff;
2208 rawBottom = in.toolMajor & 0x0000ffff;
2209 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2210 break;
2211 default:
2212 rawLeft = rawTop = rawRight = rawBottom = 0;
2213 break;
2214 }
2215
2216 // Adjust X,Y coords for device calibration
2217 // TODO: Adjust coverage coords?
2218 float xTransformed = in.x, yTransformed = in.y;
2219 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002220 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002221
2222 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002223 float left, top, right, bottom;
2224
2225 switch (mSurfaceOrientation) {
2226 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002227 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2228 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2229 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2230 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2231 orientation -= M_PI_2;
2232 if (mOrientedRanges.haveOrientation &&
2233 orientation < mOrientedRanges.orientation.min) {
2234 orientation +=
2235 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2236 }
2237 break;
2238 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002239 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2240 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2241 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2242 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2243 orientation -= M_PI;
2244 if (mOrientedRanges.haveOrientation &&
2245 orientation < mOrientedRanges.orientation.min) {
2246 orientation +=
2247 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2248 }
2249 break;
2250 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002251 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2252 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2253 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2254 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2255 orientation += M_PI_2;
2256 if (mOrientedRanges.haveOrientation &&
2257 orientation > mOrientedRanges.orientation.max) {
2258 orientation -=
2259 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2260 }
2261 break;
2262 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002263 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2264 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2265 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2266 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2267 break;
2268 }
2269
2270 // Write output coords.
2271 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2272 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002273 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2274 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002275 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2276 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2277 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2278 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2279 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2280 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2281 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wrightaff169e2020-07-02 18:30:52 +01002282 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002283 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2284 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2285 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2286 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2287 } else {
2288 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2289 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2290 }
2291
Chris Yedca44af2020-08-05 15:07:56 -07002292 // Write output relative fields if applicable.
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +00002293 uint32_t id = in.id;
2294 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2295 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2296 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2297 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2298 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2299 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2300 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2301 }
2302
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002303 // Write output properties.
2304 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002305 properties.clear();
2306 properties.id = id;
2307 properties.toolType = in.toolType;
2308
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +00002309 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002310 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +00002311 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002312 }
2313}
2314
2315void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2316 PointerUsage pointerUsage) {
2317 if (pointerUsage != mPointerUsage) {
2318 abortPointerUsage(when, policyFlags);
2319 mPointerUsage = pointerUsage;
2320 }
2321
2322 switch (mPointerUsage) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002323 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002324 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2325 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002326 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002327 dispatchPointerStylus(when, policyFlags);
2328 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002329 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002330 dispatchPointerMouse(when, policyFlags);
2331 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002332 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002333 break;
2334 }
2335}
2336
2337void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2338 switch (mPointerUsage) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002339 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002340 abortPointerGestures(when, policyFlags);
2341 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002342 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002343 abortPointerStylus(when, policyFlags);
2344 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002345 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002346 abortPointerMouse(when, policyFlags);
2347 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002348 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 break;
2350 }
2351
Michael Wrightaff169e2020-07-02 18:30:52 +01002352 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002353}
2354
2355void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2356 // Update current gesture coordinates.
2357 bool cancelPreviousGesture, finishPreviousGesture;
2358 bool sendEvents =
2359 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2360 if (!sendEvents) {
2361 return;
2362 }
2363 if (finishPreviousGesture) {
2364 cancelPreviousGesture = false;
2365 }
2366
2367 // Update the pointer presentation and spots.
Michael Wrightaff169e2020-07-02 18:30:52 +01002368 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wright976db0c2020-07-02 00:00:29 +01002369 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002370 if (finishPreviousGesture || cancelPreviousGesture) {
2371 mPointerController->clearSpots();
2372 }
2373
Michael Wrightaff169e2020-07-02 18:30:52 +01002374 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2376 mPointerGesture.currentGestureIdToIndex,
2377 mPointerGesture.currentGestureIdBits,
2378 mPointerController->getDisplayId());
2379 }
2380 } else {
Michael Wright976db0c2020-07-02 00:00:29 +01002381 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 }
2383
2384 // Show or hide the pointer if needed.
2385 switch (mPointerGesture.currentGestureMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002386 case PointerGesture::Mode::NEUTRAL:
2387 case PointerGesture::Mode::QUIET:
2388 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2389 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wright976db0c2020-07-02 00:00:29 +01002391 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002392 }
2393 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002394 case PointerGesture::Mode::TAP:
2395 case PointerGesture::Mode::TAP_DRAG:
2396 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2397 case PointerGesture::Mode::HOVER:
2398 case PointerGesture::Mode::PRESS:
2399 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002400 // Unfade the pointer when the current gesture manipulates the
2401 // area directly under the pointer.
Michael Wright976db0c2020-07-02 00:00:29 +01002402 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002403 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002404 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405 // Fade the pointer when the current gesture manipulates a different
2406 // area and there are spots to guide the user experience.
Michael Wrightaff169e2020-07-02 18:30:52 +01002407 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wright976db0c2020-07-02 00:00:29 +01002408 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409 } else {
Michael Wright976db0c2020-07-02 00:00:29 +01002410 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 }
2412 break;
2413 }
2414
2415 // Send events!
2416 int32_t metaState = getContext()->getGlobalMetaState();
2417 int32_t buttonState = mCurrentCookedState.buttonState;
2418
2419 // Update last coordinates of pointers that have moved so that we observe the new
2420 // pointer positions at the same time as other pointers that have just gone up.
Michael Wrightaff169e2020-07-02 18:30:52 +01002421 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2422 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2423 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2424 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2425 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2426 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 bool moveNeeded = false;
2428 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2429 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2430 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2431 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2432 mPointerGesture.lastGestureIdBits.value);
2433 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2434 mPointerGesture.currentGestureCoords,
2435 mPointerGesture.currentGestureIdToIndex,
2436 mPointerGesture.lastGestureProperties,
2437 mPointerGesture.lastGestureCoords,
2438 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2439 if (buttonState != mLastCookedState.buttonState) {
2440 moveNeeded = true;
2441 }
2442 }
2443
2444 // Send motion events for all pointers that went up or were canceled.
2445 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2446 if (!dispatchedGestureIdBits.isEmpty()) {
2447 if (cancelPreviousGesture) {
2448 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2449 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2450 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2451 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2452 mPointerGesture.downTime);
2453
2454 dispatchedGestureIdBits.clear();
2455 } else {
2456 BitSet32 upGestureIdBits;
2457 if (finishPreviousGesture) {
2458 upGestureIdBits = dispatchedGestureIdBits;
2459 } else {
2460 upGestureIdBits.value =
2461 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2462 }
2463 while (!upGestureIdBits.isEmpty()) {
2464 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2465
2466 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2467 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2468 mPointerGesture.lastGestureProperties,
2469 mPointerGesture.lastGestureCoords,
2470 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2471 0, mPointerGesture.downTime);
2472
2473 dispatchedGestureIdBits.clearBit(id);
2474 }
2475 }
2476 }
2477
2478 // Send motion events for all pointers that moved.
2479 if (moveNeeded) {
2480 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2481 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2482 mPointerGesture.currentGestureProperties,
2483 mPointerGesture.currentGestureCoords,
2484 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2485 mPointerGesture.downTime);
2486 }
2487
2488 // Send motion events for all pointers that went down.
2489 if (down) {
2490 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2491 ~dispatchedGestureIdBits.value);
2492 while (!downGestureIdBits.isEmpty()) {
2493 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2494 dispatchedGestureIdBits.markBit(id);
2495
2496 if (dispatchedGestureIdBits.count() == 1) {
2497 mPointerGesture.downTime = when;
2498 }
2499
2500 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2501 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2502 mPointerGesture.currentGestureCoords,
2503 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2504 0, mPointerGesture.downTime);
2505 }
2506 }
2507
2508 // Send motion events for hover.
Michael Wrightaff169e2020-07-02 18:30:52 +01002509 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002510 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2511 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2512 mPointerGesture.currentGestureProperties,
2513 mPointerGesture.currentGestureCoords,
2514 mPointerGesture.currentGestureIdToIndex,
2515 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2516 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2517 // Synthesize a hover move event after all pointers go up to indicate that
2518 // the pointer is hovering again even if the user is not currently touching
2519 // the touch pad. This ensures that a view will receive a fresh hover enter
2520 // event after a tap.
2521 float x, y;
2522 mPointerController->getPosition(&x, &y);
2523
2524 PointerProperties pointerProperties;
2525 pointerProperties.clear();
2526 pointerProperties.id = 0;
2527 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2528
2529 PointerCoords pointerCoords;
2530 pointerCoords.clear();
2531 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2532 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2533
2534 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002535 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2536 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2537 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2538 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2539 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002540 getListener()->notifyMotion(&args);
2541 }
2542
2543 // Update state.
2544 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2545 if (!down) {
2546 mPointerGesture.lastGestureIdBits.clear();
2547 } else {
2548 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2549 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2550 uint32_t id = idBits.clearFirstMarkedBit();
2551 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2552 mPointerGesture.lastGestureProperties[index].copyFrom(
2553 mPointerGesture.currentGestureProperties[index]);
2554 mPointerGesture.lastGestureCoords[index].copyFrom(
2555 mPointerGesture.currentGestureCoords[index]);
2556 mPointerGesture.lastGestureIdToIndex[id] = index;
2557 }
2558 }
2559}
2560
2561void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2562 // Cancel previously dispatches pointers.
2563 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2564 int32_t metaState = getContext()->getGlobalMetaState();
2565 int32_t buttonState = mCurrentRawState.buttonState;
2566 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2567 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2568 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2569 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2570 0, 0, mPointerGesture.downTime);
2571 }
2572
2573 // Reset the current pointer gesture.
2574 mPointerGesture.reset();
2575 mPointerVelocityControl.reset();
2576
2577 // Remove any current spots.
2578 if (mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01002579 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002580 mPointerController->clearSpots();
2581 }
2582}
2583
2584bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2585 bool* outFinishPreviousGesture, bool isTimeout) {
2586 *outCancelPreviousGesture = false;
2587 *outFinishPreviousGesture = false;
2588
2589 // Handle TAP timeout.
2590 if (isTimeout) {
2591#if DEBUG_GESTURES
2592 ALOGD("Gestures: Processing timeout");
2593#endif
2594
Michael Wrightaff169e2020-07-02 18:30:52 +01002595 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002596 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2597 // The tap/drag timeout has not yet expired.
2598 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2599 mConfig.pointerGestureTapDragInterval);
2600 } else {
2601 // The tap is finished.
2602#if DEBUG_GESTURES
2603 ALOGD("Gestures: TAP finished");
2604#endif
2605 *outFinishPreviousGesture = true;
2606
2607 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002608 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002609 mPointerGesture.currentGestureIdBits.clear();
2610
2611 mPointerVelocityControl.reset();
2612 return true;
2613 }
2614 }
2615
2616 // We did not handle this timeout.
2617 return false;
2618 }
2619
2620 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2621 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2622
2623 // Update the velocity tracker.
2624 {
2625 VelocityTracker::Position positions[MAX_POINTERS];
2626 uint32_t count = 0;
2627 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
2628 uint32_t id = idBits.clearFirstMarkedBit();
2629 const RawPointerData::Pointer& pointer =
2630 mCurrentRawState.rawPointerData.pointerForId(id);
2631 positions[count].x = pointer.x * mPointerXMovementScale;
2632 positions[count].y = pointer.y * mPointerYMovementScale;
2633 }
2634 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2635 positions);
2636 }
2637
2638 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2639 // to NEUTRAL, then we should not generate tap event.
Michael Wrightaff169e2020-07-02 18:30:52 +01002640 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2641 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2642 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002643 mPointerGesture.resetTap();
2644 }
2645
2646 // Pick a new active touch id if needed.
2647 // Choose an arbitrary pointer that just went down, if there is one.
2648 // Otherwise choose an arbitrary remaining pointer.
2649 // This guarantees we always have an active touch id when there is at least one pointer.
2650 // We keep the same active touch id for as long as possible.
2651 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2652 int32_t activeTouchId = lastActiveTouchId;
2653 if (activeTouchId < 0) {
2654 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2655 activeTouchId = mPointerGesture.activeTouchId =
2656 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2657 mPointerGesture.firstTouchTime = when;
2658 }
2659 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2660 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2661 activeTouchId = mPointerGesture.activeTouchId =
2662 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2663 } else {
2664 activeTouchId = mPointerGesture.activeTouchId = -1;
2665 }
2666 }
2667
2668 // Determine whether we are in quiet time.
2669 bool isQuietTime = false;
2670 if (activeTouchId < 0) {
2671 mPointerGesture.resetQuietTime();
2672 } else {
2673 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2674 if (!isQuietTime) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002675 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2676 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2677 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002678 currentFingerCount < 2) {
2679 // Enter quiet time when exiting swipe or freeform state.
2680 // This is to prevent accidentally entering the hover state and flinging the
2681 // pointer when finishing a swipe and there is still one pointer left onscreen.
2682 isQuietTime = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01002683 } else if (mPointerGesture.lastGestureMode ==
2684 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002685 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2686 // Enter quiet time when releasing the button and there are still two or more
2687 // fingers down. This may indicate that one finger was used to press the button
2688 // but it has not gone up yet.
2689 isQuietTime = true;
2690 }
2691 if (isQuietTime) {
2692 mPointerGesture.quietTime = when;
2693 }
2694 }
2695 }
2696
2697 // Switch states based on button and pointer state.
2698 if (isQuietTime) {
2699 // Case 1: Quiet time. (QUIET)
2700#if DEBUG_GESTURES
2701 ALOGD("Gestures: QUIET for next %0.3fms",
2702 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2703#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01002704 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002705 *outFinishPreviousGesture = true;
2706 }
2707
2708 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002709 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002710 mPointerGesture.currentGestureIdBits.clear();
2711
2712 mPointerVelocityControl.reset();
2713 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2714 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2715 // The pointer follows the active touch point.
2716 // Emit DOWN, MOVE, UP events at the pointer location.
2717 //
2718 // Only the active touch matters; other fingers are ignored. This policy helps
2719 // to handle the case where the user places a second finger on the touch pad
2720 // to apply the necessary force to depress an integrated button below the surface.
2721 // We don't want the second finger to be delivered to applications.
2722 //
2723 // For this to work well, we need to make sure to track the pointer that is really
2724 // active. If the user first puts one finger down to click then adds another
2725 // finger to drag then the active pointer should switch to the finger that is
2726 // being dragged.
2727#if DEBUG_GESTURES
2728 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2729 "currentFingerCount=%d",
2730 activeTouchId, currentFingerCount);
2731#endif
2732 // Reset state when just starting.
Michael Wrightaff169e2020-07-02 18:30:52 +01002733 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002734 *outFinishPreviousGesture = true;
2735 mPointerGesture.activeGestureId = 0;
2736 }
2737
2738 // Switch pointers if needed.
2739 // Find the fastest pointer and follow it.
2740 if (activeTouchId >= 0 && currentFingerCount > 1) {
2741 int32_t bestId = -1;
2742 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2743 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2744 uint32_t id = idBits.clearFirstMarkedBit();
2745 float vx, vy;
2746 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2747 float speed = hypotf(vx, vy);
2748 if (speed > bestSpeed) {
2749 bestId = id;
2750 bestSpeed = speed;
2751 }
2752 }
2753 }
2754 if (bestId >= 0 && bestId != activeTouchId) {
2755 mPointerGesture.activeTouchId = activeTouchId = bestId;
2756#if DEBUG_GESTURES
2757 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2758 "bestId=%d, bestSpeed=%0.3f",
2759 bestId, bestSpeed);
2760#endif
2761 }
2762 }
2763
2764 float deltaX = 0, deltaY = 0;
2765 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2766 const RawPointerData::Pointer& currentPointer =
2767 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2768 const RawPointerData::Pointer& lastPointer =
2769 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2770 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2771 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2772
2773 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2774 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2775
2776 // Move the pointer using a relative motion.
2777 // When using spots, the click will occur at the position of the anchor
2778 // spot and all other spots will move there.
2779 mPointerController->move(deltaX, deltaY);
2780 } else {
2781 mPointerVelocityControl.reset();
2782 }
2783
2784 float x, y;
2785 mPointerController->getPosition(&x, &y);
2786
Michael Wrightaff169e2020-07-02 18:30:52 +01002787 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002788 mPointerGesture.currentGestureIdBits.clear();
2789 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2790 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2791 mPointerGesture.currentGestureProperties[0].clear();
2792 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2793 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2794 mPointerGesture.currentGestureCoords[0].clear();
2795 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2796 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2797 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2798 } else if (currentFingerCount == 0) {
2799 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wrightaff169e2020-07-02 18:30:52 +01002800 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002801 *outFinishPreviousGesture = true;
2802 }
2803
2804 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2805 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2806 bool tapped = false;
Michael Wrightaff169e2020-07-02 18:30:52 +01002807 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2808 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002809 lastFingerCount == 1) {
2810 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2811 float x, y;
2812 mPointerController->getPosition(&x, &y);
2813 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2814 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2815#if DEBUG_GESTURES
2816 ALOGD("Gestures: TAP");
2817#endif
2818
2819 mPointerGesture.tapUpTime = when;
2820 getContext()->requestTimeoutAtTime(when +
2821 mConfig.pointerGestureTapDragInterval);
2822
2823 mPointerGesture.activeGestureId = 0;
Michael Wrightaff169e2020-07-02 18:30:52 +01002824 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002825 mPointerGesture.currentGestureIdBits.clear();
2826 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2827 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2828 mPointerGesture.currentGestureProperties[0].clear();
2829 mPointerGesture.currentGestureProperties[0].id =
2830 mPointerGesture.activeGestureId;
2831 mPointerGesture.currentGestureProperties[0].toolType =
2832 AMOTION_EVENT_TOOL_TYPE_FINGER;
2833 mPointerGesture.currentGestureCoords[0].clear();
2834 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2835 mPointerGesture.tapX);
2836 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2837 mPointerGesture.tapY);
2838 mPointerGesture.currentGestureCoords[0]
2839 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2840
2841 tapped = true;
2842 } else {
2843#if DEBUG_GESTURES
2844 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2845 y - mPointerGesture.tapY);
2846#endif
2847 }
2848 } else {
2849#if DEBUG_GESTURES
2850 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2851 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2852 (when - mPointerGesture.tapDownTime) * 0.000001f);
2853 } else {
2854 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2855 }
2856#endif
2857 }
2858 }
2859
2860 mPointerVelocityControl.reset();
2861
2862 if (!tapped) {
2863#if DEBUG_GESTURES
2864 ALOGD("Gestures: NEUTRAL");
2865#endif
2866 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002867 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002868 mPointerGesture.currentGestureIdBits.clear();
2869 }
2870 } else if (currentFingerCount == 1) {
2871 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2872 // The pointer follows the active touch point.
2873 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2874 // When in TAP_DRAG, emit MOVE events at the pointer location.
2875 ALOG_ASSERT(activeTouchId >= 0);
2876
Michael Wrightaff169e2020-07-02 18:30:52 +01002877 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2878 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002879 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2880 float x, y;
2881 mPointerController->getPosition(&x, &y);
2882 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2883 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002884 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002885 } else {
2886#if DEBUG_GESTURES
2887 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2888 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2889#endif
2890 }
2891 } else {
2892#if DEBUG_GESTURES
2893 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2894 (when - mPointerGesture.tapUpTime) * 0.000001f);
2895#endif
2896 }
Michael Wrightaff169e2020-07-02 18:30:52 +01002897 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2898 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002899 }
2900
2901 float deltaX = 0, deltaY = 0;
2902 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2903 const RawPointerData::Pointer& currentPointer =
2904 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2905 const RawPointerData::Pointer& lastPointer =
2906 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2907 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2908 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2909
2910 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2911 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2912
2913 // Move the pointer using a relative motion.
2914 // When using spots, the hover or drag will occur at the position of the anchor spot.
2915 mPointerController->move(deltaX, deltaY);
2916 } else {
2917 mPointerVelocityControl.reset();
2918 }
2919
2920 bool down;
Michael Wrightaff169e2020-07-02 18:30:52 +01002921 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922#if DEBUG_GESTURES
2923 ALOGD("Gestures: TAP_DRAG");
2924#endif
2925 down = true;
2926 } else {
2927#if DEBUG_GESTURES
2928 ALOGD("Gestures: HOVER");
2929#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01002930 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002931 *outFinishPreviousGesture = true;
2932 }
2933 mPointerGesture.activeGestureId = 0;
2934 down = false;
2935 }
2936
2937 float x, y;
2938 mPointerController->getPosition(&x, &y);
2939
2940 mPointerGesture.currentGestureIdBits.clear();
2941 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2942 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2943 mPointerGesture.currentGestureProperties[0].clear();
2944 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2945 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2946 mPointerGesture.currentGestureCoords[0].clear();
2947 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2948 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2949 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2950 down ? 1.0f : 0.0f);
2951
2952 if (lastFingerCount == 0 && currentFingerCount != 0) {
2953 mPointerGesture.resetTap();
2954 mPointerGesture.tapDownTime = when;
2955 mPointerGesture.tapX = x;
2956 mPointerGesture.tapY = y;
2957 }
2958 } else {
2959 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2960 // We need to provide feedback for each finger that goes down so we cannot wait
2961 // for the fingers to move before deciding what to do.
2962 //
2963 // The ambiguous case is deciding what to do when there are two fingers down but they
2964 // have not moved enough to determine whether they are part of a drag or part of a
2965 // freeform gesture, or just a press or long-press at the pointer location.
2966 //
2967 // When there are two fingers we start with the PRESS hypothesis and we generate a
2968 // down at the pointer location.
2969 //
2970 // When the two fingers move enough or when additional fingers are added, we make
2971 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2972 ALOG_ASSERT(activeTouchId >= 0);
2973
2974 bool settled = when >=
2975 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wrightaff169e2020-07-02 18:30:52 +01002976 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2977 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2978 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002979 *outFinishPreviousGesture = true;
2980 } else if (!settled && currentFingerCount > lastFingerCount) {
2981 // Additional pointers have gone down but not yet settled.
2982 // Reset the gesture.
2983#if DEBUG_GESTURES
2984 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2985 "settle time remaining %0.3fms",
2986 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2987 when) * 0.000001f);
2988#endif
2989 *outCancelPreviousGesture = true;
2990 } else {
2991 // Continue previous gesture.
2992 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2993 }
2994
2995 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002996 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002997 mPointerGesture.activeGestureId = 0;
2998 mPointerGesture.referenceIdBits.clear();
2999 mPointerVelocityControl.reset();
3000
3001 // Use the centroid and pointer location as the reference points for the gesture.
3002#if DEBUG_GESTURES
3003 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3004 "settle time remaining %0.3fms",
3005 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3006 when) * 0.000001f);
3007#endif
3008 mCurrentRawState.rawPointerData
3009 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3010 &mPointerGesture.referenceTouchY);
3011 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3012 &mPointerGesture.referenceGestureY);
3013 }
3014
3015 // Clear the reference deltas for fingers not yet included in the reference calculation.
3016 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3017 ~mPointerGesture.referenceIdBits.value);
3018 !idBits.isEmpty();) {
3019 uint32_t id = idBits.clearFirstMarkedBit();
3020 mPointerGesture.referenceDeltas[id].dx = 0;
3021 mPointerGesture.referenceDeltas[id].dy = 0;
3022 }
3023 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3024
3025 // Add delta for all fingers and calculate a common movement delta.
3026 float commonDeltaX = 0, commonDeltaY = 0;
3027 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3028 mCurrentCookedState.fingerIdBits.value);
3029 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3030 bool first = (idBits == commonIdBits);
3031 uint32_t id = idBits.clearFirstMarkedBit();
3032 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3033 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3034 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3035 delta.dx += cpd.x - lpd.x;
3036 delta.dy += cpd.y - lpd.y;
3037
3038 if (first) {
3039 commonDeltaX = delta.dx;
3040 commonDeltaY = delta.dy;
3041 } else {
3042 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3043 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3044 }
3045 }
3046
3047 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wrightaff169e2020-07-02 18:30:52 +01003048 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003049 float dist[MAX_POINTER_ID + 1];
3050 int32_t distOverThreshold = 0;
3051 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3052 uint32_t id = idBits.clearFirstMarkedBit();
3053 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3054 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3055 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3056 distOverThreshold += 1;
3057 }
3058 }
3059
3060 // Only transition when at least two pointers have moved further than
3061 // the minimum distance threshold.
3062 if (distOverThreshold >= 2) {
3063 if (currentFingerCount > 2) {
3064 // There are more than two pointers, switch to FREEFORM.
3065#if DEBUG_GESTURES
3066 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3067 currentFingerCount);
3068#endif
3069 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003070 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003071 } else {
3072 // There are exactly two pointers.
3073 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3074 uint32_t id1 = idBits.clearFirstMarkedBit();
3075 uint32_t id2 = idBits.firstMarkedBit();
3076 const RawPointerData::Pointer& p1 =
3077 mCurrentRawState.rawPointerData.pointerForId(id1);
3078 const RawPointerData::Pointer& p2 =
3079 mCurrentRawState.rawPointerData.pointerForId(id2);
3080 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3081 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3082 // There are two pointers but they are too far apart for a SWIPE,
3083 // switch to FREEFORM.
3084#if DEBUG_GESTURES
3085 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3086 mutualDistance, mPointerGestureMaxSwipeWidth);
3087#endif
3088 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003089 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003090 } else {
3091 // There are two pointers. Wait for both pointers to start moving
3092 // before deciding whether this is a SWIPE or FREEFORM gesture.
3093 float dist1 = dist[id1];
3094 float dist2 = dist[id2];
3095 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3096 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3097 // Calculate the dot product of the displacement vectors.
3098 // When the vectors are oriented in approximately the same direction,
3099 // the angle betweeen them is near zero and the cosine of the angle
3100 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3101 // mag(v2).
3102 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3103 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3104 float dx1 = delta1.dx * mPointerXZoomScale;
3105 float dy1 = delta1.dy * mPointerYZoomScale;
3106 float dx2 = delta2.dx * mPointerXZoomScale;
3107 float dy2 = delta2.dy * mPointerYZoomScale;
3108 float dot = dx1 * dx2 + dy1 * dy2;
3109 float cosine = dot / (dist1 * dist2); // denominator always > 0
3110 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3111 // Pointers are moving in the same direction. Switch to SWIPE.
3112#if DEBUG_GESTURES
3113 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3114 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3115 "cosine %0.3f >= %0.3f",
3116 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3117 mConfig.pointerGestureMultitouchMinDistance, cosine,
3118 mConfig.pointerGestureSwipeTransitionAngleCosine);
3119#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01003120 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003121 } else {
3122 // Pointers are moving in different directions. Switch to FREEFORM.
3123#if DEBUG_GESTURES
3124 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3125 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3126 "cosine %0.3f < %0.3f",
3127 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3128 mConfig.pointerGestureMultitouchMinDistance, cosine,
3129 mConfig.pointerGestureSwipeTransitionAngleCosine);
3130#endif
3131 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003132 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003133 }
3134 }
3135 }
3136 }
3137 }
Michael Wrightaff169e2020-07-02 18:30:52 +01003138 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003139 // Switch from SWIPE to FREEFORM if additional pointers go down.
3140 // Cancel previous gesture.
3141 if (currentFingerCount > 2) {
3142#if DEBUG_GESTURES
3143 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3144 currentFingerCount);
3145#endif
3146 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003147 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003148 }
3149 }
3150
3151 // Move the reference points based on the overall group motion of the fingers
3152 // except in PRESS mode while waiting for a transition to occur.
Michael Wrightaff169e2020-07-02 18:30:52 +01003153 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003154 (commonDeltaX || commonDeltaY)) {
3155 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3156 uint32_t id = idBits.clearFirstMarkedBit();
3157 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3158 delta.dx = 0;
3159 delta.dy = 0;
3160 }
3161
3162 mPointerGesture.referenceTouchX += commonDeltaX;
3163 mPointerGesture.referenceTouchY += commonDeltaY;
3164
3165 commonDeltaX *= mPointerXMovementScale;
3166 commonDeltaY *= mPointerYMovementScale;
3167
3168 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3169 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3170
3171 mPointerGesture.referenceGestureX += commonDeltaX;
3172 mPointerGesture.referenceGestureY += commonDeltaY;
3173 }
3174
3175 // Report gestures.
Michael Wrightaff169e2020-07-02 18:30:52 +01003176 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3177 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003178 // PRESS or SWIPE mode.
3179#if DEBUG_GESTURES
3180 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3181 "activeGestureId=%d, currentTouchPointerCount=%d",
3182 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3183#endif
3184 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3185
3186 mPointerGesture.currentGestureIdBits.clear();
3187 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3188 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3189 mPointerGesture.currentGestureProperties[0].clear();
3190 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3191 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3192 mPointerGesture.currentGestureCoords[0].clear();
3193 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3194 mPointerGesture.referenceGestureX);
3195 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3196 mPointerGesture.referenceGestureY);
3197 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wrightaff169e2020-07-02 18:30:52 +01003198 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003199 // FREEFORM mode.
3200#if DEBUG_GESTURES
3201 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3202 "activeGestureId=%d, currentTouchPointerCount=%d",
3203 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3204#endif
3205 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3206
3207 mPointerGesture.currentGestureIdBits.clear();
3208
3209 BitSet32 mappedTouchIdBits;
3210 BitSet32 usedGestureIdBits;
Michael Wrightaff169e2020-07-02 18:30:52 +01003211 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003212 // Initially, assign the active gesture id to the active touch point
3213 // if there is one. No other touch id bits are mapped yet.
3214 if (!*outCancelPreviousGesture) {
3215 mappedTouchIdBits.markBit(activeTouchId);
3216 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3217 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3218 mPointerGesture.activeGestureId;
3219 } else {
3220 mPointerGesture.activeGestureId = -1;
3221 }
3222 } else {
3223 // Otherwise, assume we mapped all touches from the previous frame.
3224 // Reuse all mappings that are still applicable.
3225 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3226 mCurrentCookedState.fingerIdBits.value;
3227 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3228
3229 // Check whether we need to choose a new active gesture id because the
3230 // current went went up.
3231 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3232 ~mCurrentCookedState.fingerIdBits.value);
3233 !upTouchIdBits.isEmpty();) {
3234 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3235 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3236 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3237 mPointerGesture.activeGestureId = -1;
3238 break;
3239 }
3240 }
3241 }
3242
3243#if DEBUG_GESTURES
3244 ALOGD("Gestures: FREEFORM follow up "
3245 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3246 "activeGestureId=%d",
3247 mappedTouchIdBits.value, usedGestureIdBits.value,
3248 mPointerGesture.activeGestureId);
3249#endif
3250
3251 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3252 for (uint32_t i = 0; i < currentFingerCount; i++) {
3253 uint32_t touchId = idBits.clearFirstMarkedBit();
3254 uint32_t gestureId;
3255 if (!mappedTouchIdBits.hasBit(touchId)) {
3256 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3257 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3258#if DEBUG_GESTURES
3259 ALOGD("Gestures: FREEFORM "
3260 "new mapping for touch id %d -> gesture id %d",
3261 touchId, gestureId);
3262#endif
3263 } else {
3264 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3265#if DEBUG_GESTURES
3266 ALOGD("Gestures: FREEFORM "
3267 "existing mapping for touch id %d -> gesture id %d",
3268 touchId, gestureId);
3269#endif
3270 }
3271 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3272 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3273
3274 const RawPointerData::Pointer& pointer =
3275 mCurrentRawState.rawPointerData.pointerForId(touchId);
3276 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3277 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3278 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3279
3280 mPointerGesture.currentGestureProperties[i].clear();
3281 mPointerGesture.currentGestureProperties[i].id = gestureId;
3282 mPointerGesture.currentGestureProperties[i].toolType =
3283 AMOTION_EVENT_TOOL_TYPE_FINGER;
3284 mPointerGesture.currentGestureCoords[i].clear();
3285 mPointerGesture.currentGestureCoords[i]
3286 .setAxisValue(AMOTION_EVENT_AXIS_X,
3287 mPointerGesture.referenceGestureX + deltaX);
3288 mPointerGesture.currentGestureCoords[i]
3289 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3290 mPointerGesture.referenceGestureY + deltaY);
3291 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3292 1.0f);
3293 }
3294
3295 if (mPointerGesture.activeGestureId < 0) {
3296 mPointerGesture.activeGestureId =
3297 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3298#if DEBUG_GESTURES
3299 ALOGD("Gestures: FREEFORM new "
3300 "activeGestureId=%d",
3301 mPointerGesture.activeGestureId);
3302#endif
3303 }
3304 }
3305 }
3306
3307 mPointerController->setButtonState(mCurrentRawState.buttonState);
3308
3309#if DEBUG_GESTURES
3310 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3311 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3312 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3313 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3314 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3315 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3316 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3317 uint32_t id = idBits.clearFirstMarkedBit();
3318 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3319 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3320 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3321 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3322 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3323 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3324 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3325 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3326 }
3327 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3328 uint32_t id = idBits.clearFirstMarkedBit();
3329 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3330 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3331 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3332 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3333 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3334 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3335 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3336 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3337 }
3338#endif
3339 return true;
3340}
3341
3342void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3343 mPointerSimple.currentCoords.clear();
3344 mPointerSimple.currentProperties.clear();
3345
3346 bool down, hovering;
3347 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3348 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3349 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3350 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3351 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3352 mPointerController->setPosition(x, y);
3353
3354 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3355 down = !hovering;
3356
3357 mPointerController->getPosition(&x, &y);
3358 mPointerSimple.currentCoords.copyFrom(
3359 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3360 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3361 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3362 mPointerSimple.currentProperties.id = 0;
3363 mPointerSimple.currentProperties.toolType =
3364 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3365 } else {
3366 down = false;
3367 hovering = false;
3368 }
3369
3370 dispatchPointerSimple(when, policyFlags, down, hovering);
3371}
3372
3373void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3374 abortPointerSimple(when, policyFlags);
3375}
3376
3377void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3378 mPointerSimple.currentCoords.clear();
3379 mPointerSimple.currentProperties.clear();
3380
3381 bool down, hovering;
3382 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3383 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3384 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3385 float deltaX = 0, deltaY = 0;
3386 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3387 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3388 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3389 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3390 mPointerXMovementScale;
3391 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3392 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3393 mPointerYMovementScale;
3394
3395 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3396 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3397
3398 mPointerController->move(deltaX, deltaY);
3399 } else {
3400 mPointerVelocityControl.reset();
3401 }
3402
3403 down = isPointerDown(mCurrentRawState.buttonState);
3404 hovering = !down;
3405
3406 float x, y;
3407 mPointerController->getPosition(&x, &y);
3408 mPointerSimple.currentCoords.copyFrom(
3409 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3410 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3411 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3412 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3413 hovering ? 0.0f : 1.0f);
3414 mPointerSimple.currentProperties.id = 0;
3415 mPointerSimple.currentProperties.toolType =
3416 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3417 } else {
3418 mPointerVelocityControl.reset();
3419
3420 down = false;
3421 hovering = false;
3422 }
3423
3424 dispatchPointerSimple(when, policyFlags, down, hovering);
3425}
3426
3427void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3428 abortPointerSimple(when, policyFlags);
3429
3430 mPointerVelocityControl.reset();
3431}
3432
3433void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3434 bool hovering) {
3435 int32_t metaState = getContext()->getGlobalMetaState();
3436 int32_t displayId = mViewport.displayId;
3437
3438 if (down || hovering) {
Michael Wright976db0c2020-07-02 00:00:29 +01003439 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003440 mPointerController->clearSpots();
3441 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wright976db0c2020-07-02 00:00:29 +01003442 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003443 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wright976db0c2020-07-02 00:00:29 +01003444 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003445 }
3446 displayId = mPointerController->getDisplayId();
3447
3448 float xCursorPosition;
3449 float yCursorPosition;
3450 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3451
3452 if (mPointerSimple.down && !down) {
3453 mPointerSimple.down = false;
3454
3455 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003456 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3457 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003458 mLastRawState.buttonState, MotionClassification::NONE,
3459 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3460 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3461 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3462 /* videoFrames */ {});
3463 getListener()->notifyMotion(&args);
3464 }
3465
3466 if (mPointerSimple.hovering && !hovering) {
3467 mPointerSimple.hovering = false;
3468
3469 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003470 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3471 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3472 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003473 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3474 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3475 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3476 /* videoFrames */ {});
3477 getListener()->notifyMotion(&args);
3478 }
3479
3480 if (down) {
3481 if (!mPointerSimple.down) {
3482 mPointerSimple.down = true;
3483 mPointerSimple.downTime = when;
3484
3485 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003486 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003487 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3488 metaState, mCurrentRawState.buttonState,
3489 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3490 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3491 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3492 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3493 getListener()->notifyMotion(&args);
3494 }
3495
3496 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003497 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3498 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003499 mCurrentRawState.buttonState, MotionClassification::NONE,
3500 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3501 &mPointerSimple.currentCoords, mOrientedXPrecision,
3502 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3503 mPointerSimple.downTime, /* videoFrames */ {});
3504 getListener()->notifyMotion(&args);
3505 }
3506
3507 if (hovering) {
3508 if (!mPointerSimple.hovering) {
3509 mPointerSimple.hovering = true;
3510
3511 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003512 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003513 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3514 metaState, mCurrentRawState.buttonState,
3515 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3516 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3517 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3518 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3519 getListener()->notifyMotion(&args);
3520 }
3521
3522 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003523 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3524 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3525 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003526 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3527 &mPointerSimple.currentCoords, mOrientedXPrecision,
3528 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3529 mPointerSimple.downTime, /* videoFrames */ {});
3530 getListener()->notifyMotion(&args);
3531 }
3532
3533 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3534 float vscroll = mCurrentRawState.rawVScroll;
3535 float hscroll = mCurrentRawState.rawHScroll;
3536 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3537 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3538
3539 // Send scroll.
3540 PointerCoords pointerCoords;
3541 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3542 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3543 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3544
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003545 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3546 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003547 mCurrentRawState.buttonState, MotionClassification::NONE,
3548 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3549 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3550 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3551 /* videoFrames */ {});
3552 getListener()->notifyMotion(&args);
3553 }
3554
3555 // Save state.
3556 if (down || hovering) {
3557 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3558 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3559 } else {
3560 mPointerSimple.reset();
3561 }
3562}
3563
3564void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3565 mPointerSimple.currentCoords.clear();
3566 mPointerSimple.currentProperties.clear();
3567
3568 dispatchPointerSimple(when, policyFlags, false, false);
3569}
3570
3571void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3572 int32_t action, int32_t actionButton, int32_t flags,
3573 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3574 const PointerProperties* properties,
3575 const PointerCoords* coords, const uint32_t* idToIndex,
3576 BitSet32 idBits, int32_t changedId, float xPrecision,
3577 float yPrecision, nsecs_t downTime) {
3578 PointerCoords pointerCoords[MAX_POINTERS];
3579 PointerProperties pointerProperties[MAX_POINTERS];
3580 uint32_t pointerCount = 0;
3581 while (!idBits.isEmpty()) {
3582 uint32_t id = idBits.clearFirstMarkedBit();
3583 uint32_t index = idToIndex[id];
3584 pointerProperties[pointerCount].copyFrom(properties[index]);
3585 pointerCoords[pointerCount].copyFrom(coords[index]);
3586
3587 if (changedId >= 0 && id == uint32_t(changedId)) {
3588 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3589 }
3590
3591 pointerCount += 1;
3592 }
3593
3594 ALOG_ASSERT(pointerCount != 0);
3595
3596 if (changedId >= 0 && pointerCount == 1) {
3597 // Replace initial down and final up action.
3598 // We can compare the action without masking off the changed pointer index
3599 // because we know the index is 0.
3600 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3601 action = AMOTION_EVENT_ACTION_DOWN;
3602 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhung65600042020-04-30 17:55:40 +08003603 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3604 action = AMOTION_EVENT_ACTION_CANCEL;
3605 } else {
3606 action = AMOTION_EVENT_ACTION_UP;
3607 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003608 } else {
3609 // Can't happen.
3610 ALOG_ASSERT(false);
3611 }
3612 }
3613 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3614 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wrightaff169e2020-07-02 18:30:52 +01003615 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003616 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3617 }
3618 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3619 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003620 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003621 std::for_each(frames.begin(), frames.end(),
3622 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003623 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3624 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003625 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3626 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3627 downTime, std::move(frames));
3628 getListener()->notifyMotion(&args);
3629}
3630
3631bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3632 const PointerCoords* inCoords,
3633 const uint32_t* inIdToIndex,
3634 PointerProperties* outProperties,
3635 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3636 BitSet32 idBits) const {
3637 bool changed = false;
3638 while (!idBits.isEmpty()) {
3639 uint32_t id = idBits.clearFirstMarkedBit();
3640 uint32_t inIndex = inIdToIndex[id];
3641 uint32_t outIndex = outIdToIndex[id];
3642
3643 const PointerProperties& curInProperties = inProperties[inIndex];
3644 const PointerCoords& curInCoords = inCoords[inIndex];
3645 PointerProperties& curOutProperties = outProperties[outIndex];
3646 PointerCoords& curOutCoords = outCoords[outIndex];
3647
3648 if (curInProperties != curOutProperties) {
3649 curOutProperties.copyFrom(curInProperties);
3650 changed = true;
3651 }
3652
3653 if (curInCoords != curOutCoords) {
3654 curOutCoords.copyFrom(curInCoords);
3655 changed = true;
3656 }
3657 }
3658 return changed;
3659}
3660
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003661void TouchInputMapper::cancelTouch(nsecs_t when) {
3662 abortPointerUsage(when, 0 /*policyFlags*/);
3663 abortTouches(when, 0 /* policyFlags*/);
3664}
3665
Arthur Hung4197f6b2020-03-16 15:39:59 +08003666// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003667void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003668 // Scale to surface coordinate.
3669 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3670 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3671
arthurhung10052f62020-12-29 20:28:15 +08003672 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3673 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3674
Arthur Hung4197f6b2020-03-16 15:39:59 +08003675 // Rotate to surface coordinate.
3676 // 0 - no swap and reverse.
3677 // 90 - swap x/y and reverse y.
3678 // 180 - reverse x, y.
3679 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003680 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003681 case DISPLAY_ORIENTATION_0:
3682 x = xScaled + mXTranslate;
3683 y = yScaled + mYTranslate;
3684 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003685 case DISPLAY_ORIENTATION_90:
arthurhung10052f62020-12-29 20:28:15 +08003686 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003687 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003688 break;
3689 case DISPLAY_ORIENTATION_180:
arthurhung10052f62020-12-29 20:28:15 +08003690 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3691 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003692 break;
3693 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003694 y = xScaled + mXTranslate;
arthurhung10052f62020-12-29 20:28:15 +08003695 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003696 break;
3697 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003698 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003699 }
3700}
3701
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003702bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003703 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3704 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3705
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003706 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003707 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003708 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003709 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003710}
3711
3712const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3713 for (const VirtualKey& virtualKey : mVirtualKeys) {
3714#if DEBUG_VIRTUAL_KEYS
3715 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3716 "left=%d, top=%d, right=%d, bottom=%d",
3717 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3718 virtualKey.hitRight, virtualKey.hitBottom);
3719#endif
3720
3721 if (virtualKey.isHit(x, y)) {
3722 return &virtualKey;
3723 }
3724 }
3725
3726 return nullptr;
3727}
3728
3729void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3730 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3731 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3732
3733 current->rawPointerData.clearIdBits();
3734
3735 if (currentPointerCount == 0) {
3736 // No pointers to assign.
3737 return;
3738 }
3739
3740 if (lastPointerCount == 0) {
3741 // All pointers are new.
3742 for (uint32_t i = 0; i < currentPointerCount; i++) {
3743 uint32_t id = i;
3744 current->rawPointerData.pointers[i].id = id;
3745 current->rawPointerData.idToIndex[id] = i;
3746 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3747 }
3748 return;
3749 }
3750
3751 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3752 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3753 // Only one pointer and no change in count so it must have the same id as before.
3754 uint32_t id = last->rawPointerData.pointers[0].id;
3755 current->rawPointerData.pointers[0].id = id;
3756 current->rawPointerData.idToIndex[id] = 0;
3757 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3758 return;
3759 }
3760
3761 // General case.
3762 // We build a heap of squared euclidean distances between current and last pointers
3763 // associated with the current and last pointer indices. Then, we find the best
3764 // match (by distance) for each current pointer.
3765 // The pointers must have the same tool type but it is possible for them to
3766 // transition from hovering to touching or vice-versa while retaining the same id.
3767 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3768
3769 uint32_t heapSize = 0;
3770 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3771 currentPointerIndex++) {
3772 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3773 lastPointerIndex++) {
3774 const RawPointerData::Pointer& currentPointer =
3775 current->rawPointerData.pointers[currentPointerIndex];
3776 const RawPointerData::Pointer& lastPointer =
3777 last->rawPointerData.pointers[lastPointerIndex];
3778 if (currentPointer.toolType == lastPointer.toolType) {
3779 int64_t deltaX = currentPointer.x - lastPointer.x;
3780 int64_t deltaY = currentPointer.y - lastPointer.y;
3781
3782 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3783
3784 // Insert new element into the heap (sift up).
3785 heap[heapSize].currentPointerIndex = currentPointerIndex;
3786 heap[heapSize].lastPointerIndex = lastPointerIndex;
3787 heap[heapSize].distance = distance;
3788 heapSize += 1;
3789 }
3790 }
3791 }
3792
3793 // Heapify
3794 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3795 startIndex -= 1;
3796 for (uint32_t parentIndex = startIndex;;) {
3797 uint32_t childIndex = parentIndex * 2 + 1;
3798 if (childIndex >= heapSize) {
3799 break;
3800 }
3801
3802 if (childIndex + 1 < heapSize &&
3803 heap[childIndex + 1].distance < heap[childIndex].distance) {
3804 childIndex += 1;
3805 }
3806
3807 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3808 break;
3809 }
3810
3811 swap(heap[parentIndex], heap[childIndex]);
3812 parentIndex = childIndex;
3813 }
3814 }
3815
3816#if DEBUG_POINTER_ASSIGNMENT
3817 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3818 for (size_t i = 0; i < heapSize; i++) {
3819 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3820 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3821 }
3822#endif
3823
3824 // Pull matches out by increasing order of distance.
3825 // To avoid reassigning pointers that have already been matched, the loop keeps track
3826 // of which last and current pointers have been matched using the matchedXXXBits variables.
3827 // It also tracks the used pointer id bits.
3828 BitSet32 matchedLastBits(0);
3829 BitSet32 matchedCurrentBits(0);
3830 BitSet32 usedIdBits(0);
3831 bool first = true;
3832 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3833 while (heapSize > 0) {
3834 if (first) {
3835 // The first time through the loop, we just consume the root element of
3836 // the heap (the one with smallest distance).
3837 first = false;
3838 } else {
3839 // Previous iterations consumed the root element of the heap.
3840 // Pop root element off of the heap (sift down).
3841 heap[0] = heap[heapSize];
3842 for (uint32_t parentIndex = 0;;) {
3843 uint32_t childIndex = parentIndex * 2 + 1;
3844 if (childIndex >= heapSize) {
3845 break;
3846 }
3847
3848 if (childIndex + 1 < heapSize &&
3849 heap[childIndex + 1].distance < heap[childIndex].distance) {
3850 childIndex += 1;
3851 }
3852
3853 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3854 break;
3855 }
3856
3857 swap(heap[parentIndex], heap[childIndex]);
3858 parentIndex = childIndex;
3859 }
3860
3861#if DEBUG_POINTER_ASSIGNMENT
3862 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3863 for (size_t i = 0; i < heapSize; i++) {
3864 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3865 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3866 }
3867#endif
3868 }
3869
3870 heapSize -= 1;
3871
3872 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3873 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3874
3875 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3876 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3877
3878 matchedCurrentBits.markBit(currentPointerIndex);
3879 matchedLastBits.markBit(lastPointerIndex);
3880
3881 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3882 current->rawPointerData.pointers[currentPointerIndex].id = id;
3883 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3884 current->rawPointerData.markIdBit(id,
3885 current->rawPointerData.isHovering(
3886 currentPointerIndex));
3887 usedIdBits.markBit(id);
3888
3889#if DEBUG_POINTER_ASSIGNMENT
3890 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3891 ", distance=%" PRIu64,
3892 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3893#endif
3894 break;
3895 }
3896 }
3897
3898 // Assign fresh ids to pointers that were not matched in the process.
3899 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3900 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3901 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3902
3903 current->rawPointerData.pointers[currentPointerIndex].id = id;
3904 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3905 current->rawPointerData.markIdBit(id,
3906 current->rawPointerData.isHovering(currentPointerIndex));
3907
3908#if DEBUG_POINTER_ASSIGNMENT
3909 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3910#endif
3911 }
3912}
3913
3914int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3915 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3916 return AKEY_STATE_VIRTUAL;
3917 }
3918
3919 for (const VirtualKey& virtualKey : mVirtualKeys) {
3920 if (virtualKey.keyCode == keyCode) {
3921 return AKEY_STATE_UP;
3922 }
3923 }
3924
3925 return AKEY_STATE_UNKNOWN;
3926}
3927
3928int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3929 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3930 return AKEY_STATE_VIRTUAL;
3931 }
3932
3933 for (const VirtualKey& virtualKey : mVirtualKeys) {
3934 if (virtualKey.scanCode == scanCode) {
3935 return AKEY_STATE_UP;
3936 }
3937 }
3938
3939 return AKEY_STATE_UNKNOWN;
3940}
3941
3942bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3943 const int32_t* keyCodes, uint8_t* outFlags) {
3944 for (const VirtualKey& virtualKey : mVirtualKeys) {
3945 for (size_t i = 0; i < numCodes; i++) {
3946 if (virtualKey.keyCode == keyCodes[i]) {
3947 outFlags[i] = 1;
3948 }
3949 }
3950 }
3951
3952 return true;
3953}
3954
3955std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3956 if (mParameters.hasAssociatedDisplay) {
Michael Wrightaff169e2020-07-02 18:30:52 +01003957 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003958 return std::make_optional(mPointerController->getDisplayId());
3959 } else {
3960 return std::make_optional(mViewport.displayId);
3961 }
3962 }
3963 return std::nullopt;
3964}
3965
3966} // namespace android