blob: b00e8704ab6a17c6b59add67dfa317a4a5fc1f4b [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();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000145 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700146}
147
148void CookedPointerData::copyFrom(const CookedPointerData& other) {
149 pointerCount = other.pointerCount;
150 hoveringIdBits = other.hoveringIdBits;
151 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000152 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700153
154 for (uint32_t i = 0; i < pointerCount; i++) {
155 pointerProperties[i].copyFrom(other.pointerProperties[i]);
156 pointerCoords[i].copyFrom(other.pointerCoords[i]);
157
158 int id = pointerProperties[i].id;
159 idToIndex[id] = other.idToIndex[id];
160 }
161}
162
163// --- TouchInputMapper ---
164
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800165TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
166 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700167 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100168 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800169 mRawSurfaceWidth(-1),
170 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700171 mSurfaceLeft(0),
172 mSurfaceTop(0),
Chris Ye42b06822020-08-07 11:39:33 -0700173 mSurfaceRight(0),
174 mSurfaceBottom(0),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700175 mPhysicalWidth(-1),
176 mPhysicalHeight(-1),
177 mPhysicalLeft(0),
178 mPhysicalTop(0),
179 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
180
181TouchInputMapper::~TouchInputMapper() {}
182
183uint32_t TouchInputMapper::getSources() {
184 return mSource;
185}
186
187void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
188 InputMapper::populateDeviceInfo(info);
189
Michael Wright227c5542020-07-02 18:30:52 +0100190 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700191 info->addMotionRange(mOrientedRanges.x);
192 info->addMotionRange(mOrientedRanges.y);
193 info->addMotionRange(mOrientedRanges.pressure);
194
Chris Yef74dc422020-09-02 22:41:50 -0700195 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700196 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
197 //
198 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
199 // motion, i.e. the hardware dimensions, as the finger could move completely across the
200 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700201 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
202 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
203 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
204 x.fuzz, x.resolution);
205 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
206 y.fuzz, y.resolution);
207 }
208
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700209 if (mOrientedRanges.haveSize) {
210 info->addMotionRange(mOrientedRanges.size);
211 }
212
213 if (mOrientedRanges.haveTouchSize) {
214 info->addMotionRange(mOrientedRanges.touchMajor);
215 info->addMotionRange(mOrientedRanges.touchMinor);
216 }
217
218 if (mOrientedRanges.haveToolSize) {
219 info->addMotionRange(mOrientedRanges.toolMajor);
220 info->addMotionRange(mOrientedRanges.toolMinor);
221 }
222
223 if (mOrientedRanges.haveOrientation) {
224 info->addMotionRange(mOrientedRanges.orientation);
225 }
226
227 if (mOrientedRanges.haveDistance) {
228 info->addMotionRange(mOrientedRanges.distance);
229 }
230
231 if (mOrientedRanges.haveTilt) {
232 info->addMotionRange(mOrientedRanges.tilt);
233 }
234
235 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
236 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
237 0.0f);
238 }
239 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
240 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
241 0.0f);
242 }
Michael Wright227c5542020-07-02 18:30:52 +0100243 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700244 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
245 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
246 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
247 x.fuzz, x.resolution);
248 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
249 y.fuzz, y.resolution);
250 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
251 x.fuzz, x.resolution);
252 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
253 y.fuzz, y.resolution);
254 }
255 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
256 }
257}
258
259void TouchInputMapper::dump(std::string& dump) {
260 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
261 dumpParameters(dump);
262 dumpVirtualKeys(dump);
263 dumpRawPointerAxes(dump);
264 dumpCalibration(dump);
265 dumpAffineTransformation(dump);
266 dumpSurface(dump);
267
268 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
269 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
270 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
271 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
272 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
273 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
274 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
275 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
276 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
277 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
278 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
279 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
280 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
281 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
282 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
283 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
284 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
285
286 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
287 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
288 mLastRawState.rawPointerData.pointerCount);
289 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
290 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
291 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
292 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
293 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
294 "toolType=%d, isHovering=%s\n",
295 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
296 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
297 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
298 pointer.distance, pointer.toolType, toString(pointer.isHovering));
299 }
300
301 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
302 mLastCookedState.buttonState);
303 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
304 mLastCookedState.cookedPointerData.pointerCount);
305 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
306 const PointerProperties& pointerProperties =
307 mLastCookedState.cookedPointerData.pointerProperties[i];
308 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000309 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
310 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
311 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700312 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
313 "toolType=%d, isHovering=%s\n",
314 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000315 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
316 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
325 pointerProperties.toolType,
326 toString(mLastCookedState.cookedPointerData.isHovering(i)));
327 }
328
329 dump += INDENT3 "Stylus Fusion:\n";
330 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
331 toString(mExternalStylusConnected));
332 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
333 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
334 mExternalStylusFusionTimeout);
335 dump += INDENT3 "External Stylus State:\n";
336 dumpStylusState(dump, mExternalStylusState);
337
Michael Wright227c5542020-07-02 18:30:52 +0100338 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700339 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
340 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
341 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
342 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
343 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
344 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
345 }
346}
347
348const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
349 switch (deviceMode) {
Michael Wright227c5542020-07-02 18:30:52 +0100350 case DeviceMode::DISABLED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351 return "disabled";
Michael Wright227c5542020-07-02 18:30:52 +0100352 case DeviceMode::DIRECT:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700353 return "direct";
Michael Wright227c5542020-07-02 18:30:52 +0100354 case DeviceMode::UNSCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700355 return "unscaled";
Michael Wright227c5542020-07-02 18:30:52 +0100356 case DeviceMode::NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700357 return "navigation";
Michael Wright227c5542020-07-02 18:30:52 +0100358 case DeviceMode::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700359 return "pointer";
360 }
361 return "unknown";
362}
363
364void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
365 uint32_t changes) {
366 InputMapper::configure(when, config, changes);
367
368 mConfig = *config;
369
370 if (!changes) { // first time only
371 // Configure basic parameters.
372 configureParameters();
373
374 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800375 mCursorScrollAccumulator.configure(getDeviceContext());
376 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700377
378 // Configure absolute axis information.
379 configureRawPointerAxes();
380
381 // Prepare input device calibration.
382 parseCalibration();
383 resolveCalibration();
384 }
385
386 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
387 // Update location calibration to reflect current settings
388 updateAffineTransformation();
389 }
390
391 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
392 // Update pointer speed.
393 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
394 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
395 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
396 }
397
398 bool resetNeeded = false;
399 if (!changes ||
400 (changes &
401 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800402 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700403 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
404 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
405 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
406 // Configure device sources, surface dimensions, orientation and
407 // scaling factors.
408 configureSurface(when, &resetNeeded);
409 }
410
411 if (changes && resetNeeded) {
412 // Send reset, unless this is the first time the device has been configured,
413 // in which case the reader will call reset itself after all mappers are ready.
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800414 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800415 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700416 }
417}
418
419void TouchInputMapper::resolveExternalStylusPresence() {
420 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800421 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700422 mExternalStylusConnected = !devices.empty();
423
424 if (!mExternalStylusConnected) {
425 resetExternalStylus();
426 }
427}
428
429void TouchInputMapper::configureParameters() {
430 // Use the pointer presentation mode for devices that do not support distinct
431 // multitouch. The spot-based presentation relies on being able to accurately
432 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800433 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100434 ? Parameters::GestureMode::SINGLE_TOUCH
435 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700436
437 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800438 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
439 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700440 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100441 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700442 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100443 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700444 } else if (gestureModeString != "default") {
445 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
446 }
447 }
448
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800449 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700450 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100451 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800452 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700453 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100454 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800455 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
456 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457 // The device is a cursor device with a touch pad attached.
458 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100459 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460 } else {
461 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100462 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463 }
464
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800465 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700466
467 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800468 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
469 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700470 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100471 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100473 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700474 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100475 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700476 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100477 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700478 } else if (deviceTypeString != "default") {
479 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
480 }
481 }
482
Michael Wright227c5542020-07-02 18:30:52 +0100483 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800484 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
485 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700486
487 mParameters.hasAssociatedDisplay = false;
488 mParameters.associatedDisplayIsExternal = false;
489 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100490 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
491 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700492 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100493 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700495 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800496 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
497 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700498 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
499 }
500 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800501 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502 mParameters.hasAssociatedDisplay = true;
503 }
504
505 // Initial downs on external touch devices should wake the device.
506 // Normally we don't do this for internal touch screens to prevent them from waking
507 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800508 mParameters.wake = getDeviceContext().isExternal();
509 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700510}
511
512void TouchInputMapper::dumpParameters(std::string& dump) {
513 dump += INDENT3 "Parameters:\n";
514
515 switch (mParameters.gestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +0100516 case Parameters::GestureMode::SINGLE_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700517 dump += INDENT4 "GestureMode: single-touch\n";
518 break;
Michael Wright227c5542020-07-02 18:30:52 +0100519 case Parameters::GestureMode::MULTI_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700520 dump += INDENT4 "GestureMode: multi-touch\n";
521 break;
522 default:
523 assert(false);
524 }
525
526 switch (mParameters.deviceType) {
Michael Wright227c5542020-07-02 18:30:52 +0100527 case Parameters::DeviceType::TOUCH_SCREEN:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700528 dump += INDENT4 "DeviceType: touchScreen\n";
529 break;
Michael Wright227c5542020-07-02 18:30:52 +0100530 case Parameters::DeviceType::TOUCH_PAD:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700531 dump += INDENT4 "DeviceType: touchPad\n";
532 break;
Michael Wright227c5542020-07-02 18:30:52 +0100533 case Parameters::DeviceType::TOUCH_NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700534 dump += INDENT4 "DeviceType: touchNavigation\n";
535 break;
Michael Wright227c5542020-07-02 18:30:52 +0100536 case Parameters::DeviceType::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700537 dump += INDENT4 "DeviceType: pointer\n";
538 break;
539 default:
540 ALOG_ASSERT(false);
541 }
542
543 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
544 "displayId='%s'\n",
545 toString(mParameters.hasAssociatedDisplay),
546 toString(mParameters.associatedDisplayIsExternal),
547 mParameters.uniqueDisplayId.c_str());
548 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
549}
550
551void TouchInputMapper::configureRawPointerAxes() {
552 mRawPointerAxes.clear();
553}
554
555void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
556 dump += INDENT3 "Raw Touch Axes:\n";
557 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
558 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
559 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
560 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
561 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
562 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
563 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
564 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
565 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
566 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
567 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
568 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
569 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
570}
571
572bool TouchInputMapper::hasExternalStylus() const {
573 return mExternalStylusConnected;
574}
575
576/**
577 * Determine which DisplayViewport to use.
578 * 1. If display port is specified, return the matching viewport. If matching viewport not
579 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800580 * 2. Always use the suggested viewport from WindowManagerService for pointers.
581 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700582 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800583 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700584 */
585std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800586 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800587 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700588 if (displayPort) {
589 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800590 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700591 }
592
Michael Wright227c5542020-07-02 18:30:52 +0100593 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800594 std::optional<DisplayViewport> viewport =
595 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
596 if (viewport) {
597 return viewport;
598 } else {
599 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
600 mConfig.defaultPointerDisplayId);
601 }
602 }
603
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700604 // Check if uniqueDisplayId is specified in idc file.
605 if (!mParameters.uniqueDisplayId.empty()) {
606 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
607 }
608
609 ViewportType viewportTypeToUse;
610 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100611 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700612 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100613 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700614 }
615
616 std::optional<DisplayViewport> viewport =
617 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100618 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700619 ALOGW("Input device %s should be associated with external display, "
620 "fallback to internal one for the external viewport is not found.",
621 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100622 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700623 }
624
625 return viewport;
626 }
627
628 // No associated display, return a non-display viewport.
629 DisplayViewport newViewport;
630 // Raw width and height in the natural orientation.
631 int32_t rawWidth = mRawPointerAxes.getRawWidth();
632 int32_t rawHeight = mRawPointerAxes.getRawHeight();
633 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
634 return std::make_optional(newViewport);
635}
636
637void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100638 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700639
640 resolveExternalStylusPresence();
641
642 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100643 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800644 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700645 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100646 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700647 if (hasStylus()) {
648 mSource |= AINPUT_SOURCE_STYLUS;
649 }
Michael Wright227c5542020-07-02 18:30:52 +0100650 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700651 mParameters.hasAssociatedDisplay) {
652 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100653 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700654 if (hasStylus()) {
655 mSource |= AINPUT_SOURCE_STYLUS;
656 }
657 if (hasExternalStylus()) {
658 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
659 }
Michael Wright227c5542020-07-02 18:30:52 +0100660 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700661 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100662 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700663 } else {
664 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100665 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700666 }
667
668 // Ensure we have valid X and Y axes.
669 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
670 ALOGW("Touch device '%s' did not report support for X or Y axis! "
671 "The device will be inoperable.",
672 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100673 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700674 return;
675 }
676
677 // Get associated display dimensions.
678 std::optional<DisplayViewport> newViewport = findViewport();
679 if (!newViewport) {
680 ALOGI("Touch device '%s' could not query the properties of its associated "
681 "display. The device will be inoperable until the display size "
682 "becomes available.",
683 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100684 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700685 return;
686 }
687
688 // Raw width and height in the natural orientation.
689 int32_t rawWidth = mRawPointerAxes.getRawWidth();
690 int32_t rawHeight = mRawPointerAxes.getRawHeight();
691
692 bool viewportChanged = mViewport != *newViewport;
693 if (viewportChanged) {
694 mViewport = *newViewport;
695
Michael Wright227c5542020-07-02 18:30:52 +0100696 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700697 // Convert rotated viewport to natural surface coordinates.
698 int32_t naturalLogicalWidth, naturalLogicalHeight;
699 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
700 int32_t naturalPhysicalLeft, naturalPhysicalTop;
701 int32_t naturalDeviceWidth, naturalDeviceHeight;
702 switch (mViewport.orientation) {
703 case DISPLAY_ORIENTATION_90:
704 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
705 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
706 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
707 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800708 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700709 naturalPhysicalTop = mViewport.physicalLeft;
710 naturalDeviceWidth = mViewport.deviceHeight;
711 naturalDeviceHeight = mViewport.deviceWidth;
712 break;
713 case DISPLAY_ORIENTATION_180:
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.deviceWidth - mViewport.physicalRight;
719 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
720 naturalDeviceWidth = mViewport.deviceWidth;
721 naturalDeviceHeight = mViewport.deviceHeight;
722 break;
723 case DISPLAY_ORIENTATION_270:
724 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
725 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
726 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
727 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
728 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800729 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700730 naturalDeviceWidth = mViewport.deviceHeight;
731 naturalDeviceHeight = mViewport.deviceWidth;
732 break;
733 case DISPLAY_ORIENTATION_0:
734 default:
735 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
736 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
737 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
738 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
739 naturalPhysicalLeft = mViewport.physicalLeft;
740 naturalPhysicalTop = mViewport.physicalTop;
741 naturalDeviceWidth = mViewport.deviceWidth;
742 naturalDeviceHeight = mViewport.deviceHeight;
743 break;
744 }
745
746 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
747 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
748 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
749 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
750 }
751
752 mPhysicalWidth = naturalPhysicalWidth;
753 mPhysicalHeight = naturalPhysicalHeight;
754 mPhysicalLeft = naturalPhysicalLeft;
755 mPhysicalTop = naturalPhysicalTop;
756
Arthur Hung4197f6b2020-03-16 15:39:59 +0800757 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
758 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700759 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
760 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800761 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
762 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700763
764 mSurfaceOrientation =
765 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
766 } else {
767 mPhysicalWidth = rawWidth;
768 mPhysicalHeight = rawHeight;
769 mPhysicalLeft = 0;
770 mPhysicalTop = 0;
771
Arthur Hung4197f6b2020-03-16 15:39:59 +0800772 mRawSurfaceWidth = rawWidth;
773 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700774 mSurfaceLeft = 0;
775 mSurfaceTop = 0;
776 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
777 }
778 }
779
780 // If moving between pointer modes, need to reset some state.
781 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
782 if (deviceModeChanged) {
783 mOrientedRanges.clear();
784 }
785
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800786 // Create pointer controller if needed.
Michael Wright227c5542020-07-02 18:30:52 +0100787 if (mDeviceMode == DeviceMode::POINTER ||
788 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800789 if (mPointerController == nullptr) {
790 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700791 }
792 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100793 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700794 }
795
796 if (viewportChanged || deviceModeChanged) {
797 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
798 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800799 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700800 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
801
802 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800803 mXScale = float(mRawSurfaceWidth) / rawWidth;
804 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700805 mXTranslate = -mSurfaceLeft;
806 mYTranslate = -mSurfaceTop;
807 mXPrecision = 1.0f / mXScale;
808 mYPrecision = 1.0f / mYScale;
809
810 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
811 mOrientedRanges.x.source = mSource;
812 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
813 mOrientedRanges.y.source = mSource;
814
815 configureVirtualKeys();
816
817 // Scale factor for terms that are not oriented in a particular axis.
818 // If the pixels are square then xScale == yScale otherwise we fake it
819 // by choosing an average.
820 mGeometricScale = avg(mXScale, mYScale);
821
822 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800823 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700824
825 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100826 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700827 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
828 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
829 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
830 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
831 } else {
832 mSizeScale = 0.0f;
833 }
834
835 mOrientedRanges.haveTouchSize = true;
836 mOrientedRanges.haveToolSize = true;
837 mOrientedRanges.haveSize = true;
838
839 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
840 mOrientedRanges.touchMajor.source = mSource;
841 mOrientedRanges.touchMajor.min = 0;
842 mOrientedRanges.touchMajor.max = diagonalSize;
843 mOrientedRanges.touchMajor.flat = 0;
844 mOrientedRanges.touchMajor.fuzz = 0;
845 mOrientedRanges.touchMajor.resolution = 0;
846
847 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
848 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
849
850 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
851 mOrientedRanges.toolMajor.source = mSource;
852 mOrientedRanges.toolMajor.min = 0;
853 mOrientedRanges.toolMajor.max = diagonalSize;
854 mOrientedRanges.toolMajor.flat = 0;
855 mOrientedRanges.toolMajor.fuzz = 0;
856 mOrientedRanges.toolMajor.resolution = 0;
857
858 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
859 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
860
861 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
862 mOrientedRanges.size.source = mSource;
863 mOrientedRanges.size.min = 0;
864 mOrientedRanges.size.max = 1.0;
865 mOrientedRanges.size.flat = 0;
866 mOrientedRanges.size.fuzz = 0;
867 mOrientedRanges.size.resolution = 0;
868 } else {
869 mSizeScale = 0.0f;
870 }
871
872 // Pressure factors.
873 mPressureScale = 0;
874 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100875 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
876 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700877 if (mCalibration.havePressureScale) {
878 mPressureScale = mCalibration.pressureScale;
879 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
880 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
881 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
882 }
883 }
884
885 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
886 mOrientedRanges.pressure.source = mSource;
887 mOrientedRanges.pressure.min = 0;
888 mOrientedRanges.pressure.max = pressureMax;
889 mOrientedRanges.pressure.flat = 0;
890 mOrientedRanges.pressure.fuzz = 0;
891 mOrientedRanges.pressure.resolution = 0;
892
893 // Tilt
894 mTiltXCenter = 0;
895 mTiltXScale = 0;
896 mTiltYCenter = 0;
897 mTiltYScale = 0;
898 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
899 if (mHaveTilt) {
900 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
901 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
902 mTiltXScale = M_PI / 180;
903 mTiltYScale = M_PI / 180;
904
905 mOrientedRanges.haveTilt = true;
906
907 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
908 mOrientedRanges.tilt.source = mSource;
909 mOrientedRanges.tilt.min = 0;
910 mOrientedRanges.tilt.max = M_PI_2;
911 mOrientedRanges.tilt.flat = 0;
912 mOrientedRanges.tilt.fuzz = 0;
913 mOrientedRanges.tilt.resolution = 0;
914 }
915
916 // Orientation
917 mOrientationScale = 0;
918 if (mHaveTilt) {
919 mOrientedRanges.haveOrientation = true;
920
921 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
922 mOrientedRanges.orientation.source = mSource;
923 mOrientedRanges.orientation.min = -M_PI;
924 mOrientedRanges.orientation.max = M_PI;
925 mOrientedRanges.orientation.flat = 0;
926 mOrientedRanges.orientation.fuzz = 0;
927 mOrientedRanges.orientation.resolution = 0;
928 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100929 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700930 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100931 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700932 if (mRawPointerAxes.orientation.valid) {
933 if (mRawPointerAxes.orientation.maxValue > 0) {
934 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
935 } else if (mRawPointerAxes.orientation.minValue < 0) {
936 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
937 } else {
938 mOrientationScale = 0;
939 }
940 }
941 }
942
943 mOrientedRanges.haveOrientation = true;
944
945 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
946 mOrientedRanges.orientation.source = mSource;
947 mOrientedRanges.orientation.min = -M_PI_2;
948 mOrientedRanges.orientation.max = M_PI_2;
949 mOrientedRanges.orientation.flat = 0;
950 mOrientedRanges.orientation.fuzz = 0;
951 mOrientedRanges.orientation.resolution = 0;
952 }
953
954 // Distance
955 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100956 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
957 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700958 if (mCalibration.haveDistanceScale) {
959 mDistanceScale = mCalibration.distanceScale;
960 } else {
961 mDistanceScale = 1.0f;
962 }
963 }
964
965 mOrientedRanges.haveDistance = true;
966
967 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
968 mOrientedRanges.distance.source = mSource;
969 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
970 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
971 mOrientedRanges.distance.flat = 0;
972 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
973 mOrientedRanges.distance.resolution = 0;
974 }
975
976 // Compute oriented precision, scales and ranges.
977 // Note that the maximum value reported is an inclusive maximum value so it is one
978 // unit less than the total width or height of surface.
979 switch (mSurfaceOrientation) {
980 case DISPLAY_ORIENTATION_90:
981 case DISPLAY_ORIENTATION_270:
982 mOrientedXPrecision = mYPrecision;
983 mOrientedYPrecision = mXPrecision;
984
985 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800986 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700987 mOrientedRanges.x.flat = 0;
988 mOrientedRanges.x.fuzz = 0;
989 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
990
991 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800992 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700993 mOrientedRanges.y.flat = 0;
994 mOrientedRanges.y.fuzz = 0;
995 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
996 break;
997
998 default:
999 mOrientedXPrecision = mXPrecision;
1000 mOrientedYPrecision = mYPrecision;
1001
1002 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001003 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001004 mOrientedRanges.x.flat = 0;
1005 mOrientedRanges.x.fuzz = 0;
1006 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1007
1008 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001009 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001010 mOrientedRanges.y.flat = 0;
1011 mOrientedRanges.y.fuzz = 0;
1012 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1013 break;
1014 }
1015
1016 // Location
1017 updateAffineTransformation();
1018
Michael Wright227c5542020-07-02 18:30:52 +01001019 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001020 // Compute pointer gesture detection parameters.
1021 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001022 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001023
1024 // Scale movements such that one whole swipe of the touch pad covers a
1025 // given area relative to the diagonal size of the display when no acceleration
1026 // is applied.
1027 // Assume that the touch pad has a square aspect ratio such that movements in
1028 // X and Y of the same number of raw units cover the same physical distance.
1029 mPointerXMovementScale =
1030 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1031 mPointerYMovementScale = mPointerXMovementScale;
1032
1033 // Scale zooms to cover a smaller range of the display than movements do.
1034 // This value determines the area around the pointer that is affected by freeform
1035 // pointer gestures.
1036 mPointerXZoomScale =
1037 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1038 mPointerYZoomScale = mPointerXZoomScale;
1039
1040 // Max width between pointers to detect a swipe gesture is more than some fraction
1041 // of the diagonal axis of the touch pad. Touches that are wider than this are
1042 // translated into freeform gestures.
1043 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1044
1045 // Abort current pointer usages because the state has changed.
1046 abortPointerUsage(when, 0 /*policyFlags*/);
1047 }
1048
1049 // Inform the dispatcher about the changes.
1050 *outResetNeeded = true;
1051 bumpGeneration();
1052 }
1053}
1054
1055void TouchInputMapper::dumpSurface(std::string& dump) {
1056 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001057 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1058 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001059 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1060 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001061 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1062 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001063 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1064 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1065 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1066 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1067 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1068}
1069
1070void TouchInputMapper::configureVirtualKeys() {
1071 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001072 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001073
1074 mVirtualKeys.clear();
1075
1076 if (virtualKeyDefinitions.size() == 0) {
1077 return;
1078 }
1079
1080 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1081 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1082 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1083 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1084
1085 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1086 VirtualKey virtualKey;
1087
1088 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1089 int32_t keyCode;
1090 int32_t dummyKeyMetaState;
1091 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001092 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1093 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001094 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1095 continue; // drop the key
1096 }
1097
1098 virtualKey.keyCode = keyCode;
1099 virtualKey.flags = flags;
1100
1101 // convert the key definition's display coordinates into touch coordinates for a hit box
1102 int32_t halfWidth = virtualKeyDefinition.width / 2;
1103 int32_t halfHeight = virtualKeyDefinition.height / 2;
1104
1105 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001106 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001107 touchScreenLeft;
1108 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001109 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001110 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001111 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1112 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001114 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1115 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001116 touchScreenTop;
1117 mVirtualKeys.push_back(virtualKey);
1118 }
1119}
1120
1121void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1122 if (!mVirtualKeys.empty()) {
1123 dump += INDENT3 "Virtual Keys:\n";
1124
1125 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1126 const VirtualKey& virtualKey = mVirtualKeys[i];
1127 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1128 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1129 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1130 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1131 }
1132 }
1133}
1134
1135void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001136 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 Calibration& out = mCalibration;
1138
1139 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001140 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 String8 sizeCalibrationString;
1142 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1143 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001144 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001146 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001148 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001150 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001152 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001153 } else if (sizeCalibrationString != "default") {
1154 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1155 }
1156 }
1157
1158 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1159 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1160 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1161
1162 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001163 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001164 String8 pressureCalibrationString;
1165 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1166 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (pressureCalibrationString != "default") {
1173 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1174 pressureCalibrationString.string());
1175 }
1176 }
1177
1178 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1179
1180 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 String8 orientationCalibrationString;
1183 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1184 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190 } else if (orientationCalibrationString != "default") {
1191 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1192 orientationCalibrationString.string());
1193 }
1194 }
1195
1196 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001197 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 String8 distanceCalibrationString;
1199 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1200 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001203 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 } else if (distanceCalibrationString != "default") {
1205 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1206 distanceCalibrationString.string());
1207 }
1208 }
1209
1210 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1211
Michael Wright227c5542020-07-02 18:30:52 +01001212 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 String8 coverageCalibrationString;
1214 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1215 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001216 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001218 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 } else if (coverageCalibrationString != "default") {
1220 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1221 coverageCalibrationString.string());
1222 }
1223 }
1224}
1225
1226void TouchInputMapper::resolveCalibration() {
1227 // Size
1228 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001229 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1230 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 }
1232 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001233 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001234 }
1235
1236 // Pressure
1237 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001238 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1239 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 }
1241 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001242 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243 }
1244
1245 // Orientation
1246 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001247 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1248 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 }
1250 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001251 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252 }
1253
1254 // Distance
1255 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001256 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1257 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 }
1259 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001260 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 }
1262
1263 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001264 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1265 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 }
1267}
1268
1269void TouchInputMapper::dumpCalibration(std::string& dump) {
1270 dump += INDENT3 "Calibration:\n";
1271
1272 // Size
1273 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001274 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275 dump += INDENT4 "touch.size.calibration: none\n";
1276 break;
Michael Wright227c5542020-07-02 18:30:52 +01001277 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 dump += INDENT4 "touch.size.calibration: geometric\n";
1279 break;
Michael Wright227c5542020-07-02 18:30:52 +01001280 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 dump += INDENT4 "touch.size.calibration: diameter\n";
1282 break;
Michael Wright227c5542020-07-02 18:30:52 +01001283 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 dump += INDENT4 "touch.size.calibration: box\n";
1285 break;
Michael Wright227c5542020-07-02 18:30:52 +01001286 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 dump += INDENT4 "touch.size.calibration: area\n";
1288 break;
1289 default:
1290 ALOG_ASSERT(false);
1291 }
1292
1293 if (mCalibration.haveSizeScale) {
1294 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1295 }
1296
1297 if (mCalibration.haveSizeBias) {
1298 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1299 }
1300
1301 if (mCalibration.haveSizeIsSummed) {
1302 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1303 toString(mCalibration.sizeIsSummed));
1304 }
1305
1306 // Pressure
1307 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001308 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001309 dump += INDENT4 "touch.pressure.calibration: none\n";
1310 break;
Michael Wright227c5542020-07-02 18:30:52 +01001311 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 dump += INDENT4 "touch.pressure.calibration: physical\n";
1313 break;
Michael Wright227c5542020-07-02 18:30:52 +01001314 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1316 break;
1317 default:
1318 ALOG_ASSERT(false);
1319 }
1320
1321 if (mCalibration.havePressureScale) {
1322 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1323 }
1324
1325 // Orientation
1326 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001327 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 dump += INDENT4 "touch.orientation.calibration: none\n";
1329 break;
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1332 break;
Michael Wright227c5542020-07-02 18:30:52 +01001333 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.orientation.calibration: vector\n";
1335 break;
1336 default:
1337 ALOG_ASSERT(false);
1338 }
1339
1340 // Distance
1341 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001342 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001343 dump += INDENT4 "touch.distance.calibration: none\n";
1344 break;
Michael Wright227c5542020-07-02 18:30:52 +01001345 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001346 dump += INDENT4 "touch.distance.calibration: scaled\n";
1347 break;
1348 default:
1349 ALOG_ASSERT(false);
1350 }
1351
1352 if (mCalibration.haveDistanceScale) {
1353 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1354 }
1355
1356 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001357 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001358 dump += INDENT4 "touch.coverage.calibration: none\n";
1359 break;
Michael Wright227c5542020-07-02 18:30:52 +01001360 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001361 dump += INDENT4 "touch.coverage.calibration: box\n";
1362 break;
1363 default:
1364 ALOG_ASSERT(false);
1365 }
1366}
1367
1368void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1369 dump += INDENT3 "Affine Transformation:\n";
1370
1371 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1372 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1373 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1374 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1375 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1376 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1377}
1378
1379void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001380 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001381 mSurfaceOrientation);
1382}
1383
1384void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001385 mCursorButtonAccumulator.reset(getDeviceContext());
1386 mCursorScrollAccumulator.reset(getDeviceContext());
1387 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001388
1389 mPointerVelocityControl.reset();
1390 mWheelXVelocityControl.reset();
1391 mWheelYVelocityControl.reset();
1392
1393 mRawStatesPending.clear();
1394 mCurrentRawState.clear();
1395 mCurrentCookedState.clear();
1396 mLastRawState.clear();
1397 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001398 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001399 mSentHoverEnter = false;
1400 mHavePointerIds = false;
1401 mCurrentMotionAborted = false;
1402 mDownTime = 0;
1403
1404 mCurrentVirtualKey.down = false;
1405
1406 mPointerGesture.reset();
1407 mPointerSimple.reset();
1408 resetExternalStylus();
1409
1410 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001411 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001412 mPointerController->clearSpots();
1413 }
1414
1415 InputMapper::reset(when);
1416}
1417
1418void TouchInputMapper::resetExternalStylus() {
1419 mExternalStylusState.clear();
1420 mExternalStylusId = -1;
1421 mExternalStylusFusionTimeout = LLONG_MAX;
1422 mExternalStylusDataPending = false;
1423}
1424
1425void TouchInputMapper::clearStylusDataPendingFlags() {
1426 mExternalStylusDataPending = false;
1427 mExternalStylusFusionTimeout = LLONG_MAX;
1428}
1429
1430void TouchInputMapper::process(const RawEvent* rawEvent) {
1431 mCursorButtonAccumulator.process(rawEvent);
1432 mCursorScrollAccumulator.process(rawEvent);
1433 mTouchButtonAccumulator.process(rawEvent);
1434
1435 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1436 sync(rawEvent->when);
1437 }
1438}
1439
1440void TouchInputMapper::sync(nsecs_t when) {
1441 const RawState* last =
1442 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1443
1444 // Push a new state.
1445 mRawStatesPending.emplace_back();
1446
1447 RawState* next = &mRawStatesPending.back();
1448 next->clear();
1449 next->when = when;
1450
1451 // Sync button state.
1452 next->buttonState =
1453 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1454
1455 // Sync scroll
1456 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1457 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1458 mCursorScrollAccumulator.finishSync();
1459
1460 // Sync touch
1461 syncTouch(when, next);
1462
1463 // Assign pointer ids.
1464 if (!mHavePointerIds) {
1465 assignPointerIds(last, next);
1466 }
1467
1468#if DEBUG_RAW_EVENTS
1469 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001470 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001471 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1472 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhungcc7f9802020-04-30 17:55:40 +08001473 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1474 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001475#endif
1476
1477 processRawTouches(false /*timeout*/);
1478}
1479
1480void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001481 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001482 // Drop all input if the device is disabled.
1483 mCurrentRawState.clear();
1484 mRawStatesPending.clear();
1485 return;
1486 }
1487
1488 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1489 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1490 // touching the current state will only observe the events that have been dispatched to the
1491 // rest of the pipeline.
1492 const size_t N = mRawStatesPending.size();
1493 size_t count;
1494 for (count = 0; count < N; count++) {
1495 const RawState& next = mRawStatesPending[count];
1496
1497 // A failure to assign the stylus id means that we're waiting on stylus data
1498 // and so should defer the rest of the pipeline.
1499 if (assignExternalStylusId(next, timeout)) {
1500 break;
1501 }
1502
1503 // All ready to go.
1504 clearStylusDataPendingFlags();
1505 mCurrentRawState.copyFrom(next);
1506 if (mCurrentRawState.when < mLastRawState.when) {
1507 mCurrentRawState.when = mLastRawState.when;
1508 }
1509 cookAndDispatch(mCurrentRawState.when);
1510 }
1511 if (count != 0) {
1512 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1513 }
1514
1515 if (mExternalStylusDataPending) {
1516 if (timeout) {
1517 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1518 clearStylusDataPendingFlags();
1519 mCurrentRawState.copyFrom(mLastRawState);
1520#if DEBUG_STYLUS_FUSION
1521 ALOGD("Timeout expired, synthesizing event with new stylus data");
1522#endif
1523 cookAndDispatch(when);
1524 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1525 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1526 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1527 }
1528 }
1529}
1530
1531void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1532 // Always start with a clean state.
1533 mCurrentCookedState.clear();
1534
1535 // Apply stylus buttons to current raw state.
1536 applyExternalStylusButtonState(when);
1537
1538 // Handle policy on initial down or hover events.
1539 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1540 mCurrentRawState.rawPointerData.pointerCount != 0;
1541
1542 uint32_t policyFlags = 0;
1543 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1544 if (initialDown || buttonsPressed) {
1545 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001546 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001547 getContext()->fadePointer();
1548 }
1549
1550 if (mParameters.wake) {
1551 policyFlags |= POLICY_FLAG_WAKE;
1552 }
1553 }
1554
1555 // Consume raw off-screen touches before cooking pointer data.
1556 // If touches are consumed, subsequent code will not receive any pointer data.
1557 if (consumeRawTouches(when, policyFlags)) {
1558 mCurrentRawState.rawPointerData.clear();
1559 }
1560
1561 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1562 // with cooked pointer data that has the same ids and indices as the raw data.
1563 // The following code can use either the raw or cooked data, as needed.
1564 cookPointerData();
1565
1566 // Apply stylus pressure to current cooked state.
1567 applyExternalStylusTouchState(when);
1568
1569 // Synthesize key down from raw buttons if needed.
1570 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1571 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1572 mCurrentCookedState.buttonState);
1573
1574 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001575 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001576 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1577 uint32_t id = idBits.clearFirstMarkedBit();
1578 const RawPointerData::Pointer& pointer =
1579 mCurrentRawState.rawPointerData.pointerForId(id);
1580 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1581 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1582 mCurrentCookedState.stylusIdBits.markBit(id);
1583 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1584 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1585 mCurrentCookedState.fingerIdBits.markBit(id);
1586 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1587 mCurrentCookedState.mouseIdBits.markBit(id);
1588 }
1589 }
1590 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1591 uint32_t id = idBits.clearFirstMarkedBit();
1592 const RawPointerData::Pointer& pointer =
1593 mCurrentRawState.rawPointerData.pointerForId(id);
1594 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1595 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1596 mCurrentCookedState.stylusIdBits.markBit(id);
1597 }
1598 }
1599
1600 // Stylus takes precedence over all tools, then mouse, then finger.
1601 PointerUsage pointerUsage = mPointerUsage;
1602 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1603 mCurrentCookedState.mouseIdBits.clear();
1604 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001605 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001606 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1607 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001608 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001609 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1610 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001611 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001612 }
1613
1614 dispatchPointerUsage(when, policyFlags, pointerUsage);
1615 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001616 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617 mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001618 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1619 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001620
1621 mPointerController->setButtonState(mCurrentRawState.buttonState);
1622 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1623 mCurrentCookedState.cookedPointerData.idToIndex,
1624 mCurrentCookedState.cookedPointerData.touchingIdBits,
1625 mViewport.displayId);
1626 }
1627
1628 if (!mCurrentMotionAborted) {
1629 dispatchButtonRelease(when, policyFlags);
1630 dispatchHoverExit(when, policyFlags);
1631 dispatchTouches(when, policyFlags);
1632 dispatchHoverEnterAndMove(when, policyFlags);
1633 dispatchButtonPress(when, policyFlags);
1634 }
1635
1636 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1637 mCurrentMotionAborted = false;
1638 }
1639 }
1640
1641 // Synthesize key up from raw buttons if needed.
1642 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1643 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1644 mCurrentCookedState.buttonState);
1645
1646 // Clear some transient state.
1647 mCurrentRawState.rawVScroll = 0;
1648 mCurrentRawState.rawHScroll = 0;
1649
1650 // Copy current touch to last touch in preparation for the next cycle.
1651 mLastRawState.copyFrom(mCurrentRawState);
1652 mLastCookedState.copyFrom(mCurrentCookedState);
1653}
1654
1655void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001656 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001657 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1658 }
1659}
1660
1661void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1662 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1663 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1664
1665 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1666 float pressure = mExternalStylusState.pressure;
1667 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1668 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1669 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1670 }
1671 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1672 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1673
1674 PointerProperties& properties =
1675 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1676 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1677 properties.toolType = mExternalStylusState.toolType;
1678 }
1679 }
1680}
1681
1682bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001683 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001684 return false;
1685 }
1686
1687 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1688 state.rawPointerData.pointerCount != 0;
1689 if (initialDown) {
1690 if (mExternalStylusState.pressure != 0.0f) {
1691#if DEBUG_STYLUS_FUSION
1692 ALOGD("Have both stylus and touch data, beginning fusion");
1693#endif
1694 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1695 } else if (timeout) {
1696#if DEBUG_STYLUS_FUSION
1697 ALOGD("Timeout expired, assuming touch is not a stylus.");
1698#endif
1699 resetExternalStylus();
1700 } else {
1701 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1702 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1703 }
1704#if DEBUG_STYLUS_FUSION
1705 ALOGD("No stylus data but stylus is connected, requesting timeout "
1706 "(%" PRId64 "ms)",
1707 mExternalStylusFusionTimeout);
1708#endif
1709 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1710 return true;
1711 }
1712 }
1713
1714 // Check if the stylus pointer has gone up.
1715 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1716#if DEBUG_STYLUS_FUSION
1717 ALOGD("Stylus pointer is going up");
1718#endif
1719 mExternalStylusId = -1;
1720 }
1721
1722 return false;
1723}
1724
1725void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001726 if (mDeviceMode == DeviceMode::POINTER) {
1727 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001728 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1729 }
Michael Wright227c5542020-07-02 18:30:52 +01001730 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001731 if (mExternalStylusFusionTimeout < when) {
1732 processRawTouches(true /*timeout*/);
1733 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1734 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1735 }
1736 }
1737}
1738
1739void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1740 mExternalStylusState.copyFrom(state);
1741 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1742 // We're either in the middle of a fused stream of data or we're waiting on data before
1743 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1744 // data.
1745 mExternalStylusDataPending = true;
1746 processRawTouches(false /*timeout*/);
1747 }
1748}
1749
1750bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1751 // Check for release of a virtual key.
1752 if (mCurrentVirtualKey.down) {
1753 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1754 // Pointer went up while virtual key was down.
1755 mCurrentVirtualKey.down = false;
1756 if (!mCurrentVirtualKey.ignored) {
1757#if DEBUG_VIRTUAL_KEYS
1758 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1759 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1760#endif
1761 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1762 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1763 }
1764 return true;
1765 }
1766
1767 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1768 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1769 const RawPointerData::Pointer& pointer =
1770 mCurrentRawState.rawPointerData.pointerForId(id);
1771 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1772 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1773 // Pointer is still within the space of the virtual key.
1774 return true;
1775 }
1776 }
1777
1778 // Pointer left virtual key area or another pointer also went down.
1779 // Send key cancellation but do not consume the touch yet.
1780 // This is useful when the user swipes through from the virtual key area
1781 // into the main display surface.
1782 mCurrentVirtualKey.down = false;
1783 if (!mCurrentVirtualKey.ignored) {
1784#if DEBUG_VIRTUAL_KEYS
1785 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1786 mCurrentVirtualKey.scanCode);
1787#endif
1788 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1789 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1790 AKEY_EVENT_FLAG_CANCELED);
1791 }
1792 }
1793
1794 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1795 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1796 // Pointer just went down. Check for virtual key press or off-screen touches.
1797 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1798 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001799 // Exclude unscaled device for inside surface checking.
1800 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001801 // If exactly one pointer went down, check for virtual key hit.
1802 // Otherwise we will drop the entire stroke.
1803 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1804 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1805 if (virtualKey) {
1806 mCurrentVirtualKey.down = true;
1807 mCurrentVirtualKey.downTime = when;
1808 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1809 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1810 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001811 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1812 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001813
1814 if (!mCurrentVirtualKey.ignored) {
1815#if DEBUG_VIRTUAL_KEYS
1816 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1817 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1818#endif
1819 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1820 AKEY_EVENT_FLAG_FROM_SYSTEM |
1821 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1822 }
1823 }
1824 }
1825 return true;
1826 }
1827 }
1828
1829 // Disable all virtual key touches that happen within a short time interval of the
1830 // most recent touch within the screen area. The idea is to filter out stray
1831 // virtual key presses when interacting with the touch screen.
1832 //
1833 // Problems we're trying to solve:
1834 //
1835 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1836 // virtual key area that is implemented by a separate touch panel and accidentally
1837 // triggers a virtual key.
1838 //
1839 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1840 // area and accidentally triggers a virtual key. This often happens when virtual keys
1841 // are layed out below the screen near to where the on screen keyboard's space bar
1842 // is displayed.
1843 if (mConfig.virtualKeyQuietTime > 0 &&
1844 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001845 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001846 }
1847 return false;
1848}
1849
1850void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1851 int32_t keyEventAction, int32_t keyEventFlags) {
1852 int32_t keyCode = mCurrentVirtualKey.keyCode;
1853 int32_t scanCode = mCurrentVirtualKey.scanCode;
1854 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001855 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001856 policyFlags |= POLICY_FLAG_VIRTUAL;
1857
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001858 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1859 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1860 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001861 getListener()->notifyKey(&args);
1862}
1863
1864void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1865 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1866 if (!currentIdBits.isEmpty()) {
1867 int32_t metaState = getContext()->getGlobalMetaState();
1868 int32_t buttonState = mCurrentCookedState.buttonState;
1869 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1870 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1871 mCurrentCookedState.cookedPointerData.pointerProperties,
1872 mCurrentCookedState.cookedPointerData.pointerCoords,
1873 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1874 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1875 mCurrentMotionAborted = true;
1876 }
1877}
1878
1879void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1880 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1881 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1882 int32_t metaState = getContext()->getGlobalMetaState();
1883 int32_t buttonState = mCurrentCookedState.buttonState;
1884
1885 if (currentIdBits == lastIdBits) {
1886 if (!currentIdBits.isEmpty()) {
1887 // No pointer id changes so this is a move event.
1888 // The listener takes care of batching moves so we don't have to deal with that here.
1889 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1890 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1891 mCurrentCookedState.cookedPointerData.pointerProperties,
1892 mCurrentCookedState.cookedPointerData.pointerCoords,
1893 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1894 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1895 }
1896 } else {
1897 // There may be pointers going up and pointers going down and pointers moving
1898 // all at the same time.
1899 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1900 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1901 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1902 BitSet32 dispatchedIdBits(lastIdBits.value);
1903
1904 // Update last coordinates of pointers that have moved so that we observe the new
1905 // pointer positions at the same time as other pointers that have just gone up.
1906 bool moveNeeded =
1907 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1908 mCurrentCookedState.cookedPointerData.pointerCoords,
1909 mCurrentCookedState.cookedPointerData.idToIndex,
1910 mLastCookedState.cookedPointerData.pointerProperties,
1911 mLastCookedState.cookedPointerData.pointerCoords,
1912 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1913 if (buttonState != mLastCookedState.buttonState) {
1914 moveNeeded = true;
1915 }
1916
1917 // Dispatch pointer up events.
1918 while (!upIdBits.isEmpty()) {
1919 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001920 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1921 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1922 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001923 mLastCookedState.cookedPointerData.pointerProperties,
1924 mLastCookedState.cookedPointerData.pointerCoords,
1925 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1926 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1927 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001928 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001929 }
1930
1931 // Dispatch move events if any of the remaining pointers moved from their old locations.
1932 // Although applications receive new locations as part of individual pointer up
1933 // events, they do not generally handle them except when presented in a move event.
1934 if (moveNeeded && !moveIdBits.isEmpty()) {
1935 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1936 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1937 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1938 mCurrentCookedState.cookedPointerData.pointerCoords,
1939 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1940 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1941 }
1942
1943 // Dispatch pointer down events using the new pointer locations.
1944 while (!downIdBits.isEmpty()) {
1945 uint32_t downId = downIdBits.clearFirstMarkedBit();
1946 dispatchedIdBits.markBit(downId);
1947
1948 if (dispatchedIdBits.count() == 1) {
1949 // First pointer is going down. Set down time.
1950 mDownTime = when;
1951 }
1952
1953 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1954 metaState, buttonState, 0,
1955 mCurrentCookedState.cookedPointerData.pointerProperties,
1956 mCurrentCookedState.cookedPointerData.pointerCoords,
1957 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1958 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1959 }
1960 }
1961}
1962
1963void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1964 if (mSentHoverEnter &&
1965 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1966 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1967 int32_t metaState = getContext()->getGlobalMetaState();
1968 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1969 mLastCookedState.buttonState, 0,
1970 mLastCookedState.cookedPointerData.pointerProperties,
1971 mLastCookedState.cookedPointerData.pointerCoords,
1972 mLastCookedState.cookedPointerData.idToIndex,
1973 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1974 mOrientedYPrecision, mDownTime);
1975 mSentHoverEnter = false;
1976 }
1977}
1978
1979void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1980 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1981 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1982 int32_t metaState = getContext()->getGlobalMetaState();
1983 if (!mSentHoverEnter) {
1984 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1985 metaState, mCurrentRawState.buttonState, 0,
1986 mCurrentCookedState.cookedPointerData.pointerProperties,
1987 mCurrentCookedState.cookedPointerData.pointerCoords,
1988 mCurrentCookedState.cookedPointerData.idToIndex,
1989 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1990 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1991 mSentHoverEnter = true;
1992 }
1993
1994 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1995 mCurrentRawState.buttonState, 0,
1996 mCurrentCookedState.cookedPointerData.pointerProperties,
1997 mCurrentCookedState.cookedPointerData.pointerCoords,
1998 mCurrentCookedState.cookedPointerData.idToIndex,
1999 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2000 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2001 }
2002}
2003
2004void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
2005 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2006 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2007 const int32_t metaState = getContext()->getGlobalMetaState();
2008 int32_t buttonState = mLastCookedState.buttonState;
2009 while (!releasedButtons.isEmpty()) {
2010 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2011 buttonState &= ~actionButton;
2012 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2013 actionButton, 0, metaState, buttonState, 0,
2014 mCurrentCookedState.cookedPointerData.pointerProperties,
2015 mCurrentCookedState.cookedPointerData.pointerCoords,
2016 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2017 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2018 }
2019}
2020
2021void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2022 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2023 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2024 const int32_t metaState = getContext()->getGlobalMetaState();
2025 int32_t buttonState = mLastCookedState.buttonState;
2026 while (!pressedButtons.isEmpty()) {
2027 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2028 buttonState |= actionButton;
2029 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2030 0, metaState, buttonState, 0,
2031 mCurrentCookedState.cookedPointerData.pointerProperties,
2032 mCurrentCookedState.cookedPointerData.pointerCoords,
2033 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2034 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2035 }
2036}
2037
2038const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2039 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2040 return cookedPointerData.touchingIdBits;
2041 }
2042 return cookedPointerData.hoveringIdBits;
2043}
2044
2045void TouchInputMapper::cookPointerData() {
2046 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2047
2048 mCurrentCookedState.cookedPointerData.clear();
2049 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2050 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2051 mCurrentRawState.rawPointerData.hoveringIdBits;
2052 mCurrentCookedState.cookedPointerData.touchingIdBits =
2053 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002054 mCurrentCookedState.cookedPointerData.canceledIdBits =
2055 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002056
2057 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2058 mCurrentCookedState.buttonState = 0;
2059 } else {
2060 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2061 }
2062
2063 // Walk through the the active pointers and map device coordinates onto
2064 // surface coordinates and adjust for display orientation.
2065 for (uint32_t i = 0; i < currentPointerCount; i++) {
2066 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2067
2068 // Size
2069 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2070 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002071 case Calibration::SizeCalibration::GEOMETRIC:
2072 case Calibration::SizeCalibration::DIAMETER:
2073 case Calibration::SizeCalibration::BOX:
2074 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002075 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2076 touchMajor = in.touchMajor;
2077 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2078 toolMajor = in.toolMajor;
2079 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2080 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2081 : in.touchMajor;
2082 } else if (mRawPointerAxes.touchMajor.valid) {
2083 toolMajor = touchMajor = in.touchMajor;
2084 toolMinor = touchMinor =
2085 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2086 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2087 : in.touchMajor;
2088 } else if (mRawPointerAxes.toolMajor.valid) {
2089 touchMajor = toolMajor = in.toolMajor;
2090 touchMinor = toolMinor =
2091 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2092 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2093 : in.toolMajor;
2094 } else {
2095 ALOG_ASSERT(false,
2096 "No touch or tool axes. "
2097 "Size calibration should have been resolved to NONE.");
2098 touchMajor = 0;
2099 touchMinor = 0;
2100 toolMajor = 0;
2101 toolMinor = 0;
2102 size = 0;
2103 }
2104
2105 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2106 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2107 if (touchingCount > 1) {
2108 touchMajor /= touchingCount;
2109 touchMinor /= touchingCount;
2110 toolMajor /= touchingCount;
2111 toolMinor /= touchingCount;
2112 size /= touchingCount;
2113 }
2114 }
2115
Michael Wright227c5542020-07-02 18:30:52 +01002116 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002117 touchMajor *= mGeometricScale;
2118 touchMinor *= mGeometricScale;
2119 toolMajor *= mGeometricScale;
2120 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002121 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002122 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2123 touchMinor = touchMajor;
2124 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2125 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002126 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002127 touchMinor = touchMajor;
2128 toolMinor = toolMajor;
2129 }
2130
2131 mCalibration.applySizeScaleAndBias(&touchMajor);
2132 mCalibration.applySizeScaleAndBias(&touchMinor);
2133 mCalibration.applySizeScaleAndBias(&toolMajor);
2134 mCalibration.applySizeScaleAndBias(&toolMinor);
2135 size *= mSizeScale;
2136 break;
2137 default:
2138 touchMajor = 0;
2139 touchMinor = 0;
2140 toolMajor = 0;
2141 toolMinor = 0;
2142 size = 0;
2143 break;
2144 }
2145
2146 // Pressure
2147 float pressure;
2148 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002149 case Calibration::PressureCalibration::PHYSICAL:
2150 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002151 pressure = in.pressure * mPressureScale;
2152 break;
2153 default:
2154 pressure = in.isHovering ? 0 : 1;
2155 break;
2156 }
2157
2158 // Tilt and Orientation
2159 float tilt;
2160 float orientation;
2161 if (mHaveTilt) {
2162 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2163 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2164 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2165 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2166 } else {
2167 tilt = 0;
2168
2169 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002170 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002171 orientation = in.orientation * mOrientationScale;
2172 break;
Michael Wright227c5542020-07-02 18:30:52 +01002173 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002174 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2175 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2176 if (c1 != 0 || c2 != 0) {
2177 orientation = atan2f(c1, c2) * 0.5f;
2178 float confidence = hypotf(c1, c2);
2179 float scale = 1.0f + confidence / 16.0f;
2180 touchMajor *= scale;
2181 touchMinor /= scale;
2182 toolMajor *= scale;
2183 toolMinor /= scale;
2184 } else {
2185 orientation = 0;
2186 }
2187 break;
2188 }
2189 default:
2190 orientation = 0;
2191 }
2192 }
2193
2194 // Distance
2195 float distance;
2196 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002197 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002198 distance = in.distance * mDistanceScale;
2199 break;
2200 default:
2201 distance = 0;
2202 }
2203
2204 // Coverage
2205 int32_t rawLeft, rawTop, rawRight, rawBottom;
2206 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002207 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002208 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2209 rawRight = in.toolMinor & 0x0000ffff;
2210 rawBottom = in.toolMajor & 0x0000ffff;
2211 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2212 break;
2213 default:
2214 rawLeft = rawTop = rawRight = rawBottom = 0;
2215 break;
2216 }
2217
2218 // Adjust X,Y coords for device calibration
2219 // TODO: Adjust coverage coords?
2220 float xTransformed = in.x, yTransformed = in.y;
2221 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002222 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002223
2224 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002225 float left, top, right, bottom;
2226
2227 switch (mSurfaceOrientation) {
2228 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002229 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2230 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2231 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2232 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2233 orientation -= M_PI_2;
2234 if (mOrientedRanges.haveOrientation &&
2235 orientation < mOrientedRanges.orientation.min) {
2236 orientation +=
2237 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2238 }
2239 break;
2240 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002241 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2242 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2243 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2244 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2245 orientation -= M_PI;
2246 if (mOrientedRanges.haveOrientation &&
2247 orientation < mOrientedRanges.orientation.min) {
2248 orientation +=
2249 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2250 }
2251 break;
2252 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002253 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2254 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2255 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2256 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2257 orientation += M_PI_2;
2258 if (mOrientedRanges.haveOrientation &&
2259 orientation > mOrientedRanges.orientation.max) {
2260 orientation -=
2261 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2262 }
2263 break;
2264 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002265 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2266 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2267 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2268 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2269 break;
2270 }
2271
2272 // Write output coords.
2273 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2274 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002275 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2276 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002277 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2278 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2279 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2280 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2281 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2282 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2283 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002284 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002285 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2286 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2287 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2288 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2289 } else {
2290 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2291 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2292 }
2293
Chris Ye364fdb52020-08-05 15:07:56 -07002294 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002295 uint32_t id = in.id;
2296 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2297 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2298 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2299 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2300 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2301 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2302 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2303 }
2304
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002305 // Write output properties.
2306 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002307 properties.clear();
2308 properties.id = id;
2309 properties.toolType = in.toolType;
2310
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002311 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002312 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002313 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002314 }
2315}
2316
2317void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2318 PointerUsage pointerUsage) {
2319 if (pointerUsage != mPointerUsage) {
2320 abortPointerUsage(when, policyFlags);
2321 mPointerUsage = pointerUsage;
2322 }
2323
2324 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002325 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002326 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2327 break;
Michael Wright227c5542020-07-02 18:30:52 +01002328 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002329 dispatchPointerStylus(when, policyFlags);
2330 break;
Michael Wright227c5542020-07-02 18:30:52 +01002331 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002332 dispatchPointerMouse(when, policyFlags);
2333 break;
Michael Wright227c5542020-07-02 18:30:52 +01002334 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002335 break;
2336 }
2337}
2338
2339void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2340 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002341 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002342 abortPointerGestures(when, policyFlags);
2343 break;
Michael Wright227c5542020-07-02 18:30:52 +01002344 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002345 abortPointerStylus(when, policyFlags);
2346 break;
Michael Wright227c5542020-07-02 18:30:52 +01002347 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002348 abortPointerMouse(when, policyFlags);
2349 break;
Michael Wright227c5542020-07-02 18:30:52 +01002350 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 break;
2352 }
2353
Michael Wright227c5542020-07-02 18:30:52 +01002354 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355}
2356
2357void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2358 // Update current gesture coordinates.
2359 bool cancelPreviousGesture, finishPreviousGesture;
2360 bool sendEvents =
2361 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2362 if (!sendEvents) {
2363 return;
2364 }
2365 if (finishPreviousGesture) {
2366 cancelPreviousGesture = false;
2367 }
2368
2369 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002370 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002371 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 if (finishPreviousGesture || cancelPreviousGesture) {
2373 mPointerController->clearSpots();
2374 }
2375
Michael Wright227c5542020-07-02 18:30:52 +01002376 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2378 mPointerGesture.currentGestureIdToIndex,
2379 mPointerGesture.currentGestureIdBits,
2380 mPointerController->getDisplayId());
2381 }
2382 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002383 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002384 }
2385
2386 // Show or hide the pointer if needed.
2387 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002388 case PointerGesture::Mode::NEUTRAL:
2389 case PointerGesture::Mode::QUIET:
2390 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2391 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002392 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002393 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 }
2395 break;
Michael Wright227c5542020-07-02 18:30:52 +01002396 case PointerGesture::Mode::TAP:
2397 case PointerGesture::Mode::TAP_DRAG:
2398 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2399 case PointerGesture::Mode::HOVER:
2400 case PointerGesture::Mode::PRESS:
2401 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402 // Unfade the pointer when the current gesture manipulates the
2403 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002404 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405 break;
Michael Wright227c5542020-07-02 18:30:52 +01002406 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002407 // Fade the pointer when the current gesture manipulates a different
2408 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002409 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002410 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002412 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002413 }
2414 break;
2415 }
2416
2417 // Send events!
2418 int32_t metaState = getContext()->getGlobalMetaState();
2419 int32_t buttonState = mCurrentCookedState.buttonState;
2420
2421 // Update last coordinates of pointers that have moved so that we observe the new
2422 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002423 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2424 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2425 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2426 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2427 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2428 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002429 bool moveNeeded = false;
2430 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2431 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2432 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2433 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2434 mPointerGesture.lastGestureIdBits.value);
2435 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2436 mPointerGesture.currentGestureCoords,
2437 mPointerGesture.currentGestureIdToIndex,
2438 mPointerGesture.lastGestureProperties,
2439 mPointerGesture.lastGestureCoords,
2440 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2441 if (buttonState != mLastCookedState.buttonState) {
2442 moveNeeded = true;
2443 }
2444 }
2445
2446 // Send motion events for all pointers that went up or were canceled.
2447 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2448 if (!dispatchedGestureIdBits.isEmpty()) {
2449 if (cancelPreviousGesture) {
2450 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2451 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2452 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2453 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2454 mPointerGesture.downTime);
2455
2456 dispatchedGestureIdBits.clear();
2457 } else {
2458 BitSet32 upGestureIdBits;
2459 if (finishPreviousGesture) {
2460 upGestureIdBits = dispatchedGestureIdBits;
2461 } else {
2462 upGestureIdBits.value =
2463 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2464 }
2465 while (!upGestureIdBits.isEmpty()) {
2466 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2467
2468 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2469 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2470 mPointerGesture.lastGestureProperties,
2471 mPointerGesture.lastGestureCoords,
2472 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2473 0, mPointerGesture.downTime);
2474
2475 dispatchedGestureIdBits.clearBit(id);
2476 }
2477 }
2478 }
2479
2480 // Send motion events for all pointers that moved.
2481 if (moveNeeded) {
2482 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2483 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2484 mPointerGesture.currentGestureProperties,
2485 mPointerGesture.currentGestureCoords,
2486 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2487 mPointerGesture.downTime);
2488 }
2489
2490 // Send motion events for all pointers that went down.
2491 if (down) {
2492 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2493 ~dispatchedGestureIdBits.value);
2494 while (!downGestureIdBits.isEmpty()) {
2495 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2496 dispatchedGestureIdBits.markBit(id);
2497
2498 if (dispatchedGestureIdBits.count() == 1) {
2499 mPointerGesture.downTime = when;
2500 }
2501
2502 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2503 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2504 mPointerGesture.currentGestureCoords,
2505 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2506 0, mPointerGesture.downTime);
2507 }
2508 }
2509
2510 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002511 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2513 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2514 mPointerGesture.currentGestureProperties,
2515 mPointerGesture.currentGestureCoords,
2516 mPointerGesture.currentGestureIdToIndex,
2517 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2518 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2519 // Synthesize a hover move event after all pointers go up to indicate that
2520 // the pointer is hovering again even if the user is not currently touching
2521 // the touch pad. This ensures that a view will receive a fresh hover enter
2522 // event after a tap.
2523 float x, y;
2524 mPointerController->getPosition(&x, &y);
2525
2526 PointerProperties pointerProperties;
2527 pointerProperties.clear();
2528 pointerProperties.id = 0;
2529 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2530
2531 PointerCoords pointerCoords;
2532 pointerCoords.clear();
2533 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2534 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2535
2536 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002537 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2538 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2539 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2540 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2541 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002542 getListener()->notifyMotion(&args);
2543 }
2544
2545 // Update state.
2546 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2547 if (!down) {
2548 mPointerGesture.lastGestureIdBits.clear();
2549 } else {
2550 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2551 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2552 uint32_t id = idBits.clearFirstMarkedBit();
2553 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2554 mPointerGesture.lastGestureProperties[index].copyFrom(
2555 mPointerGesture.currentGestureProperties[index]);
2556 mPointerGesture.lastGestureCoords[index].copyFrom(
2557 mPointerGesture.currentGestureCoords[index]);
2558 mPointerGesture.lastGestureIdToIndex[id] = index;
2559 }
2560 }
2561}
2562
2563void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2564 // Cancel previously dispatches pointers.
2565 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2566 int32_t metaState = getContext()->getGlobalMetaState();
2567 int32_t buttonState = mCurrentRawState.buttonState;
2568 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2569 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2570 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2571 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2572 0, 0, mPointerGesture.downTime);
2573 }
2574
2575 // Reset the current pointer gesture.
2576 mPointerGesture.reset();
2577 mPointerVelocityControl.reset();
2578
2579 // Remove any current spots.
2580 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002581 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002582 mPointerController->clearSpots();
2583 }
2584}
2585
2586bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2587 bool* outFinishPreviousGesture, bool isTimeout) {
2588 *outCancelPreviousGesture = false;
2589 *outFinishPreviousGesture = false;
2590
2591 // Handle TAP timeout.
2592 if (isTimeout) {
2593#if DEBUG_GESTURES
2594 ALOGD("Gestures: Processing timeout");
2595#endif
2596
Michael Wright227c5542020-07-02 18:30:52 +01002597 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002598 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2599 // The tap/drag timeout has not yet expired.
2600 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2601 mConfig.pointerGestureTapDragInterval);
2602 } else {
2603 // The tap is finished.
2604#if DEBUG_GESTURES
2605 ALOGD("Gestures: TAP finished");
2606#endif
2607 *outFinishPreviousGesture = true;
2608
2609 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002610 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002611 mPointerGesture.currentGestureIdBits.clear();
2612
2613 mPointerVelocityControl.reset();
2614 return true;
2615 }
2616 }
2617
2618 // We did not handle this timeout.
2619 return false;
2620 }
2621
2622 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2623 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2624
2625 // Update the velocity tracker.
2626 {
2627 VelocityTracker::Position positions[MAX_POINTERS];
2628 uint32_t count = 0;
2629 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
2630 uint32_t id = idBits.clearFirstMarkedBit();
2631 const RawPointerData::Pointer& pointer =
2632 mCurrentRawState.rawPointerData.pointerForId(id);
2633 positions[count].x = pointer.x * mPointerXMovementScale;
2634 positions[count].y = pointer.y * mPointerYMovementScale;
2635 }
2636 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2637 positions);
2638 }
2639
2640 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2641 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002642 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2643 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2644 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002645 mPointerGesture.resetTap();
2646 }
2647
2648 // Pick a new active touch id if needed.
2649 // Choose an arbitrary pointer that just went down, if there is one.
2650 // Otherwise choose an arbitrary remaining pointer.
2651 // This guarantees we always have an active touch id when there is at least one pointer.
2652 // We keep the same active touch id for as long as possible.
2653 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2654 int32_t activeTouchId = lastActiveTouchId;
2655 if (activeTouchId < 0) {
2656 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2657 activeTouchId = mPointerGesture.activeTouchId =
2658 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2659 mPointerGesture.firstTouchTime = when;
2660 }
2661 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2662 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2663 activeTouchId = mPointerGesture.activeTouchId =
2664 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2665 } else {
2666 activeTouchId = mPointerGesture.activeTouchId = -1;
2667 }
2668 }
2669
2670 // Determine whether we are in quiet time.
2671 bool isQuietTime = false;
2672 if (activeTouchId < 0) {
2673 mPointerGesture.resetQuietTime();
2674 } else {
2675 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2676 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002677 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2678 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2679 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002680 currentFingerCount < 2) {
2681 // Enter quiet time when exiting swipe or freeform state.
2682 // This is to prevent accidentally entering the hover state and flinging the
2683 // pointer when finishing a swipe and there is still one pointer left onscreen.
2684 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002685 } else if (mPointerGesture.lastGestureMode ==
2686 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002687 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2688 // Enter quiet time when releasing the button and there are still two or more
2689 // fingers down. This may indicate that one finger was used to press the button
2690 // but it has not gone up yet.
2691 isQuietTime = true;
2692 }
2693 if (isQuietTime) {
2694 mPointerGesture.quietTime = when;
2695 }
2696 }
2697 }
2698
2699 // Switch states based on button and pointer state.
2700 if (isQuietTime) {
2701 // Case 1: Quiet time. (QUIET)
2702#if DEBUG_GESTURES
2703 ALOGD("Gestures: QUIET for next %0.3fms",
2704 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2705#endif
Michael Wright227c5542020-07-02 18:30:52 +01002706 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002707 *outFinishPreviousGesture = true;
2708 }
2709
2710 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002711 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002712 mPointerGesture.currentGestureIdBits.clear();
2713
2714 mPointerVelocityControl.reset();
2715 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2716 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2717 // The pointer follows the active touch point.
2718 // Emit DOWN, MOVE, UP events at the pointer location.
2719 //
2720 // Only the active touch matters; other fingers are ignored. This policy helps
2721 // to handle the case where the user places a second finger on the touch pad
2722 // to apply the necessary force to depress an integrated button below the surface.
2723 // We don't want the second finger to be delivered to applications.
2724 //
2725 // For this to work well, we need to make sure to track the pointer that is really
2726 // active. If the user first puts one finger down to click then adds another
2727 // finger to drag then the active pointer should switch to the finger that is
2728 // being dragged.
2729#if DEBUG_GESTURES
2730 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2731 "currentFingerCount=%d",
2732 activeTouchId, currentFingerCount);
2733#endif
2734 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002735 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002736 *outFinishPreviousGesture = true;
2737 mPointerGesture.activeGestureId = 0;
2738 }
2739
2740 // Switch pointers if needed.
2741 // Find the fastest pointer and follow it.
2742 if (activeTouchId >= 0 && currentFingerCount > 1) {
2743 int32_t bestId = -1;
2744 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2745 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2746 uint32_t id = idBits.clearFirstMarkedBit();
2747 float vx, vy;
2748 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2749 float speed = hypotf(vx, vy);
2750 if (speed > bestSpeed) {
2751 bestId = id;
2752 bestSpeed = speed;
2753 }
2754 }
2755 }
2756 if (bestId >= 0 && bestId != activeTouchId) {
2757 mPointerGesture.activeTouchId = activeTouchId = bestId;
2758#if DEBUG_GESTURES
2759 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2760 "bestId=%d, bestSpeed=%0.3f",
2761 bestId, bestSpeed);
2762#endif
2763 }
2764 }
2765
2766 float deltaX = 0, deltaY = 0;
2767 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2768 const RawPointerData::Pointer& currentPointer =
2769 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2770 const RawPointerData::Pointer& lastPointer =
2771 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2772 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2773 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2774
2775 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2776 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2777
2778 // Move the pointer using a relative motion.
2779 // When using spots, the click will occur at the position of the anchor
2780 // spot and all other spots will move there.
2781 mPointerController->move(deltaX, deltaY);
2782 } else {
2783 mPointerVelocityControl.reset();
2784 }
2785
2786 float x, y;
2787 mPointerController->getPosition(&x, &y);
2788
Michael Wright227c5542020-07-02 18:30:52 +01002789 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002790 mPointerGesture.currentGestureIdBits.clear();
2791 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2792 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2793 mPointerGesture.currentGestureProperties[0].clear();
2794 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2795 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2796 mPointerGesture.currentGestureCoords[0].clear();
2797 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2798 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2799 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2800 } else if (currentFingerCount == 0) {
2801 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002802 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002803 *outFinishPreviousGesture = true;
2804 }
2805
2806 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2807 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2808 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002809 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2810 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002811 lastFingerCount == 1) {
2812 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2813 float x, y;
2814 mPointerController->getPosition(&x, &y);
2815 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2816 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2817#if DEBUG_GESTURES
2818 ALOGD("Gestures: TAP");
2819#endif
2820
2821 mPointerGesture.tapUpTime = when;
2822 getContext()->requestTimeoutAtTime(when +
2823 mConfig.pointerGestureTapDragInterval);
2824
2825 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002826 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002827 mPointerGesture.currentGestureIdBits.clear();
2828 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2829 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2830 mPointerGesture.currentGestureProperties[0].clear();
2831 mPointerGesture.currentGestureProperties[0].id =
2832 mPointerGesture.activeGestureId;
2833 mPointerGesture.currentGestureProperties[0].toolType =
2834 AMOTION_EVENT_TOOL_TYPE_FINGER;
2835 mPointerGesture.currentGestureCoords[0].clear();
2836 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2837 mPointerGesture.tapX);
2838 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2839 mPointerGesture.tapY);
2840 mPointerGesture.currentGestureCoords[0]
2841 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2842
2843 tapped = true;
2844 } else {
2845#if DEBUG_GESTURES
2846 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2847 y - mPointerGesture.tapY);
2848#endif
2849 }
2850 } else {
2851#if DEBUG_GESTURES
2852 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2853 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2854 (when - mPointerGesture.tapDownTime) * 0.000001f);
2855 } else {
2856 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2857 }
2858#endif
2859 }
2860 }
2861
2862 mPointerVelocityControl.reset();
2863
2864 if (!tapped) {
2865#if DEBUG_GESTURES
2866 ALOGD("Gestures: NEUTRAL");
2867#endif
2868 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002869 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002870 mPointerGesture.currentGestureIdBits.clear();
2871 }
2872 } else if (currentFingerCount == 1) {
2873 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2874 // The pointer follows the active touch point.
2875 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2876 // When in TAP_DRAG, emit MOVE events at the pointer location.
2877 ALOG_ASSERT(activeTouchId >= 0);
2878
Michael Wright227c5542020-07-02 18:30:52 +01002879 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2880 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002881 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2882 float x, y;
2883 mPointerController->getPosition(&x, &y);
2884 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2885 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002886 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002887 } else {
2888#if DEBUG_GESTURES
2889 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2890 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2891#endif
2892 }
2893 } else {
2894#if DEBUG_GESTURES
2895 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2896 (when - mPointerGesture.tapUpTime) * 0.000001f);
2897#endif
2898 }
Michael Wright227c5542020-07-02 18:30:52 +01002899 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2900 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002901 }
2902
2903 float deltaX = 0, deltaY = 0;
2904 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2905 const RawPointerData::Pointer& currentPointer =
2906 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2907 const RawPointerData::Pointer& lastPointer =
2908 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2909 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2910 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2911
2912 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2913 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2914
2915 // Move the pointer using a relative motion.
2916 // When using spots, the hover or drag will occur at the position of the anchor spot.
2917 mPointerController->move(deltaX, deltaY);
2918 } else {
2919 mPointerVelocityControl.reset();
2920 }
2921
2922 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002923 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002924#if DEBUG_GESTURES
2925 ALOGD("Gestures: TAP_DRAG");
2926#endif
2927 down = true;
2928 } else {
2929#if DEBUG_GESTURES
2930 ALOGD("Gestures: HOVER");
2931#endif
Michael Wright227c5542020-07-02 18:30:52 +01002932 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002933 *outFinishPreviousGesture = true;
2934 }
2935 mPointerGesture.activeGestureId = 0;
2936 down = false;
2937 }
2938
2939 float x, y;
2940 mPointerController->getPosition(&x, &y);
2941
2942 mPointerGesture.currentGestureIdBits.clear();
2943 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2944 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2945 mPointerGesture.currentGestureProperties[0].clear();
2946 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2947 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2948 mPointerGesture.currentGestureCoords[0].clear();
2949 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2950 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2951 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2952 down ? 1.0f : 0.0f);
2953
2954 if (lastFingerCount == 0 && currentFingerCount != 0) {
2955 mPointerGesture.resetTap();
2956 mPointerGesture.tapDownTime = when;
2957 mPointerGesture.tapX = x;
2958 mPointerGesture.tapY = y;
2959 }
2960 } else {
2961 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2962 // We need to provide feedback for each finger that goes down so we cannot wait
2963 // for the fingers to move before deciding what to do.
2964 //
2965 // The ambiguous case is deciding what to do when there are two fingers down but they
2966 // have not moved enough to determine whether they are part of a drag or part of a
2967 // freeform gesture, or just a press or long-press at the pointer location.
2968 //
2969 // When there are two fingers we start with the PRESS hypothesis and we generate a
2970 // down at the pointer location.
2971 //
2972 // When the two fingers move enough or when additional fingers are added, we make
2973 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2974 ALOG_ASSERT(activeTouchId >= 0);
2975
2976 bool settled = when >=
2977 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002978 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2979 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2980 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 *outFinishPreviousGesture = true;
2982 } else if (!settled && currentFingerCount > lastFingerCount) {
2983 // Additional pointers have gone down but not yet settled.
2984 // Reset the gesture.
2985#if DEBUG_GESTURES
2986 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2987 "settle time remaining %0.3fms",
2988 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2989 when) * 0.000001f);
2990#endif
2991 *outCancelPreviousGesture = true;
2992 } else {
2993 // Continue previous gesture.
2994 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2995 }
2996
2997 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01002998 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002999 mPointerGesture.activeGestureId = 0;
3000 mPointerGesture.referenceIdBits.clear();
3001 mPointerVelocityControl.reset();
3002
3003 // Use the centroid and pointer location as the reference points for the gesture.
3004#if DEBUG_GESTURES
3005 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3006 "settle time remaining %0.3fms",
3007 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3008 when) * 0.000001f);
3009#endif
3010 mCurrentRawState.rawPointerData
3011 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3012 &mPointerGesture.referenceTouchY);
3013 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3014 &mPointerGesture.referenceGestureY);
3015 }
3016
3017 // Clear the reference deltas for fingers not yet included in the reference calculation.
3018 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3019 ~mPointerGesture.referenceIdBits.value);
3020 !idBits.isEmpty();) {
3021 uint32_t id = idBits.clearFirstMarkedBit();
3022 mPointerGesture.referenceDeltas[id].dx = 0;
3023 mPointerGesture.referenceDeltas[id].dy = 0;
3024 }
3025 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3026
3027 // Add delta for all fingers and calculate a common movement delta.
3028 float commonDeltaX = 0, commonDeltaY = 0;
3029 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3030 mCurrentCookedState.fingerIdBits.value);
3031 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3032 bool first = (idBits == commonIdBits);
3033 uint32_t id = idBits.clearFirstMarkedBit();
3034 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3035 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3036 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3037 delta.dx += cpd.x - lpd.x;
3038 delta.dy += cpd.y - lpd.y;
3039
3040 if (first) {
3041 commonDeltaX = delta.dx;
3042 commonDeltaY = delta.dy;
3043 } else {
3044 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3045 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3046 }
3047 }
3048
3049 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003050 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003051 float dist[MAX_POINTER_ID + 1];
3052 int32_t distOverThreshold = 0;
3053 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3054 uint32_t id = idBits.clearFirstMarkedBit();
3055 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3056 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3057 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3058 distOverThreshold += 1;
3059 }
3060 }
3061
3062 // Only transition when at least two pointers have moved further than
3063 // the minimum distance threshold.
3064 if (distOverThreshold >= 2) {
3065 if (currentFingerCount > 2) {
3066 // There are more than two pointers, switch to FREEFORM.
3067#if DEBUG_GESTURES
3068 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3069 currentFingerCount);
3070#endif
3071 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003072 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003073 } else {
3074 // There are exactly two pointers.
3075 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3076 uint32_t id1 = idBits.clearFirstMarkedBit();
3077 uint32_t id2 = idBits.firstMarkedBit();
3078 const RawPointerData::Pointer& p1 =
3079 mCurrentRawState.rawPointerData.pointerForId(id1);
3080 const RawPointerData::Pointer& p2 =
3081 mCurrentRawState.rawPointerData.pointerForId(id2);
3082 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3083 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3084 // There are two pointers but they are too far apart for a SWIPE,
3085 // switch to FREEFORM.
3086#if DEBUG_GESTURES
3087 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3088 mutualDistance, mPointerGestureMaxSwipeWidth);
3089#endif
3090 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003091 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003092 } else {
3093 // There are two pointers. Wait for both pointers to start moving
3094 // before deciding whether this is a SWIPE or FREEFORM gesture.
3095 float dist1 = dist[id1];
3096 float dist2 = dist[id2];
3097 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3098 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3099 // Calculate the dot product of the displacement vectors.
3100 // When the vectors are oriented in approximately the same direction,
3101 // the angle betweeen them is near zero and the cosine of the angle
3102 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3103 // mag(v2).
3104 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3105 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3106 float dx1 = delta1.dx * mPointerXZoomScale;
3107 float dy1 = delta1.dy * mPointerYZoomScale;
3108 float dx2 = delta2.dx * mPointerXZoomScale;
3109 float dy2 = delta2.dy * mPointerYZoomScale;
3110 float dot = dx1 * dx2 + dy1 * dy2;
3111 float cosine = dot / (dist1 * dist2); // denominator always > 0
3112 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3113 // Pointers are moving in the same direction. Switch to SWIPE.
3114#if DEBUG_GESTURES
3115 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3116 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3117 "cosine %0.3f >= %0.3f",
3118 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3119 mConfig.pointerGestureMultitouchMinDistance, cosine,
3120 mConfig.pointerGestureSwipeTransitionAngleCosine);
3121#endif
Michael Wright227c5542020-07-02 18:30:52 +01003122 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003123 } else {
3124 // Pointers are moving in different directions. Switch to FREEFORM.
3125#if DEBUG_GESTURES
3126 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3127 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3128 "cosine %0.3f < %0.3f",
3129 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3130 mConfig.pointerGestureMultitouchMinDistance, cosine,
3131 mConfig.pointerGestureSwipeTransitionAngleCosine);
3132#endif
3133 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003134 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003135 }
3136 }
3137 }
3138 }
3139 }
Michael Wright227c5542020-07-02 18:30:52 +01003140 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003141 // Switch from SWIPE to FREEFORM if additional pointers go down.
3142 // Cancel previous gesture.
3143 if (currentFingerCount > 2) {
3144#if DEBUG_GESTURES
3145 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3146 currentFingerCount);
3147#endif
3148 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003149 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003150 }
3151 }
3152
3153 // Move the reference points based on the overall group motion of the fingers
3154 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003155 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003156 (commonDeltaX || commonDeltaY)) {
3157 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3158 uint32_t id = idBits.clearFirstMarkedBit();
3159 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3160 delta.dx = 0;
3161 delta.dy = 0;
3162 }
3163
3164 mPointerGesture.referenceTouchX += commonDeltaX;
3165 mPointerGesture.referenceTouchY += commonDeltaY;
3166
3167 commonDeltaX *= mPointerXMovementScale;
3168 commonDeltaY *= mPointerYMovementScale;
3169
3170 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3171 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3172
3173 mPointerGesture.referenceGestureX += commonDeltaX;
3174 mPointerGesture.referenceGestureY += commonDeltaY;
3175 }
3176
3177 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003178 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3179 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003180 // PRESS or SWIPE mode.
3181#if DEBUG_GESTURES
3182 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3183 "activeGestureId=%d, currentTouchPointerCount=%d",
3184 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3185#endif
3186 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3187
3188 mPointerGesture.currentGestureIdBits.clear();
3189 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3190 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3191 mPointerGesture.currentGestureProperties[0].clear();
3192 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3193 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3194 mPointerGesture.currentGestureCoords[0].clear();
3195 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3196 mPointerGesture.referenceGestureX);
3197 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3198 mPointerGesture.referenceGestureY);
3199 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003200 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003201 // FREEFORM mode.
3202#if DEBUG_GESTURES
3203 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3204 "activeGestureId=%d, currentTouchPointerCount=%d",
3205 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3206#endif
3207 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3208
3209 mPointerGesture.currentGestureIdBits.clear();
3210
3211 BitSet32 mappedTouchIdBits;
3212 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003213 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003214 // Initially, assign the active gesture id to the active touch point
3215 // if there is one. No other touch id bits are mapped yet.
3216 if (!*outCancelPreviousGesture) {
3217 mappedTouchIdBits.markBit(activeTouchId);
3218 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3219 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3220 mPointerGesture.activeGestureId;
3221 } else {
3222 mPointerGesture.activeGestureId = -1;
3223 }
3224 } else {
3225 // Otherwise, assume we mapped all touches from the previous frame.
3226 // Reuse all mappings that are still applicable.
3227 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3228 mCurrentCookedState.fingerIdBits.value;
3229 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3230
3231 // Check whether we need to choose a new active gesture id because the
3232 // current went went up.
3233 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3234 ~mCurrentCookedState.fingerIdBits.value);
3235 !upTouchIdBits.isEmpty();) {
3236 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3237 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3238 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3239 mPointerGesture.activeGestureId = -1;
3240 break;
3241 }
3242 }
3243 }
3244
3245#if DEBUG_GESTURES
3246 ALOGD("Gestures: FREEFORM follow up "
3247 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3248 "activeGestureId=%d",
3249 mappedTouchIdBits.value, usedGestureIdBits.value,
3250 mPointerGesture.activeGestureId);
3251#endif
3252
3253 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3254 for (uint32_t i = 0; i < currentFingerCount; i++) {
3255 uint32_t touchId = idBits.clearFirstMarkedBit();
3256 uint32_t gestureId;
3257 if (!mappedTouchIdBits.hasBit(touchId)) {
3258 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3259 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3260#if DEBUG_GESTURES
3261 ALOGD("Gestures: FREEFORM "
3262 "new mapping for touch id %d -> gesture id %d",
3263 touchId, gestureId);
3264#endif
3265 } else {
3266 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3267#if DEBUG_GESTURES
3268 ALOGD("Gestures: FREEFORM "
3269 "existing mapping for touch id %d -> gesture id %d",
3270 touchId, gestureId);
3271#endif
3272 }
3273 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3274 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3275
3276 const RawPointerData::Pointer& pointer =
3277 mCurrentRawState.rawPointerData.pointerForId(touchId);
3278 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3279 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3280 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3281
3282 mPointerGesture.currentGestureProperties[i].clear();
3283 mPointerGesture.currentGestureProperties[i].id = gestureId;
3284 mPointerGesture.currentGestureProperties[i].toolType =
3285 AMOTION_EVENT_TOOL_TYPE_FINGER;
3286 mPointerGesture.currentGestureCoords[i].clear();
3287 mPointerGesture.currentGestureCoords[i]
3288 .setAxisValue(AMOTION_EVENT_AXIS_X,
3289 mPointerGesture.referenceGestureX + deltaX);
3290 mPointerGesture.currentGestureCoords[i]
3291 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3292 mPointerGesture.referenceGestureY + deltaY);
3293 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3294 1.0f);
3295 }
3296
3297 if (mPointerGesture.activeGestureId < 0) {
3298 mPointerGesture.activeGestureId =
3299 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3300#if DEBUG_GESTURES
3301 ALOGD("Gestures: FREEFORM new "
3302 "activeGestureId=%d",
3303 mPointerGesture.activeGestureId);
3304#endif
3305 }
3306 }
3307 }
3308
3309 mPointerController->setButtonState(mCurrentRawState.buttonState);
3310
3311#if DEBUG_GESTURES
3312 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3313 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3314 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3315 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3316 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3317 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3318 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3319 uint32_t id = idBits.clearFirstMarkedBit();
3320 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3321 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3322 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3323 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3324 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3325 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3326 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3327 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3328 }
3329 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3330 uint32_t id = idBits.clearFirstMarkedBit();
3331 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3332 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3333 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3334 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3335 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3336 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3337 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3338 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3339 }
3340#endif
3341 return true;
3342}
3343
3344void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3345 mPointerSimple.currentCoords.clear();
3346 mPointerSimple.currentProperties.clear();
3347
3348 bool down, hovering;
3349 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3350 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3351 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3352 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3353 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3354 mPointerController->setPosition(x, y);
3355
3356 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3357 down = !hovering;
3358
3359 mPointerController->getPosition(&x, &y);
3360 mPointerSimple.currentCoords.copyFrom(
3361 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3362 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3363 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3364 mPointerSimple.currentProperties.id = 0;
3365 mPointerSimple.currentProperties.toolType =
3366 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3367 } else {
3368 down = false;
3369 hovering = false;
3370 }
3371
3372 dispatchPointerSimple(when, policyFlags, down, hovering);
3373}
3374
3375void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3376 abortPointerSimple(when, policyFlags);
3377}
3378
3379void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3380 mPointerSimple.currentCoords.clear();
3381 mPointerSimple.currentProperties.clear();
3382
3383 bool down, hovering;
3384 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3385 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3386 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3387 float deltaX = 0, deltaY = 0;
3388 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3389 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3390 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3391 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3392 mPointerXMovementScale;
3393 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3394 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3395 mPointerYMovementScale;
3396
3397 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3398 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3399
3400 mPointerController->move(deltaX, deltaY);
3401 } else {
3402 mPointerVelocityControl.reset();
3403 }
3404
3405 down = isPointerDown(mCurrentRawState.buttonState);
3406 hovering = !down;
3407
3408 float x, y;
3409 mPointerController->getPosition(&x, &y);
3410 mPointerSimple.currentCoords.copyFrom(
3411 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3412 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3413 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3414 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3415 hovering ? 0.0f : 1.0f);
3416 mPointerSimple.currentProperties.id = 0;
3417 mPointerSimple.currentProperties.toolType =
3418 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3419 } else {
3420 mPointerVelocityControl.reset();
3421
3422 down = false;
3423 hovering = false;
3424 }
3425
3426 dispatchPointerSimple(when, policyFlags, down, hovering);
3427}
3428
3429void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3430 abortPointerSimple(when, policyFlags);
3431
3432 mPointerVelocityControl.reset();
3433}
3434
3435void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3436 bool hovering) {
3437 int32_t metaState = getContext()->getGlobalMetaState();
3438 int32_t displayId = mViewport.displayId;
3439
3440 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003441 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003442 mPointerController->clearSpots();
3443 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003444 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003445 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003446 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003447 }
3448 displayId = mPointerController->getDisplayId();
3449
3450 float xCursorPosition;
3451 float yCursorPosition;
3452 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3453
3454 if (mPointerSimple.down && !down) {
3455 mPointerSimple.down = false;
3456
3457 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003458 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3459 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003460 mLastRawState.buttonState, MotionClassification::NONE,
3461 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3462 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3463 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3464 /* videoFrames */ {});
3465 getListener()->notifyMotion(&args);
3466 }
3467
3468 if (mPointerSimple.hovering && !hovering) {
3469 mPointerSimple.hovering = false;
3470
3471 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003472 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3473 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3474 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003475 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3476 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3477 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3478 /* videoFrames */ {});
3479 getListener()->notifyMotion(&args);
3480 }
3481
3482 if (down) {
3483 if (!mPointerSimple.down) {
3484 mPointerSimple.down = true;
3485 mPointerSimple.downTime = when;
3486
3487 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003488 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003489 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3490 metaState, mCurrentRawState.buttonState,
3491 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3492 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3493 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3494 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3495 getListener()->notifyMotion(&args);
3496 }
3497
3498 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003499 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3500 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003501 mCurrentRawState.buttonState, MotionClassification::NONE,
3502 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3503 &mPointerSimple.currentCoords, mOrientedXPrecision,
3504 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3505 mPointerSimple.downTime, /* videoFrames */ {});
3506 getListener()->notifyMotion(&args);
3507 }
3508
3509 if (hovering) {
3510 if (!mPointerSimple.hovering) {
3511 mPointerSimple.hovering = true;
3512
3513 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003514 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3516 metaState, mCurrentRawState.buttonState,
3517 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3518 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3519 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3520 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3521 getListener()->notifyMotion(&args);
3522 }
3523
3524 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003525 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3526 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3527 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003528 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3529 &mPointerSimple.currentCoords, mOrientedXPrecision,
3530 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3531 mPointerSimple.downTime, /* videoFrames */ {});
3532 getListener()->notifyMotion(&args);
3533 }
3534
3535 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3536 float vscroll = mCurrentRawState.rawVScroll;
3537 float hscroll = mCurrentRawState.rawHScroll;
3538 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3539 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3540
3541 // Send scroll.
3542 PointerCoords pointerCoords;
3543 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3544 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3545 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3546
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003547 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3548 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003549 mCurrentRawState.buttonState, MotionClassification::NONE,
3550 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3551 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3552 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3553 /* videoFrames */ {});
3554 getListener()->notifyMotion(&args);
3555 }
3556
3557 // Save state.
3558 if (down || hovering) {
3559 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3560 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3561 } else {
3562 mPointerSimple.reset();
3563 }
3564}
3565
3566void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3567 mPointerSimple.currentCoords.clear();
3568 mPointerSimple.currentProperties.clear();
3569
3570 dispatchPointerSimple(when, policyFlags, false, false);
3571}
3572
3573void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3574 int32_t action, int32_t actionButton, int32_t flags,
3575 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3576 const PointerProperties* properties,
3577 const PointerCoords* coords, const uint32_t* idToIndex,
3578 BitSet32 idBits, int32_t changedId, float xPrecision,
3579 float yPrecision, nsecs_t downTime) {
3580 PointerCoords pointerCoords[MAX_POINTERS];
3581 PointerProperties pointerProperties[MAX_POINTERS];
3582 uint32_t pointerCount = 0;
3583 while (!idBits.isEmpty()) {
3584 uint32_t id = idBits.clearFirstMarkedBit();
3585 uint32_t index = idToIndex[id];
3586 pointerProperties[pointerCount].copyFrom(properties[index]);
3587 pointerCoords[pointerCount].copyFrom(coords[index]);
3588
3589 if (changedId >= 0 && id == uint32_t(changedId)) {
3590 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3591 }
3592
3593 pointerCount += 1;
3594 }
3595
3596 ALOG_ASSERT(pointerCount != 0);
3597
3598 if (changedId >= 0 && pointerCount == 1) {
3599 // Replace initial down and final up action.
3600 // We can compare the action without masking off the changed pointer index
3601 // because we know the index is 0.
3602 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3603 action = AMOTION_EVENT_ACTION_DOWN;
3604 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003605 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3606 action = AMOTION_EVENT_ACTION_CANCEL;
3607 } else {
3608 action = AMOTION_EVENT_ACTION_UP;
3609 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003610 } else {
3611 // Can't happen.
3612 ALOG_ASSERT(false);
3613 }
3614 }
3615 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3616 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003617 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003618 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3619 }
3620 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3621 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003622 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003623 std::for_each(frames.begin(), frames.end(),
3624 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003625 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3626 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003627 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3628 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3629 downTime, std::move(frames));
3630 getListener()->notifyMotion(&args);
3631}
3632
3633bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3634 const PointerCoords* inCoords,
3635 const uint32_t* inIdToIndex,
3636 PointerProperties* outProperties,
3637 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3638 BitSet32 idBits) const {
3639 bool changed = false;
3640 while (!idBits.isEmpty()) {
3641 uint32_t id = idBits.clearFirstMarkedBit();
3642 uint32_t inIndex = inIdToIndex[id];
3643 uint32_t outIndex = outIdToIndex[id];
3644
3645 const PointerProperties& curInProperties = inProperties[inIndex];
3646 const PointerCoords& curInCoords = inCoords[inIndex];
3647 PointerProperties& curOutProperties = outProperties[outIndex];
3648 PointerCoords& curOutCoords = outCoords[outIndex];
3649
3650 if (curInProperties != curOutProperties) {
3651 curOutProperties.copyFrom(curInProperties);
3652 changed = true;
3653 }
3654
3655 if (curInCoords != curOutCoords) {
3656 curOutCoords.copyFrom(curInCoords);
3657 changed = true;
3658 }
3659 }
3660 return changed;
3661}
3662
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003663void TouchInputMapper::cancelTouch(nsecs_t when) {
3664 abortPointerUsage(when, 0 /*policyFlags*/);
3665 abortTouches(when, 0 /* policyFlags*/);
3666}
3667
Arthur Hung4197f6b2020-03-16 15:39:59 +08003668// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003669void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003670 // Scale to surface coordinate.
3671 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3672 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3673
3674 // Rotate to surface coordinate.
3675 // 0 - no swap and reverse.
3676 // 90 - swap x/y and reverse y.
3677 // 180 - reverse x, y.
3678 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003679 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003680 case DISPLAY_ORIENTATION_0:
3681 x = xScaled + mXTranslate;
3682 y = yScaled + mYTranslate;
3683 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003684 case DISPLAY_ORIENTATION_90:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003685 y = mSurfaceRight - xScaled;
3686 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003687 break;
3688 case DISPLAY_ORIENTATION_180:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003689 x = mSurfaceRight - xScaled;
3690 y = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003691 break;
3692 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003693 y = xScaled + mXTranslate;
3694 x = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003695 break;
3696 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003697 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003698 }
3699}
3700
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003701bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003702 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3703 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3704
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003705 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003706 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003707 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003708 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003709}
3710
3711const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3712 for (const VirtualKey& virtualKey : mVirtualKeys) {
3713#if DEBUG_VIRTUAL_KEYS
3714 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3715 "left=%d, top=%d, right=%d, bottom=%d",
3716 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3717 virtualKey.hitRight, virtualKey.hitBottom);
3718#endif
3719
3720 if (virtualKey.isHit(x, y)) {
3721 return &virtualKey;
3722 }
3723 }
3724
3725 return nullptr;
3726}
3727
3728void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3729 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3730 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3731
3732 current->rawPointerData.clearIdBits();
3733
3734 if (currentPointerCount == 0) {
3735 // No pointers to assign.
3736 return;
3737 }
3738
3739 if (lastPointerCount == 0) {
3740 // All pointers are new.
3741 for (uint32_t i = 0; i < currentPointerCount; i++) {
3742 uint32_t id = i;
3743 current->rawPointerData.pointers[i].id = id;
3744 current->rawPointerData.idToIndex[id] = i;
3745 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3746 }
3747 return;
3748 }
3749
3750 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3751 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3752 // Only one pointer and no change in count so it must have the same id as before.
3753 uint32_t id = last->rawPointerData.pointers[0].id;
3754 current->rawPointerData.pointers[0].id = id;
3755 current->rawPointerData.idToIndex[id] = 0;
3756 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3757 return;
3758 }
3759
3760 // General case.
3761 // We build a heap of squared euclidean distances between current and last pointers
3762 // associated with the current and last pointer indices. Then, we find the best
3763 // match (by distance) for each current pointer.
3764 // The pointers must have the same tool type but it is possible for them to
3765 // transition from hovering to touching or vice-versa while retaining the same id.
3766 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3767
3768 uint32_t heapSize = 0;
3769 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3770 currentPointerIndex++) {
3771 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3772 lastPointerIndex++) {
3773 const RawPointerData::Pointer& currentPointer =
3774 current->rawPointerData.pointers[currentPointerIndex];
3775 const RawPointerData::Pointer& lastPointer =
3776 last->rawPointerData.pointers[lastPointerIndex];
3777 if (currentPointer.toolType == lastPointer.toolType) {
3778 int64_t deltaX = currentPointer.x - lastPointer.x;
3779 int64_t deltaY = currentPointer.y - lastPointer.y;
3780
3781 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3782
3783 // Insert new element into the heap (sift up).
3784 heap[heapSize].currentPointerIndex = currentPointerIndex;
3785 heap[heapSize].lastPointerIndex = lastPointerIndex;
3786 heap[heapSize].distance = distance;
3787 heapSize += 1;
3788 }
3789 }
3790 }
3791
3792 // Heapify
3793 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3794 startIndex -= 1;
3795 for (uint32_t parentIndex = startIndex;;) {
3796 uint32_t childIndex = parentIndex * 2 + 1;
3797 if (childIndex >= heapSize) {
3798 break;
3799 }
3800
3801 if (childIndex + 1 < heapSize &&
3802 heap[childIndex + 1].distance < heap[childIndex].distance) {
3803 childIndex += 1;
3804 }
3805
3806 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3807 break;
3808 }
3809
3810 swap(heap[parentIndex], heap[childIndex]);
3811 parentIndex = childIndex;
3812 }
3813 }
3814
3815#if DEBUG_POINTER_ASSIGNMENT
3816 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3817 for (size_t i = 0; i < heapSize; i++) {
3818 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3819 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3820 }
3821#endif
3822
3823 // Pull matches out by increasing order of distance.
3824 // To avoid reassigning pointers that have already been matched, the loop keeps track
3825 // of which last and current pointers have been matched using the matchedXXXBits variables.
3826 // It also tracks the used pointer id bits.
3827 BitSet32 matchedLastBits(0);
3828 BitSet32 matchedCurrentBits(0);
3829 BitSet32 usedIdBits(0);
3830 bool first = true;
3831 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3832 while (heapSize > 0) {
3833 if (first) {
3834 // The first time through the loop, we just consume the root element of
3835 // the heap (the one with smallest distance).
3836 first = false;
3837 } else {
3838 // Previous iterations consumed the root element of the heap.
3839 // Pop root element off of the heap (sift down).
3840 heap[0] = heap[heapSize];
3841 for (uint32_t parentIndex = 0;;) {
3842 uint32_t childIndex = parentIndex * 2 + 1;
3843 if (childIndex >= heapSize) {
3844 break;
3845 }
3846
3847 if (childIndex + 1 < heapSize &&
3848 heap[childIndex + 1].distance < heap[childIndex].distance) {
3849 childIndex += 1;
3850 }
3851
3852 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3853 break;
3854 }
3855
3856 swap(heap[parentIndex], heap[childIndex]);
3857 parentIndex = childIndex;
3858 }
3859
3860#if DEBUG_POINTER_ASSIGNMENT
3861 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003862 for (size_t j = 0; j < heapSize; j++) {
3863 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3864 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003865 }
3866#endif
3867 }
3868
3869 heapSize -= 1;
3870
3871 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3872 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3873
3874 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3875 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3876
3877 matchedCurrentBits.markBit(currentPointerIndex);
3878 matchedLastBits.markBit(lastPointerIndex);
3879
3880 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3881 current->rawPointerData.pointers[currentPointerIndex].id = id;
3882 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3883 current->rawPointerData.markIdBit(id,
3884 current->rawPointerData.isHovering(
3885 currentPointerIndex));
3886 usedIdBits.markBit(id);
3887
3888#if DEBUG_POINTER_ASSIGNMENT
3889 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3890 ", distance=%" PRIu64,
3891 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3892#endif
3893 break;
3894 }
3895 }
3896
3897 // Assign fresh ids to pointers that were not matched in the process.
3898 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3899 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3900 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3901
3902 current->rawPointerData.pointers[currentPointerIndex].id = id;
3903 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3904 current->rawPointerData.markIdBit(id,
3905 current->rawPointerData.isHovering(currentPointerIndex));
3906
3907#if DEBUG_POINTER_ASSIGNMENT
3908 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3909#endif
3910 }
3911}
3912
3913int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3914 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3915 return AKEY_STATE_VIRTUAL;
3916 }
3917
3918 for (const VirtualKey& virtualKey : mVirtualKeys) {
3919 if (virtualKey.keyCode == keyCode) {
3920 return AKEY_STATE_UP;
3921 }
3922 }
3923
3924 return AKEY_STATE_UNKNOWN;
3925}
3926
3927int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3928 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3929 return AKEY_STATE_VIRTUAL;
3930 }
3931
3932 for (const VirtualKey& virtualKey : mVirtualKeys) {
3933 if (virtualKey.scanCode == scanCode) {
3934 return AKEY_STATE_UP;
3935 }
3936 }
3937
3938 return AKEY_STATE_UNKNOWN;
3939}
3940
3941bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3942 const int32_t* keyCodes, uint8_t* outFlags) {
3943 for (const VirtualKey& virtualKey : mVirtualKeys) {
3944 for (size_t i = 0; i < numCodes; i++) {
3945 if (virtualKey.keyCode == keyCodes[i]) {
3946 outFlags[i] = 1;
3947 }
3948 }
3949 }
3950
3951 return true;
3952}
3953
3954std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3955 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003956 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003957 return std::make_optional(mPointerController->getDisplayId());
3958 } else {
3959 return std::make_optional(mViewport.displayId);
3960 }
3961 }
3962 return std::nullopt;
3963}
3964
3965} // namespace android