blob: 394c9e49b5b7aad9bf96102d5c11dfcae023f21a [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) {
194 // Populate RELATIVE_X and RELATIVE_Y motion range for touchpad capture mode
195 // RELATIVE_X and RELATIVE_Y motion range is the largest possible hardware relative
196 // motion, e.g. the hardware size finger moved completely across the touchpad in one
197 // sample cycle.
198 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
199 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
200 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
201 x.fuzz, x.resolution);
202 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
203 y.fuzz, y.resolution);
204 }
205
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700206 if (mOrientedRanges.haveSize) {
207 info->addMotionRange(mOrientedRanges.size);
208 }
209
210 if (mOrientedRanges.haveTouchSize) {
211 info->addMotionRange(mOrientedRanges.touchMajor);
212 info->addMotionRange(mOrientedRanges.touchMinor);
213 }
214
215 if (mOrientedRanges.haveToolSize) {
216 info->addMotionRange(mOrientedRanges.toolMajor);
217 info->addMotionRange(mOrientedRanges.toolMinor);
218 }
219
220 if (mOrientedRanges.haveOrientation) {
221 info->addMotionRange(mOrientedRanges.orientation);
222 }
223
224 if (mOrientedRanges.haveDistance) {
225 info->addMotionRange(mOrientedRanges.distance);
226 }
227
228 if (mOrientedRanges.haveTilt) {
229 info->addMotionRange(mOrientedRanges.tilt);
230 }
231
232 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
233 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
234 0.0f);
235 }
236 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
237 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
238 0.0f);
239 }
Michael Wrightaff169e2020-07-02 18:30:52 +0100240 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700241 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
242 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
243 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
244 x.fuzz, x.resolution);
245 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
246 y.fuzz, y.resolution);
247 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
248 x.fuzz, x.resolution);
249 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
250 y.fuzz, y.resolution);
251 }
252 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
253 }
254}
255
256void TouchInputMapper::dump(std::string& dump) {
257 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
258 dumpParameters(dump);
259 dumpVirtualKeys(dump);
260 dumpRawPointerAxes(dump);
261 dumpCalibration(dump);
262 dumpAffineTransformation(dump);
263 dumpSurface(dump);
264
265 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
266 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
267 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
268 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
269 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
270 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
271 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
272 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
273 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
274 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
275 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
276 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
277 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
278 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
279 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
280 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
281 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
282
283 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
284 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
285 mLastRawState.rawPointerData.pointerCount);
286 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
287 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
288 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
289 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
290 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
291 "toolType=%d, isHovering=%s\n",
292 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
293 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
294 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
295 pointer.distance, pointer.toolType, toString(pointer.isHovering));
296 }
297
298 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
299 mLastCookedState.buttonState);
300 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
301 mLastCookedState.cookedPointerData.pointerCount);
302 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
303 const PointerProperties& pointerProperties =
304 mLastCookedState.cookedPointerData.pointerProperties[i];
305 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +0000306 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
307 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
308 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700309 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
310 "toolType=%d, isHovering=%s\n",
311 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +0000312 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
313 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
315 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
316 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
322 pointerProperties.toolType,
323 toString(mLastCookedState.cookedPointerData.isHovering(i)));
324 }
325
326 dump += INDENT3 "Stylus Fusion:\n";
327 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
328 toString(mExternalStylusConnected));
329 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
330 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
331 mExternalStylusFusionTimeout);
332 dump += INDENT3 "External Stylus State:\n";
333 dumpStylusState(dump, mExternalStylusState);
334
Michael Wrightaff169e2020-07-02 18:30:52 +0100335 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700336 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
337 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
338 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
339 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
340 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
341 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
342 }
343}
344
345const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
346 switch (deviceMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100347 case DeviceMode::DISABLED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700348 return "disabled";
Michael Wrightaff169e2020-07-02 18:30:52 +0100349 case DeviceMode::DIRECT:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350 return "direct";
Michael Wrightaff169e2020-07-02 18:30:52 +0100351 case DeviceMode::UNSCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700352 return "unscaled";
Michael Wrightaff169e2020-07-02 18:30:52 +0100353 case DeviceMode::NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700354 return "navigation";
Michael Wrightaff169e2020-07-02 18:30:52 +0100355 case DeviceMode::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700356 return "pointer";
357 }
358 return "unknown";
359}
360
361void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
362 uint32_t changes) {
363 InputMapper::configure(when, config, changes);
364
365 mConfig = *config;
366
367 if (!changes) { // first time only
368 // Configure basic parameters.
369 configureParameters();
370
371 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800372 mCursorScrollAccumulator.configure(getDeviceContext());
373 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374
375 // Configure absolute axis information.
376 configureRawPointerAxes();
377
378 // Prepare input device calibration.
379 parseCalibration();
380 resolveCalibration();
381 }
382
383 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
384 // Update location calibration to reflect current settings
385 updateAffineTransformation();
386 }
387
388 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
389 // Update pointer speed.
390 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
391 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
392 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
393 }
394
395 bool resetNeeded = false;
396 if (!changes ||
397 (changes &
398 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewiseba157b2018-02-22 13:31:42 -0800399 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700400 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
401 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
402 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
403 // Configure device sources, surface dimensions, orientation and
404 // scaling factors.
405 configureSurface(when, &resetNeeded);
406 }
407
408 if (changes && resetNeeded) {
409 // Send reset, unless this is the first time the device has been configured,
410 // in which case the reader will call reset itself after all mappers are ready.
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800411 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800412 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700413 }
414}
415
416void TouchInputMapper::resolveExternalStylusPresence() {
417 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800418 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700419 mExternalStylusConnected = !devices.empty();
420
421 if (!mExternalStylusConnected) {
422 resetExternalStylus();
423 }
424}
425
426void TouchInputMapper::configureParameters() {
427 // Use the pointer presentation mode for devices that do not support distinct
428 // multitouch. The spot-based presentation relies on being able to accurately
429 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800430 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wrightaff169e2020-07-02 18:30:52 +0100431 ? Parameters::GestureMode::SINGLE_TOUCH
432 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700433
434 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800435 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
436 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700437 if (gestureModeString == "single-touch") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100438 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439 } else if (gestureModeString == "multi-touch") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100440 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700441 } else if (gestureModeString != "default") {
442 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
443 }
444 }
445
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800446 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700447 // The device is a touch screen.
Michael Wrightaff169e2020-07-02 18:30:52 +0100448 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800449 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700450 // The device is a pointing device like a track pad.
Michael Wrightaff169e2020-07-02 18:30:52 +0100451 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800452 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
453 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700454 // The device is a cursor device with a touch pad attached.
455 // By default don't use the touch pad to move the pointer.
Michael Wrightaff169e2020-07-02 18:30:52 +0100456 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457 } else {
458 // The device is a touch pad of unknown purpose.
Michael Wrightaff169e2020-07-02 18:30:52 +0100459 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460 }
461
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800462 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463
464 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800465 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
466 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700467 if (deviceTypeString == "touchScreen") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100468 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700469 } else if (deviceTypeString == "touchPad") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100470 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700471 } else if (deviceTypeString == "touchNavigation") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100472 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700473 } else if (deviceTypeString == "pointer") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100474 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700475 } else if (deviceTypeString != "default") {
476 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
477 }
478 }
479
Michael Wrightaff169e2020-07-02 18:30:52 +0100480 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800481 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
482 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700483
484 mParameters.hasAssociatedDisplay = false;
485 mParameters.associatedDisplayIsExternal = false;
486 if (mParameters.orientationAware ||
Michael Wrightaff169e2020-07-02 18:30:52 +0100487 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
488 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700489 mParameters.hasAssociatedDisplay = true;
Michael Wrightaff169e2020-07-02 18:30:52 +0100490 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800491 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700492 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800493 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
494 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700495 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
496 }
497 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800498 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700499 mParameters.hasAssociatedDisplay = true;
500 }
501
502 // Initial downs on external touch devices should wake the device.
503 // Normally we don't do this for internal touch screens to prevent them from waking
504 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800505 mParameters.wake = getDeviceContext().isExternal();
506 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700507}
508
509void TouchInputMapper::dumpParameters(std::string& dump) {
510 dump += INDENT3 "Parameters:\n";
511
512 switch (mParameters.gestureMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100513 case Parameters::GestureMode::SINGLE_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700514 dump += INDENT4 "GestureMode: single-touch\n";
515 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100516 case Parameters::GestureMode::MULTI_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700517 dump += INDENT4 "GestureMode: multi-touch\n";
518 break;
519 default:
520 assert(false);
521 }
522
523 switch (mParameters.deviceType) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100524 case Parameters::DeviceType::TOUCH_SCREEN:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700525 dump += INDENT4 "DeviceType: touchScreen\n";
526 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100527 case Parameters::DeviceType::TOUCH_PAD:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700528 dump += INDENT4 "DeviceType: touchPad\n";
529 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100530 case Parameters::DeviceType::TOUCH_NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700531 dump += INDENT4 "DeviceType: touchNavigation\n";
532 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100533 case Parameters::DeviceType::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700534 dump += INDENT4 "DeviceType: pointer\n";
535 break;
536 default:
537 ALOG_ASSERT(false);
538 }
539
540 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
541 "displayId='%s'\n",
542 toString(mParameters.hasAssociatedDisplay),
543 toString(mParameters.associatedDisplayIsExternal),
544 mParameters.uniqueDisplayId.c_str());
545 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
546}
547
548void TouchInputMapper::configureRawPointerAxes() {
549 mRawPointerAxes.clear();
550}
551
552void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
553 dump += INDENT3 "Raw Touch Axes:\n";
554 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
555 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
556 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
557 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
558 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
559 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
560 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
561 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
562 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
563 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
564 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
565 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
566 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
567}
568
569bool TouchInputMapper::hasExternalStylus() const {
570 return mExternalStylusConnected;
571}
572
573/**
574 * Determine which DisplayViewport to use.
575 * 1. If display port is specified, return the matching viewport. If matching viewport not
576 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800577 * 2. Always use the suggested viewport from WindowManagerService for pointers.
578 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700579 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800580 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700581 */
582std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewiseba157b2018-02-22 13:31:42 -0800583 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800584 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700585 if (displayPort) {
586 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800587 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700588 }
589
Michael Wrightaff169e2020-07-02 18:30:52 +0100590 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800591 std::optional<DisplayViewport> viewport =
592 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
593 if (viewport) {
594 return viewport;
595 } else {
596 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
597 mConfig.defaultPointerDisplayId);
598 }
599 }
600
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700601 // Check if uniqueDisplayId is specified in idc file.
602 if (!mParameters.uniqueDisplayId.empty()) {
603 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
604 }
605
606 ViewportType viewportTypeToUse;
607 if (mParameters.associatedDisplayIsExternal) {
608 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
609 } else {
610 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
611 }
612
613 std::optional<DisplayViewport> viewport =
614 mConfig.getDisplayViewportByType(viewportTypeToUse);
615 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
616 ALOGW("Input device %s should be associated with external display, "
617 "fallback to internal one for the external viewport is not found.",
618 getDeviceName().c_str());
619 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
620 }
621
622 return viewport;
623 }
624
625 // No associated display, return a non-display viewport.
626 DisplayViewport newViewport;
627 // Raw width and height in the natural orientation.
628 int32_t rawWidth = mRawPointerAxes.getRawWidth();
629 int32_t rawHeight = mRawPointerAxes.getRawHeight();
630 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
631 return std::make_optional(newViewport);
632}
633
634void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100635 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700636
637 resolveExternalStylusPresence();
638
639 // Determine device mode.
Michael Wrightaff169e2020-07-02 18:30:52 +0100640 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewiseba157b2018-02-22 13:31:42 -0800641 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700642 mSource = AINPUT_SOURCE_MOUSE;
Michael Wrightaff169e2020-07-02 18:30:52 +0100643 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700644 if (hasStylus()) {
645 mSource |= AINPUT_SOURCE_STYLUS;
646 }
Michael Wrightaff169e2020-07-02 18:30:52 +0100647 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700648 mParameters.hasAssociatedDisplay) {
649 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wrightaff169e2020-07-02 18:30:52 +0100650 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700651 if (hasStylus()) {
652 mSource |= AINPUT_SOURCE_STYLUS;
653 }
654 if (hasExternalStylus()) {
655 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
656 }
Michael Wrightaff169e2020-07-02 18:30:52 +0100657 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700658 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wrightaff169e2020-07-02 18:30:52 +0100659 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700660 } else {
661 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wrightaff169e2020-07-02 18:30:52 +0100662 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700663 }
664
665 // Ensure we have valid X and Y axes.
666 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
667 ALOGW("Touch device '%s' did not report support for X or Y axis! "
668 "The device will be inoperable.",
669 getDeviceName().c_str());
Michael Wrightaff169e2020-07-02 18:30:52 +0100670 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700671 return;
672 }
673
674 // Get associated display dimensions.
675 std::optional<DisplayViewport> newViewport = findViewport();
676 if (!newViewport) {
677 ALOGI("Touch device '%s' could not query the properties of its associated "
678 "display. The device will be inoperable until the display size "
679 "becomes available.",
680 getDeviceName().c_str());
Michael Wrightaff169e2020-07-02 18:30:52 +0100681 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700682 return;
683 }
684
685 // Raw width and height in the natural orientation.
686 int32_t rawWidth = mRawPointerAxes.getRawWidth();
687 int32_t rawHeight = mRawPointerAxes.getRawHeight();
688
689 bool viewportChanged = mViewport != *newViewport;
690 if (viewportChanged) {
691 mViewport = *newViewport;
692
Michael Wrightaff169e2020-07-02 18:30:52 +0100693 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700694 // Convert rotated viewport to natural surface coordinates.
695 int32_t naturalLogicalWidth, naturalLogicalHeight;
696 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
697 int32_t naturalPhysicalLeft, naturalPhysicalTop;
698 int32_t naturalDeviceWidth, naturalDeviceHeight;
699 switch (mViewport.orientation) {
700 case DISPLAY_ORIENTATION_90:
701 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
702 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
703 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
704 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800705 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700706 naturalPhysicalTop = mViewport.physicalLeft;
707 naturalDeviceWidth = mViewport.deviceHeight;
708 naturalDeviceHeight = mViewport.deviceWidth;
709 break;
710 case DISPLAY_ORIENTATION_180:
711 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
712 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
713 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
714 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
715 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
716 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
717 naturalDeviceWidth = mViewport.deviceWidth;
718 naturalDeviceHeight = mViewport.deviceHeight;
719 break;
720 case DISPLAY_ORIENTATION_270:
721 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
722 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
723 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
724 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
725 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800726 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700727 naturalDeviceWidth = mViewport.deviceHeight;
728 naturalDeviceHeight = mViewport.deviceWidth;
729 break;
730 case DISPLAY_ORIENTATION_0:
731 default:
732 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
733 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
734 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
735 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
736 naturalPhysicalLeft = mViewport.physicalLeft;
737 naturalPhysicalTop = mViewport.physicalTop;
738 naturalDeviceWidth = mViewport.deviceWidth;
739 naturalDeviceHeight = mViewport.deviceHeight;
740 break;
741 }
742
743 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
744 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
745 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
746 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
747 }
748
749 mPhysicalWidth = naturalPhysicalWidth;
750 mPhysicalHeight = naturalPhysicalHeight;
751 mPhysicalLeft = naturalPhysicalLeft;
752 mPhysicalTop = naturalPhysicalTop;
753
Arthur Hung4197f6b2020-03-16 15:39:59 +0800754 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
755 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700756 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
757 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800758 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
759 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700760
761 mSurfaceOrientation =
762 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
763 } else {
764 mPhysicalWidth = rawWidth;
765 mPhysicalHeight = rawHeight;
766 mPhysicalLeft = 0;
767 mPhysicalTop = 0;
768
Arthur Hung4197f6b2020-03-16 15:39:59 +0800769 mRawSurfaceWidth = rawWidth;
770 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700771 mSurfaceLeft = 0;
772 mSurfaceTop = 0;
773 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
774 }
775 }
776
777 // If moving between pointer modes, need to reset some state.
778 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
779 if (deviceModeChanged) {
780 mOrientedRanges.clear();
781 }
782
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800783 // Create pointer controller if needed.
Michael Wrightaff169e2020-07-02 18:30:52 +0100784 if (mDeviceMode == DeviceMode::POINTER ||
785 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800786 if (mPointerController == nullptr) {
787 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700788 }
789 } else {
Michael Wright7a376672020-06-26 20:51:44 +0100790 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700791 }
792
793 if (viewportChanged || deviceModeChanged) {
794 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
795 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800796 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700797 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
798
799 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800800 mXScale = float(mRawSurfaceWidth) / rawWidth;
801 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700802 mXTranslate = -mSurfaceLeft;
803 mYTranslate = -mSurfaceTop;
804 mXPrecision = 1.0f / mXScale;
805 mYPrecision = 1.0f / mYScale;
806
807 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
808 mOrientedRanges.x.source = mSource;
809 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
810 mOrientedRanges.y.source = mSource;
811
812 configureVirtualKeys();
813
814 // Scale factor for terms that are not oriented in a particular axis.
815 // If the pixels are square then xScale == yScale otherwise we fake it
816 // by choosing an average.
817 mGeometricScale = avg(mXScale, mYScale);
818
819 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800820 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700821
822 // Size factors.
Michael Wrightaff169e2020-07-02 18:30:52 +0100823 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700824 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
825 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
826 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
827 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
828 } else {
829 mSizeScale = 0.0f;
830 }
831
832 mOrientedRanges.haveTouchSize = true;
833 mOrientedRanges.haveToolSize = true;
834 mOrientedRanges.haveSize = true;
835
836 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
837 mOrientedRanges.touchMajor.source = mSource;
838 mOrientedRanges.touchMajor.min = 0;
839 mOrientedRanges.touchMajor.max = diagonalSize;
840 mOrientedRanges.touchMajor.flat = 0;
841 mOrientedRanges.touchMajor.fuzz = 0;
842 mOrientedRanges.touchMajor.resolution = 0;
843
844 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
845 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
846
847 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
848 mOrientedRanges.toolMajor.source = mSource;
849 mOrientedRanges.toolMajor.min = 0;
850 mOrientedRanges.toolMajor.max = diagonalSize;
851 mOrientedRanges.toolMajor.flat = 0;
852 mOrientedRanges.toolMajor.fuzz = 0;
853 mOrientedRanges.toolMajor.resolution = 0;
854
855 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
856 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
857
858 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
859 mOrientedRanges.size.source = mSource;
860 mOrientedRanges.size.min = 0;
861 mOrientedRanges.size.max = 1.0;
862 mOrientedRanges.size.flat = 0;
863 mOrientedRanges.size.fuzz = 0;
864 mOrientedRanges.size.resolution = 0;
865 } else {
866 mSizeScale = 0.0f;
867 }
868
869 // Pressure factors.
870 mPressureScale = 0;
871 float pressureMax = 1.0;
Michael Wrightaff169e2020-07-02 18:30:52 +0100872 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
873 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700874 if (mCalibration.havePressureScale) {
875 mPressureScale = mCalibration.pressureScale;
876 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
877 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
878 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
879 }
880 }
881
882 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
883 mOrientedRanges.pressure.source = mSource;
884 mOrientedRanges.pressure.min = 0;
885 mOrientedRanges.pressure.max = pressureMax;
886 mOrientedRanges.pressure.flat = 0;
887 mOrientedRanges.pressure.fuzz = 0;
888 mOrientedRanges.pressure.resolution = 0;
889
890 // Tilt
891 mTiltXCenter = 0;
892 mTiltXScale = 0;
893 mTiltYCenter = 0;
894 mTiltYScale = 0;
895 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
896 if (mHaveTilt) {
897 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
898 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
899 mTiltXScale = M_PI / 180;
900 mTiltYScale = M_PI / 180;
901
902 mOrientedRanges.haveTilt = true;
903
904 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
905 mOrientedRanges.tilt.source = mSource;
906 mOrientedRanges.tilt.min = 0;
907 mOrientedRanges.tilt.max = M_PI_2;
908 mOrientedRanges.tilt.flat = 0;
909 mOrientedRanges.tilt.fuzz = 0;
910 mOrientedRanges.tilt.resolution = 0;
911 }
912
913 // Orientation
914 mOrientationScale = 0;
915 if (mHaveTilt) {
916 mOrientedRanges.haveOrientation = true;
917
918 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
919 mOrientedRanges.orientation.source = mSource;
920 mOrientedRanges.orientation.min = -M_PI;
921 mOrientedRanges.orientation.max = M_PI;
922 mOrientedRanges.orientation.flat = 0;
923 mOrientedRanges.orientation.fuzz = 0;
924 mOrientedRanges.orientation.resolution = 0;
925 } else if (mCalibration.orientationCalibration !=
Michael Wrightaff169e2020-07-02 18:30:52 +0100926 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700927 if (mCalibration.orientationCalibration ==
Michael Wrightaff169e2020-07-02 18:30:52 +0100928 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700929 if (mRawPointerAxes.orientation.valid) {
930 if (mRawPointerAxes.orientation.maxValue > 0) {
931 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
932 } else if (mRawPointerAxes.orientation.minValue < 0) {
933 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
934 } else {
935 mOrientationScale = 0;
936 }
937 }
938 }
939
940 mOrientedRanges.haveOrientation = true;
941
942 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
943 mOrientedRanges.orientation.source = mSource;
944 mOrientedRanges.orientation.min = -M_PI_2;
945 mOrientedRanges.orientation.max = M_PI_2;
946 mOrientedRanges.orientation.flat = 0;
947 mOrientedRanges.orientation.fuzz = 0;
948 mOrientedRanges.orientation.resolution = 0;
949 }
950
951 // Distance
952 mDistanceScale = 0;
Michael Wrightaff169e2020-07-02 18:30:52 +0100953 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
954 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700955 if (mCalibration.haveDistanceScale) {
956 mDistanceScale = mCalibration.distanceScale;
957 } else {
958 mDistanceScale = 1.0f;
959 }
960 }
961
962 mOrientedRanges.haveDistance = true;
963
964 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
965 mOrientedRanges.distance.source = mSource;
966 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
967 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
968 mOrientedRanges.distance.flat = 0;
969 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
970 mOrientedRanges.distance.resolution = 0;
971 }
972
973 // Compute oriented precision, scales and ranges.
974 // Note that the maximum value reported is an inclusive maximum value so it is one
975 // unit less than the total width or height of surface.
976 switch (mSurfaceOrientation) {
977 case DISPLAY_ORIENTATION_90:
978 case DISPLAY_ORIENTATION_270:
979 mOrientedXPrecision = mYPrecision;
980 mOrientedYPrecision = mXPrecision;
981
982 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800983 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700984 mOrientedRanges.x.flat = 0;
985 mOrientedRanges.x.fuzz = 0;
986 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
987
988 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800989 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700990 mOrientedRanges.y.flat = 0;
991 mOrientedRanges.y.fuzz = 0;
992 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
993 break;
994
995 default:
996 mOrientedXPrecision = mXPrecision;
997 mOrientedYPrecision = mYPrecision;
998
999 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001000 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001001 mOrientedRanges.x.flat = 0;
1002 mOrientedRanges.x.fuzz = 0;
1003 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1004
1005 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001006 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001007 mOrientedRanges.y.flat = 0;
1008 mOrientedRanges.y.fuzz = 0;
1009 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1010 break;
1011 }
1012
1013 // Location
1014 updateAffineTransformation();
1015
Michael Wrightaff169e2020-07-02 18:30:52 +01001016 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001017 // Compute pointer gesture detection parameters.
1018 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001019 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001020
1021 // Scale movements such that one whole swipe of the touch pad covers a
1022 // given area relative to the diagonal size of the display when no acceleration
1023 // is applied.
1024 // Assume that the touch pad has a square aspect ratio such that movements in
1025 // X and Y of the same number of raw units cover the same physical distance.
1026 mPointerXMovementScale =
1027 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1028 mPointerYMovementScale = mPointerXMovementScale;
1029
1030 // Scale zooms to cover a smaller range of the display than movements do.
1031 // This value determines the area around the pointer that is affected by freeform
1032 // pointer gestures.
1033 mPointerXZoomScale =
1034 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1035 mPointerYZoomScale = mPointerXZoomScale;
1036
1037 // Max width between pointers to detect a swipe gesture is more than some fraction
1038 // of the diagonal axis of the touch pad. Touches that are wider than this are
1039 // translated into freeform gestures.
1040 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1041
1042 // Abort current pointer usages because the state has changed.
1043 abortPointerUsage(when, 0 /*policyFlags*/);
1044 }
1045
1046 // Inform the dispatcher about the changes.
1047 *outResetNeeded = true;
1048 bumpGeneration();
1049 }
1050}
1051
1052void TouchInputMapper::dumpSurface(std::string& dump) {
1053 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001054 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1055 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001056 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1057 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001058 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1059 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001060 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1061 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1062 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1063 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1064 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1065}
1066
1067void TouchInputMapper::configureVirtualKeys() {
1068 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001069 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001070
1071 mVirtualKeys.clear();
1072
1073 if (virtualKeyDefinitions.size() == 0) {
1074 return;
1075 }
1076
1077 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1078 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1079 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1080 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1081
1082 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1083 VirtualKey virtualKey;
1084
1085 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1086 int32_t keyCode;
1087 int32_t dummyKeyMetaState;
1088 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001089 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1090 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001091 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1092 continue; // drop the key
1093 }
1094
1095 virtualKey.keyCode = keyCode;
1096 virtualKey.flags = flags;
1097
1098 // convert the key definition's display coordinates into touch coordinates for a hit box
1099 int32_t halfWidth = virtualKeyDefinition.width / 2;
1100 int32_t halfHeight = virtualKeyDefinition.height / 2;
1101
1102 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001103 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001104 touchScreenLeft;
1105 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001106 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001107 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001108 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1109 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001110 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001111 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1112 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 touchScreenTop;
1114 mVirtualKeys.push_back(virtualKey);
1115 }
1116}
1117
1118void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1119 if (!mVirtualKeys.empty()) {
1120 dump += INDENT3 "Virtual Keys:\n";
1121
1122 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1123 const VirtualKey& virtualKey = mVirtualKeys[i];
1124 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1125 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1126 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1127 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1128 }
1129 }
1130}
1131
1132void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001133 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001134 Calibration& out = mCalibration;
1135
1136 // Size
Michael Wrightaff169e2020-07-02 18:30:52 +01001137 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001138 String8 sizeCalibrationString;
1139 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1140 if (sizeCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001141 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 } else if (sizeCalibrationString == "geometric") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001143 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 } else if (sizeCalibrationString == "diameter") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001145 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001146 } else if (sizeCalibrationString == "box") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001147 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 } else if (sizeCalibrationString == "area") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001149 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 } else if (sizeCalibrationString != "default") {
1151 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1152 }
1153 }
1154
1155 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1156 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1157 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1158
1159 // Pressure
Michael Wrightaff169e2020-07-02 18:30:52 +01001160 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001161 String8 pressureCalibrationString;
1162 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1163 if (pressureCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001164 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165 } else if (pressureCalibrationString == "physical") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001166 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 } else if (pressureCalibrationString == "amplitude") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001168 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 } else if (pressureCalibrationString != "default") {
1170 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1171 pressureCalibrationString.string());
1172 }
1173 }
1174
1175 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1176
1177 // Orientation
Michael Wrightaff169e2020-07-02 18:30:52 +01001178 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179 String8 orientationCalibrationString;
1180 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1181 if (orientationCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001182 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001183 } else if (orientationCalibrationString == "interpolated") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001184 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001185 } else if (orientationCalibrationString == "vector") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001186 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001187 } else if (orientationCalibrationString != "default") {
1188 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1189 orientationCalibrationString.string());
1190 }
1191 }
1192
1193 // Distance
Michael Wrightaff169e2020-07-02 18:30:52 +01001194 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195 String8 distanceCalibrationString;
1196 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1197 if (distanceCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001198 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 } else if (distanceCalibrationString == "scaled") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001200 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 } else if (distanceCalibrationString != "default") {
1202 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1203 distanceCalibrationString.string());
1204 }
1205 }
1206
1207 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1208
Michael Wrightaff169e2020-07-02 18:30:52 +01001209 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210 String8 coverageCalibrationString;
1211 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1212 if (coverageCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001213 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 } else if (coverageCalibrationString == "box") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001215 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 } else if (coverageCalibrationString != "default") {
1217 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1218 coverageCalibrationString.string());
1219 }
1220 }
1221}
1222
1223void TouchInputMapper::resolveCalibration() {
1224 // Size
1225 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001226 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1227 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001228 }
1229 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001230 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 }
1232
1233 // Pressure
1234 if (mRawPointerAxes.pressure.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001235 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1236 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 }
1238 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001239 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 }
1241
1242 // Orientation
1243 if (mRawPointerAxes.orientation.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001244 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1245 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 }
1247 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001248 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 }
1250
1251 // Distance
1252 if (mRawPointerAxes.distance.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001253 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1254 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001257 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 }
1259
1260 // Coverage
Michael Wrightaff169e2020-07-02 18:30:52 +01001261 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1262 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 }
1264}
1265
1266void TouchInputMapper::dumpCalibration(std::string& dump) {
1267 dump += INDENT3 "Calibration:\n";
1268
1269 // Size
1270 switch (mCalibration.sizeCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001271 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001272 dump += INDENT4 "touch.size.calibration: none\n";
1273 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001274 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275 dump += INDENT4 "touch.size.calibration: geometric\n";
1276 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001277 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 dump += INDENT4 "touch.size.calibration: diameter\n";
1279 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001280 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 dump += INDENT4 "touch.size.calibration: box\n";
1282 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001283 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 dump += INDENT4 "touch.size.calibration: area\n";
1285 break;
1286 default:
1287 ALOG_ASSERT(false);
1288 }
1289
1290 if (mCalibration.haveSizeScale) {
1291 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1292 }
1293
1294 if (mCalibration.haveSizeBias) {
1295 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1296 }
1297
1298 if (mCalibration.haveSizeIsSummed) {
1299 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1300 toString(mCalibration.sizeIsSummed));
1301 }
1302
1303 // Pressure
1304 switch (mCalibration.pressureCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001305 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 dump += INDENT4 "touch.pressure.calibration: none\n";
1307 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001308 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001309 dump += INDENT4 "touch.pressure.calibration: physical\n";
1310 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001311 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1313 break;
1314 default:
1315 ALOG_ASSERT(false);
1316 }
1317
1318 if (mCalibration.havePressureScale) {
1319 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1320 }
1321
1322 // Orientation
1323 switch (mCalibration.orientationCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001324 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 dump += INDENT4 "touch.orientation.calibration: none\n";
1326 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001327 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1329 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001330 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.orientation.calibration: vector\n";
1332 break;
1333 default:
1334 ALOG_ASSERT(false);
1335 }
1336
1337 // Distance
1338 switch (mCalibration.distanceCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001339 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001340 dump += INDENT4 "touch.distance.calibration: none\n";
1341 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001342 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001343 dump += INDENT4 "touch.distance.calibration: scaled\n";
1344 break;
1345 default:
1346 ALOG_ASSERT(false);
1347 }
1348
1349 if (mCalibration.haveDistanceScale) {
1350 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1351 }
1352
1353 switch (mCalibration.coverageCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001354 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001355 dump += INDENT4 "touch.coverage.calibration: none\n";
1356 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001357 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001358 dump += INDENT4 "touch.coverage.calibration: box\n";
1359 break;
1360 default:
1361 ALOG_ASSERT(false);
1362 }
1363}
1364
1365void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1366 dump += INDENT3 "Affine Transformation:\n";
1367
1368 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1369 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1370 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1371 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1372 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1373 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1374}
1375
1376void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001377 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001378 mSurfaceOrientation);
1379}
1380
1381void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001382 mCursorButtonAccumulator.reset(getDeviceContext());
1383 mCursorScrollAccumulator.reset(getDeviceContext());
1384 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001385
1386 mPointerVelocityControl.reset();
1387 mWheelXVelocityControl.reset();
1388 mWheelYVelocityControl.reset();
1389
1390 mRawStatesPending.clear();
1391 mCurrentRawState.clear();
1392 mCurrentCookedState.clear();
1393 mLastRawState.clear();
1394 mLastCookedState.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001395 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001396 mSentHoverEnter = false;
1397 mHavePointerIds = false;
1398 mCurrentMotionAborted = false;
1399 mDownTime = 0;
1400
1401 mCurrentVirtualKey.down = false;
1402
1403 mPointerGesture.reset();
1404 mPointerSimple.reset();
1405 resetExternalStylus();
1406
1407 if (mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01001408 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001409 mPointerController->clearSpots();
1410 }
1411
1412 InputMapper::reset(when);
1413}
1414
1415void TouchInputMapper::resetExternalStylus() {
1416 mExternalStylusState.clear();
1417 mExternalStylusId = -1;
1418 mExternalStylusFusionTimeout = LLONG_MAX;
1419 mExternalStylusDataPending = false;
1420}
1421
1422void TouchInputMapper::clearStylusDataPendingFlags() {
1423 mExternalStylusDataPending = false;
1424 mExternalStylusFusionTimeout = LLONG_MAX;
1425}
1426
1427void TouchInputMapper::process(const RawEvent* rawEvent) {
1428 mCursorButtonAccumulator.process(rawEvent);
1429 mCursorScrollAccumulator.process(rawEvent);
1430 mTouchButtonAccumulator.process(rawEvent);
1431
1432 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1433 sync(rawEvent->when);
1434 }
1435}
1436
1437void TouchInputMapper::sync(nsecs_t when) {
1438 const RawState* last =
1439 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1440
1441 // Push a new state.
1442 mRawStatesPending.emplace_back();
1443
1444 RawState* next = &mRawStatesPending.back();
1445 next->clear();
1446 next->when = when;
1447
1448 // Sync button state.
1449 next->buttonState =
1450 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1451
1452 // Sync scroll
1453 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1454 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1455 mCursorScrollAccumulator.finishSync();
1456
1457 // Sync touch
1458 syncTouch(when, next);
1459
1460 // Assign pointer ids.
1461 if (!mHavePointerIds) {
1462 assignPointerIds(last, next);
1463 }
1464
1465#if DEBUG_RAW_EVENTS
1466 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhung65600042020-04-30 17:55:40 +08001467 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001468 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1469 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhung65600042020-04-30 17:55:40 +08001470 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1471 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001472#endif
1473
1474 processRawTouches(false /*timeout*/);
1475}
1476
1477void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001478 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001479 // Drop all input if the device is disabled.
1480 mCurrentRawState.clear();
1481 mRawStatesPending.clear();
1482 return;
1483 }
1484
1485 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1486 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1487 // touching the current state will only observe the events that have been dispatched to the
1488 // rest of the pipeline.
1489 const size_t N = mRawStatesPending.size();
1490 size_t count;
1491 for (count = 0; count < N; count++) {
1492 const RawState& next = mRawStatesPending[count];
1493
1494 // A failure to assign the stylus id means that we're waiting on stylus data
1495 // and so should defer the rest of the pipeline.
1496 if (assignExternalStylusId(next, timeout)) {
1497 break;
1498 }
1499
1500 // All ready to go.
1501 clearStylusDataPendingFlags();
1502 mCurrentRawState.copyFrom(next);
1503 if (mCurrentRawState.when < mLastRawState.when) {
1504 mCurrentRawState.when = mLastRawState.when;
1505 }
1506 cookAndDispatch(mCurrentRawState.when);
1507 }
1508 if (count != 0) {
1509 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1510 }
1511
1512 if (mExternalStylusDataPending) {
1513 if (timeout) {
1514 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1515 clearStylusDataPendingFlags();
1516 mCurrentRawState.copyFrom(mLastRawState);
1517#if DEBUG_STYLUS_FUSION
1518 ALOGD("Timeout expired, synthesizing event with new stylus data");
1519#endif
1520 cookAndDispatch(when);
1521 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1522 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1523 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1524 }
1525 }
1526}
1527
1528void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1529 // Always start with a clean state.
1530 mCurrentCookedState.clear();
1531
1532 // Apply stylus buttons to current raw state.
1533 applyExternalStylusButtonState(when);
1534
1535 // Handle policy on initial down or hover events.
1536 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1537 mCurrentRawState.rawPointerData.pointerCount != 0;
1538
1539 uint32_t policyFlags = 0;
1540 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1541 if (initialDown || buttonsPressed) {
1542 // If this is a touch screen, hide the pointer on an initial down.
Michael Wrightaff169e2020-07-02 18:30:52 +01001543 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001544 getContext()->fadePointer();
1545 }
1546
1547 if (mParameters.wake) {
1548 policyFlags |= POLICY_FLAG_WAKE;
1549 }
1550 }
1551
1552 // Consume raw off-screen touches before cooking pointer data.
1553 // If touches are consumed, subsequent code will not receive any pointer data.
1554 if (consumeRawTouches(when, policyFlags)) {
1555 mCurrentRawState.rawPointerData.clear();
1556 }
1557
1558 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1559 // with cooked pointer data that has the same ids and indices as the raw data.
1560 // The following code can use either the raw or cooked data, as needed.
1561 cookPointerData();
1562
1563 // Apply stylus pressure to current cooked state.
1564 applyExternalStylusTouchState(when);
1565
1566 // Synthesize key down from raw buttons if needed.
1567 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1568 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1569 mCurrentCookedState.buttonState);
1570
1571 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wrightaff169e2020-07-02 18:30:52 +01001572 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001573 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1574 uint32_t id = idBits.clearFirstMarkedBit();
1575 const RawPointerData::Pointer& pointer =
1576 mCurrentRawState.rawPointerData.pointerForId(id);
1577 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1578 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1579 mCurrentCookedState.stylusIdBits.markBit(id);
1580 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1581 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1582 mCurrentCookedState.fingerIdBits.markBit(id);
1583 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1584 mCurrentCookedState.mouseIdBits.markBit(id);
1585 }
1586 }
1587 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1588 uint32_t id = idBits.clearFirstMarkedBit();
1589 const RawPointerData::Pointer& pointer =
1590 mCurrentRawState.rawPointerData.pointerForId(id);
1591 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1592 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1593 mCurrentCookedState.stylusIdBits.markBit(id);
1594 }
1595 }
1596
1597 // Stylus takes precedence over all tools, then mouse, then finger.
1598 PointerUsage pointerUsage = mPointerUsage;
1599 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1600 mCurrentCookedState.mouseIdBits.clear();
1601 mCurrentCookedState.fingerIdBits.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001602 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001603 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1604 mCurrentCookedState.fingerIdBits.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001605 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001606 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1607 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001608 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001609 }
1610
1611 dispatchPointerUsage(when, policyFlags, pointerUsage);
1612 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001613 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001614 mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01001615 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1616 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617
1618 mPointerController->setButtonState(mCurrentRawState.buttonState);
1619 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1620 mCurrentCookedState.cookedPointerData.idToIndex,
1621 mCurrentCookedState.cookedPointerData.touchingIdBits,
1622 mViewport.displayId);
1623 }
1624
1625 if (!mCurrentMotionAborted) {
1626 dispatchButtonRelease(when, policyFlags);
1627 dispatchHoverExit(when, policyFlags);
1628 dispatchTouches(when, policyFlags);
1629 dispatchHoverEnterAndMove(when, policyFlags);
1630 dispatchButtonPress(when, policyFlags);
1631 }
1632
1633 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1634 mCurrentMotionAborted = false;
1635 }
1636 }
1637
1638 // Synthesize key up from raw buttons if needed.
1639 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1640 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1641 mCurrentCookedState.buttonState);
1642
1643 // Clear some transient state.
1644 mCurrentRawState.rawVScroll = 0;
1645 mCurrentRawState.rawHScroll = 0;
1646
1647 // Copy current touch to last touch in preparation for the next cycle.
1648 mLastRawState.copyFrom(mCurrentRawState);
1649 mLastCookedState.copyFrom(mCurrentCookedState);
1650}
1651
1652void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001653 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001654 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1655 }
1656}
1657
1658void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1659 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1660 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1661
1662 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1663 float pressure = mExternalStylusState.pressure;
1664 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1665 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1666 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1667 }
1668 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1669 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1670
1671 PointerProperties& properties =
1672 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1673 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1674 properties.toolType = mExternalStylusState.toolType;
1675 }
1676 }
1677}
1678
1679bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001680 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001681 return false;
1682 }
1683
1684 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1685 state.rawPointerData.pointerCount != 0;
1686 if (initialDown) {
1687 if (mExternalStylusState.pressure != 0.0f) {
1688#if DEBUG_STYLUS_FUSION
1689 ALOGD("Have both stylus and touch data, beginning fusion");
1690#endif
1691 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1692 } else if (timeout) {
1693#if DEBUG_STYLUS_FUSION
1694 ALOGD("Timeout expired, assuming touch is not a stylus.");
1695#endif
1696 resetExternalStylus();
1697 } else {
1698 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1699 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1700 }
1701#if DEBUG_STYLUS_FUSION
1702 ALOGD("No stylus data but stylus is connected, requesting timeout "
1703 "(%" PRId64 "ms)",
1704 mExternalStylusFusionTimeout);
1705#endif
1706 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1707 return true;
1708 }
1709 }
1710
1711 // Check if the stylus pointer has gone up.
1712 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1713#if DEBUG_STYLUS_FUSION
1714 ALOGD("Stylus pointer is going up");
1715#endif
1716 mExternalStylusId = -1;
1717 }
1718
1719 return false;
1720}
1721
1722void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001723 if (mDeviceMode == DeviceMode::POINTER) {
1724 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001725 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1726 }
Michael Wrightaff169e2020-07-02 18:30:52 +01001727 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001728 if (mExternalStylusFusionTimeout < when) {
1729 processRawTouches(true /*timeout*/);
1730 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1731 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1732 }
1733 }
1734}
1735
1736void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1737 mExternalStylusState.copyFrom(state);
1738 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1739 // We're either in the middle of a fused stream of data or we're waiting on data before
1740 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1741 // data.
1742 mExternalStylusDataPending = true;
1743 processRawTouches(false /*timeout*/);
1744 }
1745}
1746
1747bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1748 // Check for release of a virtual key.
1749 if (mCurrentVirtualKey.down) {
1750 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1751 // Pointer went up while virtual key was down.
1752 mCurrentVirtualKey.down = false;
1753 if (!mCurrentVirtualKey.ignored) {
1754#if DEBUG_VIRTUAL_KEYS
1755 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1756 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1757#endif
1758 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1759 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1760 }
1761 return true;
1762 }
1763
1764 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1765 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1766 const RawPointerData::Pointer& pointer =
1767 mCurrentRawState.rawPointerData.pointerForId(id);
1768 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1769 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1770 // Pointer is still within the space of the virtual key.
1771 return true;
1772 }
1773 }
1774
1775 // Pointer left virtual key area or another pointer also went down.
1776 // Send key cancellation but do not consume the touch yet.
1777 // This is useful when the user swipes through from the virtual key area
1778 // into the main display surface.
1779 mCurrentVirtualKey.down = false;
1780 if (!mCurrentVirtualKey.ignored) {
1781#if DEBUG_VIRTUAL_KEYS
1782 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1783 mCurrentVirtualKey.scanCode);
1784#endif
1785 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1786 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1787 AKEY_EVENT_FLAG_CANCELED);
1788 }
1789 }
1790
1791 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1792 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1793 // Pointer just went down. Check for virtual key press or off-screen touches.
1794 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1795 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Yedca44af2020-08-05 15:07:56 -07001796 // Exclude unscaled device for inside surface checking.
1797 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001798 // If exactly one pointer went down, check for virtual key hit.
1799 // Otherwise we will drop the entire stroke.
1800 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1801 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1802 if (virtualKey) {
1803 mCurrentVirtualKey.down = true;
1804 mCurrentVirtualKey.downTime = when;
1805 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1806 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1807 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001808 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1809 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001810
1811 if (!mCurrentVirtualKey.ignored) {
1812#if DEBUG_VIRTUAL_KEYS
1813 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1814 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1815#endif
1816 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1817 AKEY_EVENT_FLAG_FROM_SYSTEM |
1818 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1819 }
1820 }
1821 }
1822 return true;
1823 }
1824 }
1825
1826 // Disable all virtual key touches that happen within a short time interval of the
1827 // most recent touch within the screen area. The idea is to filter out stray
1828 // virtual key presses when interacting with the touch screen.
1829 //
1830 // Problems we're trying to solve:
1831 //
1832 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1833 // virtual key area that is implemented by a separate touch panel and accidentally
1834 // triggers a virtual key.
1835 //
1836 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1837 // area and accidentally triggers a virtual key. This often happens when virtual keys
1838 // are layed out below the screen near to where the on screen keyboard's space bar
1839 // is displayed.
1840 if (mConfig.virtualKeyQuietTime > 0 &&
1841 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001842 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001843 }
1844 return false;
1845}
1846
1847void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1848 int32_t keyEventAction, int32_t keyEventFlags) {
1849 int32_t keyCode = mCurrentVirtualKey.keyCode;
1850 int32_t scanCode = mCurrentVirtualKey.scanCode;
1851 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001852 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001853 policyFlags |= POLICY_FLAG_VIRTUAL;
1854
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001855 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1856 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1857 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001858 getListener()->notifyKey(&args);
1859}
1860
1861void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1862 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1863 if (!currentIdBits.isEmpty()) {
1864 int32_t metaState = getContext()->getGlobalMetaState();
1865 int32_t buttonState = mCurrentCookedState.buttonState;
1866 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1867 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1868 mCurrentCookedState.cookedPointerData.pointerProperties,
1869 mCurrentCookedState.cookedPointerData.pointerCoords,
1870 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1871 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1872 mCurrentMotionAborted = true;
1873 }
1874}
1875
1876void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1877 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1878 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1879 int32_t metaState = getContext()->getGlobalMetaState();
1880 int32_t buttonState = mCurrentCookedState.buttonState;
1881
1882 if (currentIdBits == lastIdBits) {
1883 if (!currentIdBits.isEmpty()) {
1884 // No pointer id changes so this is a move event.
1885 // The listener takes care of batching moves so we don't have to deal with that here.
1886 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1887 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1888 mCurrentCookedState.cookedPointerData.pointerProperties,
1889 mCurrentCookedState.cookedPointerData.pointerCoords,
1890 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1891 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1892 }
1893 } else {
1894 // There may be pointers going up and pointers going down and pointers moving
1895 // all at the same time.
1896 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1897 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1898 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1899 BitSet32 dispatchedIdBits(lastIdBits.value);
1900
1901 // Update last coordinates of pointers that have moved so that we observe the new
1902 // pointer positions at the same time as other pointers that have just gone up.
1903 bool moveNeeded =
1904 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1905 mCurrentCookedState.cookedPointerData.pointerCoords,
1906 mCurrentCookedState.cookedPointerData.idToIndex,
1907 mLastCookedState.cookedPointerData.pointerProperties,
1908 mLastCookedState.cookedPointerData.pointerCoords,
1909 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1910 if (buttonState != mLastCookedState.buttonState) {
1911 moveNeeded = true;
1912 }
1913
1914 // Dispatch pointer up events.
1915 while (!upIdBits.isEmpty()) {
1916 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhung65600042020-04-30 17:55:40 +08001917 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1918 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1919 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001920 mLastCookedState.cookedPointerData.pointerProperties,
1921 mLastCookedState.cookedPointerData.pointerCoords,
1922 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1923 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1924 dispatchedIdBits.clearBit(upId);
arthurhung65600042020-04-30 17:55:40 +08001925 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001926 }
1927
1928 // Dispatch move events if any of the remaining pointers moved from their old locations.
1929 // Although applications receive new locations as part of individual pointer up
1930 // events, they do not generally handle them except when presented in a move event.
1931 if (moveNeeded && !moveIdBits.isEmpty()) {
1932 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1933 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1934 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1935 mCurrentCookedState.cookedPointerData.pointerCoords,
1936 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1937 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1938 }
1939
1940 // Dispatch pointer down events using the new pointer locations.
1941 while (!downIdBits.isEmpty()) {
1942 uint32_t downId = downIdBits.clearFirstMarkedBit();
1943 dispatchedIdBits.markBit(downId);
1944
1945 if (dispatchedIdBits.count() == 1) {
1946 // First pointer is going down. Set down time.
1947 mDownTime = when;
1948 }
1949
1950 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1951 metaState, buttonState, 0,
1952 mCurrentCookedState.cookedPointerData.pointerProperties,
1953 mCurrentCookedState.cookedPointerData.pointerCoords,
1954 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1955 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1956 }
1957 }
1958}
1959
1960void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1961 if (mSentHoverEnter &&
1962 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1963 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1964 int32_t metaState = getContext()->getGlobalMetaState();
1965 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1966 mLastCookedState.buttonState, 0,
1967 mLastCookedState.cookedPointerData.pointerProperties,
1968 mLastCookedState.cookedPointerData.pointerCoords,
1969 mLastCookedState.cookedPointerData.idToIndex,
1970 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1971 mOrientedYPrecision, mDownTime);
1972 mSentHoverEnter = false;
1973 }
1974}
1975
1976void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1977 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1978 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1979 int32_t metaState = getContext()->getGlobalMetaState();
1980 if (!mSentHoverEnter) {
1981 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1982 metaState, mCurrentRawState.buttonState, 0,
1983 mCurrentCookedState.cookedPointerData.pointerProperties,
1984 mCurrentCookedState.cookedPointerData.pointerCoords,
1985 mCurrentCookedState.cookedPointerData.idToIndex,
1986 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1987 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1988 mSentHoverEnter = true;
1989 }
1990
1991 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1992 mCurrentRawState.buttonState, 0,
1993 mCurrentCookedState.cookedPointerData.pointerProperties,
1994 mCurrentCookedState.cookedPointerData.pointerCoords,
1995 mCurrentCookedState.cookedPointerData.idToIndex,
1996 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1997 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1998 }
1999}
2000
2001void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
2002 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2003 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2004 const int32_t metaState = getContext()->getGlobalMetaState();
2005 int32_t buttonState = mLastCookedState.buttonState;
2006 while (!releasedButtons.isEmpty()) {
2007 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2008 buttonState &= ~actionButton;
2009 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2010 actionButton, 0, metaState, buttonState, 0,
2011 mCurrentCookedState.cookedPointerData.pointerProperties,
2012 mCurrentCookedState.cookedPointerData.pointerCoords,
2013 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2014 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2015 }
2016}
2017
2018void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2019 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2020 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2021 const int32_t metaState = getContext()->getGlobalMetaState();
2022 int32_t buttonState = mLastCookedState.buttonState;
2023 while (!pressedButtons.isEmpty()) {
2024 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2025 buttonState |= actionButton;
2026 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2027 0, metaState, buttonState, 0,
2028 mCurrentCookedState.cookedPointerData.pointerProperties,
2029 mCurrentCookedState.cookedPointerData.pointerCoords,
2030 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2031 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2032 }
2033}
2034
2035const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2036 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2037 return cookedPointerData.touchingIdBits;
2038 }
2039 return cookedPointerData.hoveringIdBits;
2040}
2041
2042void TouchInputMapper::cookPointerData() {
2043 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2044
2045 mCurrentCookedState.cookedPointerData.clear();
2046 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2047 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2048 mCurrentRawState.rawPointerData.hoveringIdBits;
2049 mCurrentCookedState.cookedPointerData.touchingIdBits =
2050 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhung65600042020-04-30 17:55:40 +08002051 mCurrentCookedState.cookedPointerData.canceledIdBits =
2052 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002053
2054 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2055 mCurrentCookedState.buttonState = 0;
2056 } else {
2057 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2058 }
2059
2060 // Walk through the the active pointers and map device coordinates onto
2061 // surface coordinates and adjust for display orientation.
2062 for (uint32_t i = 0; i < currentPointerCount; i++) {
2063 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2064
2065 // Size
2066 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2067 switch (mCalibration.sizeCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002068 case Calibration::SizeCalibration::GEOMETRIC:
2069 case Calibration::SizeCalibration::DIAMETER:
2070 case Calibration::SizeCalibration::BOX:
2071 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002072 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2073 touchMajor = in.touchMajor;
2074 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2075 toolMajor = in.toolMajor;
2076 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2077 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2078 : in.touchMajor;
2079 } else if (mRawPointerAxes.touchMajor.valid) {
2080 toolMajor = touchMajor = in.touchMajor;
2081 toolMinor = touchMinor =
2082 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2083 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2084 : in.touchMajor;
2085 } else if (mRawPointerAxes.toolMajor.valid) {
2086 touchMajor = toolMajor = in.toolMajor;
2087 touchMinor = toolMinor =
2088 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2089 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2090 : in.toolMajor;
2091 } else {
2092 ALOG_ASSERT(false,
2093 "No touch or tool axes. "
2094 "Size calibration should have been resolved to NONE.");
2095 touchMajor = 0;
2096 touchMinor = 0;
2097 toolMajor = 0;
2098 toolMinor = 0;
2099 size = 0;
2100 }
2101
2102 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2103 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2104 if (touchingCount > 1) {
2105 touchMajor /= touchingCount;
2106 touchMinor /= touchingCount;
2107 toolMajor /= touchingCount;
2108 toolMinor /= touchingCount;
2109 size /= touchingCount;
2110 }
2111 }
2112
Michael Wrightaff169e2020-07-02 18:30:52 +01002113 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002114 touchMajor *= mGeometricScale;
2115 touchMinor *= mGeometricScale;
2116 toolMajor *= mGeometricScale;
2117 toolMinor *= mGeometricScale;
Michael Wrightaff169e2020-07-02 18:30:52 +01002118 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002119 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2120 touchMinor = touchMajor;
2121 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2122 toolMinor = toolMajor;
Michael Wrightaff169e2020-07-02 18:30:52 +01002123 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002124 touchMinor = touchMajor;
2125 toolMinor = toolMajor;
2126 }
2127
2128 mCalibration.applySizeScaleAndBias(&touchMajor);
2129 mCalibration.applySizeScaleAndBias(&touchMinor);
2130 mCalibration.applySizeScaleAndBias(&toolMajor);
2131 mCalibration.applySizeScaleAndBias(&toolMinor);
2132 size *= mSizeScale;
2133 break;
2134 default:
2135 touchMajor = 0;
2136 touchMinor = 0;
2137 toolMajor = 0;
2138 toolMinor = 0;
2139 size = 0;
2140 break;
2141 }
2142
2143 // Pressure
2144 float pressure;
2145 switch (mCalibration.pressureCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002146 case Calibration::PressureCalibration::PHYSICAL:
2147 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002148 pressure = in.pressure * mPressureScale;
2149 break;
2150 default:
2151 pressure = in.isHovering ? 0 : 1;
2152 break;
2153 }
2154
2155 // Tilt and Orientation
2156 float tilt;
2157 float orientation;
2158 if (mHaveTilt) {
2159 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2160 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2161 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2162 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2163 } else {
2164 tilt = 0;
2165
2166 switch (mCalibration.orientationCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002167 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002168 orientation = in.orientation * mOrientationScale;
2169 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002170 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002171 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2172 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2173 if (c1 != 0 || c2 != 0) {
2174 orientation = atan2f(c1, c2) * 0.5f;
2175 float confidence = hypotf(c1, c2);
2176 float scale = 1.0f + confidence / 16.0f;
2177 touchMajor *= scale;
2178 touchMinor /= scale;
2179 toolMajor *= scale;
2180 toolMinor /= scale;
2181 } else {
2182 orientation = 0;
2183 }
2184 break;
2185 }
2186 default:
2187 orientation = 0;
2188 }
2189 }
2190
2191 // Distance
2192 float distance;
2193 switch (mCalibration.distanceCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002194 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002195 distance = in.distance * mDistanceScale;
2196 break;
2197 default:
2198 distance = 0;
2199 }
2200
2201 // Coverage
2202 int32_t rawLeft, rawTop, rawRight, rawBottom;
2203 switch (mCalibration.coverageCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002204 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002205 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2206 rawRight = in.toolMinor & 0x0000ffff;
2207 rawBottom = in.toolMajor & 0x0000ffff;
2208 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2209 break;
2210 default:
2211 rawLeft = rawTop = rawRight = rawBottom = 0;
2212 break;
2213 }
2214
2215 // Adjust X,Y coords for device calibration
2216 // TODO: Adjust coverage coords?
2217 float xTransformed = in.x, yTransformed = in.y;
2218 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002219 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002220
2221 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002222 float left, top, right, bottom;
2223
2224 switch (mSurfaceOrientation) {
2225 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002226 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2227 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2228 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2229 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2230 orientation -= M_PI_2;
2231 if (mOrientedRanges.haveOrientation &&
2232 orientation < mOrientedRanges.orientation.min) {
2233 orientation +=
2234 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2235 }
2236 break;
2237 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002238 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2239 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2240 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2241 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2242 orientation -= M_PI;
2243 if (mOrientedRanges.haveOrientation &&
2244 orientation < mOrientedRanges.orientation.min) {
2245 orientation +=
2246 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2247 }
2248 break;
2249 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002250 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2251 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2252 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2253 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2254 orientation += M_PI_2;
2255 if (mOrientedRanges.haveOrientation &&
2256 orientation > mOrientedRanges.orientation.max) {
2257 orientation -=
2258 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2259 }
2260 break;
2261 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002262 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2263 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2264 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2265 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2266 break;
2267 }
2268
2269 // Write output coords.
2270 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2271 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002272 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2273 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002274 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2275 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2276 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2277 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2278 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2279 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2280 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wrightaff169e2020-07-02 18:30:52 +01002281 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002282 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2283 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2284 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2285 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2286 } else {
2287 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2288 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2289 }
2290
Chris Yedca44af2020-08-05 15:07:56 -07002291 // Write output relative fields if applicable.
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +00002292 uint32_t id = in.id;
2293 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2294 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2295 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2296 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2297 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2298 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2299 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2300 }
2301
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002302 // Write output properties.
2303 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002304 properties.clear();
2305 properties.id = id;
2306 properties.toolType = in.toolType;
2307
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +00002308 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002309 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +00002310 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002311 }
2312}
2313
2314void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2315 PointerUsage pointerUsage) {
2316 if (pointerUsage != mPointerUsage) {
2317 abortPointerUsage(when, policyFlags);
2318 mPointerUsage = pointerUsage;
2319 }
2320
2321 switch (mPointerUsage) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002322 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002323 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2324 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002325 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002326 dispatchPointerStylus(when, policyFlags);
2327 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002328 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002329 dispatchPointerMouse(when, policyFlags);
2330 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002331 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002332 break;
2333 }
2334}
2335
2336void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2337 switch (mPointerUsage) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002338 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002339 abortPointerGestures(when, policyFlags);
2340 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002341 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002342 abortPointerStylus(when, policyFlags);
2343 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002344 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002345 abortPointerMouse(when, policyFlags);
2346 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002347 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002348 break;
2349 }
2350
Michael Wrightaff169e2020-07-02 18:30:52 +01002351 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352}
2353
2354void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2355 // Update current gesture coordinates.
2356 bool cancelPreviousGesture, finishPreviousGesture;
2357 bool sendEvents =
2358 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2359 if (!sendEvents) {
2360 return;
2361 }
2362 if (finishPreviousGesture) {
2363 cancelPreviousGesture = false;
2364 }
2365
2366 // Update the pointer presentation and spots.
Michael Wrightaff169e2020-07-02 18:30:52 +01002367 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wright976db0c2020-07-02 00:00:29 +01002368 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 if (finishPreviousGesture || cancelPreviousGesture) {
2370 mPointerController->clearSpots();
2371 }
2372
Michael Wrightaff169e2020-07-02 18:30:52 +01002373 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2375 mPointerGesture.currentGestureIdToIndex,
2376 mPointerGesture.currentGestureIdBits,
2377 mPointerController->getDisplayId());
2378 }
2379 } else {
Michael Wright976db0c2020-07-02 00:00:29 +01002380 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 }
2382
2383 // Show or hide the pointer if needed.
2384 switch (mPointerGesture.currentGestureMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002385 case PointerGesture::Mode::NEUTRAL:
2386 case PointerGesture::Mode::QUIET:
2387 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2388 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wright976db0c2020-07-02 00:00:29 +01002390 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 }
2392 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002393 case PointerGesture::Mode::TAP:
2394 case PointerGesture::Mode::TAP_DRAG:
2395 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2396 case PointerGesture::Mode::HOVER:
2397 case PointerGesture::Mode::PRESS:
2398 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002399 // Unfade the pointer when the current gesture manipulates the
2400 // area directly under the pointer.
Michael Wright976db0c2020-07-02 00:00:29 +01002401 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002403 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 // Fade the pointer when the current gesture manipulates a different
2405 // area and there are spots to guide the user experience.
Michael Wrightaff169e2020-07-02 18:30:52 +01002406 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wright976db0c2020-07-02 00:00:29 +01002407 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002408 } else {
Michael Wright976db0c2020-07-02 00:00:29 +01002409 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 }
2411 break;
2412 }
2413
2414 // Send events!
2415 int32_t metaState = getContext()->getGlobalMetaState();
2416 int32_t buttonState = mCurrentCookedState.buttonState;
2417
2418 // Update last coordinates of pointers that have moved so that we observe the new
2419 // pointer positions at the same time as other pointers that have just gone up.
Michael Wrightaff169e2020-07-02 18:30:52 +01002420 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2421 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2422 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2423 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2424 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2425 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002426 bool moveNeeded = false;
2427 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2428 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2429 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2430 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2431 mPointerGesture.lastGestureIdBits.value);
2432 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2433 mPointerGesture.currentGestureCoords,
2434 mPointerGesture.currentGestureIdToIndex,
2435 mPointerGesture.lastGestureProperties,
2436 mPointerGesture.lastGestureCoords,
2437 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2438 if (buttonState != mLastCookedState.buttonState) {
2439 moveNeeded = true;
2440 }
2441 }
2442
2443 // Send motion events for all pointers that went up or were canceled.
2444 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2445 if (!dispatchedGestureIdBits.isEmpty()) {
2446 if (cancelPreviousGesture) {
2447 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2448 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2449 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2450 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2451 mPointerGesture.downTime);
2452
2453 dispatchedGestureIdBits.clear();
2454 } else {
2455 BitSet32 upGestureIdBits;
2456 if (finishPreviousGesture) {
2457 upGestureIdBits = dispatchedGestureIdBits;
2458 } else {
2459 upGestureIdBits.value =
2460 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2461 }
2462 while (!upGestureIdBits.isEmpty()) {
2463 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2464
2465 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2466 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2467 mPointerGesture.lastGestureProperties,
2468 mPointerGesture.lastGestureCoords,
2469 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2470 0, mPointerGesture.downTime);
2471
2472 dispatchedGestureIdBits.clearBit(id);
2473 }
2474 }
2475 }
2476
2477 // Send motion events for all pointers that moved.
2478 if (moveNeeded) {
2479 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2480 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2481 mPointerGesture.currentGestureProperties,
2482 mPointerGesture.currentGestureCoords,
2483 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2484 mPointerGesture.downTime);
2485 }
2486
2487 // Send motion events for all pointers that went down.
2488 if (down) {
2489 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2490 ~dispatchedGestureIdBits.value);
2491 while (!downGestureIdBits.isEmpty()) {
2492 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2493 dispatchedGestureIdBits.markBit(id);
2494
2495 if (dispatchedGestureIdBits.count() == 1) {
2496 mPointerGesture.downTime = when;
2497 }
2498
2499 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2500 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2501 mPointerGesture.currentGestureCoords,
2502 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2503 0, mPointerGesture.downTime);
2504 }
2505 }
2506
2507 // Send motion events for hover.
Michael Wrightaff169e2020-07-02 18:30:52 +01002508 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2510 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2511 mPointerGesture.currentGestureProperties,
2512 mPointerGesture.currentGestureCoords,
2513 mPointerGesture.currentGestureIdToIndex,
2514 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2515 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2516 // Synthesize a hover move event after all pointers go up to indicate that
2517 // the pointer is hovering again even if the user is not currently touching
2518 // the touch pad. This ensures that a view will receive a fresh hover enter
2519 // event after a tap.
2520 float x, y;
2521 mPointerController->getPosition(&x, &y);
2522
2523 PointerProperties pointerProperties;
2524 pointerProperties.clear();
2525 pointerProperties.id = 0;
2526 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2527
2528 PointerCoords pointerCoords;
2529 pointerCoords.clear();
2530 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2531 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2532
2533 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002534 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2535 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2536 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2537 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2538 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002539 getListener()->notifyMotion(&args);
2540 }
2541
2542 // Update state.
2543 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2544 if (!down) {
2545 mPointerGesture.lastGestureIdBits.clear();
2546 } else {
2547 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2548 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2549 uint32_t id = idBits.clearFirstMarkedBit();
2550 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2551 mPointerGesture.lastGestureProperties[index].copyFrom(
2552 mPointerGesture.currentGestureProperties[index]);
2553 mPointerGesture.lastGestureCoords[index].copyFrom(
2554 mPointerGesture.currentGestureCoords[index]);
2555 mPointerGesture.lastGestureIdToIndex[id] = index;
2556 }
2557 }
2558}
2559
2560void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2561 // Cancel previously dispatches pointers.
2562 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2563 int32_t metaState = getContext()->getGlobalMetaState();
2564 int32_t buttonState = mCurrentRawState.buttonState;
2565 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2566 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2567 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2568 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2569 0, 0, mPointerGesture.downTime);
2570 }
2571
2572 // Reset the current pointer gesture.
2573 mPointerGesture.reset();
2574 mPointerVelocityControl.reset();
2575
2576 // Remove any current spots.
2577 if (mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01002578 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002579 mPointerController->clearSpots();
2580 }
2581}
2582
2583bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2584 bool* outFinishPreviousGesture, bool isTimeout) {
2585 *outCancelPreviousGesture = false;
2586 *outFinishPreviousGesture = false;
2587
2588 // Handle TAP timeout.
2589 if (isTimeout) {
2590#if DEBUG_GESTURES
2591 ALOGD("Gestures: Processing timeout");
2592#endif
2593
Michael Wrightaff169e2020-07-02 18:30:52 +01002594 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002595 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2596 // The tap/drag timeout has not yet expired.
2597 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2598 mConfig.pointerGestureTapDragInterval);
2599 } else {
2600 // The tap is finished.
2601#if DEBUG_GESTURES
2602 ALOGD("Gestures: TAP finished");
2603#endif
2604 *outFinishPreviousGesture = true;
2605
2606 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002607 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002608 mPointerGesture.currentGestureIdBits.clear();
2609
2610 mPointerVelocityControl.reset();
2611 return true;
2612 }
2613 }
2614
2615 // We did not handle this timeout.
2616 return false;
2617 }
2618
2619 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2620 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2621
2622 // Update the velocity tracker.
2623 {
2624 VelocityTracker::Position positions[MAX_POINTERS];
2625 uint32_t count = 0;
2626 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
2627 uint32_t id = idBits.clearFirstMarkedBit();
2628 const RawPointerData::Pointer& pointer =
2629 mCurrentRawState.rawPointerData.pointerForId(id);
2630 positions[count].x = pointer.x * mPointerXMovementScale;
2631 positions[count].y = pointer.y * mPointerYMovementScale;
2632 }
2633 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2634 positions);
2635 }
2636
2637 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2638 // to NEUTRAL, then we should not generate tap event.
Michael Wrightaff169e2020-07-02 18:30:52 +01002639 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2640 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2641 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002642 mPointerGesture.resetTap();
2643 }
2644
2645 // Pick a new active touch id if needed.
2646 // Choose an arbitrary pointer that just went down, if there is one.
2647 // Otherwise choose an arbitrary remaining pointer.
2648 // This guarantees we always have an active touch id when there is at least one pointer.
2649 // We keep the same active touch id for as long as possible.
2650 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2651 int32_t activeTouchId = lastActiveTouchId;
2652 if (activeTouchId < 0) {
2653 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2654 activeTouchId = mPointerGesture.activeTouchId =
2655 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2656 mPointerGesture.firstTouchTime = when;
2657 }
2658 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2659 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2660 activeTouchId = mPointerGesture.activeTouchId =
2661 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2662 } else {
2663 activeTouchId = mPointerGesture.activeTouchId = -1;
2664 }
2665 }
2666
2667 // Determine whether we are in quiet time.
2668 bool isQuietTime = false;
2669 if (activeTouchId < 0) {
2670 mPointerGesture.resetQuietTime();
2671 } else {
2672 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2673 if (!isQuietTime) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002674 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2675 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2676 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002677 currentFingerCount < 2) {
2678 // Enter quiet time when exiting swipe or freeform state.
2679 // This is to prevent accidentally entering the hover state and flinging the
2680 // pointer when finishing a swipe and there is still one pointer left onscreen.
2681 isQuietTime = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01002682 } else if (mPointerGesture.lastGestureMode ==
2683 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002684 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2685 // Enter quiet time when releasing the button and there are still two or more
2686 // fingers down. This may indicate that one finger was used to press the button
2687 // but it has not gone up yet.
2688 isQuietTime = true;
2689 }
2690 if (isQuietTime) {
2691 mPointerGesture.quietTime = when;
2692 }
2693 }
2694 }
2695
2696 // Switch states based on button and pointer state.
2697 if (isQuietTime) {
2698 // Case 1: Quiet time. (QUIET)
2699#if DEBUG_GESTURES
2700 ALOGD("Gestures: QUIET for next %0.3fms",
2701 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2702#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01002703 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002704 *outFinishPreviousGesture = true;
2705 }
2706
2707 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002708 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002709 mPointerGesture.currentGestureIdBits.clear();
2710
2711 mPointerVelocityControl.reset();
2712 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2713 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2714 // The pointer follows the active touch point.
2715 // Emit DOWN, MOVE, UP events at the pointer location.
2716 //
2717 // Only the active touch matters; other fingers are ignored. This policy helps
2718 // to handle the case where the user places a second finger on the touch pad
2719 // to apply the necessary force to depress an integrated button below the surface.
2720 // We don't want the second finger to be delivered to applications.
2721 //
2722 // For this to work well, we need to make sure to track the pointer that is really
2723 // active. If the user first puts one finger down to click then adds another
2724 // finger to drag then the active pointer should switch to the finger that is
2725 // being dragged.
2726#if DEBUG_GESTURES
2727 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2728 "currentFingerCount=%d",
2729 activeTouchId, currentFingerCount);
2730#endif
2731 // Reset state when just starting.
Michael Wrightaff169e2020-07-02 18:30:52 +01002732 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002733 *outFinishPreviousGesture = true;
2734 mPointerGesture.activeGestureId = 0;
2735 }
2736
2737 // Switch pointers if needed.
2738 // Find the fastest pointer and follow it.
2739 if (activeTouchId >= 0 && currentFingerCount > 1) {
2740 int32_t bestId = -1;
2741 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2742 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2743 uint32_t id = idBits.clearFirstMarkedBit();
2744 float vx, vy;
2745 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2746 float speed = hypotf(vx, vy);
2747 if (speed > bestSpeed) {
2748 bestId = id;
2749 bestSpeed = speed;
2750 }
2751 }
2752 }
2753 if (bestId >= 0 && bestId != activeTouchId) {
2754 mPointerGesture.activeTouchId = activeTouchId = bestId;
2755#if DEBUG_GESTURES
2756 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2757 "bestId=%d, bestSpeed=%0.3f",
2758 bestId, bestSpeed);
2759#endif
2760 }
2761 }
2762
2763 float deltaX = 0, deltaY = 0;
2764 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2765 const RawPointerData::Pointer& currentPointer =
2766 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2767 const RawPointerData::Pointer& lastPointer =
2768 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2769 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2770 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2771
2772 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2773 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2774
2775 // Move the pointer using a relative motion.
2776 // When using spots, the click will occur at the position of the anchor
2777 // spot and all other spots will move there.
2778 mPointerController->move(deltaX, deltaY);
2779 } else {
2780 mPointerVelocityControl.reset();
2781 }
2782
2783 float x, y;
2784 mPointerController->getPosition(&x, &y);
2785
Michael Wrightaff169e2020-07-02 18:30:52 +01002786 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002787 mPointerGesture.currentGestureIdBits.clear();
2788 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2789 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2790 mPointerGesture.currentGestureProperties[0].clear();
2791 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2792 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2793 mPointerGesture.currentGestureCoords[0].clear();
2794 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2795 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2796 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2797 } else if (currentFingerCount == 0) {
2798 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wrightaff169e2020-07-02 18:30:52 +01002799 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002800 *outFinishPreviousGesture = true;
2801 }
2802
2803 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2804 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2805 bool tapped = false;
Michael Wrightaff169e2020-07-02 18:30:52 +01002806 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2807 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002808 lastFingerCount == 1) {
2809 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2810 float x, y;
2811 mPointerController->getPosition(&x, &y);
2812 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2813 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2814#if DEBUG_GESTURES
2815 ALOGD("Gestures: TAP");
2816#endif
2817
2818 mPointerGesture.tapUpTime = when;
2819 getContext()->requestTimeoutAtTime(when +
2820 mConfig.pointerGestureTapDragInterval);
2821
2822 mPointerGesture.activeGestureId = 0;
Michael Wrightaff169e2020-07-02 18:30:52 +01002823 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002824 mPointerGesture.currentGestureIdBits.clear();
2825 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2826 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2827 mPointerGesture.currentGestureProperties[0].clear();
2828 mPointerGesture.currentGestureProperties[0].id =
2829 mPointerGesture.activeGestureId;
2830 mPointerGesture.currentGestureProperties[0].toolType =
2831 AMOTION_EVENT_TOOL_TYPE_FINGER;
2832 mPointerGesture.currentGestureCoords[0].clear();
2833 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2834 mPointerGesture.tapX);
2835 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2836 mPointerGesture.tapY);
2837 mPointerGesture.currentGestureCoords[0]
2838 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2839
2840 tapped = true;
2841 } else {
2842#if DEBUG_GESTURES
2843 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2844 y - mPointerGesture.tapY);
2845#endif
2846 }
2847 } else {
2848#if DEBUG_GESTURES
2849 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2850 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2851 (when - mPointerGesture.tapDownTime) * 0.000001f);
2852 } else {
2853 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2854 }
2855#endif
2856 }
2857 }
2858
2859 mPointerVelocityControl.reset();
2860
2861 if (!tapped) {
2862#if DEBUG_GESTURES
2863 ALOGD("Gestures: NEUTRAL");
2864#endif
2865 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002866 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002867 mPointerGesture.currentGestureIdBits.clear();
2868 }
2869 } else if (currentFingerCount == 1) {
2870 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2871 // The pointer follows the active touch point.
2872 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2873 // When in TAP_DRAG, emit MOVE events at the pointer location.
2874 ALOG_ASSERT(activeTouchId >= 0);
2875
Michael Wrightaff169e2020-07-02 18:30:52 +01002876 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2877 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002878 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2879 float x, y;
2880 mPointerController->getPosition(&x, &y);
2881 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2882 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002883 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884 } else {
2885#if DEBUG_GESTURES
2886 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2887 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2888#endif
2889 }
2890 } else {
2891#if DEBUG_GESTURES
2892 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2893 (when - mPointerGesture.tapUpTime) * 0.000001f);
2894#endif
2895 }
Michael Wrightaff169e2020-07-02 18:30:52 +01002896 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2897 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002898 }
2899
2900 float deltaX = 0, deltaY = 0;
2901 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2902 const RawPointerData::Pointer& currentPointer =
2903 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2904 const RawPointerData::Pointer& lastPointer =
2905 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2906 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2907 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2908
2909 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2910 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2911
2912 // Move the pointer using a relative motion.
2913 // When using spots, the hover or drag will occur at the position of the anchor spot.
2914 mPointerController->move(deltaX, deltaY);
2915 } else {
2916 mPointerVelocityControl.reset();
2917 }
2918
2919 bool down;
Michael Wrightaff169e2020-07-02 18:30:52 +01002920 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002921#if DEBUG_GESTURES
2922 ALOGD("Gestures: TAP_DRAG");
2923#endif
2924 down = true;
2925 } else {
2926#if DEBUG_GESTURES
2927 ALOGD("Gestures: HOVER");
2928#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01002929 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002930 *outFinishPreviousGesture = true;
2931 }
2932 mPointerGesture.activeGestureId = 0;
2933 down = false;
2934 }
2935
2936 float x, y;
2937 mPointerController->getPosition(&x, &y);
2938
2939 mPointerGesture.currentGestureIdBits.clear();
2940 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2941 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2942 mPointerGesture.currentGestureProperties[0].clear();
2943 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2944 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2945 mPointerGesture.currentGestureCoords[0].clear();
2946 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2947 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2948 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2949 down ? 1.0f : 0.0f);
2950
2951 if (lastFingerCount == 0 && currentFingerCount != 0) {
2952 mPointerGesture.resetTap();
2953 mPointerGesture.tapDownTime = when;
2954 mPointerGesture.tapX = x;
2955 mPointerGesture.tapY = y;
2956 }
2957 } else {
2958 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2959 // We need to provide feedback for each finger that goes down so we cannot wait
2960 // for the fingers to move before deciding what to do.
2961 //
2962 // The ambiguous case is deciding what to do when there are two fingers down but they
2963 // have not moved enough to determine whether they are part of a drag or part of a
2964 // freeform gesture, or just a press or long-press at the pointer location.
2965 //
2966 // When there are two fingers we start with the PRESS hypothesis and we generate a
2967 // down at the pointer location.
2968 //
2969 // When the two fingers move enough or when additional fingers are added, we make
2970 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2971 ALOG_ASSERT(activeTouchId >= 0);
2972
2973 bool settled = when >=
2974 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wrightaff169e2020-07-02 18:30:52 +01002975 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2976 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2977 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002978 *outFinishPreviousGesture = true;
2979 } else if (!settled && currentFingerCount > lastFingerCount) {
2980 // Additional pointers have gone down but not yet settled.
2981 // Reset the gesture.
2982#if DEBUG_GESTURES
2983 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2984 "settle time remaining %0.3fms",
2985 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2986 when) * 0.000001f);
2987#endif
2988 *outCancelPreviousGesture = true;
2989 } else {
2990 // Continue previous gesture.
2991 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2992 }
2993
2994 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002995 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002996 mPointerGesture.activeGestureId = 0;
2997 mPointerGesture.referenceIdBits.clear();
2998 mPointerVelocityControl.reset();
2999
3000 // Use the centroid and pointer location as the reference points for the gesture.
3001#if DEBUG_GESTURES
3002 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3003 "settle time remaining %0.3fms",
3004 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3005 when) * 0.000001f);
3006#endif
3007 mCurrentRawState.rawPointerData
3008 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3009 &mPointerGesture.referenceTouchY);
3010 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3011 &mPointerGesture.referenceGestureY);
3012 }
3013
3014 // Clear the reference deltas for fingers not yet included in the reference calculation.
3015 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3016 ~mPointerGesture.referenceIdBits.value);
3017 !idBits.isEmpty();) {
3018 uint32_t id = idBits.clearFirstMarkedBit();
3019 mPointerGesture.referenceDeltas[id].dx = 0;
3020 mPointerGesture.referenceDeltas[id].dy = 0;
3021 }
3022 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3023
3024 // Add delta for all fingers and calculate a common movement delta.
3025 float commonDeltaX = 0, commonDeltaY = 0;
3026 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3027 mCurrentCookedState.fingerIdBits.value);
3028 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3029 bool first = (idBits == commonIdBits);
3030 uint32_t id = idBits.clearFirstMarkedBit();
3031 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3032 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3033 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3034 delta.dx += cpd.x - lpd.x;
3035 delta.dy += cpd.y - lpd.y;
3036
3037 if (first) {
3038 commonDeltaX = delta.dx;
3039 commonDeltaY = delta.dy;
3040 } else {
3041 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3042 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3043 }
3044 }
3045
3046 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wrightaff169e2020-07-02 18:30:52 +01003047 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003048 float dist[MAX_POINTER_ID + 1];
3049 int32_t distOverThreshold = 0;
3050 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3051 uint32_t id = idBits.clearFirstMarkedBit();
3052 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3053 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3054 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3055 distOverThreshold += 1;
3056 }
3057 }
3058
3059 // Only transition when at least two pointers have moved further than
3060 // the minimum distance threshold.
3061 if (distOverThreshold >= 2) {
3062 if (currentFingerCount > 2) {
3063 // There are more than two pointers, switch to FREEFORM.
3064#if DEBUG_GESTURES
3065 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3066 currentFingerCount);
3067#endif
3068 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003069 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003070 } else {
3071 // There are exactly two pointers.
3072 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3073 uint32_t id1 = idBits.clearFirstMarkedBit();
3074 uint32_t id2 = idBits.firstMarkedBit();
3075 const RawPointerData::Pointer& p1 =
3076 mCurrentRawState.rawPointerData.pointerForId(id1);
3077 const RawPointerData::Pointer& p2 =
3078 mCurrentRawState.rawPointerData.pointerForId(id2);
3079 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3080 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3081 // There are two pointers but they are too far apart for a SWIPE,
3082 // switch to FREEFORM.
3083#if DEBUG_GESTURES
3084 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3085 mutualDistance, mPointerGestureMaxSwipeWidth);
3086#endif
3087 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003088 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003089 } else {
3090 // There are two pointers. Wait for both pointers to start moving
3091 // before deciding whether this is a SWIPE or FREEFORM gesture.
3092 float dist1 = dist[id1];
3093 float dist2 = dist[id2];
3094 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3095 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3096 // Calculate the dot product of the displacement vectors.
3097 // When the vectors are oriented in approximately the same direction,
3098 // the angle betweeen them is near zero and the cosine of the angle
3099 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3100 // mag(v2).
3101 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3102 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3103 float dx1 = delta1.dx * mPointerXZoomScale;
3104 float dy1 = delta1.dy * mPointerYZoomScale;
3105 float dx2 = delta2.dx * mPointerXZoomScale;
3106 float dy2 = delta2.dy * mPointerYZoomScale;
3107 float dot = dx1 * dx2 + dy1 * dy2;
3108 float cosine = dot / (dist1 * dist2); // denominator always > 0
3109 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3110 // Pointers are moving in the same direction. Switch to SWIPE.
3111#if DEBUG_GESTURES
3112 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3113 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3114 "cosine %0.3f >= %0.3f",
3115 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3116 mConfig.pointerGestureMultitouchMinDistance, cosine,
3117 mConfig.pointerGestureSwipeTransitionAngleCosine);
3118#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01003119 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003120 } else {
3121 // Pointers are moving in different directions. Switch to FREEFORM.
3122#if DEBUG_GESTURES
3123 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3124 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3125 "cosine %0.3f < %0.3f",
3126 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3127 mConfig.pointerGestureMultitouchMinDistance, cosine,
3128 mConfig.pointerGestureSwipeTransitionAngleCosine);
3129#endif
3130 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003131 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003132 }
3133 }
3134 }
3135 }
3136 }
Michael Wrightaff169e2020-07-02 18:30:52 +01003137 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003138 // Switch from SWIPE to FREEFORM if additional pointers go down.
3139 // Cancel previous gesture.
3140 if (currentFingerCount > 2) {
3141#if DEBUG_GESTURES
3142 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3143 currentFingerCount);
3144#endif
3145 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003146 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003147 }
3148 }
3149
3150 // Move the reference points based on the overall group motion of the fingers
3151 // except in PRESS mode while waiting for a transition to occur.
Michael Wrightaff169e2020-07-02 18:30:52 +01003152 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003153 (commonDeltaX || commonDeltaY)) {
3154 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3155 uint32_t id = idBits.clearFirstMarkedBit();
3156 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3157 delta.dx = 0;
3158 delta.dy = 0;
3159 }
3160
3161 mPointerGesture.referenceTouchX += commonDeltaX;
3162 mPointerGesture.referenceTouchY += commonDeltaY;
3163
3164 commonDeltaX *= mPointerXMovementScale;
3165 commonDeltaY *= mPointerYMovementScale;
3166
3167 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3168 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3169
3170 mPointerGesture.referenceGestureX += commonDeltaX;
3171 mPointerGesture.referenceGestureY += commonDeltaY;
3172 }
3173
3174 // Report gestures.
Michael Wrightaff169e2020-07-02 18:30:52 +01003175 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3176 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003177 // PRESS or SWIPE mode.
3178#if DEBUG_GESTURES
3179 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3180 "activeGestureId=%d, currentTouchPointerCount=%d",
3181 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3182#endif
3183 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3184
3185 mPointerGesture.currentGestureIdBits.clear();
3186 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3187 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3188 mPointerGesture.currentGestureProperties[0].clear();
3189 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3190 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3191 mPointerGesture.currentGestureCoords[0].clear();
3192 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3193 mPointerGesture.referenceGestureX);
3194 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3195 mPointerGesture.referenceGestureY);
3196 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wrightaff169e2020-07-02 18:30:52 +01003197 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003198 // FREEFORM mode.
3199#if DEBUG_GESTURES
3200 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3201 "activeGestureId=%d, currentTouchPointerCount=%d",
3202 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3203#endif
3204 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3205
3206 mPointerGesture.currentGestureIdBits.clear();
3207
3208 BitSet32 mappedTouchIdBits;
3209 BitSet32 usedGestureIdBits;
Michael Wrightaff169e2020-07-02 18:30:52 +01003210 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003211 // Initially, assign the active gesture id to the active touch point
3212 // if there is one. No other touch id bits are mapped yet.
3213 if (!*outCancelPreviousGesture) {
3214 mappedTouchIdBits.markBit(activeTouchId);
3215 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3216 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3217 mPointerGesture.activeGestureId;
3218 } else {
3219 mPointerGesture.activeGestureId = -1;
3220 }
3221 } else {
3222 // Otherwise, assume we mapped all touches from the previous frame.
3223 // Reuse all mappings that are still applicable.
3224 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3225 mCurrentCookedState.fingerIdBits.value;
3226 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3227
3228 // Check whether we need to choose a new active gesture id because the
3229 // current went went up.
3230 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3231 ~mCurrentCookedState.fingerIdBits.value);
3232 !upTouchIdBits.isEmpty();) {
3233 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3234 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3235 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3236 mPointerGesture.activeGestureId = -1;
3237 break;
3238 }
3239 }
3240 }
3241
3242#if DEBUG_GESTURES
3243 ALOGD("Gestures: FREEFORM follow up "
3244 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3245 "activeGestureId=%d",
3246 mappedTouchIdBits.value, usedGestureIdBits.value,
3247 mPointerGesture.activeGestureId);
3248#endif
3249
3250 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3251 for (uint32_t i = 0; i < currentFingerCount; i++) {
3252 uint32_t touchId = idBits.clearFirstMarkedBit();
3253 uint32_t gestureId;
3254 if (!mappedTouchIdBits.hasBit(touchId)) {
3255 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3256 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3257#if DEBUG_GESTURES
3258 ALOGD("Gestures: FREEFORM "
3259 "new mapping for touch id %d -> gesture id %d",
3260 touchId, gestureId);
3261#endif
3262 } else {
3263 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3264#if DEBUG_GESTURES
3265 ALOGD("Gestures: FREEFORM "
3266 "existing mapping for touch id %d -> gesture id %d",
3267 touchId, gestureId);
3268#endif
3269 }
3270 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3271 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3272
3273 const RawPointerData::Pointer& pointer =
3274 mCurrentRawState.rawPointerData.pointerForId(touchId);
3275 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3276 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3277 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3278
3279 mPointerGesture.currentGestureProperties[i].clear();
3280 mPointerGesture.currentGestureProperties[i].id = gestureId;
3281 mPointerGesture.currentGestureProperties[i].toolType =
3282 AMOTION_EVENT_TOOL_TYPE_FINGER;
3283 mPointerGesture.currentGestureCoords[i].clear();
3284 mPointerGesture.currentGestureCoords[i]
3285 .setAxisValue(AMOTION_EVENT_AXIS_X,
3286 mPointerGesture.referenceGestureX + deltaX);
3287 mPointerGesture.currentGestureCoords[i]
3288 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3289 mPointerGesture.referenceGestureY + deltaY);
3290 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3291 1.0f);
3292 }
3293
3294 if (mPointerGesture.activeGestureId < 0) {
3295 mPointerGesture.activeGestureId =
3296 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3297#if DEBUG_GESTURES
3298 ALOGD("Gestures: FREEFORM new "
3299 "activeGestureId=%d",
3300 mPointerGesture.activeGestureId);
3301#endif
3302 }
3303 }
3304 }
3305
3306 mPointerController->setButtonState(mCurrentRawState.buttonState);
3307
3308#if DEBUG_GESTURES
3309 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3310 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3311 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3312 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3313 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3314 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3315 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3316 uint32_t id = idBits.clearFirstMarkedBit();
3317 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3318 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3319 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3320 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3321 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3322 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3323 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3324 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3325 }
3326 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3327 uint32_t id = idBits.clearFirstMarkedBit();
3328 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3329 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3330 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3331 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3332 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3333 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3334 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3335 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3336 }
3337#endif
3338 return true;
3339}
3340
3341void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3342 mPointerSimple.currentCoords.clear();
3343 mPointerSimple.currentProperties.clear();
3344
3345 bool down, hovering;
3346 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3347 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3348 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3349 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3350 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3351 mPointerController->setPosition(x, y);
3352
3353 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3354 down = !hovering;
3355
3356 mPointerController->getPosition(&x, &y);
3357 mPointerSimple.currentCoords.copyFrom(
3358 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3359 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3360 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3361 mPointerSimple.currentProperties.id = 0;
3362 mPointerSimple.currentProperties.toolType =
3363 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3364 } else {
3365 down = false;
3366 hovering = false;
3367 }
3368
3369 dispatchPointerSimple(when, policyFlags, down, hovering);
3370}
3371
3372void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3373 abortPointerSimple(when, policyFlags);
3374}
3375
3376void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3377 mPointerSimple.currentCoords.clear();
3378 mPointerSimple.currentProperties.clear();
3379
3380 bool down, hovering;
3381 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3382 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3383 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3384 float deltaX = 0, deltaY = 0;
3385 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3386 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3387 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3388 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3389 mPointerXMovementScale;
3390 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3391 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3392 mPointerYMovementScale;
3393
3394 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3395 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3396
3397 mPointerController->move(deltaX, deltaY);
3398 } else {
3399 mPointerVelocityControl.reset();
3400 }
3401
3402 down = isPointerDown(mCurrentRawState.buttonState);
3403 hovering = !down;
3404
3405 float x, y;
3406 mPointerController->getPosition(&x, &y);
3407 mPointerSimple.currentCoords.copyFrom(
3408 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3409 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3410 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3411 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3412 hovering ? 0.0f : 1.0f);
3413 mPointerSimple.currentProperties.id = 0;
3414 mPointerSimple.currentProperties.toolType =
3415 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3416 } else {
3417 mPointerVelocityControl.reset();
3418
3419 down = false;
3420 hovering = false;
3421 }
3422
3423 dispatchPointerSimple(when, policyFlags, down, hovering);
3424}
3425
3426void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3427 abortPointerSimple(when, policyFlags);
3428
3429 mPointerVelocityControl.reset();
3430}
3431
3432void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3433 bool hovering) {
3434 int32_t metaState = getContext()->getGlobalMetaState();
3435 int32_t displayId = mViewport.displayId;
3436
3437 if (down || hovering) {
Michael Wright976db0c2020-07-02 00:00:29 +01003438 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003439 mPointerController->clearSpots();
3440 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wright976db0c2020-07-02 00:00:29 +01003441 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003442 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wright976db0c2020-07-02 00:00:29 +01003443 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003444 }
3445 displayId = mPointerController->getDisplayId();
3446
3447 float xCursorPosition;
3448 float yCursorPosition;
3449 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3450
3451 if (mPointerSimple.down && !down) {
3452 mPointerSimple.down = false;
3453
3454 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003455 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3456 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003457 mLastRawState.buttonState, MotionClassification::NONE,
3458 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3459 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3460 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3461 /* videoFrames */ {});
3462 getListener()->notifyMotion(&args);
3463 }
3464
3465 if (mPointerSimple.hovering && !hovering) {
3466 mPointerSimple.hovering = false;
3467
3468 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003469 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3470 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3471 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003472 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3473 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3474 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3475 /* videoFrames */ {});
3476 getListener()->notifyMotion(&args);
3477 }
3478
3479 if (down) {
3480 if (!mPointerSimple.down) {
3481 mPointerSimple.down = true;
3482 mPointerSimple.downTime = when;
3483
3484 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003485 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003486 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3487 metaState, mCurrentRawState.buttonState,
3488 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3489 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3490 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3491 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3492 getListener()->notifyMotion(&args);
3493 }
3494
3495 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003496 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3497 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003498 mCurrentRawState.buttonState, MotionClassification::NONE,
3499 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3500 &mPointerSimple.currentCoords, mOrientedXPrecision,
3501 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3502 mPointerSimple.downTime, /* videoFrames */ {});
3503 getListener()->notifyMotion(&args);
3504 }
3505
3506 if (hovering) {
3507 if (!mPointerSimple.hovering) {
3508 mPointerSimple.hovering = true;
3509
3510 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003511 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003512 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3513 metaState, mCurrentRawState.buttonState,
3514 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3515 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3516 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3517 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3518 getListener()->notifyMotion(&args);
3519 }
3520
3521 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003522 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3523 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3524 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003525 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3526 &mPointerSimple.currentCoords, mOrientedXPrecision,
3527 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3528 mPointerSimple.downTime, /* videoFrames */ {});
3529 getListener()->notifyMotion(&args);
3530 }
3531
3532 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3533 float vscroll = mCurrentRawState.rawVScroll;
3534 float hscroll = mCurrentRawState.rawHScroll;
3535 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3536 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3537
3538 // Send scroll.
3539 PointerCoords pointerCoords;
3540 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3541 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3542 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3543
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003544 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3545 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003546 mCurrentRawState.buttonState, MotionClassification::NONE,
3547 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3548 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3549 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3550 /* videoFrames */ {});
3551 getListener()->notifyMotion(&args);
3552 }
3553
3554 // Save state.
3555 if (down || hovering) {
3556 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3557 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3558 } else {
3559 mPointerSimple.reset();
3560 }
3561}
3562
3563void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3564 mPointerSimple.currentCoords.clear();
3565 mPointerSimple.currentProperties.clear();
3566
3567 dispatchPointerSimple(when, policyFlags, false, false);
3568}
3569
3570void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3571 int32_t action, int32_t actionButton, int32_t flags,
3572 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3573 const PointerProperties* properties,
3574 const PointerCoords* coords, const uint32_t* idToIndex,
3575 BitSet32 idBits, int32_t changedId, float xPrecision,
3576 float yPrecision, nsecs_t downTime) {
3577 PointerCoords pointerCoords[MAX_POINTERS];
3578 PointerProperties pointerProperties[MAX_POINTERS];
3579 uint32_t pointerCount = 0;
3580 while (!idBits.isEmpty()) {
3581 uint32_t id = idBits.clearFirstMarkedBit();
3582 uint32_t index = idToIndex[id];
3583 pointerProperties[pointerCount].copyFrom(properties[index]);
3584 pointerCoords[pointerCount].copyFrom(coords[index]);
3585
3586 if (changedId >= 0 && id == uint32_t(changedId)) {
3587 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3588 }
3589
3590 pointerCount += 1;
3591 }
3592
3593 ALOG_ASSERT(pointerCount != 0);
3594
3595 if (changedId >= 0 && pointerCount == 1) {
3596 // Replace initial down and final up action.
3597 // We can compare the action without masking off the changed pointer index
3598 // because we know the index is 0.
3599 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3600 action = AMOTION_EVENT_ACTION_DOWN;
3601 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhung65600042020-04-30 17:55:40 +08003602 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3603 action = AMOTION_EVENT_ACTION_CANCEL;
3604 } else {
3605 action = AMOTION_EVENT_ACTION_UP;
3606 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003607 } else {
3608 // Can't happen.
3609 ALOG_ASSERT(false);
3610 }
3611 }
3612 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3613 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wrightaff169e2020-07-02 18:30:52 +01003614 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003615 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3616 }
3617 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3618 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003619 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003620 std::for_each(frames.begin(), frames.end(),
3621 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003622 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3623 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003624 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3625 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3626 downTime, std::move(frames));
3627 getListener()->notifyMotion(&args);
3628}
3629
3630bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3631 const PointerCoords* inCoords,
3632 const uint32_t* inIdToIndex,
3633 PointerProperties* outProperties,
3634 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3635 BitSet32 idBits) const {
3636 bool changed = false;
3637 while (!idBits.isEmpty()) {
3638 uint32_t id = idBits.clearFirstMarkedBit();
3639 uint32_t inIndex = inIdToIndex[id];
3640 uint32_t outIndex = outIdToIndex[id];
3641
3642 const PointerProperties& curInProperties = inProperties[inIndex];
3643 const PointerCoords& curInCoords = inCoords[inIndex];
3644 PointerProperties& curOutProperties = outProperties[outIndex];
3645 PointerCoords& curOutCoords = outCoords[outIndex];
3646
3647 if (curInProperties != curOutProperties) {
3648 curOutProperties.copyFrom(curInProperties);
3649 changed = true;
3650 }
3651
3652 if (curInCoords != curOutCoords) {
3653 curOutCoords.copyFrom(curInCoords);
3654 changed = true;
3655 }
3656 }
3657 return changed;
3658}
3659
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003660void TouchInputMapper::cancelTouch(nsecs_t when) {
3661 abortPointerUsage(when, 0 /*policyFlags*/);
3662 abortTouches(when, 0 /* policyFlags*/);
3663}
3664
Arthur Hung4197f6b2020-03-16 15:39:59 +08003665// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003666void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003667 // Scale to surface coordinate.
3668 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3669 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3670
3671 // Rotate to surface coordinate.
3672 // 0 - no swap and reverse.
3673 // 90 - swap x/y and reverse y.
3674 // 180 - reverse x, y.
3675 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003676 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003677 case DISPLAY_ORIENTATION_0:
3678 x = xScaled + mXTranslate;
3679 y = yScaled + mYTranslate;
3680 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003681 case DISPLAY_ORIENTATION_90:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003682 y = mSurfaceRight - xScaled;
3683 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003684 break;
3685 case DISPLAY_ORIENTATION_180:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003686 x = mSurfaceRight - xScaled;
3687 y = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003688 break;
3689 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003690 y = xScaled + mXTranslate;
3691 x = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003692 break;
3693 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003694 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003695 }
3696}
3697
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003698bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003699 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3700 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3701
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003702 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003703 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003704 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003705 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003706}
3707
3708const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3709 for (const VirtualKey& virtualKey : mVirtualKeys) {
3710#if DEBUG_VIRTUAL_KEYS
3711 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3712 "left=%d, top=%d, right=%d, bottom=%d",
3713 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3714 virtualKey.hitRight, virtualKey.hitBottom);
3715#endif
3716
3717 if (virtualKey.isHit(x, y)) {
3718 return &virtualKey;
3719 }
3720 }
3721
3722 return nullptr;
3723}
3724
3725void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3726 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3727 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3728
3729 current->rawPointerData.clearIdBits();
3730
3731 if (currentPointerCount == 0) {
3732 // No pointers to assign.
3733 return;
3734 }
3735
3736 if (lastPointerCount == 0) {
3737 // All pointers are new.
3738 for (uint32_t i = 0; i < currentPointerCount; i++) {
3739 uint32_t id = i;
3740 current->rawPointerData.pointers[i].id = id;
3741 current->rawPointerData.idToIndex[id] = i;
3742 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3743 }
3744 return;
3745 }
3746
3747 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3748 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3749 // Only one pointer and no change in count so it must have the same id as before.
3750 uint32_t id = last->rawPointerData.pointers[0].id;
3751 current->rawPointerData.pointers[0].id = id;
3752 current->rawPointerData.idToIndex[id] = 0;
3753 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3754 return;
3755 }
3756
3757 // General case.
3758 // We build a heap of squared euclidean distances between current and last pointers
3759 // associated with the current and last pointer indices. Then, we find the best
3760 // match (by distance) for each current pointer.
3761 // The pointers must have the same tool type but it is possible for them to
3762 // transition from hovering to touching or vice-versa while retaining the same id.
3763 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3764
3765 uint32_t heapSize = 0;
3766 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3767 currentPointerIndex++) {
3768 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3769 lastPointerIndex++) {
3770 const RawPointerData::Pointer& currentPointer =
3771 current->rawPointerData.pointers[currentPointerIndex];
3772 const RawPointerData::Pointer& lastPointer =
3773 last->rawPointerData.pointers[lastPointerIndex];
3774 if (currentPointer.toolType == lastPointer.toolType) {
3775 int64_t deltaX = currentPointer.x - lastPointer.x;
3776 int64_t deltaY = currentPointer.y - lastPointer.y;
3777
3778 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3779
3780 // Insert new element into the heap (sift up).
3781 heap[heapSize].currentPointerIndex = currentPointerIndex;
3782 heap[heapSize].lastPointerIndex = lastPointerIndex;
3783 heap[heapSize].distance = distance;
3784 heapSize += 1;
3785 }
3786 }
3787 }
3788
3789 // Heapify
3790 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3791 startIndex -= 1;
3792 for (uint32_t parentIndex = startIndex;;) {
3793 uint32_t childIndex = parentIndex * 2 + 1;
3794 if (childIndex >= heapSize) {
3795 break;
3796 }
3797
3798 if (childIndex + 1 < heapSize &&
3799 heap[childIndex + 1].distance < heap[childIndex].distance) {
3800 childIndex += 1;
3801 }
3802
3803 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3804 break;
3805 }
3806
3807 swap(heap[parentIndex], heap[childIndex]);
3808 parentIndex = childIndex;
3809 }
3810 }
3811
3812#if DEBUG_POINTER_ASSIGNMENT
3813 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3814 for (size_t i = 0; i < heapSize; i++) {
3815 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3816 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3817 }
3818#endif
3819
3820 // Pull matches out by increasing order of distance.
3821 // To avoid reassigning pointers that have already been matched, the loop keeps track
3822 // of which last and current pointers have been matched using the matchedXXXBits variables.
3823 // It also tracks the used pointer id bits.
3824 BitSet32 matchedLastBits(0);
3825 BitSet32 matchedCurrentBits(0);
3826 BitSet32 usedIdBits(0);
3827 bool first = true;
3828 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3829 while (heapSize > 0) {
3830 if (first) {
3831 // The first time through the loop, we just consume the root element of
3832 // the heap (the one with smallest distance).
3833 first = false;
3834 } else {
3835 // Previous iterations consumed the root element of the heap.
3836 // Pop root element off of the heap (sift down).
3837 heap[0] = heap[heapSize];
3838 for (uint32_t parentIndex = 0;;) {
3839 uint32_t childIndex = parentIndex * 2 + 1;
3840 if (childIndex >= heapSize) {
3841 break;
3842 }
3843
3844 if (childIndex + 1 < heapSize &&
3845 heap[childIndex + 1].distance < heap[childIndex].distance) {
3846 childIndex += 1;
3847 }
3848
3849 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3850 break;
3851 }
3852
3853 swap(heap[parentIndex], heap[childIndex]);
3854 parentIndex = childIndex;
3855 }
3856
3857#if DEBUG_POINTER_ASSIGNMENT
3858 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3859 for (size_t i = 0; i < heapSize; i++) {
3860 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3861 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3862 }
3863#endif
3864 }
3865
3866 heapSize -= 1;
3867
3868 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3869 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3870
3871 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3872 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3873
3874 matchedCurrentBits.markBit(currentPointerIndex);
3875 matchedLastBits.markBit(lastPointerIndex);
3876
3877 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3878 current->rawPointerData.pointers[currentPointerIndex].id = id;
3879 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3880 current->rawPointerData.markIdBit(id,
3881 current->rawPointerData.isHovering(
3882 currentPointerIndex));
3883 usedIdBits.markBit(id);
3884
3885#if DEBUG_POINTER_ASSIGNMENT
3886 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3887 ", distance=%" PRIu64,
3888 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3889#endif
3890 break;
3891 }
3892 }
3893
3894 // Assign fresh ids to pointers that were not matched in the process.
3895 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3896 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3897 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3898
3899 current->rawPointerData.pointers[currentPointerIndex].id = id;
3900 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3901 current->rawPointerData.markIdBit(id,
3902 current->rawPointerData.isHovering(currentPointerIndex));
3903
3904#if DEBUG_POINTER_ASSIGNMENT
3905 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3906#endif
3907 }
3908}
3909
3910int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3911 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3912 return AKEY_STATE_VIRTUAL;
3913 }
3914
3915 for (const VirtualKey& virtualKey : mVirtualKeys) {
3916 if (virtualKey.keyCode == keyCode) {
3917 return AKEY_STATE_UP;
3918 }
3919 }
3920
3921 return AKEY_STATE_UNKNOWN;
3922}
3923
3924int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3925 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3926 return AKEY_STATE_VIRTUAL;
3927 }
3928
3929 for (const VirtualKey& virtualKey : mVirtualKeys) {
3930 if (virtualKey.scanCode == scanCode) {
3931 return AKEY_STATE_UP;
3932 }
3933 }
3934
3935 return AKEY_STATE_UNKNOWN;
3936}
3937
3938bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3939 const int32_t* keyCodes, uint8_t* outFlags) {
3940 for (const VirtualKey& virtualKey : mVirtualKeys) {
3941 for (size_t i = 0; i < numCodes; i++) {
3942 if (virtualKey.keyCode == keyCodes[i]) {
3943 outFlags[i] = 1;
3944 }
3945 }
3946 }
3947
3948 return true;
3949}
3950
3951std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3952 if (mParameters.hasAssociatedDisplay) {
Michael Wrightaff169e2020-07-02 18:30:52 +01003953 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003954 return std::make_optional(mPointerController->getDisplayId());
3955 } else {
3956 return std::make_optional(mViewport.displayId);
3957 }
3958 }
3959 return std::nullopt;
3960}
3961
3962} // namespace android