blob: 15d528896f61d9fedb69c1a8bc192609ec0424e2 [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
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;
arthurhungcc7f9802020-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();
arthurhungcc7f9802020-04-30 17:55:40 +0800144 canceledIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700145}
146
147void CookedPointerData::copyFrom(const CookedPointerData& other) {
148 pointerCount = other.pointerCount;
149 hoveringIdBits = other.hoveringIdBits;
150 touchingIdBits = other.touchingIdBits;
151
152 for (uint32_t i = 0; i < pointerCount; i++) {
153 pointerProperties[i].copyFrom(other.pointerProperties[i]);
154 pointerCoords[i].copyFrom(other.pointerCoords[i]);
155
156 int id = pointerProperties[i].id;
157 idToIndex[id] = other.idToIndex[id];
158 }
159}
160
161// --- TouchInputMapper ---
162
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800163TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
164 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700165 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100166 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800167 mRawSurfaceWidth(-1),
168 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700169 mSurfaceLeft(0),
170 mSurfaceTop(0),
171 mPhysicalWidth(-1),
172 mPhysicalHeight(-1),
173 mPhysicalLeft(0),
174 mPhysicalTop(0),
175 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
176
177TouchInputMapper::~TouchInputMapper() {}
178
179uint32_t TouchInputMapper::getSources() {
180 return mSource;
181}
182
183void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
184 InputMapper::populateDeviceInfo(info);
185
Michael Wright227c5542020-07-02 18:30:52 +0100186 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700187 info->addMotionRange(mOrientedRanges.x);
188 info->addMotionRange(mOrientedRanges.y);
189 info->addMotionRange(mOrientedRanges.pressure);
190
191 if (mOrientedRanges.haveSize) {
192 info->addMotionRange(mOrientedRanges.size);
193 }
194
195 if (mOrientedRanges.haveTouchSize) {
196 info->addMotionRange(mOrientedRanges.touchMajor);
197 info->addMotionRange(mOrientedRanges.touchMinor);
198 }
199
200 if (mOrientedRanges.haveToolSize) {
201 info->addMotionRange(mOrientedRanges.toolMajor);
202 info->addMotionRange(mOrientedRanges.toolMinor);
203 }
204
205 if (mOrientedRanges.haveOrientation) {
206 info->addMotionRange(mOrientedRanges.orientation);
207 }
208
209 if (mOrientedRanges.haveDistance) {
210 info->addMotionRange(mOrientedRanges.distance);
211 }
212
213 if (mOrientedRanges.haveTilt) {
214 info->addMotionRange(mOrientedRanges.tilt);
215 }
216
217 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
218 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
219 0.0f);
220 }
221 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
222 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
223 0.0f);
224 }
Michael Wright227c5542020-07-02 18:30:52 +0100225 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700226 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
227 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
228 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
229 x.fuzz, x.resolution);
230 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
231 y.fuzz, y.resolution);
232 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
233 x.fuzz, x.resolution);
234 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
235 y.fuzz, y.resolution);
236 }
237 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
238 }
239}
240
241void TouchInputMapper::dump(std::string& dump) {
242 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
243 dumpParameters(dump);
244 dumpVirtualKeys(dump);
245 dumpRawPointerAxes(dump);
246 dumpCalibration(dump);
247 dumpAffineTransformation(dump);
248 dumpSurface(dump);
249
250 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
251 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
252 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
253 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
254 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
255 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
256 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
257 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
258 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
259 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
260 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
261 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
262 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
263 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
264 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
265 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
266 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
267
268 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
269 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
270 mLastRawState.rawPointerData.pointerCount);
271 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
272 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
273 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
274 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
275 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
276 "toolType=%d, isHovering=%s\n",
277 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
278 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
279 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
280 pointer.distance, pointer.toolType, toString(pointer.isHovering));
281 }
282
283 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
284 mLastCookedState.buttonState);
285 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
286 mLastCookedState.cookedPointerData.pointerCount);
287 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
288 const PointerProperties& pointerProperties =
289 mLastCookedState.cookedPointerData.pointerProperties[i];
290 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
291 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
292 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, "
293 "toolMinor=%0.3f, "
294 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
295 "toolType=%d, isHovering=%s\n",
296 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
297 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
298 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
299 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
300 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
301 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
302 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
303 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
304 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
305 pointerProperties.toolType,
306 toString(mLastCookedState.cookedPointerData.isHovering(i)));
307 }
308
309 dump += INDENT3 "Stylus Fusion:\n";
310 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
311 toString(mExternalStylusConnected));
312 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
313 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
314 mExternalStylusFusionTimeout);
315 dump += INDENT3 "External Stylus State:\n";
316 dumpStylusState(dump, mExternalStylusState);
317
Michael Wright227c5542020-07-02 18:30:52 +0100318 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700319 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
320 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
321 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
322 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
323 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
324 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
325 }
326}
327
328const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
329 switch (deviceMode) {
Michael Wright227c5542020-07-02 18:30:52 +0100330 case DeviceMode::DISABLED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700331 return "disabled";
Michael Wright227c5542020-07-02 18:30:52 +0100332 case DeviceMode::DIRECT:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700333 return "direct";
Michael Wright227c5542020-07-02 18:30:52 +0100334 case DeviceMode::UNSCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700335 return "unscaled";
Michael Wright227c5542020-07-02 18:30:52 +0100336 case DeviceMode::NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337 return "navigation";
Michael Wright227c5542020-07-02 18:30:52 +0100338 case DeviceMode::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700339 return "pointer";
340 }
341 return "unknown";
342}
343
344void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
345 uint32_t changes) {
346 InputMapper::configure(when, config, changes);
347
348 mConfig = *config;
349
350 if (!changes) { // first time only
351 // Configure basic parameters.
352 configureParameters();
353
354 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800355 mCursorScrollAccumulator.configure(getDeviceContext());
356 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700357
358 // Configure absolute axis information.
359 configureRawPointerAxes();
360
361 // Prepare input device calibration.
362 parseCalibration();
363 resolveCalibration();
364 }
365
366 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
367 // Update location calibration to reflect current settings
368 updateAffineTransformation();
369 }
370
371 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
372 // Update pointer speed.
373 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
374 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
375 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
376 }
377
378 bool resetNeeded = false;
379 if (!changes ||
380 (changes &
381 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
382 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
383 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
384 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
385 // Configure device sources, surface dimensions, orientation and
386 // scaling factors.
387 configureSurface(when, &resetNeeded);
388 }
389
390 if (changes && resetNeeded) {
391 // Send reset, unless this is the first time the device has been configured,
392 // in which case the reader will call reset itself after all mappers are ready.
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800393 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800394 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700395 }
396}
397
398void TouchInputMapper::resolveExternalStylusPresence() {
399 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800400 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700401 mExternalStylusConnected = !devices.empty();
402
403 if (!mExternalStylusConnected) {
404 resetExternalStylus();
405 }
406}
407
408void TouchInputMapper::configureParameters() {
409 // Use the pointer presentation mode for devices that do not support distinct
410 // multitouch. The spot-based presentation relies on being able to accurately
411 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800412 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100413 ? Parameters::GestureMode::SINGLE_TOUCH
414 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700415
416 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800417 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
418 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700419 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100420 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700421 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100422 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700423 } else if (gestureModeString != "default") {
424 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
425 }
426 }
427
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800428 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700429 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100430 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800431 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700432 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100433 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800434 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
435 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700436 // The device is a cursor device with a touch pad attached.
437 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100438 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439 } else {
440 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100441 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700442 }
443
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800444 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700445
446 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800447 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
448 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700449 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100450 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700451 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100452 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700453 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100454 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700455 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100456 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457 } else if (deviceTypeString != "default") {
458 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
459 }
460 }
461
Michael Wright227c5542020-07-02 18:30:52 +0100462 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800463 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
464 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700465
466 mParameters.hasAssociatedDisplay = false;
467 mParameters.associatedDisplayIsExternal = false;
468 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100469 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
470 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700471 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100472 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800473 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700474 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800475 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
476 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700477 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
478 }
479 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800480 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700481 mParameters.hasAssociatedDisplay = true;
482 }
483
484 // Initial downs on external touch devices should wake the device.
485 // Normally we don't do this for internal touch screens to prevent them from waking
486 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800487 mParameters.wake = getDeviceContext().isExternal();
488 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700489}
490
491void TouchInputMapper::dumpParameters(std::string& dump) {
492 dump += INDENT3 "Parameters:\n";
493
494 switch (mParameters.gestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +0100495 case Parameters::GestureMode::SINGLE_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496 dump += INDENT4 "GestureMode: single-touch\n";
497 break;
Michael Wright227c5542020-07-02 18:30:52 +0100498 case Parameters::GestureMode::MULTI_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700499 dump += INDENT4 "GestureMode: multi-touch\n";
500 break;
501 default:
502 assert(false);
503 }
504
505 switch (mParameters.deviceType) {
Michael Wright227c5542020-07-02 18:30:52 +0100506 case Parameters::DeviceType::TOUCH_SCREEN:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700507 dump += INDENT4 "DeviceType: touchScreen\n";
508 break;
Michael Wright227c5542020-07-02 18:30:52 +0100509 case Parameters::DeviceType::TOUCH_PAD:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700510 dump += INDENT4 "DeviceType: touchPad\n";
511 break;
Michael Wright227c5542020-07-02 18:30:52 +0100512 case Parameters::DeviceType::TOUCH_NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700513 dump += INDENT4 "DeviceType: touchNavigation\n";
514 break;
Michael Wright227c5542020-07-02 18:30:52 +0100515 case Parameters::DeviceType::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700516 dump += INDENT4 "DeviceType: pointer\n";
517 break;
518 default:
519 ALOG_ASSERT(false);
520 }
521
522 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
523 "displayId='%s'\n",
524 toString(mParameters.hasAssociatedDisplay),
525 toString(mParameters.associatedDisplayIsExternal),
526 mParameters.uniqueDisplayId.c_str());
527 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
528}
529
530void TouchInputMapper::configureRawPointerAxes() {
531 mRawPointerAxes.clear();
532}
533
534void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
535 dump += INDENT3 "Raw Touch Axes:\n";
536 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
537 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
538 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
539 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
540 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
541 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
542 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
545 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
546 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
547 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
548 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
549}
550
551bool TouchInputMapper::hasExternalStylus() const {
552 return mExternalStylusConnected;
553}
554
555/**
556 * Determine which DisplayViewport to use.
557 * 1. If display port is specified, return the matching viewport. If matching viewport not
558 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800559 * 2. Always use the suggested viewport from WindowManagerService for pointers.
560 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700561 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800562 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700563 */
564std::optional<DisplayViewport> TouchInputMapper::findViewport() {
565 if (mParameters.hasAssociatedDisplay) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800566 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700567 if (displayPort) {
568 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800569 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700570 }
571
Michael Wright227c5542020-07-02 18:30:52 +0100572 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800573 std::optional<DisplayViewport> viewport =
574 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
575 if (viewport) {
576 return viewport;
577 } else {
578 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
579 mConfig.defaultPointerDisplayId);
580 }
581 }
582
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700583 // Check if uniqueDisplayId is specified in idc file.
584 if (!mParameters.uniqueDisplayId.empty()) {
585 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
586 }
587
588 ViewportType viewportTypeToUse;
589 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100590 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700591 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100592 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700593 }
594
595 std::optional<DisplayViewport> viewport =
596 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100597 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700598 ALOGW("Input device %s should be associated with external display, "
599 "fallback to internal one for the external viewport is not found.",
600 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100601 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700602 }
603
604 return viewport;
605 }
606
607 // No associated display, return a non-display viewport.
608 DisplayViewport newViewport;
609 // Raw width and height in the natural orientation.
610 int32_t rawWidth = mRawPointerAxes.getRawWidth();
611 int32_t rawHeight = mRawPointerAxes.getRawHeight();
612 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
613 return std::make_optional(newViewport);
614}
615
616void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100617 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700618
619 resolveExternalStylusPresence();
620
621 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100622 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700623 mConfig.pointerGesturesEnabled) {
624 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100625 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700626 if (hasStylus()) {
627 mSource |= AINPUT_SOURCE_STYLUS;
628 }
Michael Wright227c5542020-07-02 18:30:52 +0100629 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700630 mParameters.hasAssociatedDisplay) {
631 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100632 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700633 if (hasStylus()) {
634 mSource |= AINPUT_SOURCE_STYLUS;
635 }
636 if (hasExternalStylus()) {
637 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
638 }
Michael Wright227c5542020-07-02 18:30:52 +0100639 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700640 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100641 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700642 } else {
643 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100644 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700645 }
646
647 // Ensure we have valid X and Y axes.
648 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
649 ALOGW("Touch device '%s' did not report support for X or Y axis! "
650 "The device will be inoperable.",
651 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100652 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700653 return;
654 }
655
656 // Get associated display dimensions.
657 std::optional<DisplayViewport> newViewport = findViewport();
658 if (!newViewport) {
659 ALOGI("Touch device '%s' could not query the properties of its associated "
660 "display. The device will be inoperable until the display size "
661 "becomes available.",
662 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100663 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700664 return;
665 }
666
667 // Raw width and height in the natural orientation.
668 int32_t rawWidth = mRawPointerAxes.getRawWidth();
669 int32_t rawHeight = mRawPointerAxes.getRawHeight();
670
671 bool viewportChanged = mViewport != *newViewport;
672 if (viewportChanged) {
673 mViewport = *newViewport;
674
Michael Wright227c5542020-07-02 18:30:52 +0100675 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700676 // Convert rotated viewport to natural surface coordinates.
677 int32_t naturalLogicalWidth, naturalLogicalHeight;
678 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
679 int32_t naturalPhysicalLeft, naturalPhysicalTop;
680 int32_t naturalDeviceWidth, naturalDeviceHeight;
681 switch (mViewport.orientation) {
682 case DISPLAY_ORIENTATION_90:
683 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
684 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
685 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
686 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800687 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700688 naturalPhysicalTop = mViewport.physicalLeft;
689 naturalDeviceWidth = mViewport.deviceHeight;
690 naturalDeviceHeight = mViewport.deviceWidth;
691 break;
692 case DISPLAY_ORIENTATION_180:
693 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
694 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
695 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
696 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
697 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
698 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
699 naturalDeviceWidth = mViewport.deviceWidth;
700 naturalDeviceHeight = mViewport.deviceHeight;
701 break;
702 case DISPLAY_ORIENTATION_270:
703 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
704 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
705 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
706 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
707 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800708 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700709 naturalDeviceWidth = mViewport.deviceHeight;
710 naturalDeviceHeight = mViewport.deviceWidth;
711 break;
712 case DISPLAY_ORIENTATION_0:
713 default:
714 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
715 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
716 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
717 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
718 naturalPhysicalLeft = mViewport.physicalLeft;
719 naturalPhysicalTop = mViewport.physicalTop;
720 naturalDeviceWidth = mViewport.deviceWidth;
721 naturalDeviceHeight = mViewport.deviceHeight;
722 break;
723 }
724
725 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
726 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
727 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
728 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
729 }
730
731 mPhysicalWidth = naturalPhysicalWidth;
732 mPhysicalHeight = naturalPhysicalHeight;
733 mPhysicalLeft = naturalPhysicalLeft;
734 mPhysicalTop = naturalPhysicalTop;
735
Arthur Hung4197f6b2020-03-16 15:39:59 +0800736 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
737 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700738 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
739 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800740 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
741 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700742
743 mSurfaceOrientation =
744 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
745 } else {
746 mPhysicalWidth = rawWidth;
747 mPhysicalHeight = rawHeight;
748 mPhysicalLeft = 0;
749 mPhysicalTop = 0;
750
Arthur Hung4197f6b2020-03-16 15:39:59 +0800751 mRawSurfaceWidth = rawWidth;
752 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700753 mSurfaceLeft = 0;
754 mSurfaceTop = 0;
755 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
756 }
757 }
758
759 // If moving between pointer modes, need to reset some state.
760 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
761 if (deviceModeChanged) {
762 mOrientedRanges.clear();
763 }
764
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800765 // Create pointer controller if needed.
Michael Wright227c5542020-07-02 18:30:52 +0100766 if (mDeviceMode == DeviceMode::POINTER ||
767 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800768 if (mPointerController == nullptr) {
769 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700770 }
771 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100772 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700773 }
774
775 if (viewportChanged || deviceModeChanged) {
776 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
777 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800778 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700779 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
780
781 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800782 mXScale = float(mRawSurfaceWidth) / rawWidth;
783 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700784 mXTranslate = -mSurfaceLeft;
785 mYTranslate = -mSurfaceTop;
786 mXPrecision = 1.0f / mXScale;
787 mYPrecision = 1.0f / mYScale;
788
789 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
790 mOrientedRanges.x.source = mSource;
791 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
792 mOrientedRanges.y.source = mSource;
793
794 configureVirtualKeys();
795
796 // Scale factor for terms that are not oriented in a particular axis.
797 // If the pixels are square then xScale == yScale otherwise we fake it
798 // by choosing an average.
799 mGeometricScale = avg(mXScale, mYScale);
800
801 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800802 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700803
804 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100805 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700806 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
807 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
808 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
809 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
810 } else {
811 mSizeScale = 0.0f;
812 }
813
814 mOrientedRanges.haveTouchSize = true;
815 mOrientedRanges.haveToolSize = true;
816 mOrientedRanges.haveSize = true;
817
818 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
819 mOrientedRanges.touchMajor.source = mSource;
820 mOrientedRanges.touchMajor.min = 0;
821 mOrientedRanges.touchMajor.max = diagonalSize;
822 mOrientedRanges.touchMajor.flat = 0;
823 mOrientedRanges.touchMajor.fuzz = 0;
824 mOrientedRanges.touchMajor.resolution = 0;
825
826 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
827 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
828
829 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
830 mOrientedRanges.toolMajor.source = mSource;
831 mOrientedRanges.toolMajor.min = 0;
832 mOrientedRanges.toolMajor.max = diagonalSize;
833 mOrientedRanges.toolMajor.flat = 0;
834 mOrientedRanges.toolMajor.fuzz = 0;
835 mOrientedRanges.toolMajor.resolution = 0;
836
837 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
838 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
839
840 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
841 mOrientedRanges.size.source = mSource;
842 mOrientedRanges.size.min = 0;
843 mOrientedRanges.size.max = 1.0;
844 mOrientedRanges.size.flat = 0;
845 mOrientedRanges.size.fuzz = 0;
846 mOrientedRanges.size.resolution = 0;
847 } else {
848 mSizeScale = 0.0f;
849 }
850
851 // Pressure factors.
852 mPressureScale = 0;
853 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100854 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
855 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700856 if (mCalibration.havePressureScale) {
857 mPressureScale = mCalibration.pressureScale;
858 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
859 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
860 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
861 }
862 }
863
864 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
865 mOrientedRanges.pressure.source = mSource;
866 mOrientedRanges.pressure.min = 0;
867 mOrientedRanges.pressure.max = pressureMax;
868 mOrientedRanges.pressure.flat = 0;
869 mOrientedRanges.pressure.fuzz = 0;
870 mOrientedRanges.pressure.resolution = 0;
871
872 // Tilt
873 mTiltXCenter = 0;
874 mTiltXScale = 0;
875 mTiltYCenter = 0;
876 mTiltYScale = 0;
877 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
878 if (mHaveTilt) {
879 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
880 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
881 mTiltXScale = M_PI / 180;
882 mTiltYScale = M_PI / 180;
883
884 mOrientedRanges.haveTilt = true;
885
886 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
887 mOrientedRanges.tilt.source = mSource;
888 mOrientedRanges.tilt.min = 0;
889 mOrientedRanges.tilt.max = M_PI_2;
890 mOrientedRanges.tilt.flat = 0;
891 mOrientedRanges.tilt.fuzz = 0;
892 mOrientedRanges.tilt.resolution = 0;
893 }
894
895 // Orientation
896 mOrientationScale = 0;
897 if (mHaveTilt) {
898 mOrientedRanges.haveOrientation = true;
899
900 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
901 mOrientedRanges.orientation.source = mSource;
902 mOrientedRanges.orientation.min = -M_PI;
903 mOrientedRanges.orientation.max = M_PI;
904 mOrientedRanges.orientation.flat = 0;
905 mOrientedRanges.orientation.fuzz = 0;
906 mOrientedRanges.orientation.resolution = 0;
907 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100908 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700909 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100910 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700911 if (mRawPointerAxes.orientation.valid) {
912 if (mRawPointerAxes.orientation.maxValue > 0) {
913 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
914 } else if (mRawPointerAxes.orientation.minValue < 0) {
915 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
916 } else {
917 mOrientationScale = 0;
918 }
919 }
920 }
921
922 mOrientedRanges.haveOrientation = true;
923
924 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
925 mOrientedRanges.orientation.source = mSource;
926 mOrientedRanges.orientation.min = -M_PI_2;
927 mOrientedRanges.orientation.max = M_PI_2;
928 mOrientedRanges.orientation.flat = 0;
929 mOrientedRanges.orientation.fuzz = 0;
930 mOrientedRanges.orientation.resolution = 0;
931 }
932
933 // Distance
934 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100935 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
936 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700937 if (mCalibration.haveDistanceScale) {
938 mDistanceScale = mCalibration.distanceScale;
939 } else {
940 mDistanceScale = 1.0f;
941 }
942 }
943
944 mOrientedRanges.haveDistance = true;
945
946 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
947 mOrientedRanges.distance.source = mSource;
948 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
949 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
950 mOrientedRanges.distance.flat = 0;
951 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
952 mOrientedRanges.distance.resolution = 0;
953 }
954
955 // Compute oriented precision, scales and ranges.
956 // Note that the maximum value reported is an inclusive maximum value so it is one
957 // unit less than the total width or height of surface.
958 switch (mSurfaceOrientation) {
959 case DISPLAY_ORIENTATION_90:
960 case DISPLAY_ORIENTATION_270:
961 mOrientedXPrecision = mYPrecision;
962 mOrientedYPrecision = mXPrecision;
963
964 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800965 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966 mOrientedRanges.x.flat = 0;
967 mOrientedRanges.x.fuzz = 0;
968 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
969
970 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800971 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700972 mOrientedRanges.y.flat = 0;
973 mOrientedRanges.y.fuzz = 0;
974 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
975 break;
976
977 default:
978 mOrientedXPrecision = mXPrecision;
979 mOrientedYPrecision = mYPrecision;
980
981 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800982 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700983 mOrientedRanges.x.flat = 0;
984 mOrientedRanges.x.fuzz = 0;
985 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
986
987 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800988 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700989 mOrientedRanges.y.flat = 0;
990 mOrientedRanges.y.fuzz = 0;
991 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
992 break;
993 }
994
995 // Location
996 updateAffineTransformation();
997
Michael Wright227c5542020-07-02 18:30:52 +0100998 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700999 // Compute pointer gesture detection parameters.
1000 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001001 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001002
1003 // Scale movements such that one whole swipe of the touch pad covers a
1004 // given area relative to the diagonal size of the display when no acceleration
1005 // is applied.
1006 // Assume that the touch pad has a square aspect ratio such that movements in
1007 // X and Y of the same number of raw units cover the same physical distance.
1008 mPointerXMovementScale =
1009 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1010 mPointerYMovementScale = mPointerXMovementScale;
1011
1012 // Scale zooms to cover a smaller range of the display than movements do.
1013 // This value determines the area around the pointer that is affected by freeform
1014 // pointer gestures.
1015 mPointerXZoomScale =
1016 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1017 mPointerYZoomScale = mPointerXZoomScale;
1018
1019 // Max width between pointers to detect a swipe gesture is more than some fraction
1020 // of the diagonal axis of the touch pad. Touches that are wider than this are
1021 // translated into freeform gestures.
1022 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1023
1024 // Abort current pointer usages because the state has changed.
1025 abortPointerUsage(when, 0 /*policyFlags*/);
1026 }
1027
1028 // Inform the dispatcher about the changes.
1029 *outResetNeeded = true;
1030 bumpGeneration();
1031 }
1032}
1033
1034void TouchInputMapper::dumpSurface(std::string& dump) {
1035 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001036 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1037 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001038 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1039 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001040 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1041 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001042 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1043 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1044 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1045 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1046 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1047}
1048
1049void TouchInputMapper::configureVirtualKeys() {
1050 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001051 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001052
1053 mVirtualKeys.clear();
1054
1055 if (virtualKeyDefinitions.size() == 0) {
1056 return;
1057 }
1058
1059 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1060 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1061 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1062 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1063
1064 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1065 VirtualKey virtualKey;
1066
1067 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1068 int32_t keyCode;
1069 int32_t dummyKeyMetaState;
1070 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001071 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1072 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001073 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1074 continue; // drop the key
1075 }
1076
1077 virtualKey.keyCode = keyCode;
1078 virtualKey.flags = flags;
1079
1080 // convert the key definition's display coordinates into touch coordinates for a hit box
1081 int32_t halfWidth = virtualKeyDefinition.width / 2;
1082 int32_t halfHeight = virtualKeyDefinition.height / 2;
1083
1084 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001085 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086 touchScreenLeft;
1087 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001088 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001089 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001090 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1091 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001092 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001093 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1094 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001095 touchScreenTop;
1096 mVirtualKeys.push_back(virtualKey);
1097 }
1098}
1099
1100void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1101 if (!mVirtualKeys.empty()) {
1102 dump += INDENT3 "Virtual Keys:\n";
1103
1104 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1105 const VirtualKey& virtualKey = mVirtualKeys[i];
1106 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1107 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1108 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1109 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1110 }
1111 }
1112}
1113
1114void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001115 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001116 Calibration& out = mCalibration;
1117
1118 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001119 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001120 String8 sizeCalibrationString;
1121 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1122 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001123 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001124 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001125 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001127 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001128 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001129 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001130 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001131 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001132 } else if (sizeCalibrationString != "default") {
1133 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1134 }
1135 }
1136
1137 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1138 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1139 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1140
1141 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 String8 pressureCalibrationString;
1144 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1145 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001146 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001148 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001150 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 } else if (pressureCalibrationString != "default") {
1152 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1153 pressureCalibrationString.string());
1154 }
1155 }
1156
1157 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1158
1159 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001160 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001161 String8 orientationCalibrationString;
1162 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1163 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001164 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001166 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001168 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 } else if (orientationCalibrationString != "default") {
1170 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1171 orientationCalibrationString.string());
1172 }
1173 }
1174
1175 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001176 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 String8 distanceCalibrationString;
1178 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1179 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001180 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001182 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001183 } else if (distanceCalibrationString != "default") {
1184 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1185 distanceCalibrationString.string());
1186 }
1187 }
1188
1189 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1190
Michael Wright227c5542020-07-02 18:30:52 +01001191 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 String8 coverageCalibrationString;
1193 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1194 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001195 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001197 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 } else if (coverageCalibrationString != "default") {
1199 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1200 coverageCalibrationString.string());
1201 }
1202 }
1203}
1204
1205void TouchInputMapper::resolveCalibration() {
1206 // Size
1207 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001208 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1209 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210 }
1211 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001212 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 }
1214
1215 // Pressure
1216 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001217 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1218 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 }
1220 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001221 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222 }
1223
1224 // Orientation
1225 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001226 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1227 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001228 }
1229 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001230 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 }
1232
1233 // Distance
1234 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001235 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1236 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 }
1238 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001239 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 }
1241
1242 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001243 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1244 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 }
1246}
1247
1248void TouchInputMapper::dumpCalibration(std::string& dump) {
1249 dump += INDENT3 "Calibration:\n";
1250
1251 // Size
1252 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001253 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 dump += INDENT4 "touch.size.calibration: none\n";
1255 break;
Michael Wright227c5542020-07-02 18:30:52 +01001256 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 dump += INDENT4 "touch.size.calibration: geometric\n";
1258 break;
Michael Wright227c5542020-07-02 18:30:52 +01001259 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 dump += INDENT4 "touch.size.calibration: diameter\n";
1261 break;
Michael Wright227c5542020-07-02 18:30:52 +01001262 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 dump += INDENT4 "touch.size.calibration: box\n";
1264 break;
Michael Wright227c5542020-07-02 18:30:52 +01001265 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 dump += INDENT4 "touch.size.calibration: area\n";
1267 break;
1268 default:
1269 ALOG_ASSERT(false);
1270 }
1271
1272 if (mCalibration.haveSizeScale) {
1273 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1274 }
1275
1276 if (mCalibration.haveSizeBias) {
1277 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1278 }
1279
1280 if (mCalibration.haveSizeIsSummed) {
1281 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1282 toString(mCalibration.sizeIsSummed));
1283 }
1284
1285 // Pressure
1286 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001287 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288 dump += INDENT4 "touch.pressure.calibration: none\n";
1289 break;
Michael Wright227c5542020-07-02 18:30:52 +01001290 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291 dump += INDENT4 "touch.pressure.calibration: physical\n";
1292 break;
Michael Wright227c5542020-07-02 18:30:52 +01001293 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1295 break;
1296 default:
1297 ALOG_ASSERT(false);
1298 }
1299
1300 if (mCalibration.havePressureScale) {
1301 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1302 }
1303
1304 // Orientation
1305 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001306 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.orientation.calibration: none\n";
1308 break;
Michael Wright227c5542020-07-02 18:30:52 +01001309 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1311 break;
Michael Wright227c5542020-07-02 18:30:52 +01001312 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.orientation.calibration: vector\n";
1314 break;
1315 default:
1316 ALOG_ASSERT(false);
1317 }
1318
1319 // Distance
1320 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001321 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 dump += INDENT4 "touch.distance.calibration: none\n";
1323 break;
Michael Wright227c5542020-07-02 18:30:52 +01001324 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 dump += INDENT4 "touch.distance.calibration: scaled\n";
1326 break;
1327 default:
1328 ALOG_ASSERT(false);
1329 }
1330
1331 if (mCalibration.haveDistanceScale) {
1332 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1333 }
1334
1335 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001336 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001337 dump += INDENT4 "touch.coverage.calibration: none\n";
1338 break;
Michael Wright227c5542020-07-02 18:30:52 +01001339 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001340 dump += INDENT4 "touch.coverage.calibration: box\n";
1341 break;
1342 default:
1343 ALOG_ASSERT(false);
1344 }
1345}
1346
1347void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1348 dump += INDENT3 "Affine Transformation:\n";
1349
1350 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1351 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1352 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1353 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1354 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1355 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1356}
1357
1358void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001359 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360 mSurfaceOrientation);
1361}
1362
1363void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001364 mCursorButtonAccumulator.reset(getDeviceContext());
1365 mCursorScrollAccumulator.reset(getDeviceContext());
1366 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001367
1368 mPointerVelocityControl.reset();
1369 mWheelXVelocityControl.reset();
1370 mWheelYVelocityControl.reset();
1371
1372 mRawStatesPending.clear();
1373 mCurrentRawState.clear();
1374 mCurrentCookedState.clear();
1375 mLastRawState.clear();
1376 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001377 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001378 mSentHoverEnter = false;
1379 mHavePointerIds = false;
1380 mCurrentMotionAborted = false;
1381 mDownTime = 0;
1382
1383 mCurrentVirtualKey.down = false;
1384
1385 mPointerGesture.reset();
1386 mPointerSimple.reset();
1387 resetExternalStylus();
1388
1389 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001390 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001391 mPointerController->clearSpots();
1392 }
1393
1394 InputMapper::reset(when);
1395}
1396
1397void TouchInputMapper::resetExternalStylus() {
1398 mExternalStylusState.clear();
1399 mExternalStylusId = -1;
1400 mExternalStylusFusionTimeout = LLONG_MAX;
1401 mExternalStylusDataPending = false;
1402}
1403
1404void TouchInputMapper::clearStylusDataPendingFlags() {
1405 mExternalStylusDataPending = false;
1406 mExternalStylusFusionTimeout = LLONG_MAX;
1407}
1408
1409void TouchInputMapper::process(const RawEvent* rawEvent) {
1410 mCursorButtonAccumulator.process(rawEvent);
1411 mCursorScrollAccumulator.process(rawEvent);
1412 mTouchButtonAccumulator.process(rawEvent);
1413
1414 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1415 sync(rawEvent->when);
1416 }
1417}
1418
1419void TouchInputMapper::sync(nsecs_t when) {
1420 const RawState* last =
1421 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1422
1423 // Push a new state.
1424 mRawStatesPending.emplace_back();
1425
1426 RawState* next = &mRawStatesPending.back();
1427 next->clear();
1428 next->when = when;
1429
1430 // Sync button state.
1431 next->buttonState =
1432 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1433
1434 // Sync scroll
1435 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1436 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1437 mCursorScrollAccumulator.finishSync();
1438
1439 // Sync touch
1440 syncTouch(when, next);
1441
1442 // Assign pointer ids.
1443 if (!mHavePointerIds) {
1444 assignPointerIds(last, next);
1445 }
1446
1447#if DEBUG_RAW_EVENTS
1448 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001449 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001450 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1451 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhungcc7f9802020-04-30 17:55:40 +08001452 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1453 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001454#endif
1455
1456 processRawTouches(false /*timeout*/);
1457}
1458
1459void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001460 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001461 // Drop all input if the device is disabled.
1462 mCurrentRawState.clear();
1463 mRawStatesPending.clear();
1464 return;
1465 }
1466
1467 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1468 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1469 // touching the current state will only observe the events that have been dispatched to the
1470 // rest of the pipeline.
1471 const size_t N = mRawStatesPending.size();
1472 size_t count;
1473 for (count = 0; count < N; count++) {
1474 const RawState& next = mRawStatesPending[count];
1475
1476 // A failure to assign the stylus id means that we're waiting on stylus data
1477 // and so should defer the rest of the pipeline.
1478 if (assignExternalStylusId(next, timeout)) {
1479 break;
1480 }
1481
1482 // All ready to go.
1483 clearStylusDataPendingFlags();
1484 mCurrentRawState.copyFrom(next);
1485 if (mCurrentRawState.when < mLastRawState.when) {
1486 mCurrentRawState.when = mLastRawState.when;
1487 }
1488 cookAndDispatch(mCurrentRawState.when);
1489 }
1490 if (count != 0) {
1491 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1492 }
1493
1494 if (mExternalStylusDataPending) {
1495 if (timeout) {
1496 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1497 clearStylusDataPendingFlags();
1498 mCurrentRawState.copyFrom(mLastRawState);
1499#if DEBUG_STYLUS_FUSION
1500 ALOGD("Timeout expired, synthesizing event with new stylus data");
1501#endif
1502 cookAndDispatch(when);
1503 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1504 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1505 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1506 }
1507 }
1508}
1509
1510void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1511 // Always start with a clean state.
1512 mCurrentCookedState.clear();
1513
1514 // Apply stylus buttons to current raw state.
1515 applyExternalStylusButtonState(when);
1516
1517 // Handle policy on initial down or hover events.
1518 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1519 mCurrentRawState.rawPointerData.pointerCount != 0;
1520
1521 uint32_t policyFlags = 0;
1522 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1523 if (initialDown || buttonsPressed) {
1524 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001525 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001526 getContext()->fadePointer();
1527 }
1528
1529 if (mParameters.wake) {
1530 policyFlags |= POLICY_FLAG_WAKE;
1531 }
1532 }
1533
1534 // Consume raw off-screen touches before cooking pointer data.
1535 // If touches are consumed, subsequent code will not receive any pointer data.
1536 if (consumeRawTouches(when, policyFlags)) {
1537 mCurrentRawState.rawPointerData.clear();
1538 }
1539
1540 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1541 // with cooked pointer data that has the same ids and indices as the raw data.
1542 // The following code can use either the raw or cooked data, as needed.
1543 cookPointerData();
1544
1545 // Apply stylus pressure to current cooked state.
1546 applyExternalStylusTouchState(when);
1547
1548 // Synthesize key down from raw buttons if needed.
1549 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1550 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1551 mCurrentCookedState.buttonState);
1552
1553 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001554 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001555 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1556 uint32_t id = idBits.clearFirstMarkedBit();
1557 const RawPointerData::Pointer& pointer =
1558 mCurrentRawState.rawPointerData.pointerForId(id);
1559 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1560 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1561 mCurrentCookedState.stylusIdBits.markBit(id);
1562 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1563 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1564 mCurrentCookedState.fingerIdBits.markBit(id);
1565 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1566 mCurrentCookedState.mouseIdBits.markBit(id);
1567 }
1568 }
1569 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1570 uint32_t id = idBits.clearFirstMarkedBit();
1571 const RawPointerData::Pointer& pointer =
1572 mCurrentRawState.rawPointerData.pointerForId(id);
1573 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1574 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1575 mCurrentCookedState.stylusIdBits.markBit(id);
1576 }
1577 }
1578
1579 // Stylus takes precedence over all tools, then mouse, then finger.
1580 PointerUsage pointerUsage = mPointerUsage;
1581 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1582 mCurrentCookedState.mouseIdBits.clear();
1583 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001584 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001585 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1586 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001587 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001588 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1589 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001590 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001591 }
1592
1593 dispatchPointerUsage(when, policyFlags, pointerUsage);
1594 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001595 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596 mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001597 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1598 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001599
1600 mPointerController->setButtonState(mCurrentRawState.buttonState);
1601 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1602 mCurrentCookedState.cookedPointerData.idToIndex,
1603 mCurrentCookedState.cookedPointerData.touchingIdBits,
1604 mViewport.displayId);
1605 }
1606
1607 if (!mCurrentMotionAborted) {
1608 dispatchButtonRelease(when, policyFlags);
1609 dispatchHoverExit(when, policyFlags);
1610 dispatchTouches(when, policyFlags);
1611 dispatchHoverEnterAndMove(when, policyFlags);
1612 dispatchButtonPress(when, policyFlags);
1613 }
1614
1615 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1616 mCurrentMotionAborted = false;
1617 }
1618 }
1619
1620 // Synthesize key up from raw buttons if needed.
1621 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1622 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1623 mCurrentCookedState.buttonState);
1624
1625 // Clear some transient state.
1626 mCurrentRawState.rawVScroll = 0;
1627 mCurrentRawState.rawHScroll = 0;
1628
1629 // Copy current touch to last touch in preparation for the next cycle.
1630 mLastRawState.copyFrom(mCurrentRawState);
1631 mLastCookedState.copyFrom(mCurrentCookedState);
1632}
1633
1634void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001635 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001636 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1637 }
1638}
1639
1640void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1641 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1642 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1643
1644 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1645 float pressure = mExternalStylusState.pressure;
1646 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1647 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1648 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1649 }
1650 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1651 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1652
1653 PointerProperties& properties =
1654 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1655 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1656 properties.toolType = mExternalStylusState.toolType;
1657 }
1658 }
1659}
1660
1661bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001662 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001663 return false;
1664 }
1665
1666 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1667 state.rawPointerData.pointerCount != 0;
1668 if (initialDown) {
1669 if (mExternalStylusState.pressure != 0.0f) {
1670#if DEBUG_STYLUS_FUSION
1671 ALOGD("Have both stylus and touch data, beginning fusion");
1672#endif
1673 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1674 } else if (timeout) {
1675#if DEBUG_STYLUS_FUSION
1676 ALOGD("Timeout expired, assuming touch is not a stylus.");
1677#endif
1678 resetExternalStylus();
1679 } else {
1680 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1681 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1682 }
1683#if DEBUG_STYLUS_FUSION
1684 ALOGD("No stylus data but stylus is connected, requesting timeout "
1685 "(%" PRId64 "ms)",
1686 mExternalStylusFusionTimeout);
1687#endif
1688 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1689 return true;
1690 }
1691 }
1692
1693 // Check if the stylus pointer has gone up.
1694 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1695#if DEBUG_STYLUS_FUSION
1696 ALOGD("Stylus pointer is going up");
1697#endif
1698 mExternalStylusId = -1;
1699 }
1700
1701 return false;
1702}
1703
1704void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001705 if (mDeviceMode == DeviceMode::POINTER) {
1706 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001707 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1708 }
Michael Wright227c5542020-07-02 18:30:52 +01001709 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001710 if (mExternalStylusFusionTimeout < when) {
1711 processRawTouches(true /*timeout*/);
1712 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1713 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1714 }
1715 }
1716}
1717
1718void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1719 mExternalStylusState.copyFrom(state);
1720 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1721 // We're either in the middle of a fused stream of data or we're waiting on data before
1722 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1723 // data.
1724 mExternalStylusDataPending = true;
1725 processRawTouches(false /*timeout*/);
1726 }
1727}
1728
1729bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1730 // Check for release of a virtual key.
1731 if (mCurrentVirtualKey.down) {
1732 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1733 // Pointer went up while virtual key was down.
1734 mCurrentVirtualKey.down = false;
1735 if (!mCurrentVirtualKey.ignored) {
1736#if DEBUG_VIRTUAL_KEYS
1737 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1738 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1739#endif
1740 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1741 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1742 }
1743 return true;
1744 }
1745
1746 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1747 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1748 const RawPointerData::Pointer& pointer =
1749 mCurrentRawState.rawPointerData.pointerForId(id);
1750 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1751 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1752 // Pointer is still within the space of the virtual key.
1753 return true;
1754 }
1755 }
1756
1757 // Pointer left virtual key area or another pointer also went down.
1758 // Send key cancellation but do not consume the touch yet.
1759 // This is useful when the user swipes through from the virtual key area
1760 // into the main display surface.
1761 mCurrentVirtualKey.down = false;
1762 if (!mCurrentVirtualKey.ignored) {
1763#if DEBUG_VIRTUAL_KEYS
1764 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1765 mCurrentVirtualKey.scanCode);
1766#endif
1767 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1768 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1769 AKEY_EVENT_FLAG_CANCELED);
1770 }
1771 }
1772
1773 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1774 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1775 // Pointer just went down. Check for virtual key press or off-screen touches.
1776 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1777 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1778 if (!isPointInsideSurface(pointer.x, pointer.y)) {
1779 // If exactly one pointer went down, check for virtual key hit.
1780 // Otherwise we will drop the entire stroke.
1781 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1782 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1783 if (virtualKey) {
1784 mCurrentVirtualKey.down = true;
1785 mCurrentVirtualKey.downTime = when;
1786 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1787 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1788 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001789 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1790 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001791
1792 if (!mCurrentVirtualKey.ignored) {
1793#if DEBUG_VIRTUAL_KEYS
1794 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1795 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1796#endif
1797 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1798 AKEY_EVENT_FLAG_FROM_SYSTEM |
1799 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1800 }
1801 }
1802 }
1803 return true;
1804 }
1805 }
1806
1807 // Disable all virtual key touches that happen within a short time interval of the
1808 // most recent touch within the screen area. The idea is to filter out stray
1809 // virtual key presses when interacting with the touch screen.
1810 //
1811 // Problems we're trying to solve:
1812 //
1813 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1814 // virtual key area that is implemented by a separate touch panel and accidentally
1815 // triggers a virtual key.
1816 //
1817 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1818 // area and accidentally triggers a virtual key. This often happens when virtual keys
1819 // are layed out below the screen near to where the on screen keyboard's space bar
1820 // is displayed.
1821 if (mConfig.virtualKeyQuietTime > 0 &&
1822 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001823 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001824 }
1825 return false;
1826}
1827
1828void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1829 int32_t keyEventAction, int32_t keyEventFlags) {
1830 int32_t keyCode = mCurrentVirtualKey.keyCode;
1831 int32_t scanCode = mCurrentVirtualKey.scanCode;
1832 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001833 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001834 policyFlags |= POLICY_FLAG_VIRTUAL;
1835
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001836 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1837 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1838 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001839 getListener()->notifyKey(&args);
1840}
1841
1842void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1843 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1844 if (!currentIdBits.isEmpty()) {
1845 int32_t metaState = getContext()->getGlobalMetaState();
1846 int32_t buttonState = mCurrentCookedState.buttonState;
1847 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1848 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1849 mCurrentCookedState.cookedPointerData.pointerProperties,
1850 mCurrentCookedState.cookedPointerData.pointerCoords,
1851 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1852 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1853 mCurrentMotionAborted = true;
1854 }
1855}
1856
1857void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1858 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1859 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1860 int32_t metaState = getContext()->getGlobalMetaState();
1861 int32_t buttonState = mCurrentCookedState.buttonState;
1862
1863 if (currentIdBits == lastIdBits) {
1864 if (!currentIdBits.isEmpty()) {
1865 // No pointer id changes so this is a move event.
1866 // The listener takes care of batching moves so we don't have to deal with that here.
1867 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1868 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1869 mCurrentCookedState.cookedPointerData.pointerProperties,
1870 mCurrentCookedState.cookedPointerData.pointerCoords,
1871 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1872 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1873 }
1874 } else {
1875 // There may be pointers going up and pointers going down and pointers moving
1876 // all at the same time.
1877 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1878 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1879 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1880 BitSet32 dispatchedIdBits(lastIdBits.value);
1881
1882 // Update last coordinates of pointers that have moved so that we observe the new
1883 // pointer positions at the same time as other pointers that have just gone up.
1884 bool moveNeeded =
1885 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1886 mCurrentCookedState.cookedPointerData.pointerCoords,
1887 mCurrentCookedState.cookedPointerData.idToIndex,
1888 mLastCookedState.cookedPointerData.pointerProperties,
1889 mLastCookedState.cookedPointerData.pointerCoords,
1890 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1891 if (buttonState != mLastCookedState.buttonState) {
1892 moveNeeded = true;
1893 }
1894
1895 // Dispatch pointer up events.
1896 while (!upIdBits.isEmpty()) {
1897 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001898 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1899 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1900 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001901 mLastCookedState.cookedPointerData.pointerProperties,
1902 mLastCookedState.cookedPointerData.pointerCoords,
1903 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1904 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1905 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001906 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001907 }
1908
1909 // Dispatch move events if any of the remaining pointers moved from their old locations.
1910 // Although applications receive new locations as part of individual pointer up
1911 // events, they do not generally handle them except when presented in a move event.
1912 if (moveNeeded && !moveIdBits.isEmpty()) {
1913 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1914 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1915 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1916 mCurrentCookedState.cookedPointerData.pointerCoords,
1917 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1918 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1919 }
1920
1921 // Dispatch pointer down events using the new pointer locations.
1922 while (!downIdBits.isEmpty()) {
1923 uint32_t downId = downIdBits.clearFirstMarkedBit();
1924 dispatchedIdBits.markBit(downId);
1925
1926 if (dispatchedIdBits.count() == 1) {
1927 // First pointer is going down. Set down time.
1928 mDownTime = when;
1929 }
1930
1931 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1932 metaState, buttonState, 0,
1933 mCurrentCookedState.cookedPointerData.pointerProperties,
1934 mCurrentCookedState.cookedPointerData.pointerCoords,
1935 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1936 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1937 }
1938 }
1939}
1940
1941void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1942 if (mSentHoverEnter &&
1943 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1944 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1945 int32_t metaState = getContext()->getGlobalMetaState();
1946 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1947 mLastCookedState.buttonState, 0,
1948 mLastCookedState.cookedPointerData.pointerProperties,
1949 mLastCookedState.cookedPointerData.pointerCoords,
1950 mLastCookedState.cookedPointerData.idToIndex,
1951 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1952 mOrientedYPrecision, mDownTime);
1953 mSentHoverEnter = false;
1954 }
1955}
1956
1957void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1958 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1959 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1960 int32_t metaState = getContext()->getGlobalMetaState();
1961 if (!mSentHoverEnter) {
1962 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1963 metaState, mCurrentRawState.buttonState, 0,
1964 mCurrentCookedState.cookedPointerData.pointerProperties,
1965 mCurrentCookedState.cookedPointerData.pointerCoords,
1966 mCurrentCookedState.cookedPointerData.idToIndex,
1967 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1968 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1969 mSentHoverEnter = true;
1970 }
1971
1972 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1973 mCurrentRawState.buttonState, 0,
1974 mCurrentCookedState.cookedPointerData.pointerProperties,
1975 mCurrentCookedState.cookedPointerData.pointerCoords,
1976 mCurrentCookedState.cookedPointerData.idToIndex,
1977 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1978 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1979 }
1980}
1981
1982void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
1983 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
1984 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
1985 const int32_t metaState = getContext()->getGlobalMetaState();
1986 int32_t buttonState = mLastCookedState.buttonState;
1987 while (!releasedButtons.isEmpty()) {
1988 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
1989 buttonState &= ~actionButton;
1990 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1991 actionButton, 0, metaState, buttonState, 0,
1992 mCurrentCookedState.cookedPointerData.pointerProperties,
1993 mCurrentCookedState.cookedPointerData.pointerCoords,
1994 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
1995 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1996 }
1997}
1998
1999void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2000 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2001 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2002 const int32_t metaState = getContext()->getGlobalMetaState();
2003 int32_t buttonState = mLastCookedState.buttonState;
2004 while (!pressedButtons.isEmpty()) {
2005 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2006 buttonState |= actionButton;
2007 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2008 0, metaState, buttonState, 0,
2009 mCurrentCookedState.cookedPointerData.pointerProperties,
2010 mCurrentCookedState.cookedPointerData.pointerCoords,
2011 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2012 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2013 }
2014}
2015
2016const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2017 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2018 return cookedPointerData.touchingIdBits;
2019 }
2020 return cookedPointerData.hoveringIdBits;
2021}
2022
2023void TouchInputMapper::cookPointerData() {
2024 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2025
2026 mCurrentCookedState.cookedPointerData.clear();
2027 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2028 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2029 mCurrentRawState.rawPointerData.hoveringIdBits;
2030 mCurrentCookedState.cookedPointerData.touchingIdBits =
2031 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002032 mCurrentCookedState.cookedPointerData.canceledIdBits =
2033 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002034
2035 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2036 mCurrentCookedState.buttonState = 0;
2037 } else {
2038 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2039 }
2040
2041 // Walk through the the active pointers and map device coordinates onto
2042 // surface coordinates and adjust for display orientation.
2043 for (uint32_t i = 0; i < currentPointerCount; i++) {
2044 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2045
2046 // Size
2047 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2048 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002049 case Calibration::SizeCalibration::GEOMETRIC:
2050 case Calibration::SizeCalibration::DIAMETER:
2051 case Calibration::SizeCalibration::BOX:
2052 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002053 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2054 touchMajor = in.touchMajor;
2055 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2056 toolMajor = in.toolMajor;
2057 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2058 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2059 : in.touchMajor;
2060 } else if (mRawPointerAxes.touchMajor.valid) {
2061 toolMajor = touchMajor = in.touchMajor;
2062 toolMinor = touchMinor =
2063 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2064 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2065 : in.touchMajor;
2066 } else if (mRawPointerAxes.toolMajor.valid) {
2067 touchMajor = toolMajor = in.toolMajor;
2068 touchMinor = toolMinor =
2069 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2070 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2071 : in.toolMajor;
2072 } else {
2073 ALOG_ASSERT(false,
2074 "No touch or tool axes. "
2075 "Size calibration should have been resolved to NONE.");
2076 touchMajor = 0;
2077 touchMinor = 0;
2078 toolMajor = 0;
2079 toolMinor = 0;
2080 size = 0;
2081 }
2082
2083 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2084 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2085 if (touchingCount > 1) {
2086 touchMajor /= touchingCount;
2087 touchMinor /= touchingCount;
2088 toolMajor /= touchingCount;
2089 toolMinor /= touchingCount;
2090 size /= touchingCount;
2091 }
2092 }
2093
Michael Wright227c5542020-07-02 18:30:52 +01002094 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002095 touchMajor *= mGeometricScale;
2096 touchMinor *= mGeometricScale;
2097 toolMajor *= mGeometricScale;
2098 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002099 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002100 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2101 touchMinor = touchMajor;
2102 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2103 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002104 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002105 touchMinor = touchMajor;
2106 toolMinor = toolMajor;
2107 }
2108
2109 mCalibration.applySizeScaleAndBias(&touchMajor);
2110 mCalibration.applySizeScaleAndBias(&touchMinor);
2111 mCalibration.applySizeScaleAndBias(&toolMajor);
2112 mCalibration.applySizeScaleAndBias(&toolMinor);
2113 size *= mSizeScale;
2114 break;
2115 default:
2116 touchMajor = 0;
2117 touchMinor = 0;
2118 toolMajor = 0;
2119 toolMinor = 0;
2120 size = 0;
2121 break;
2122 }
2123
2124 // Pressure
2125 float pressure;
2126 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002127 case Calibration::PressureCalibration::PHYSICAL:
2128 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002129 pressure = in.pressure * mPressureScale;
2130 break;
2131 default:
2132 pressure = in.isHovering ? 0 : 1;
2133 break;
2134 }
2135
2136 // Tilt and Orientation
2137 float tilt;
2138 float orientation;
2139 if (mHaveTilt) {
2140 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2141 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2142 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2143 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2144 } else {
2145 tilt = 0;
2146
2147 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002148 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002149 orientation = in.orientation * mOrientationScale;
2150 break;
Michael Wright227c5542020-07-02 18:30:52 +01002151 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002152 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2153 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2154 if (c1 != 0 || c2 != 0) {
2155 orientation = atan2f(c1, c2) * 0.5f;
2156 float confidence = hypotf(c1, c2);
2157 float scale = 1.0f + confidence / 16.0f;
2158 touchMajor *= scale;
2159 touchMinor /= scale;
2160 toolMajor *= scale;
2161 toolMinor /= scale;
2162 } else {
2163 orientation = 0;
2164 }
2165 break;
2166 }
2167 default:
2168 orientation = 0;
2169 }
2170 }
2171
2172 // Distance
2173 float distance;
2174 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002175 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002176 distance = in.distance * mDistanceScale;
2177 break;
2178 default:
2179 distance = 0;
2180 }
2181
2182 // Coverage
2183 int32_t rawLeft, rawTop, rawRight, rawBottom;
2184 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002185 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002186 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2187 rawRight = in.toolMinor & 0x0000ffff;
2188 rawBottom = in.toolMajor & 0x0000ffff;
2189 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2190 break;
2191 default:
2192 rawLeft = rawTop = rawRight = rawBottom = 0;
2193 break;
2194 }
2195
2196 // Adjust X,Y coords for device calibration
2197 // TODO: Adjust coverage coords?
2198 float xTransformed = in.x, yTransformed = in.y;
2199 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002200 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002201
2202 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002203 float left, top, right, bottom;
2204
2205 switch (mSurfaceOrientation) {
2206 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002207 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2208 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2209 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2210 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2211 orientation -= M_PI_2;
2212 if (mOrientedRanges.haveOrientation &&
2213 orientation < mOrientedRanges.orientation.min) {
2214 orientation +=
2215 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2216 }
2217 break;
2218 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002219 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2220 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2221 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2222 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2223 orientation -= M_PI;
2224 if (mOrientedRanges.haveOrientation &&
2225 orientation < mOrientedRanges.orientation.min) {
2226 orientation +=
2227 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2228 }
2229 break;
2230 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002231 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2232 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2233 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2234 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2235 orientation += M_PI_2;
2236 if (mOrientedRanges.haveOrientation &&
2237 orientation > mOrientedRanges.orientation.max) {
2238 orientation -=
2239 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2240 }
2241 break;
2242 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002243 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2244 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2245 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2246 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2247 break;
2248 }
2249
2250 // Write output coords.
2251 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2252 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002253 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2254 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002255 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2256 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2257 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2258 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2259 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2260 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2261 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002262 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002263 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2264 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2265 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2266 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2267 } else {
2268 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2269 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2270 }
2271
2272 // Write output properties.
2273 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
2274 uint32_t id = in.id;
2275 properties.clear();
2276 properties.id = id;
2277 properties.toolType = in.toolType;
2278
2279 // Write id index.
2280 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
2281 }
2282}
2283
2284void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2285 PointerUsage pointerUsage) {
2286 if (pointerUsage != mPointerUsage) {
2287 abortPointerUsage(when, policyFlags);
2288 mPointerUsage = pointerUsage;
2289 }
2290
2291 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002292 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002293 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2294 break;
Michael Wright227c5542020-07-02 18:30:52 +01002295 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 dispatchPointerStylus(when, policyFlags);
2297 break;
Michael Wright227c5542020-07-02 18:30:52 +01002298 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002299 dispatchPointerMouse(when, policyFlags);
2300 break;
Michael Wright227c5542020-07-02 18:30:52 +01002301 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002302 break;
2303 }
2304}
2305
2306void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2307 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002308 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002309 abortPointerGestures(when, policyFlags);
2310 break;
Michael Wright227c5542020-07-02 18:30:52 +01002311 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002312 abortPointerStylus(when, policyFlags);
2313 break;
Michael Wright227c5542020-07-02 18:30:52 +01002314 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 abortPointerMouse(when, policyFlags);
2316 break;
Michael Wright227c5542020-07-02 18:30:52 +01002317 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002318 break;
2319 }
2320
Michael Wright227c5542020-07-02 18:30:52 +01002321 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002322}
2323
2324void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2325 // Update current gesture coordinates.
2326 bool cancelPreviousGesture, finishPreviousGesture;
2327 bool sendEvents =
2328 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2329 if (!sendEvents) {
2330 return;
2331 }
2332 if (finishPreviousGesture) {
2333 cancelPreviousGesture = false;
2334 }
2335
2336 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002337 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002338 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002339 if (finishPreviousGesture || cancelPreviousGesture) {
2340 mPointerController->clearSpots();
2341 }
2342
Michael Wright227c5542020-07-02 18:30:52 +01002343 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2345 mPointerGesture.currentGestureIdToIndex,
2346 mPointerGesture.currentGestureIdBits,
2347 mPointerController->getDisplayId());
2348 }
2349 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002350 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 }
2352
2353 // Show or hide the pointer if needed.
2354 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002355 case PointerGesture::Mode::NEUTRAL:
2356 case PointerGesture::Mode::QUIET:
2357 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2358 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002360 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 }
2362 break;
Michael Wright227c5542020-07-02 18:30:52 +01002363 case PointerGesture::Mode::TAP:
2364 case PointerGesture::Mode::TAP_DRAG:
2365 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2366 case PointerGesture::Mode::HOVER:
2367 case PointerGesture::Mode::PRESS:
2368 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369 // Unfade the pointer when the current gesture manipulates the
2370 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002371 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 break;
Michael Wright227c5542020-07-02 18:30:52 +01002373 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 // Fade the pointer when the current gesture manipulates a different
2375 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002376 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002377 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002379 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 }
2381 break;
2382 }
2383
2384 // Send events!
2385 int32_t metaState = getContext()->getGlobalMetaState();
2386 int32_t buttonState = mCurrentCookedState.buttonState;
2387
2388 // Update last coordinates of pointers that have moved so that we observe the new
2389 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002390 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2391 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2392 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2393 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2394 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2395 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 bool moveNeeded = false;
2397 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2398 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2399 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2400 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2401 mPointerGesture.lastGestureIdBits.value);
2402 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2403 mPointerGesture.currentGestureCoords,
2404 mPointerGesture.currentGestureIdToIndex,
2405 mPointerGesture.lastGestureProperties,
2406 mPointerGesture.lastGestureCoords,
2407 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2408 if (buttonState != mLastCookedState.buttonState) {
2409 moveNeeded = true;
2410 }
2411 }
2412
2413 // Send motion events for all pointers that went up or were canceled.
2414 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2415 if (!dispatchedGestureIdBits.isEmpty()) {
2416 if (cancelPreviousGesture) {
2417 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2418 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2419 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2420 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2421 mPointerGesture.downTime);
2422
2423 dispatchedGestureIdBits.clear();
2424 } else {
2425 BitSet32 upGestureIdBits;
2426 if (finishPreviousGesture) {
2427 upGestureIdBits = dispatchedGestureIdBits;
2428 } else {
2429 upGestureIdBits.value =
2430 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2431 }
2432 while (!upGestureIdBits.isEmpty()) {
2433 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2434
2435 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2436 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2437 mPointerGesture.lastGestureProperties,
2438 mPointerGesture.lastGestureCoords,
2439 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2440 0, mPointerGesture.downTime);
2441
2442 dispatchedGestureIdBits.clearBit(id);
2443 }
2444 }
2445 }
2446
2447 // Send motion events for all pointers that moved.
2448 if (moveNeeded) {
2449 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2450 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2451 mPointerGesture.currentGestureProperties,
2452 mPointerGesture.currentGestureCoords,
2453 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2454 mPointerGesture.downTime);
2455 }
2456
2457 // Send motion events for all pointers that went down.
2458 if (down) {
2459 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2460 ~dispatchedGestureIdBits.value);
2461 while (!downGestureIdBits.isEmpty()) {
2462 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2463 dispatchedGestureIdBits.markBit(id);
2464
2465 if (dispatchedGestureIdBits.count() == 1) {
2466 mPointerGesture.downTime = when;
2467 }
2468
2469 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2470 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2471 mPointerGesture.currentGestureCoords,
2472 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2473 0, mPointerGesture.downTime);
2474 }
2475 }
2476
2477 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002478 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2480 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2481 mPointerGesture.currentGestureProperties,
2482 mPointerGesture.currentGestureCoords,
2483 mPointerGesture.currentGestureIdToIndex,
2484 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2485 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2486 // Synthesize a hover move event after all pointers go up to indicate that
2487 // the pointer is hovering again even if the user is not currently touching
2488 // the touch pad. This ensures that a view will receive a fresh hover enter
2489 // event after a tap.
2490 float x, y;
2491 mPointerController->getPosition(&x, &y);
2492
2493 PointerProperties pointerProperties;
2494 pointerProperties.clear();
2495 pointerProperties.id = 0;
2496 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2497
2498 PointerCoords pointerCoords;
2499 pointerCoords.clear();
2500 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2501 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2502
2503 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002504 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2505 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2506 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2507 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2508 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 getListener()->notifyMotion(&args);
2510 }
2511
2512 // Update state.
2513 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2514 if (!down) {
2515 mPointerGesture.lastGestureIdBits.clear();
2516 } else {
2517 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2518 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2519 uint32_t id = idBits.clearFirstMarkedBit();
2520 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2521 mPointerGesture.lastGestureProperties[index].copyFrom(
2522 mPointerGesture.currentGestureProperties[index]);
2523 mPointerGesture.lastGestureCoords[index].copyFrom(
2524 mPointerGesture.currentGestureCoords[index]);
2525 mPointerGesture.lastGestureIdToIndex[id] = index;
2526 }
2527 }
2528}
2529
2530void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2531 // Cancel previously dispatches pointers.
2532 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2533 int32_t metaState = getContext()->getGlobalMetaState();
2534 int32_t buttonState = mCurrentRawState.buttonState;
2535 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2536 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2537 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2538 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2539 0, 0, mPointerGesture.downTime);
2540 }
2541
2542 // Reset the current pointer gesture.
2543 mPointerGesture.reset();
2544 mPointerVelocityControl.reset();
2545
2546 // Remove any current spots.
2547 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002548 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002549 mPointerController->clearSpots();
2550 }
2551}
2552
2553bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2554 bool* outFinishPreviousGesture, bool isTimeout) {
2555 *outCancelPreviousGesture = false;
2556 *outFinishPreviousGesture = false;
2557
2558 // Handle TAP timeout.
2559 if (isTimeout) {
2560#if DEBUG_GESTURES
2561 ALOGD("Gestures: Processing timeout");
2562#endif
2563
Michael Wright227c5542020-07-02 18:30:52 +01002564 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002565 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2566 // The tap/drag timeout has not yet expired.
2567 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2568 mConfig.pointerGestureTapDragInterval);
2569 } else {
2570 // The tap is finished.
2571#if DEBUG_GESTURES
2572 ALOGD("Gestures: TAP finished");
2573#endif
2574 *outFinishPreviousGesture = true;
2575
2576 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002577 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002578 mPointerGesture.currentGestureIdBits.clear();
2579
2580 mPointerVelocityControl.reset();
2581 return true;
2582 }
2583 }
2584
2585 // We did not handle this timeout.
2586 return false;
2587 }
2588
2589 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2590 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2591
2592 // Update the velocity tracker.
2593 {
2594 VelocityTracker::Position positions[MAX_POINTERS];
2595 uint32_t count = 0;
2596 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
2597 uint32_t id = idBits.clearFirstMarkedBit();
2598 const RawPointerData::Pointer& pointer =
2599 mCurrentRawState.rawPointerData.pointerForId(id);
2600 positions[count].x = pointer.x * mPointerXMovementScale;
2601 positions[count].y = pointer.y * mPointerYMovementScale;
2602 }
2603 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2604 positions);
2605 }
2606
2607 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2608 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002609 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2610 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2611 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002612 mPointerGesture.resetTap();
2613 }
2614
2615 // Pick a new active touch id if needed.
2616 // Choose an arbitrary pointer that just went down, if there is one.
2617 // Otherwise choose an arbitrary remaining pointer.
2618 // This guarantees we always have an active touch id when there is at least one pointer.
2619 // We keep the same active touch id for as long as possible.
2620 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2621 int32_t activeTouchId = lastActiveTouchId;
2622 if (activeTouchId < 0) {
2623 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2624 activeTouchId = mPointerGesture.activeTouchId =
2625 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2626 mPointerGesture.firstTouchTime = when;
2627 }
2628 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2629 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2630 activeTouchId = mPointerGesture.activeTouchId =
2631 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2632 } else {
2633 activeTouchId = mPointerGesture.activeTouchId = -1;
2634 }
2635 }
2636
2637 // Determine whether we are in quiet time.
2638 bool isQuietTime = false;
2639 if (activeTouchId < 0) {
2640 mPointerGesture.resetQuietTime();
2641 } else {
2642 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2643 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002644 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2645 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2646 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002647 currentFingerCount < 2) {
2648 // Enter quiet time when exiting swipe or freeform state.
2649 // This is to prevent accidentally entering the hover state and flinging the
2650 // pointer when finishing a swipe and there is still one pointer left onscreen.
2651 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002652 } else if (mPointerGesture.lastGestureMode ==
2653 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002654 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2655 // Enter quiet time when releasing the button and there are still two or more
2656 // fingers down. This may indicate that one finger was used to press the button
2657 // but it has not gone up yet.
2658 isQuietTime = true;
2659 }
2660 if (isQuietTime) {
2661 mPointerGesture.quietTime = when;
2662 }
2663 }
2664 }
2665
2666 // Switch states based on button and pointer state.
2667 if (isQuietTime) {
2668 // Case 1: Quiet time. (QUIET)
2669#if DEBUG_GESTURES
2670 ALOGD("Gestures: QUIET for next %0.3fms",
2671 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2672#endif
Michael Wright227c5542020-07-02 18:30:52 +01002673 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002674 *outFinishPreviousGesture = true;
2675 }
2676
2677 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002678 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002679 mPointerGesture.currentGestureIdBits.clear();
2680
2681 mPointerVelocityControl.reset();
2682 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2683 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2684 // The pointer follows the active touch point.
2685 // Emit DOWN, MOVE, UP events at the pointer location.
2686 //
2687 // Only the active touch matters; other fingers are ignored. This policy helps
2688 // to handle the case where the user places a second finger on the touch pad
2689 // to apply the necessary force to depress an integrated button below the surface.
2690 // We don't want the second finger to be delivered to applications.
2691 //
2692 // For this to work well, we need to make sure to track the pointer that is really
2693 // active. If the user first puts one finger down to click then adds another
2694 // finger to drag then the active pointer should switch to the finger that is
2695 // being dragged.
2696#if DEBUG_GESTURES
2697 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2698 "currentFingerCount=%d",
2699 activeTouchId, currentFingerCount);
2700#endif
2701 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002702 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002703 *outFinishPreviousGesture = true;
2704 mPointerGesture.activeGestureId = 0;
2705 }
2706
2707 // Switch pointers if needed.
2708 // Find the fastest pointer and follow it.
2709 if (activeTouchId >= 0 && currentFingerCount > 1) {
2710 int32_t bestId = -1;
2711 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2712 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2713 uint32_t id = idBits.clearFirstMarkedBit();
2714 float vx, vy;
2715 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2716 float speed = hypotf(vx, vy);
2717 if (speed > bestSpeed) {
2718 bestId = id;
2719 bestSpeed = speed;
2720 }
2721 }
2722 }
2723 if (bestId >= 0 && bestId != activeTouchId) {
2724 mPointerGesture.activeTouchId = activeTouchId = bestId;
2725#if DEBUG_GESTURES
2726 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2727 "bestId=%d, bestSpeed=%0.3f",
2728 bestId, bestSpeed);
2729#endif
2730 }
2731 }
2732
2733 float deltaX = 0, deltaY = 0;
2734 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2735 const RawPointerData::Pointer& currentPointer =
2736 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2737 const RawPointerData::Pointer& lastPointer =
2738 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2739 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2740 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2741
2742 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2743 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2744
2745 // Move the pointer using a relative motion.
2746 // When using spots, the click will occur at the position of the anchor
2747 // spot and all other spots will move there.
2748 mPointerController->move(deltaX, deltaY);
2749 } else {
2750 mPointerVelocityControl.reset();
2751 }
2752
2753 float x, y;
2754 mPointerController->getPosition(&x, &y);
2755
Michael Wright227c5542020-07-02 18:30:52 +01002756 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002757 mPointerGesture.currentGestureIdBits.clear();
2758 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2759 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2760 mPointerGesture.currentGestureProperties[0].clear();
2761 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2762 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2763 mPointerGesture.currentGestureCoords[0].clear();
2764 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2765 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2766 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2767 } else if (currentFingerCount == 0) {
2768 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002769 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002770 *outFinishPreviousGesture = true;
2771 }
2772
2773 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2774 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2775 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002776 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2777 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002778 lastFingerCount == 1) {
2779 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2780 float x, y;
2781 mPointerController->getPosition(&x, &y);
2782 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2783 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2784#if DEBUG_GESTURES
2785 ALOGD("Gestures: TAP");
2786#endif
2787
2788 mPointerGesture.tapUpTime = when;
2789 getContext()->requestTimeoutAtTime(when +
2790 mConfig.pointerGestureTapDragInterval);
2791
2792 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002793 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002794 mPointerGesture.currentGestureIdBits.clear();
2795 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2796 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2797 mPointerGesture.currentGestureProperties[0].clear();
2798 mPointerGesture.currentGestureProperties[0].id =
2799 mPointerGesture.activeGestureId;
2800 mPointerGesture.currentGestureProperties[0].toolType =
2801 AMOTION_EVENT_TOOL_TYPE_FINGER;
2802 mPointerGesture.currentGestureCoords[0].clear();
2803 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2804 mPointerGesture.tapX);
2805 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2806 mPointerGesture.tapY);
2807 mPointerGesture.currentGestureCoords[0]
2808 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2809
2810 tapped = true;
2811 } else {
2812#if DEBUG_GESTURES
2813 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2814 y - mPointerGesture.tapY);
2815#endif
2816 }
2817 } else {
2818#if DEBUG_GESTURES
2819 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2820 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2821 (when - mPointerGesture.tapDownTime) * 0.000001f);
2822 } else {
2823 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2824 }
2825#endif
2826 }
2827 }
2828
2829 mPointerVelocityControl.reset();
2830
2831 if (!tapped) {
2832#if DEBUG_GESTURES
2833 ALOGD("Gestures: NEUTRAL");
2834#endif
2835 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002836 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002837 mPointerGesture.currentGestureIdBits.clear();
2838 }
2839 } else if (currentFingerCount == 1) {
2840 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2841 // The pointer follows the active touch point.
2842 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2843 // When in TAP_DRAG, emit MOVE events at the pointer location.
2844 ALOG_ASSERT(activeTouchId >= 0);
2845
Michael Wright227c5542020-07-02 18:30:52 +01002846 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2847 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002848 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2849 float x, y;
2850 mPointerController->getPosition(&x, &y);
2851 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2852 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002853 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 } else {
2855#if DEBUG_GESTURES
2856 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2857 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2858#endif
2859 }
2860 } else {
2861#if DEBUG_GESTURES
2862 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2863 (when - mPointerGesture.tapUpTime) * 0.000001f);
2864#endif
2865 }
Michael Wright227c5542020-07-02 18:30:52 +01002866 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2867 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002868 }
2869
2870 float deltaX = 0, deltaY = 0;
2871 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2872 const RawPointerData::Pointer& currentPointer =
2873 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2874 const RawPointerData::Pointer& lastPointer =
2875 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2876 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2877 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2878
2879 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2880 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2881
2882 // Move the pointer using a relative motion.
2883 // When using spots, the hover or drag will occur at the position of the anchor spot.
2884 mPointerController->move(deltaX, deltaY);
2885 } else {
2886 mPointerVelocityControl.reset();
2887 }
2888
2889 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002890 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891#if DEBUG_GESTURES
2892 ALOGD("Gestures: TAP_DRAG");
2893#endif
2894 down = true;
2895 } else {
2896#if DEBUG_GESTURES
2897 ALOGD("Gestures: HOVER");
2898#endif
Michael Wright227c5542020-07-02 18:30:52 +01002899 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002900 *outFinishPreviousGesture = true;
2901 }
2902 mPointerGesture.activeGestureId = 0;
2903 down = false;
2904 }
2905
2906 float x, y;
2907 mPointerController->getPosition(&x, &y);
2908
2909 mPointerGesture.currentGestureIdBits.clear();
2910 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2911 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2912 mPointerGesture.currentGestureProperties[0].clear();
2913 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2914 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2915 mPointerGesture.currentGestureCoords[0].clear();
2916 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2917 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2918 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2919 down ? 1.0f : 0.0f);
2920
2921 if (lastFingerCount == 0 && currentFingerCount != 0) {
2922 mPointerGesture.resetTap();
2923 mPointerGesture.tapDownTime = when;
2924 mPointerGesture.tapX = x;
2925 mPointerGesture.tapY = y;
2926 }
2927 } else {
2928 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2929 // We need to provide feedback for each finger that goes down so we cannot wait
2930 // for the fingers to move before deciding what to do.
2931 //
2932 // The ambiguous case is deciding what to do when there are two fingers down but they
2933 // have not moved enough to determine whether they are part of a drag or part of a
2934 // freeform gesture, or just a press or long-press at the pointer location.
2935 //
2936 // When there are two fingers we start with the PRESS hypothesis and we generate a
2937 // down at the pointer location.
2938 //
2939 // When the two fingers move enough or when additional fingers are added, we make
2940 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2941 ALOG_ASSERT(activeTouchId >= 0);
2942
2943 bool settled = when >=
2944 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002945 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2946 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2947 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002948 *outFinishPreviousGesture = true;
2949 } else if (!settled && currentFingerCount > lastFingerCount) {
2950 // Additional pointers have gone down but not yet settled.
2951 // Reset the gesture.
2952#if DEBUG_GESTURES
2953 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2954 "settle time remaining %0.3fms",
2955 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2956 when) * 0.000001f);
2957#endif
2958 *outCancelPreviousGesture = true;
2959 } else {
2960 // Continue previous gesture.
2961 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2962 }
2963
2964 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01002965 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002966 mPointerGesture.activeGestureId = 0;
2967 mPointerGesture.referenceIdBits.clear();
2968 mPointerVelocityControl.reset();
2969
2970 // Use the centroid and pointer location as the reference points for the gesture.
2971#if DEBUG_GESTURES
2972 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
2973 "settle time remaining %0.3fms",
2974 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2975 when) * 0.000001f);
2976#endif
2977 mCurrentRawState.rawPointerData
2978 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
2979 &mPointerGesture.referenceTouchY);
2980 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
2981 &mPointerGesture.referenceGestureY);
2982 }
2983
2984 // Clear the reference deltas for fingers not yet included in the reference calculation.
2985 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
2986 ~mPointerGesture.referenceIdBits.value);
2987 !idBits.isEmpty();) {
2988 uint32_t id = idBits.clearFirstMarkedBit();
2989 mPointerGesture.referenceDeltas[id].dx = 0;
2990 mPointerGesture.referenceDeltas[id].dy = 0;
2991 }
2992 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
2993
2994 // Add delta for all fingers and calculate a common movement delta.
2995 float commonDeltaX = 0, commonDeltaY = 0;
2996 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
2997 mCurrentCookedState.fingerIdBits.value);
2998 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
2999 bool first = (idBits == commonIdBits);
3000 uint32_t id = idBits.clearFirstMarkedBit();
3001 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3002 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3003 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3004 delta.dx += cpd.x - lpd.x;
3005 delta.dy += cpd.y - lpd.y;
3006
3007 if (first) {
3008 commonDeltaX = delta.dx;
3009 commonDeltaY = delta.dy;
3010 } else {
3011 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3012 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3013 }
3014 }
3015
3016 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003017 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003018 float dist[MAX_POINTER_ID + 1];
3019 int32_t distOverThreshold = 0;
3020 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3021 uint32_t id = idBits.clearFirstMarkedBit();
3022 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3023 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3024 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3025 distOverThreshold += 1;
3026 }
3027 }
3028
3029 // Only transition when at least two pointers have moved further than
3030 // the minimum distance threshold.
3031 if (distOverThreshold >= 2) {
3032 if (currentFingerCount > 2) {
3033 // There are more than two pointers, switch to FREEFORM.
3034#if DEBUG_GESTURES
3035 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3036 currentFingerCount);
3037#endif
3038 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003039 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003040 } else {
3041 // There are exactly two pointers.
3042 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3043 uint32_t id1 = idBits.clearFirstMarkedBit();
3044 uint32_t id2 = idBits.firstMarkedBit();
3045 const RawPointerData::Pointer& p1 =
3046 mCurrentRawState.rawPointerData.pointerForId(id1);
3047 const RawPointerData::Pointer& p2 =
3048 mCurrentRawState.rawPointerData.pointerForId(id2);
3049 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3050 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3051 // There are two pointers but they are too far apart for a SWIPE,
3052 // switch to FREEFORM.
3053#if DEBUG_GESTURES
3054 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3055 mutualDistance, mPointerGestureMaxSwipeWidth);
3056#endif
3057 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003058 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003059 } else {
3060 // There are two pointers. Wait for both pointers to start moving
3061 // before deciding whether this is a SWIPE or FREEFORM gesture.
3062 float dist1 = dist[id1];
3063 float dist2 = dist[id2];
3064 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3065 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3066 // Calculate the dot product of the displacement vectors.
3067 // When the vectors are oriented in approximately the same direction,
3068 // the angle betweeen them is near zero and the cosine of the angle
3069 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3070 // mag(v2).
3071 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3072 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3073 float dx1 = delta1.dx * mPointerXZoomScale;
3074 float dy1 = delta1.dy * mPointerYZoomScale;
3075 float dx2 = delta2.dx * mPointerXZoomScale;
3076 float dy2 = delta2.dy * mPointerYZoomScale;
3077 float dot = dx1 * dx2 + dy1 * dy2;
3078 float cosine = dot / (dist1 * dist2); // denominator always > 0
3079 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3080 // Pointers are moving in the same direction. Switch to SWIPE.
3081#if DEBUG_GESTURES
3082 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3083 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3084 "cosine %0.3f >= %0.3f",
3085 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3086 mConfig.pointerGestureMultitouchMinDistance, cosine,
3087 mConfig.pointerGestureSwipeTransitionAngleCosine);
3088#endif
Michael Wright227c5542020-07-02 18:30:52 +01003089 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003090 } else {
3091 // Pointers are moving in different directions. Switch to FREEFORM.
3092#if DEBUG_GESTURES
3093 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3094 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3095 "cosine %0.3f < %0.3f",
3096 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3097 mConfig.pointerGestureMultitouchMinDistance, cosine,
3098 mConfig.pointerGestureSwipeTransitionAngleCosine);
3099#endif
3100 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003101 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003102 }
3103 }
3104 }
3105 }
3106 }
Michael Wright227c5542020-07-02 18:30:52 +01003107 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003108 // Switch from SWIPE to FREEFORM if additional pointers go down.
3109 // Cancel previous gesture.
3110 if (currentFingerCount > 2) {
3111#if DEBUG_GESTURES
3112 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3113 currentFingerCount);
3114#endif
3115 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003116 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003117 }
3118 }
3119
3120 // Move the reference points based on the overall group motion of the fingers
3121 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003122 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003123 (commonDeltaX || commonDeltaY)) {
3124 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3125 uint32_t id = idBits.clearFirstMarkedBit();
3126 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3127 delta.dx = 0;
3128 delta.dy = 0;
3129 }
3130
3131 mPointerGesture.referenceTouchX += commonDeltaX;
3132 mPointerGesture.referenceTouchY += commonDeltaY;
3133
3134 commonDeltaX *= mPointerXMovementScale;
3135 commonDeltaY *= mPointerYMovementScale;
3136
3137 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3138 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3139
3140 mPointerGesture.referenceGestureX += commonDeltaX;
3141 mPointerGesture.referenceGestureY += commonDeltaY;
3142 }
3143
3144 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003145 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3146 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003147 // PRESS or SWIPE mode.
3148#if DEBUG_GESTURES
3149 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3150 "activeGestureId=%d, currentTouchPointerCount=%d",
3151 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3152#endif
3153 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3154
3155 mPointerGesture.currentGestureIdBits.clear();
3156 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3157 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3158 mPointerGesture.currentGestureProperties[0].clear();
3159 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3160 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3161 mPointerGesture.currentGestureCoords[0].clear();
3162 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3163 mPointerGesture.referenceGestureX);
3164 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3165 mPointerGesture.referenceGestureY);
3166 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003167 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003168 // FREEFORM mode.
3169#if DEBUG_GESTURES
3170 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3171 "activeGestureId=%d, currentTouchPointerCount=%d",
3172 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3173#endif
3174 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3175
3176 mPointerGesture.currentGestureIdBits.clear();
3177
3178 BitSet32 mappedTouchIdBits;
3179 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003180 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003181 // Initially, assign the active gesture id to the active touch point
3182 // if there is one. No other touch id bits are mapped yet.
3183 if (!*outCancelPreviousGesture) {
3184 mappedTouchIdBits.markBit(activeTouchId);
3185 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3186 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3187 mPointerGesture.activeGestureId;
3188 } else {
3189 mPointerGesture.activeGestureId = -1;
3190 }
3191 } else {
3192 // Otherwise, assume we mapped all touches from the previous frame.
3193 // Reuse all mappings that are still applicable.
3194 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3195 mCurrentCookedState.fingerIdBits.value;
3196 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3197
3198 // Check whether we need to choose a new active gesture id because the
3199 // current went went up.
3200 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3201 ~mCurrentCookedState.fingerIdBits.value);
3202 !upTouchIdBits.isEmpty();) {
3203 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3204 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3205 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3206 mPointerGesture.activeGestureId = -1;
3207 break;
3208 }
3209 }
3210 }
3211
3212#if DEBUG_GESTURES
3213 ALOGD("Gestures: FREEFORM follow up "
3214 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3215 "activeGestureId=%d",
3216 mappedTouchIdBits.value, usedGestureIdBits.value,
3217 mPointerGesture.activeGestureId);
3218#endif
3219
3220 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3221 for (uint32_t i = 0; i < currentFingerCount; i++) {
3222 uint32_t touchId = idBits.clearFirstMarkedBit();
3223 uint32_t gestureId;
3224 if (!mappedTouchIdBits.hasBit(touchId)) {
3225 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3226 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3227#if DEBUG_GESTURES
3228 ALOGD("Gestures: FREEFORM "
3229 "new mapping for touch id %d -> gesture id %d",
3230 touchId, gestureId);
3231#endif
3232 } else {
3233 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3234#if DEBUG_GESTURES
3235 ALOGD("Gestures: FREEFORM "
3236 "existing mapping for touch id %d -> gesture id %d",
3237 touchId, gestureId);
3238#endif
3239 }
3240 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3241 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3242
3243 const RawPointerData::Pointer& pointer =
3244 mCurrentRawState.rawPointerData.pointerForId(touchId);
3245 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3246 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3247 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3248
3249 mPointerGesture.currentGestureProperties[i].clear();
3250 mPointerGesture.currentGestureProperties[i].id = gestureId;
3251 mPointerGesture.currentGestureProperties[i].toolType =
3252 AMOTION_EVENT_TOOL_TYPE_FINGER;
3253 mPointerGesture.currentGestureCoords[i].clear();
3254 mPointerGesture.currentGestureCoords[i]
3255 .setAxisValue(AMOTION_EVENT_AXIS_X,
3256 mPointerGesture.referenceGestureX + deltaX);
3257 mPointerGesture.currentGestureCoords[i]
3258 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3259 mPointerGesture.referenceGestureY + deltaY);
3260 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3261 1.0f);
3262 }
3263
3264 if (mPointerGesture.activeGestureId < 0) {
3265 mPointerGesture.activeGestureId =
3266 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3267#if DEBUG_GESTURES
3268 ALOGD("Gestures: FREEFORM new "
3269 "activeGestureId=%d",
3270 mPointerGesture.activeGestureId);
3271#endif
3272 }
3273 }
3274 }
3275
3276 mPointerController->setButtonState(mCurrentRawState.buttonState);
3277
3278#if DEBUG_GESTURES
3279 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3280 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3281 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3282 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3283 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3284 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3285 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3286 uint32_t id = idBits.clearFirstMarkedBit();
3287 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3288 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3289 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3290 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3291 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3292 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3293 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3294 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3295 }
3296 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3297 uint32_t id = idBits.clearFirstMarkedBit();
3298 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3299 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3300 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3301 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3302 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3303 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3304 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3305 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3306 }
3307#endif
3308 return true;
3309}
3310
3311void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3312 mPointerSimple.currentCoords.clear();
3313 mPointerSimple.currentProperties.clear();
3314
3315 bool down, hovering;
3316 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3317 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3318 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3319 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3320 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3321 mPointerController->setPosition(x, y);
3322
3323 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3324 down = !hovering;
3325
3326 mPointerController->getPosition(&x, &y);
3327 mPointerSimple.currentCoords.copyFrom(
3328 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3329 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3330 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3331 mPointerSimple.currentProperties.id = 0;
3332 mPointerSimple.currentProperties.toolType =
3333 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3334 } else {
3335 down = false;
3336 hovering = false;
3337 }
3338
3339 dispatchPointerSimple(when, policyFlags, down, hovering);
3340}
3341
3342void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3343 abortPointerSimple(when, policyFlags);
3344}
3345
3346void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3347 mPointerSimple.currentCoords.clear();
3348 mPointerSimple.currentProperties.clear();
3349
3350 bool down, hovering;
3351 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3352 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3353 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3354 float deltaX = 0, deltaY = 0;
3355 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3356 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3357 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3358 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3359 mPointerXMovementScale;
3360 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3361 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3362 mPointerYMovementScale;
3363
3364 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3365 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3366
3367 mPointerController->move(deltaX, deltaY);
3368 } else {
3369 mPointerVelocityControl.reset();
3370 }
3371
3372 down = isPointerDown(mCurrentRawState.buttonState);
3373 hovering = !down;
3374
3375 float x, y;
3376 mPointerController->getPosition(&x, &y);
3377 mPointerSimple.currentCoords.copyFrom(
3378 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3379 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3380 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3381 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3382 hovering ? 0.0f : 1.0f);
3383 mPointerSimple.currentProperties.id = 0;
3384 mPointerSimple.currentProperties.toolType =
3385 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3386 } else {
3387 mPointerVelocityControl.reset();
3388
3389 down = false;
3390 hovering = false;
3391 }
3392
3393 dispatchPointerSimple(when, policyFlags, down, hovering);
3394}
3395
3396void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3397 abortPointerSimple(when, policyFlags);
3398
3399 mPointerVelocityControl.reset();
3400}
3401
3402void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3403 bool hovering) {
3404 int32_t metaState = getContext()->getGlobalMetaState();
3405 int32_t displayId = mViewport.displayId;
3406
3407 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003408 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003409 mPointerController->clearSpots();
3410 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003411 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003412 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003413 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003414 }
3415 displayId = mPointerController->getDisplayId();
3416
3417 float xCursorPosition;
3418 float yCursorPosition;
3419 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3420
3421 if (mPointerSimple.down && !down) {
3422 mPointerSimple.down = false;
3423
3424 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003425 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3426 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003427 mLastRawState.buttonState, MotionClassification::NONE,
3428 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3429 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3430 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3431 /* videoFrames */ {});
3432 getListener()->notifyMotion(&args);
3433 }
3434
3435 if (mPointerSimple.hovering && !hovering) {
3436 mPointerSimple.hovering = false;
3437
3438 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003439 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3440 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3441 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003442 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3443 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3444 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3445 /* videoFrames */ {});
3446 getListener()->notifyMotion(&args);
3447 }
3448
3449 if (down) {
3450 if (!mPointerSimple.down) {
3451 mPointerSimple.down = true;
3452 mPointerSimple.downTime = when;
3453
3454 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003455 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003456 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3457 metaState, mCurrentRawState.buttonState,
3458 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3459 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3460 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3461 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3462 getListener()->notifyMotion(&args);
3463 }
3464
3465 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003466 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3467 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003468 mCurrentRawState.buttonState, MotionClassification::NONE,
3469 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3470 &mPointerSimple.currentCoords, mOrientedXPrecision,
3471 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3472 mPointerSimple.downTime, /* videoFrames */ {});
3473 getListener()->notifyMotion(&args);
3474 }
3475
3476 if (hovering) {
3477 if (!mPointerSimple.hovering) {
3478 mPointerSimple.hovering = true;
3479
3480 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003481 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003482 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3483 metaState, mCurrentRawState.buttonState,
3484 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3485 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3486 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3487 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3488 getListener()->notifyMotion(&args);
3489 }
3490
3491 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003492 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3493 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3494 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003495 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3496 &mPointerSimple.currentCoords, mOrientedXPrecision,
3497 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3498 mPointerSimple.downTime, /* videoFrames */ {});
3499 getListener()->notifyMotion(&args);
3500 }
3501
3502 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3503 float vscroll = mCurrentRawState.rawVScroll;
3504 float hscroll = mCurrentRawState.rawHScroll;
3505 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3506 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3507
3508 // Send scroll.
3509 PointerCoords pointerCoords;
3510 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3511 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3512 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3513
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003514 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3515 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003516 mCurrentRawState.buttonState, MotionClassification::NONE,
3517 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3518 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3519 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3520 /* videoFrames */ {});
3521 getListener()->notifyMotion(&args);
3522 }
3523
3524 // Save state.
3525 if (down || hovering) {
3526 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3527 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3528 } else {
3529 mPointerSimple.reset();
3530 }
3531}
3532
3533void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3534 mPointerSimple.currentCoords.clear();
3535 mPointerSimple.currentProperties.clear();
3536
3537 dispatchPointerSimple(when, policyFlags, false, false);
3538}
3539
3540void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3541 int32_t action, int32_t actionButton, int32_t flags,
3542 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3543 const PointerProperties* properties,
3544 const PointerCoords* coords, const uint32_t* idToIndex,
3545 BitSet32 idBits, int32_t changedId, float xPrecision,
3546 float yPrecision, nsecs_t downTime) {
3547 PointerCoords pointerCoords[MAX_POINTERS];
3548 PointerProperties pointerProperties[MAX_POINTERS];
3549 uint32_t pointerCount = 0;
3550 while (!idBits.isEmpty()) {
3551 uint32_t id = idBits.clearFirstMarkedBit();
3552 uint32_t index = idToIndex[id];
3553 pointerProperties[pointerCount].copyFrom(properties[index]);
3554 pointerCoords[pointerCount].copyFrom(coords[index]);
3555
3556 if (changedId >= 0 && id == uint32_t(changedId)) {
3557 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3558 }
3559
3560 pointerCount += 1;
3561 }
3562
3563 ALOG_ASSERT(pointerCount != 0);
3564
3565 if (changedId >= 0 && pointerCount == 1) {
3566 // Replace initial down and final up action.
3567 // We can compare the action without masking off the changed pointer index
3568 // because we know the index is 0.
3569 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3570 action = AMOTION_EVENT_ACTION_DOWN;
3571 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003572 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3573 action = AMOTION_EVENT_ACTION_CANCEL;
3574 } else {
3575 action = AMOTION_EVENT_ACTION_UP;
3576 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003577 } else {
3578 // Can't happen.
3579 ALOG_ASSERT(false);
3580 }
3581 }
3582 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3583 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003584 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003585 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3586 }
3587 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3588 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003589 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003590 std::for_each(frames.begin(), frames.end(),
3591 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003592 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3593 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003594 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3595 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3596 downTime, std::move(frames));
3597 getListener()->notifyMotion(&args);
3598}
3599
3600bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3601 const PointerCoords* inCoords,
3602 const uint32_t* inIdToIndex,
3603 PointerProperties* outProperties,
3604 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3605 BitSet32 idBits) const {
3606 bool changed = false;
3607 while (!idBits.isEmpty()) {
3608 uint32_t id = idBits.clearFirstMarkedBit();
3609 uint32_t inIndex = inIdToIndex[id];
3610 uint32_t outIndex = outIdToIndex[id];
3611
3612 const PointerProperties& curInProperties = inProperties[inIndex];
3613 const PointerCoords& curInCoords = inCoords[inIndex];
3614 PointerProperties& curOutProperties = outProperties[outIndex];
3615 PointerCoords& curOutCoords = outCoords[outIndex];
3616
3617 if (curInProperties != curOutProperties) {
3618 curOutProperties.copyFrom(curInProperties);
3619 changed = true;
3620 }
3621
3622 if (curInCoords != curOutCoords) {
3623 curOutCoords.copyFrom(curInCoords);
3624 changed = true;
3625 }
3626 }
3627 return changed;
3628}
3629
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003630void TouchInputMapper::cancelTouch(nsecs_t when) {
3631 abortPointerUsage(when, 0 /*policyFlags*/);
3632 abortTouches(when, 0 /* policyFlags*/);
3633}
3634
Arthur Hung4197f6b2020-03-16 15:39:59 +08003635// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003636void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003637 // Scale to surface coordinate.
3638 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3639 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3640
3641 // Rotate to surface coordinate.
3642 // 0 - no swap and reverse.
3643 // 90 - swap x/y and reverse y.
3644 // 180 - reverse x, y.
3645 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003646 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003647 case DISPLAY_ORIENTATION_0:
3648 x = xScaled + mXTranslate;
3649 y = yScaled + mYTranslate;
3650 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003651 case DISPLAY_ORIENTATION_90:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003652 y = mSurfaceRight - xScaled;
3653 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003654 break;
3655 case DISPLAY_ORIENTATION_180:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003656 x = mSurfaceRight - xScaled;
3657 y = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003658 break;
3659 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003660 y = xScaled + mXTranslate;
3661 x = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003662 break;
3663 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003664 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003665 }
3666}
3667
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003668bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003669 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3670 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3671
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003672 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003673 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003674 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003675 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003676}
3677
3678const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3679 for (const VirtualKey& virtualKey : mVirtualKeys) {
3680#if DEBUG_VIRTUAL_KEYS
3681 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3682 "left=%d, top=%d, right=%d, bottom=%d",
3683 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3684 virtualKey.hitRight, virtualKey.hitBottom);
3685#endif
3686
3687 if (virtualKey.isHit(x, y)) {
3688 return &virtualKey;
3689 }
3690 }
3691
3692 return nullptr;
3693}
3694
3695void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3696 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3697 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3698
3699 current->rawPointerData.clearIdBits();
3700
3701 if (currentPointerCount == 0) {
3702 // No pointers to assign.
3703 return;
3704 }
3705
3706 if (lastPointerCount == 0) {
3707 // All pointers are new.
3708 for (uint32_t i = 0; i < currentPointerCount; i++) {
3709 uint32_t id = i;
3710 current->rawPointerData.pointers[i].id = id;
3711 current->rawPointerData.idToIndex[id] = i;
3712 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3713 }
3714 return;
3715 }
3716
3717 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3718 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3719 // Only one pointer and no change in count so it must have the same id as before.
3720 uint32_t id = last->rawPointerData.pointers[0].id;
3721 current->rawPointerData.pointers[0].id = id;
3722 current->rawPointerData.idToIndex[id] = 0;
3723 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3724 return;
3725 }
3726
3727 // General case.
3728 // We build a heap of squared euclidean distances between current and last pointers
3729 // associated with the current and last pointer indices. Then, we find the best
3730 // match (by distance) for each current pointer.
3731 // The pointers must have the same tool type but it is possible for them to
3732 // transition from hovering to touching or vice-versa while retaining the same id.
3733 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3734
3735 uint32_t heapSize = 0;
3736 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3737 currentPointerIndex++) {
3738 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3739 lastPointerIndex++) {
3740 const RawPointerData::Pointer& currentPointer =
3741 current->rawPointerData.pointers[currentPointerIndex];
3742 const RawPointerData::Pointer& lastPointer =
3743 last->rawPointerData.pointers[lastPointerIndex];
3744 if (currentPointer.toolType == lastPointer.toolType) {
3745 int64_t deltaX = currentPointer.x - lastPointer.x;
3746 int64_t deltaY = currentPointer.y - lastPointer.y;
3747
3748 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3749
3750 // Insert new element into the heap (sift up).
3751 heap[heapSize].currentPointerIndex = currentPointerIndex;
3752 heap[heapSize].lastPointerIndex = lastPointerIndex;
3753 heap[heapSize].distance = distance;
3754 heapSize += 1;
3755 }
3756 }
3757 }
3758
3759 // Heapify
3760 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3761 startIndex -= 1;
3762 for (uint32_t parentIndex = startIndex;;) {
3763 uint32_t childIndex = parentIndex * 2 + 1;
3764 if (childIndex >= heapSize) {
3765 break;
3766 }
3767
3768 if (childIndex + 1 < heapSize &&
3769 heap[childIndex + 1].distance < heap[childIndex].distance) {
3770 childIndex += 1;
3771 }
3772
3773 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3774 break;
3775 }
3776
3777 swap(heap[parentIndex], heap[childIndex]);
3778 parentIndex = childIndex;
3779 }
3780 }
3781
3782#if DEBUG_POINTER_ASSIGNMENT
3783 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3784 for (size_t i = 0; i < heapSize; i++) {
3785 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3786 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3787 }
3788#endif
3789
3790 // Pull matches out by increasing order of distance.
3791 // To avoid reassigning pointers that have already been matched, the loop keeps track
3792 // of which last and current pointers have been matched using the matchedXXXBits variables.
3793 // It also tracks the used pointer id bits.
3794 BitSet32 matchedLastBits(0);
3795 BitSet32 matchedCurrentBits(0);
3796 BitSet32 usedIdBits(0);
3797 bool first = true;
3798 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3799 while (heapSize > 0) {
3800 if (first) {
3801 // The first time through the loop, we just consume the root element of
3802 // the heap (the one with smallest distance).
3803 first = false;
3804 } else {
3805 // Previous iterations consumed the root element of the heap.
3806 // Pop root element off of the heap (sift down).
3807 heap[0] = heap[heapSize];
3808 for (uint32_t parentIndex = 0;;) {
3809 uint32_t childIndex = parentIndex * 2 + 1;
3810 if (childIndex >= heapSize) {
3811 break;
3812 }
3813
3814 if (childIndex + 1 < heapSize &&
3815 heap[childIndex + 1].distance < heap[childIndex].distance) {
3816 childIndex += 1;
3817 }
3818
3819 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3820 break;
3821 }
3822
3823 swap(heap[parentIndex], heap[childIndex]);
3824 parentIndex = childIndex;
3825 }
3826
3827#if DEBUG_POINTER_ASSIGNMENT
3828 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3829 for (size_t i = 0; i < heapSize; i++) {
3830 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3831 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3832 }
3833#endif
3834 }
3835
3836 heapSize -= 1;
3837
3838 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3839 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3840
3841 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3842 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3843
3844 matchedCurrentBits.markBit(currentPointerIndex);
3845 matchedLastBits.markBit(lastPointerIndex);
3846
3847 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3848 current->rawPointerData.pointers[currentPointerIndex].id = id;
3849 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3850 current->rawPointerData.markIdBit(id,
3851 current->rawPointerData.isHovering(
3852 currentPointerIndex));
3853 usedIdBits.markBit(id);
3854
3855#if DEBUG_POINTER_ASSIGNMENT
3856 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3857 ", distance=%" PRIu64,
3858 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3859#endif
3860 break;
3861 }
3862 }
3863
3864 // Assign fresh ids to pointers that were not matched in the process.
3865 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3866 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3867 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3868
3869 current->rawPointerData.pointers[currentPointerIndex].id = id;
3870 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3871 current->rawPointerData.markIdBit(id,
3872 current->rawPointerData.isHovering(currentPointerIndex));
3873
3874#if DEBUG_POINTER_ASSIGNMENT
3875 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3876#endif
3877 }
3878}
3879
3880int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3881 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3882 return AKEY_STATE_VIRTUAL;
3883 }
3884
3885 for (const VirtualKey& virtualKey : mVirtualKeys) {
3886 if (virtualKey.keyCode == keyCode) {
3887 return AKEY_STATE_UP;
3888 }
3889 }
3890
3891 return AKEY_STATE_UNKNOWN;
3892}
3893
3894int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3895 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3896 return AKEY_STATE_VIRTUAL;
3897 }
3898
3899 for (const VirtualKey& virtualKey : mVirtualKeys) {
3900 if (virtualKey.scanCode == scanCode) {
3901 return AKEY_STATE_UP;
3902 }
3903 }
3904
3905 return AKEY_STATE_UNKNOWN;
3906}
3907
3908bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3909 const int32_t* keyCodes, uint8_t* outFlags) {
3910 for (const VirtualKey& virtualKey : mVirtualKeys) {
3911 for (size_t i = 0; i < numCodes; i++) {
3912 if (virtualKey.keyCode == keyCodes[i]) {
3913 outFlags[i] = 1;
3914 }
3915 }
3916 }
3917
3918 return true;
3919}
3920
3921std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3922 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003923 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003924 return std::make_optional(mPointerController->getDisplayId());
3925 } else {
3926 return std::make_optional(mViewport.displayId);
3927 }
3928 }
3929 return std::nullopt;
3930}
3931
3932} // namespace android