blob: 20de22de9364ebd412085bce63eef4f0cfe6bc24 [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) {
196 // Populate RELATIVE_X and RELATIVE_Y motion range for touchpad capture mode
197 // RELATIVE_X and RELATIVE_Y motion range is the largest possible hardware relative
198 // motion, e.g. the hardware size finger moved completely across the touchpad in one
199 // sample cycle.
200 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
201 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
202 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
203 x.fuzz, x.resolution);
204 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
205 y.fuzz, y.resolution);
206 }
207
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700208 if (mOrientedRanges.haveSize) {
209 info->addMotionRange(mOrientedRanges.size);
210 }
211
212 if (mOrientedRanges.haveTouchSize) {
213 info->addMotionRange(mOrientedRanges.touchMajor);
214 info->addMotionRange(mOrientedRanges.touchMinor);
215 }
216
217 if (mOrientedRanges.haveToolSize) {
218 info->addMotionRange(mOrientedRanges.toolMajor);
219 info->addMotionRange(mOrientedRanges.toolMinor);
220 }
221
222 if (mOrientedRanges.haveOrientation) {
223 info->addMotionRange(mOrientedRanges.orientation);
224 }
225
226 if (mOrientedRanges.haveDistance) {
227 info->addMotionRange(mOrientedRanges.distance);
228 }
229
230 if (mOrientedRanges.haveTilt) {
231 info->addMotionRange(mOrientedRanges.tilt);
232 }
233
234 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
235 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
236 0.0f);
237 }
238 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
239 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
240 0.0f);
241 }
Michael Wright227c5542020-07-02 18:30:52 +0100242 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700243 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
244 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
245 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
246 x.fuzz, x.resolution);
247 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
248 y.fuzz, y.resolution);
249 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
250 x.fuzz, x.resolution);
251 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
252 y.fuzz, y.resolution);
253 }
254 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
255 }
256}
257
258void TouchInputMapper::dump(std::string& dump) {
259 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
260 dumpParameters(dump);
261 dumpVirtualKeys(dump);
262 dumpRawPointerAxes(dump);
263 dumpCalibration(dump);
264 dumpAffineTransformation(dump);
265 dumpSurface(dump);
266
267 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
268 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
269 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
270 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
271 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
272 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
273 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
274 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
275 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
276 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
277 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
278 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
279 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
280 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
281 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
282 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
283 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
284
285 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
286 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
287 mLastRawState.rawPointerData.pointerCount);
288 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
289 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
290 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
291 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
292 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
293 "toolType=%d, isHovering=%s\n",
294 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
295 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
296 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
297 pointer.distance, pointer.toolType, toString(pointer.isHovering));
298 }
299
300 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
301 mLastCookedState.buttonState);
302 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
303 mLastCookedState.cookedPointerData.pointerCount);
304 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
305 const PointerProperties& pointerProperties =
306 mLastCookedState.cookedPointerData.pointerProperties[i];
307 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000308 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
309 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
310 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700311 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
312 "toolType=%d, isHovering=%s\n",
313 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000314 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
315 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700316 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
324 pointerProperties.toolType,
325 toString(mLastCookedState.cookedPointerData.isHovering(i)));
326 }
327
328 dump += INDENT3 "Stylus Fusion:\n";
329 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
330 toString(mExternalStylusConnected));
331 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
332 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
333 mExternalStylusFusionTimeout);
334 dump += INDENT3 "External Stylus State:\n";
335 dumpStylusState(dump, mExternalStylusState);
336
Michael Wright227c5542020-07-02 18:30:52 +0100337 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700338 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
339 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
340 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
341 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
342 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
343 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
344 }
345}
346
347const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
348 switch (deviceMode) {
Michael Wright227c5542020-07-02 18:30:52 +0100349 case DeviceMode::DISABLED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350 return "disabled";
Michael Wright227c5542020-07-02 18:30:52 +0100351 case DeviceMode::DIRECT:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700352 return "direct";
Michael Wright227c5542020-07-02 18:30:52 +0100353 case DeviceMode::UNSCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700354 return "unscaled";
Michael Wright227c5542020-07-02 18:30:52 +0100355 case DeviceMode::NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700356 return "navigation";
Michael Wright227c5542020-07-02 18:30:52 +0100357 case DeviceMode::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700358 return "pointer";
359 }
360 return "unknown";
361}
362
363void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
364 uint32_t changes) {
365 InputMapper::configure(when, config, changes);
366
367 mConfig = *config;
368
369 if (!changes) { // first time only
370 // Configure basic parameters.
371 configureParameters();
372
373 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800374 mCursorScrollAccumulator.configure(getDeviceContext());
375 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700376
377 // Configure absolute axis information.
378 configureRawPointerAxes();
379
380 // Prepare input device calibration.
381 parseCalibration();
382 resolveCalibration();
383 }
384
385 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
386 // Update location calibration to reflect current settings
387 updateAffineTransformation();
388 }
389
390 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
391 // Update pointer speed.
392 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
393 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
394 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
395 }
396
397 bool resetNeeded = false;
398 if (!changes ||
399 (changes &
400 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800401 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
403 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
404 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
405 // Configure device sources, surface dimensions, orientation and
406 // scaling factors.
407 configureSurface(when, &resetNeeded);
408 }
409
410 if (changes && resetNeeded) {
411 // Send reset, unless this is the first time the device has been configured,
412 // in which case the reader will call reset itself after all mappers are ready.
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800413 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800414 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700415 }
416}
417
418void TouchInputMapper::resolveExternalStylusPresence() {
419 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800420 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700421 mExternalStylusConnected = !devices.empty();
422
423 if (!mExternalStylusConnected) {
424 resetExternalStylus();
425 }
426}
427
428void TouchInputMapper::configureParameters() {
429 // Use the pointer presentation mode for devices that do not support distinct
430 // multitouch. The spot-based presentation relies on being able to accurately
431 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800432 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100433 ? Parameters::GestureMode::SINGLE_TOUCH
434 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700435
436 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800437 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
438 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100440 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700441 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100442 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443 } else if (gestureModeString != "default") {
444 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
445 }
446 }
447
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800448 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700449 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100450 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800451 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100453 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800454 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
455 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456 // The device is a cursor device with a touch pad attached.
457 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100458 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700459 } else {
460 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100461 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700462 }
463
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800464 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700465
466 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800467 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
468 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700469 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100470 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700471 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100472 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700473 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100474 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700475 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100476 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700477 } else if (deviceTypeString != "default") {
478 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
479 }
480 }
481
Michael Wright227c5542020-07-02 18:30:52 +0100482 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800483 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
484 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700485
486 mParameters.hasAssociatedDisplay = false;
487 mParameters.associatedDisplayIsExternal = false;
488 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100489 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
490 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700491 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100492 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800493 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700494 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800495 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
496 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700497 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
498 }
499 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800500 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700501 mParameters.hasAssociatedDisplay = true;
502 }
503
504 // Initial downs on external touch devices should wake the device.
505 // Normally we don't do this for internal touch screens to prevent them from waking
506 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800507 mParameters.wake = getDeviceContext().isExternal();
508 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700509}
510
511void TouchInputMapper::dumpParameters(std::string& dump) {
512 dump += INDENT3 "Parameters:\n";
513
514 switch (mParameters.gestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +0100515 case Parameters::GestureMode::SINGLE_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700516 dump += INDENT4 "GestureMode: single-touch\n";
517 break;
Michael Wright227c5542020-07-02 18:30:52 +0100518 case Parameters::GestureMode::MULTI_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700519 dump += INDENT4 "GestureMode: multi-touch\n";
520 break;
521 default:
522 assert(false);
523 }
524
525 switch (mParameters.deviceType) {
Michael Wright227c5542020-07-02 18:30:52 +0100526 case Parameters::DeviceType::TOUCH_SCREEN:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700527 dump += INDENT4 "DeviceType: touchScreen\n";
528 break;
Michael Wright227c5542020-07-02 18:30:52 +0100529 case Parameters::DeviceType::TOUCH_PAD:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700530 dump += INDENT4 "DeviceType: touchPad\n";
531 break;
Michael Wright227c5542020-07-02 18:30:52 +0100532 case Parameters::DeviceType::TOUCH_NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700533 dump += INDENT4 "DeviceType: touchNavigation\n";
534 break;
Michael Wright227c5542020-07-02 18:30:52 +0100535 case Parameters::DeviceType::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700536 dump += INDENT4 "DeviceType: pointer\n";
537 break;
538 default:
539 ALOG_ASSERT(false);
540 }
541
542 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
543 "displayId='%s'\n",
544 toString(mParameters.hasAssociatedDisplay),
545 toString(mParameters.associatedDisplayIsExternal),
546 mParameters.uniqueDisplayId.c_str());
547 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
548}
549
550void TouchInputMapper::configureRawPointerAxes() {
551 mRawPointerAxes.clear();
552}
553
554void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
555 dump += INDENT3 "Raw Touch Axes:\n";
556 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
557 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
558 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
559 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
560 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
561 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
562 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
563 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
564 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
565 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
566 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
567 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
568 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
569}
570
571bool TouchInputMapper::hasExternalStylus() const {
572 return mExternalStylusConnected;
573}
574
575/**
576 * Determine which DisplayViewport to use.
577 * 1. If display port is specified, return the matching viewport. If matching viewport not
578 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800579 * 2. Always use the suggested viewport from WindowManagerService for pointers.
580 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700581 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800582 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700583 */
584std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800585 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800586 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700587 if (displayPort) {
588 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800589 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700590 }
591
Michael Wright227c5542020-07-02 18:30:52 +0100592 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800593 std::optional<DisplayViewport> viewport =
594 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
595 if (viewport) {
596 return viewport;
597 } else {
598 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
599 mConfig.defaultPointerDisplayId);
600 }
601 }
602
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700603 // Check if uniqueDisplayId is specified in idc file.
604 if (!mParameters.uniqueDisplayId.empty()) {
605 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
606 }
607
608 ViewportType viewportTypeToUse;
609 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100610 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700611 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100612 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700613 }
614
615 std::optional<DisplayViewport> viewport =
616 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100617 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700618 ALOGW("Input device %s should be associated with external display, "
619 "fallback to internal one for the external viewport is not found.",
620 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100621 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700622 }
623
624 return viewport;
625 }
626
627 // No associated display, return a non-display viewport.
628 DisplayViewport newViewport;
629 // Raw width and height in the natural orientation.
630 int32_t rawWidth = mRawPointerAxes.getRawWidth();
631 int32_t rawHeight = mRawPointerAxes.getRawHeight();
632 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
633 return std::make_optional(newViewport);
634}
635
636void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100637 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700638
639 resolveExternalStylusPresence();
640
641 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100642 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800643 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700644 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100645 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700646 if (hasStylus()) {
647 mSource |= AINPUT_SOURCE_STYLUS;
648 }
Michael Wright227c5542020-07-02 18:30:52 +0100649 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700650 mParameters.hasAssociatedDisplay) {
651 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100652 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700653 if (hasStylus()) {
654 mSource |= AINPUT_SOURCE_STYLUS;
655 }
656 if (hasExternalStylus()) {
657 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
658 }
Michael Wright227c5542020-07-02 18:30:52 +0100659 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700660 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100661 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700662 } else {
663 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100664 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700665 }
666
667 // Ensure we have valid X and Y axes.
668 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
669 ALOGW("Touch device '%s' did not report support for X or Y axis! "
670 "The device will be inoperable.",
671 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100672 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700673 return;
674 }
675
676 // Get associated display dimensions.
677 std::optional<DisplayViewport> newViewport = findViewport();
678 if (!newViewport) {
679 ALOGI("Touch device '%s' could not query the properties of its associated "
680 "display. The device will be inoperable until the display size "
681 "becomes available.",
682 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100683 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700684 return;
685 }
686
687 // Raw width and height in the natural orientation.
688 int32_t rawWidth = mRawPointerAxes.getRawWidth();
689 int32_t rawHeight = mRawPointerAxes.getRawHeight();
690
691 bool viewportChanged = mViewport != *newViewport;
692 if (viewportChanged) {
693 mViewport = *newViewport;
694
Michael Wright227c5542020-07-02 18:30:52 +0100695 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700696 // Convert rotated viewport to natural surface coordinates.
697 int32_t naturalLogicalWidth, naturalLogicalHeight;
698 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
699 int32_t naturalPhysicalLeft, naturalPhysicalTop;
700 int32_t naturalDeviceWidth, naturalDeviceHeight;
701 switch (mViewport.orientation) {
702 case DISPLAY_ORIENTATION_90:
703 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
704 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
705 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
706 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800707 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700708 naturalPhysicalTop = mViewport.physicalLeft;
709 naturalDeviceWidth = mViewport.deviceHeight;
710 naturalDeviceHeight = mViewport.deviceWidth;
711 break;
712 case DISPLAY_ORIENTATION_180:
713 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
714 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
715 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
716 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
717 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
718 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
719 naturalDeviceWidth = mViewport.deviceWidth;
720 naturalDeviceHeight = mViewport.deviceHeight;
721 break;
722 case DISPLAY_ORIENTATION_270:
723 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
724 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
725 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
726 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
727 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800728 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700729 naturalDeviceWidth = mViewport.deviceHeight;
730 naturalDeviceHeight = mViewport.deviceWidth;
731 break;
732 case DISPLAY_ORIENTATION_0:
733 default:
734 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
735 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
736 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
737 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
738 naturalPhysicalLeft = mViewport.physicalLeft;
739 naturalPhysicalTop = mViewport.physicalTop;
740 naturalDeviceWidth = mViewport.deviceWidth;
741 naturalDeviceHeight = mViewport.deviceHeight;
742 break;
743 }
744
745 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
746 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
747 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
748 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
749 }
750
751 mPhysicalWidth = naturalPhysicalWidth;
752 mPhysicalHeight = naturalPhysicalHeight;
753 mPhysicalLeft = naturalPhysicalLeft;
754 mPhysicalTop = naturalPhysicalTop;
755
Arthur Hung4197f6b2020-03-16 15:39:59 +0800756 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
757 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700758 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
759 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800760 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
761 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700762
763 mSurfaceOrientation =
764 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
765 } else {
766 mPhysicalWidth = rawWidth;
767 mPhysicalHeight = rawHeight;
768 mPhysicalLeft = 0;
769 mPhysicalTop = 0;
770
Arthur Hung4197f6b2020-03-16 15:39:59 +0800771 mRawSurfaceWidth = rawWidth;
772 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700773 mSurfaceLeft = 0;
774 mSurfaceTop = 0;
775 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
776 }
777 }
778
779 // If moving between pointer modes, need to reset some state.
780 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
781 if (deviceModeChanged) {
782 mOrientedRanges.clear();
783 }
784
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800785 // Create pointer controller if needed.
Michael Wright227c5542020-07-02 18:30:52 +0100786 if (mDeviceMode == DeviceMode::POINTER ||
787 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800788 if (mPointerController == nullptr) {
789 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700790 }
791 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100792 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700793 }
794
795 if (viewportChanged || deviceModeChanged) {
796 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
797 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800798 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700799 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
800
801 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800802 mXScale = float(mRawSurfaceWidth) / rawWidth;
803 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700804 mXTranslate = -mSurfaceLeft;
805 mYTranslate = -mSurfaceTop;
806 mXPrecision = 1.0f / mXScale;
807 mYPrecision = 1.0f / mYScale;
808
809 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
810 mOrientedRanges.x.source = mSource;
811 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
812 mOrientedRanges.y.source = mSource;
813
814 configureVirtualKeys();
815
816 // Scale factor for terms that are not oriented in a particular axis.
817 // If the pixels are square then xScale == yScale otherwise we fake it
818 // by choosing an average.
819 mGeometricScale = avg(mXScale, mYScale);
820
821 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800822 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700823
824 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100825 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700826 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
827 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
828 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
829 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
830 } else {
831 mSizeScale = 0.0f;
832 }
833
834 mOrientedRanges.haveTouchSize = true;
835 mOrientedRanges.haveToolSize = true;
836 mOrientedRanges.haveSize = true;
837
838 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
839 mOrientedRanges.touchMajor.source = mSource;
840 mOrientedRanges.touchMajor.min = 0;
841 mOrientedRanges.touchMajor.max = diagonalSize;
842 mOrientedRanges.touchMajor.flat = 0;
843 mOrientedRanges.touchMajor.fuzz = 0;
844 mOrientedRanges.touchMajor.resolution = 0;
845
846 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
847 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
848
849 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
850 mOrientedRanges.toolMajor.source = mSource;
851 mOrientedRanges.toolMajor.min = 0;
852 mOrientedRanges.toolMajor.max = diagonalSize;
853 mOrientedRanges.toolMajor.flat = 0;
854 mOrientedRanges.toolMajor.fuzz = 0;
855 mOrientedRanges.toolMajor.resolution = 0;
856
857 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
858 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
859
860 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
861 mOrientedRanges.size.source = mSource;
862 mOrientedRanges.size.min = 0;
863 mOrientedRanges.size.max = 1.0;
864 mOrientedRanges.size.flat = 0;
865 mOrientedRanges.size.fuzz = 0;
866 mOrientedRanges.size.resolution = 0;
867 } else {
868 mSizeScale = 0.0f;
869 }
870
871 // Pressure factors.
872 mPressureScale = 0;
873 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100874 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
875 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700876 if (mCalibration.havePressureScale) {
877 mPressureScale = mCalibration.pressureScale;
878 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
879 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
880 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
881 }
882 }
883
884 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
885 mOrientedRanges.pressure.source = mSource;
886 mOrientedRanges.pressure.min = 0;
887 mOrientedRanges.pressure.max = pressureMax;
888 mOrientedRanges.pressure.flat = 0;
889 mOrientedRanges.pressure.fuzz = 0;
890 mOrientedRanges.pressure.resolution = 0;
891
892 // Tilt
893 mTiltXCenter = 0;
894 mTiltXScale = 0;
895 mTiltYCenter = 0;
896 mTiltYScale = 0;
897 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
898 if (mHaveTilt) {
899 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
900 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
901 mTiltXScale = M_PI / 180;
902 mTiltYScale = M_PI / 180;
903
904 mOrientedRanges.haveTilt = true;
905
906 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
907 mOrientedRanges.tilt.source = mSource;
908 mOrientedRanges.tilt.min = 0;
909 mOrientedRanges.tilt.max = M_PI_2;
910 mOrientedRanges.tilt.flat = 0;
911 mOrientedRanges.tilt.fuzz = 0;
912 mOrientedRanges.tilt.resolution = 0;
913 }
914
915 // Orientation
916 mOrientationScale = 0;
917 if (mHaveTilt) {
918 mOrientedRanges.haveOrientation = true;
919
920 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
921 mOrientedRanges.orientation.source = mSource;
922 mOrientedRanges.orientation.min = -M_PI;
923 mOrientedRanges.orientation.max = M_PI;
924 mOrientedRanges.orientation.flat = 0;
925 mOrientedRanges.orientation.fuzz = 0;
926 mOrientedRanges.orientation.resolution = 0;
927 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100928 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700929 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100930 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700931 if (mRawPointerAxes.orientation.valid) {
932 if (mRawPointerAxes.orientation.maxValue > 0) {
933 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
934 } else if (mRawPointerAxes.orientation.minValue < 0) {
935 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
936 } else {
937 mOrientationScale = 0;
938 }
939 }
940 }
941
942 mOrientedRanges.haveOrientation = true;
943
944 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
945 mOrientedRanges.orientation.source = mSource;
946 mOrientedRanges.orientation.min = -M_PI_2;
947 mOrientedRanges.orientation.max = M_PI_2;
948 mOrientedRanges.orientation.flat = 0;
949 mOrientedRanges.orientation.fuzz = 0;
950 mOrientedRanges.orientation.resolution = 0;
951 }
952
953 // Distance
954 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100955 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
956 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700957 if (mCalibration.haveDistanceScale) {
958 mDistanceScale = mCalibration.distanceScale;
959 } else {
960 mDistanceScale = 1.0f;
961 }
962 }
963
964 mOrientedRanges.haveDistance = true;
965
966 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
967 mOrientedRanges.distance.source = mSource;
968 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
969 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
970 mOrientedRanges.distance.flat = 0;
971 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
972 mOrientedRanges.distance.resolution = 0;
973 }
974
975 // Compute oriented precision, scales and ranges.
976 // Note that the maximum value reported is an inclusive maximum value so it is one
977 // unit less than the total width or height of surface.
978 switch (mSurfaceOrientation) {
979 case DISPLAY_ORIENTATION_90:
980 case DISPLAY_ORIENTATION_270:
981 mOrientedXPrecision = mYPrecision;
982 mOrientedYPrecision = mXPrecision;
983
984 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800985 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700986 mOrientedRanges.x.flat = 0;
987 mOrientedRanges.x.fuzz = 0;
988 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
989
990 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800991 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700992 mOrientedRanges.y.flat = 0;
993 mOrientedRanges.y.fuzz = 0;
994 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
995 break;
996
997 default:
998 mOrientedXPrecision = mXPrecision;
999 mOrientedYPrecision = mYPrecision;
1000
1001 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001002 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001003 mOrientedRanges.x.flat = 0;
1004 mOrientedRanges.x.fuzz = 0;
1005 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1006
1007 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001008 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001009 mOrientedRanges.y.flat = 0;
1010 mOrientedRanges.y.fuzz = 0;
1011 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1012 break;
1013 }
1014
1015 // Location
1016 updateAffineTransformation();
1017
Michael Wright227c5542020-07-02 18:30:52 +01001018 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001019 // Compute pointer gesture detection parameters.
1020 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001021 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001022
1023 // Scale movements such that one whole swipe of the touch pad covers a
1024 // given area relative to the diagonal size of the display when no acceleration
1025 // is applied.
1026 // Assume that the touch pad has a square aspect ratio such that movements in
1027 // X and Y of the same number of raw units cover the same physical distance.
1028 mPointerXMovementScale =
1029 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1030 mPointerYMovementScale = mPointerXMovementScale;
1031
1032 // Scale zooms to cover a smaller range of the display than movements do.
1033 // This value determines the area around the pointer that is affected by freeform
1034 // pointer gestures.
1035 mPointerXZoomScale =
1036 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1037 mPointerYZoomScale = mPointerXZoomScale;
1038
1039 // Max width between pointers to detect a swipe gesture is more than some fraction
1040 // of the diagonal axis of the touch pad. Touches that are wider than this are
1041 // translated into freeform gestures.
1042 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1043
1044 // Abort current pointer usages because the state has changed.
1045 abortPointerUsage(when, 0 /*policyFlags*/);
1046 }
1047
1048 // Inform the dispatcher about the changes.
1049 *outResetNeeded = true;
1050 bumpGeneration();
1051 }
1052}
1053
1054void TouchInputMapper::dumpSurface(std::string& dump) {
1055 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001056 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1057 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001058 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1059 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001060 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1061 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001062 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1063 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1064 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1065 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1066 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1067}
1068
1069void TouchInputMapper::configureVirtualKeys() {
1070 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001071 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001072
1073 mVirtualKeys.clear();
1074
1075 if (virtualKeyDefinitions.size() == 0) {
1076 return;
1077 }
1078
1079 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1080 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1081 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1082 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1083
1084 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1085 VirtualKey virtualKey;
1086
1087 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1088 int32_t keyCode;
1089 int32_t dummyKeyMetaState;
1090 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001091 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1092 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001093 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1094 continue; // drop the key
1095 }
1096
1097 virtualKey.keyCode = keyCode;
1098 virtualKey.flags = flags;
1099
1100 // convert the key definition's display coordinates into touch coordinates for a hit box
1101 int32_t halfWidth = virtualKeyDefinition.width / 2;
1102 int32_t halfHeight = virtualKeyDefinition.height / 2;
1103
1104 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001105 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001106 touchScreenLeft;
1107 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001108 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001109 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001110 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1111 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001112 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001113 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1114 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001115 touchScreenTop;
1116 mVirtualKeys.push_back(virtualKey);
1117 }
1118}
1119
1120void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1121 if (!mVirtualKeys.empty()) {
1122 dump += INDENT3 "Virtual Keys:\n";
1123
1124 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1125 const VirtualKey& virtualKey = mVirtualKeys[i];
1126 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1127 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1128 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1129 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1130 }
1131 }
1132}
1133
1134void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001135 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 Calibration& out = mCalibration;
1137
1138 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001139 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001140 String8 sizeCalibrationString;
1141 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1142 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001143 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001145 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001146 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001147 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001149 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001151 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001152 } else if (sizeCalibrationString != "default") {
1153 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1154 }
1155 }
1156
1157 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1158 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1159 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1160
1161 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001162 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001163 String8 pressureCalibrationString;
1164 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1165 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001166 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001168 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 } else if (pressureCalibrationString != "default") {
1172 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1173 pressureCalibrationString.string());
1174 }
1175 }
1176
1177 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1178
1179 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001180 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181 String8 orientationCalibrationString;
1182 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1183 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001185 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001186 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001187 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001189 } else if (orientationCalibrationString != "default") {
1190 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1191 orientationCalibrationString.string());
1192 }
1193 }
1194
1195 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001196 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 String8 distanceCalibrationString;
1198 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1199 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001202 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 } else if (distanceCalibrationString != "default") {
1204 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1205 distanceCalibrationString.string());
1206 }
1207 }
1208
1209 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1210
Michael Wright227c5542020-07-02 18:30:52 +01001211 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 String8 coverageCalibrationString;
1213 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1214 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001215 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001217 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001218 } else if (coverageCalibrationString != "default") {
1219 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1220 coverageCalibrationString.string());
1221 }
1222 }
1223}
1224
1225void TouchInputMapper::resolveCalibration() {
1226 // Size
1227 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001228 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1229 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001230 }
1231 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001232 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 }
1234
1235 // Pressure
1236 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001237 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1238 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 }
1240 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001241 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 }
1243
1244 // Orientation
1245 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001246 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1247 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 }
1249 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001250 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001251 }
1252
1253 // Distance
1254 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001255 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1256 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 }
1258 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001259 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 }
1261
1262 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001263 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1264 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 }
1266}
1267
1268void TouchInputMapper::dumpCalibration(std::string& dump) {
1269 dump += INDENT3 "Calibration:\n";
1270
1271 // Size
1272 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001273 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001274 dump += INDENT4 "touch.size.calibration: none\n";
1275 break;
Michael Wright227c5542020-07-02 18:30:52 +01001276 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277 dump += INDENT4 "touch.size.calibration: geometric\n";
1278 break;
Michael Wright227c5542020-07-02 18:30:52 +01001279 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 dump += INDENT4 "touch.size.calibration: diameter\n";
1281 break;
Michael Wright227c5542020-07-02 18:30:52 +01001282 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 dump += INDENT4 "touch.size.calibration: box\n";
1284 break;
Michael Wright227c5542020-07-02 18:30:52 +01001285 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001286 dump += INDENT4 "touch.size.calibration: area\n";
1287 break;
1288 default:
1289 ALOG_ASSERT(false);
1290 }
1291
1292 if (mCalibration.haveSizeScale) {
1293 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1294 }
1295
1296 if (mCalibration.haveSizeBias) {
1297 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1298 }
1299
1300 if (mCalibration.haveSizeIsSummed) {
1301 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1302 toString(mCalibration.sizeIsSummed));
1303 }
1304
1305 // Pressure
1306 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001307 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 dump += INDENT4 "touch.pressure.calibration: none\n";
1309 break;
Michael Wright227c5542020-07-02 18:30:52 +01001310 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 dump += INDENT4 "touch.pressure.calibration: physical\n";
1312 break;
Michael Wright227c5542020-07-02 18:30:52 +01001313 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001314 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1315 break;
1316 default:
1317 ALOG_ASSERT(false);
1318 }
1319
1320 if (mCalibration.havePressureScale) {
1321 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1322 }
1323
1324 // Orientation
1325 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001326 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001327 dump += INDENT4 "touch.orientation.calibration: none\n";
1328 break;
Michael Wright227c5542020-07-02 18:30:52 +01001329 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1331 break;
Michael Wright227c5542020-07-02 18:30:52 +01001332 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001333 dump += INDENT4 "touch.orientation.calibration: vector\n";
1334 break;
1335 default:
1336 ALOG_ASSERT(false);
1337 }
1338
1339 // Distance
1340 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001341 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001342 dump += INDENT4 "touch.distance.calibration: none\n";
1343 break;
Michael Wright227c5542020-07-02 18:30:52 +01001344 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001345 dump += INDENT4 "touch.distance.calibration: scaled\n";
1346 break;
1347 default:
1348 ALOG_ASSERT(false);
1349 }
1350
1351 if (mCalibration.haveDistanceScale) {
1352 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1353 }
1354
1355 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001356 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357 dump += INDENT4 "touch.coverage.calibration: none\n";
1358 break;
Michael Wright227c5542020-07-02 18:30:52 +01001359 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360 dump += INDENT4 "touch.coverage.calibration: box\n";
1361 break;
1362 default:
1363 ALOG_ASSERT(false);
1364 }
1365}
1366
1367void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1368 dump += INDENT3 "Affine Transformation:\n";
1369
1370 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1371 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1372 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1373 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1374 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1375 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1376}
1377
1378void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001379 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001380 mSurfaceOrientation);
1381}
1382
1383void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001384 mCursorButtonAccumulator.reset(getDeviceContext());
1385 mCursorScrollAccumulator.reset(getDeviceContext());
1386 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001387
1388 mPointerVelocityControl.reset();
1389 mWheelXVelocityControl.reset();
1390 mWheelYVelocityControl.reset();
1391
1392 mRawStatesPending.clear();
1393 mCurrentRawState.clear();
1394 mCurrentCookedState.clear();
1395 mLastRawState.clear();
1396 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001397 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001398 mSentHoverEnter = false;
1399 mHavePointerIds = false;
1400 mCurrentMotionAborted = false;
1401 mDownTime = 0;
1402
1403 mCurrentVirtualKey.down = false;
1404
1405 mPointerGesture.reset();
1406 mPointerSimple.reset();
1407 resetExternalStylus();
1408
1409 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001410 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411 mPointerController->clearSpots();
1412 }
1413
1414 InputMapper::reset(when);
1415}
1416
1417void TouchInputMapper::resetExternalStylus() {
1418 mExternalStylusState.clear();
1419 mExternalStylusId = -1;
1420 mExternalStylusFusionTimeout = LLONG_MAX;
1421 mExternalStylusDataPending = false;
1422}
1423
1424void TouchInputMapper::clearStylusDataPendingFlags() {
1425 mExternalStylusDataPending = false;
1426 mExternalStylusFusionTimeout = LLONG_MAX;
1427}
1428
1429void TouchInputMapper::process(const RawEvent* rawEvent) {
1430 mCursorButtonAccumulator.process(rawEvent);
1431 mCursorScrollAccumulator.process(rawEvent);
1432 mTouchButtonAccumulator.process(rawEvent);
1433
1434 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1435 sync(rawEvent->when);
1436 }
1437}
1438
1439void TouchInputMapper::sync(nsecs_t when) {
1440 const RawState* last =
1441 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1442
1443 // Push a new state.
1444 mRawStatesPending.emplace_back();
1445
1446 RawState* next = &mRawStatesPending.back();
1447 next->clear();
1448 next->when = when;
1449
1450 // Sync button state.
1451 next->buttonState =
1452 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1453
1454 // Sync scroll
1455 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1456 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1457 mCursorScrollAccumulator.finishSync();
1458
1459 // Sync touch
1460 syncTouch(when, next);
1461
1462 // Assign pointer ids.
1463 if (!mHavePointerIds) {
1464 assignPointerIds(last, next);
1465 }
1466
1467#if DEBUG_RAW_EVENTS
1468 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001469 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001470 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1471 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhungcc7f9802020-04-30 17:55:40 +08001472 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1473 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001474#endif
1475
1476 processRawTouches(false /*timeout*/);
1477}
1478
1479void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001480 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001481 // Drop all input if the device is disabled.
1482 mCurrentRawState.clear();
1483 mRawStatesPending.clear();
1484 return;
1485 }
1486
1487 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1488 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1489 // touching the current state will only observe the events that have been dispatched to the
1490 // rest of the pipeline.
1491 const size_t N = mRawStatesPending.size();
1492 size_t count;
1493 for (count = 0; count < N; count++) {
1494 const RawState& next = mRawStatesPending[count];
1495
1496 // A failure to assign the stylus id means that we're waiting on stylus data
1497 // and so should defer the rest of the pipeline.
1498 if (assignExternalStylusId(next, timeout)) {
1499 break;
1500 }
1501
1502 // All ready to go.
1503 clearStylusDataPendingFlags();
1504 mCurrentRawState.copyFrom(next);
1505 if (mCurrentRawState.when < mLastRawState.when) {
1506 mCurrentRawState.when = mLastRawState.when;
1507 }
1508 cookAndDispatch(mCurrentRawState.when);
1509 }
1510 if (count != 0) {
1511 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1512 }
1513
1514 if (mExternalStylusDataPending) {
1515 if (timeout) {
1516 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1517 clearStylusDataPendingFlags();
1518 mCurrentRawState.copyFrom(mLastRawState);
1519#if DEBUG_STYLUS_FUSION
1520 ALOGD("Timeout expired, synthesizing event with new stylus data");
1521#endif
1522 cookAndDispatch(when);
1523 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1524 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1525 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1526 }
1527 }
1528}
1529
1530void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1531 // Always start with a clean state.
1532 mCurrentCookedState.clear();
1533
1534 // Apply stylus buttons to current raw state.
1535 applyExternalStylusButtonState(when);
1536
1537 // Handle policy on initial down or hover events.
1538 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1539 mCurrentRawState.rawPointerData.pointerCount != 0;
1540
1541 uint32_t policyFlags = 0;
1542 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1543 if (initialDown || buttonsPressed) {
1544 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001545 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001546 getContext()->fadePointer();
1547 }
1548
1549 if (mParameters.wake) {
1550 policyFlags |= POLICY_FLAG_WAKE;
1551 }
1552 }
1553
1554 // Consume raw off-screen touches before cooking pointer data.
1555 // If touches are consumed, subsequent code will not receive any pointer data.
1556 if (consumeRawTouches(when, policyFlags)) {
1557 mCurrentRawState.rawPointerData.clear();
1558 }
1559
1560 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1561 // with cooked pointer data that has the same ids and indices as the raw data.
1562 // The following code can use either the raw or cooked data, as needed.
1563 cookPointerData();
1564
1565 // Apply stylus pressure to current cooked state.
1566 applyExternalStylusTouchState(when);
1567
1568 // Synthesize key down from raw buttons if needed.
1569 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1570 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1571 mCurrentCookedState.buttonState);
1572
1573 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001574 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001575 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1576 uint32_t id = idBits.clearFirstMarkedBit();
1577 const RawPointerData::Pointer& pointer =
1578 mCurrentRawState.rawPointerData.pointerForId(id);
1579 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1580 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1581 mCurrentCookedState.stylusIdBits.markBit(id);
1582 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1583 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1584 mCurrentCookedState.fingerIdBits.markBit(id);
1585 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1586 mCurrentCookedState.mouseIdBits.markBit(id);
1587 }
1588 }
1589 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1590 uint32_t id = idBits.clearFirstMarkedBit();
1591 const RawPointerData::Pointer& pointer =
1592 mCurrentRawState.rawPointerData.pointerForId(id);
1593 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1594 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1595 mCurrentCookedState.stylusIdBits.markBit(id);
1596 }
1597 }
1598
1599 // Stylus takes precedence over all tools, then mouse, then finger.
1600 PointerUsage pointerUsage = mPointerUsage;
1601 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1602 mCurrentCookedState.mouseIdBits.clear();
1603 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001604 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001605 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1606 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001607 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001608 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1609 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001610 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001611 }
1612
1613 dispatchPointerUsage(when, policyFlags, pointerUsage);
1614 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001615 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001616 mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001617 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1618 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001619
1620 mPointerController->setButtonState(mCurrentRawState.buttonState);
1621 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1622 mCurrentCookedState.cookedPointerData.idToIndex,
1623 mCurrentCookedState.cookedPointerData.touchingIdBits,
1624 mViewport.displayId);
1625 }
1626
1627 if (!mCurrentMotionAborted) {
1628 dispatchButtonRelease(when, policyFlags);
1629 dispatchHoverExit(when, policyFlags);
1630 dispatchTouches(when, policyFlags);
1631 dispatchHoverEnterAndMove(when, policyFlags);
1632 dispatchButtonPress(when, policyFlags);
1633 }
1634
1635 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1636 mCurrentMotionAborted = false;
1637 }
1638 }
1639
1640 // Synthesize key up from raw buttons if needed.
1641 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1642 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1643 mCurrentCookedState.buttonState);
1644
1645 // Clear some transient state.
1646 mCurrentRawState.rawVScroll = 0;
1647 mCurrentRawState.rawHScroll = 0;
1648
1649 // Copy current touch to last touch in preparation for the next cycle.
1650 mLastRawState.copyFrom(mCurrentRawState);
1651 mLastCookedState.copyFrom(mCurrentCookedState);
1652}
1653
1654void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001655 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001656 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1657 }
1658}
1659
1660void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1661 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1662 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1663
1664 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1665 float pressure = mExternalStylusState.pressure;
1666 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1667 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1668 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1669 }
1670 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1671 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1672
1673 PointerProperties& properties =
1674 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1675 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1676 properties.toolType = mExternalStylusState.toolType;
1677 }
1678 }
1679}
1680
1681bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001682 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001683 return false;
1684 }
1685
1686 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1687 state.rawPointerData.pointerCount != 0;
1688 if (initialDown) {
1689 if (mExternalStylusState.pressure != 0.0f) {
1690#if DEBUG_STYLUS_FUSION
1691 ALOGD("Have both stylus and touch data, beginning fusion");
1692#endif
1693 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1694 } else if (timeout) {
1695#if DEBUG_STYLUS_FUSION
1696 ALOGD("Timeout expired, assuming touch is not a stylus.");
1697#endif
1698 resetExternalStylus();
1699 } else {
1700 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1701 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1702 }
1703#if DEBUG_STYLUS_FUSION
1704 ALOGD("No stylus data but stylus is connected, requesting timeout "
1705 "(%" PRId64 "ms)",
1706 mExternalStylusFusionTimeout);
1707#endif
1708 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1709 return true;
1710 }
1711 }
1712
1713 // Check if the stylus pointer has gone up.
1714 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1715#if DEBUG_STYLUS_FUSION
1716 ALOGD("Stylus pointer is going up");
1717#endif
1718 mExternalStylusId = -1;
1719 }
1720
1721 return false;
1722}
1723
1724void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001725 if (mDeviceMode == DeviceMode::POINTER) {
1726 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001727 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1728 }
Michael Wright227c5542020-07-02 18:30:52 +01001729 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001730 if (mExternalStylusFusionTimeout < when) {
1731 processRawTouches(true /*timeout*/);
1732 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1733 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1734 }
1735 }
1736}
1737
1738void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1739 mExternalStylusState.copyFrom(state);
1740 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1741 // We're either in the middle of a fused stream of data or we're waiting on data before
1742 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1743 // data.
1744 mExternalStylusDataPending = true;
1745 processRawTouches(false /*timeout*/);
1746 }
1747}
1748
1749bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1750 // Check for release of a virtual key.
1751 if (mCurrentVirtualKey.down) {
1752 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1753 // Pointer went up while virtual key was down.
1754 mCurrentVirtualKey.down = false;
1755 if (!mCurrentVirtualKey.ignored) {
1756#if DEBUG_VIRTUAL_KEYS
1757 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1758 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1759#endif
1760 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1761 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1762 }
1763 return true;
1764 }
1765
1766 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1767 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1768 const RawPointerData::Pointer& pointer =
1769 mCurrentRawState.rawPointerData.pointerForId(id);
1770 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1771 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1772 // Pointer is still within the space of the virtual key.
1773 return true;
1774 }
1775 }
1776
1777 // Pointer left virtual key area or another pointer also went down.
1778 // Send key cancellation but do not consume the touch yet.
1779 // This is useful when the user swipes through from the virtual key area
1780 // into the main display surface.
1781 mCurrentVirtualKey.down = false;
1782 if (!mCurrentVirtualKey.ignored) {
1783#if DEBUG_VIRTUAL_KEYS
1784 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1785 mCurrentVirtualKey.scanCode);
1786#endif
1787 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1788 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1789 AKEY_EVENT_FLAG_CANCELED);
1790 }
1791 }
1792
1793 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1794 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1795 // Pointer just went down. Check for virtual key press or off-screen touches.
1796 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1797 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001798 // Exclude unscaled device for inside surface checking.
1799 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001800 // If exactly one pointer went down, check for virtual key hit.
1801 // Otherwise we will drop the entire stroke.
1802 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1803 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1804 if (virtualKey) {
1805 mCurrentVirtualKey.down = true;
1806 mCurrentVirtualKey.downTime = when;
1807 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1808 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1809 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001810 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1811 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001812
1813 if (!mCurrentVirtualKey.ignored) {
1814#if DEBUG_VIRTUAL_KEYS
1815 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1816 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1817#endif
1818 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1819 AKEY_EVENT_FLAG_FROM_SYSTEM |
1820 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1821 }
1822 }
1823 }
1824 return true;
1825 }
1826 }
1827
1828 // Disable all virtual key touches that happen within a short time interval of the
1829 // most recent touch within the screen area. The idea is to filter out stray
1830 // virtual key presses when interacting with the touch screen.
1831 //
1832 // Problems we're trying to solve:
1833 //
1834 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1835 // virtual key area that is implemented by a separate touch panel and accidentally
1836 // triggers a virtual key.
1837 //
1838 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1839 // area and accidentally triggers a virtual key. This often happens when virtual keys
1840 // are layed out below the screen near to where the on screen keyboard's space bar
1841 // is displayed.
1842 if (mConfig.virtualKeyQuietTime > 0 &&
1843 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001844 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001845 }
1846 return false;
1847}
1848
1849void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1850 int32_t keyEventAction, int32_t keyEventFlags) {
1851 int32_t keyCode = mCurrentVirtualKey.keyCode;
1852 int32_t scanCode = mCurrentVirtualKey.scanCode;
1853 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001854 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001855 policyFlags |= POLICY_FLAG_VIRTUAL;
1856
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001857 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1858 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1859 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001860 getListener()->notifyKey(&args);
1861}
1862
1863void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1864 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1865 if (!currentIdBits.isEmpty()) {
1866 int32_t metaState = getContext()->getGlobalMetaState();
1867 int32_t buttonState = mCurrentCookedState.buttonState;
1868 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1869 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1870 mCurrentCookedState.cookedPointerData.pointerProperties,
1871 mCurrentCookedState.cookedPointerData.pointerCoords,
1872 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1873 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1874 mCurrentMotionAborted = true;
1875 }
1876}
1877
1878void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1879 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1880 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1881 int32_t metaState = getContext()->getGlobalMetaState();
1882 int32_t buttonState = mCurrentCookedState.buttonState;
1883
1884 if (currentIdBits == lastIdBits) {
1885 if (!currentIdBits.isEmpty()) {
1886 // No pointer id changes so this is a move event.
1887 // The listener takes care of batching moves so we don't have to deal with that here.
1888 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1889 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1890 mCurrentCookedState.cookedPointerData.pointerProperties,
1891 mCurrentCookedState.cookedPointerData.pointerCoords,
1892 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1893 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1894 }
1895 } else {
1896 // There may be pointers going up and pointers going down and pointers moving
1897 // all at the same time.
1898 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1899 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1900 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1901 BitSet32 dispatchedIdBits(lastIdBits.value);
1902
1903 // Update last coordinates of pointers that have moved so that we observe the new
1904 // pointer positions at the same time as other pointers that have just gone up.
1905 bool moveNeeded =
1906 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1907 mCurrentCookedState.cookedPointerData.pointerCoords,
1908 mCurrentCookedState.cookedPointerData.idToIndex,
1909 mLastCookedState.cookedPointerData.pointerProperties,
1910 mLastCookedState.cookedPointerData.pointerCoords,
1911 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1912 if (buttonState != mLastCookedState.buttonState) {
1913 moveNeeded = true;
1914 }
1915
1916 // Dispatch pointer up events.
1917 while (!upIdBits.isEmpty()) {
1918 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001919 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1920 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1921 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001922 mLastCookedState.cookedPointerData.pointerProperties,
1923 mLastCookedState.cookedPointerData.pointerCoords,
1924 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1925 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1926 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001927 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001928 }
1929
1930 // Dispatch move events if any of the remaining pointers moved from their old locations.
1931 // Although applications receive new locations as part of individual pointer up
1932 // events, they do not generally handle them except when presented in a move event.
1933 if (moveNeeded && !moveIdBits.isEmpty()) {
1934 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1935 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1936 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1937 mCurrentCookedState.cookedPointerData.pointerCoords,
1938 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1939 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1940 }
1941
1942 // Dispatch pointer down events using the new pointer locations.
1943 while (!downIdBits.isEmpty()) {
1944 uint32_t downId = downIdBits.clearFirstMarkedBit();
1945 dispatchedIdBits.markBit(downId);
1946
1947 if (dispatchedIdBits.count() == 1) {
1948 // First pointer is going down. Set down time.
1949 mDownTime = when;
1950 }
1951
1952 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1953 metaState, buttonState, 0,
1954 mCurrentCookedState.cookedPointerData.pointerProperties,
1955 mCurrentCookedState.cookedPointerData.pointerCoords,
1956 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1957 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1958 }
1959 }
1960}
1961
1962void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1963 if (mSentHoverEnter &&
1964 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1965 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1966 int32_t metaState = getContext()->getGlobalMetaState();
1967 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1968 mLastCookedState.buttonState, 0,
1969 mLastCookedState.cookedPointerData.pointerProperties,
1970 mLastCookedState.cookedPointerData.pointerCoords,
1971 mLastCookedState.cookedPointerData.idToIndex,
1972 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1973 mOrientedYPrecision, mDownTime);
1974 mSentHoverEnter = false;
1975 }
1976}
1977
1978void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1979 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1980 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1981 int32_t metaState = getContext()->getGlobalMetaState();
1982 if (!mSentHoverEnter) {
1983 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1984 metaState, mCurrentRawState.buttonState, 0,
1985 mCurrentCookedState.cookedPointerData.pointerProperties,
1986 mCurrentCookedState.cookedPointerData.pointerCoords,
1987 mCurrentCookedState.cookedPointerData.idToIndex,
1988 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1989 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1990 mSentHoverEnter = true;
1991 }
1992
1993 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1994 mCurrentRawState.buttonState, 0,
1995 mCurrentCookedState.cookedPointerData.pointerProperties,
1996 mCurrentCookedState.cookedPointerData.pointerCoords,
1997 mCurrentCookedState.cookedPointerData.idToIndex,
1998 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1999 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2000 }
2001}
2002
2003void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
2004 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2005 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2006 const int32_t metaState = getContext()->getGlobalMetaState();
2007 int32_t buttonState = mLastCookedState.buttonState;
2008 while (!releasedButtons.isEmpty()) {
2009 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2010 buttonState &= ~actionButton;
2011 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2012 actionButton, 0, metaState, buttonState, 0,
2013 mCurrentCookedState.cookedPointerData.pointerProperties,
2014 mCurrentCookedState.cookedPointerData.pointerCoords,
2015 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2016 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2017 }
2018}
2019
2020void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2021 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2022 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2023 const int32_t metaState = getContext()->getGlobalMetaState();
2024 int32_t buttonState = mLastCookedState.buttonState;
2025 while (!pressedButtons.isEmpty()) {
2026 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2027 buttonState |= actionButton;
2028 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2029 0, metaState, buttonState, 0,
2030 mCurrentCookedState.cookedPointerData.pointerProperties,
2031 mCurrentCookedState.cookedPointerData.pointerCoords,
2032 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2033 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2034 }
2035}
2036
2037const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2038 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2039 return cookedPointerData.touchingIdBits;
2040 }
2041 return cookedPointerData.hoveringIdBits;
2042}
2043
2044void TouchInputMapper::cookPointerData() {
2045 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2046
2047 mCurrentCookedState.cookedPointerData.clear();
2048 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2049 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2050 mCurrentRawState.rawPointerData.hoveringIdBits;
2051 mCurrentCookedState.cookedPointerData.touchingIdBits =
2052 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002053 mCurrentCookedState.cookedPointerData.canceledIdBits =
2054 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002055
2056 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2057 mCurrentCookedState.buttonState = 0;
2058 } else {
2059 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2060 }
2061
2062 // Walk through the the active pointers and map device coordinates onto
2063 // surface coordinates and adjust for display orientation.
2064 for (uint32_t i = 0; i < currentPointerCount; i++) {
2065 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2066
2067 // Size
2068 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2069 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002070 case Calibration::SizeCalibration::GEOMETRIC:
2071 case Calibration::SizeCalibration::DIAMETER:
2072 case Calibration::SizeCalibration::BOX:
2073 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002074 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2075 touchMajor = in.touchMajor;
2076 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2077 toolMajor = in.toolMajor;
2078 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2079 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2080 : in.touchMajor;
2081 } else if (mRawPointerAxes.touchMajor.valid) {
2082 toolMajor = touchMajor = in.touchMajor;
2083 toolMinor = touchMinor =
2084 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2085 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2086 : in.touchMajor;
2087 } else if (mRawPointerAxes.toolMajor.valid) {
2088 touchMajor = toolMajor = in.toolMajor;
2089 touchMinor = toolMinor =
2090 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2091 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2092 : in.toolMajor;
2093 } else {
2094 ALOG_ASSERT(false,
2095 "No touch or tool axes. "
2096 "Size calibration should have been resolved to NONE.");
2097 touchMajor = 0;
2098 touchMinor = 0;
2099 toolMajor = 0;
2100 toolMinor = 0;
2101 size = 0;
2102 }
2103
2104 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2105 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2106 if (touchingCount > 1) {
2107 touchMajor /= touchingCount;
2108 touchMinor /= touchingCount;
2109 toolMajor /= touchingCount;
2110 toolMinor /= touchingCount;
2111 size /= touchingCount;
2112 }
2113 }
2114
Michael Wright227c5542020-07-02 18:30:52 +01002115 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002116 touchMajor *= mGeometricScale;
2117 touchMinor *= mGeometricScale;
2118 toolMajor *= mGeometricScale;
2119 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002120 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002121 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2122 touchMinor = touchMajor;
2123 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2124 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002125 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002126 touchMinor = touchMajor;
2127 toolMinor = toolMajor;
2128 }
2129
2130 mCalibration.applySizeScaleAndBias(&touchMajor);
2131 mCalibration.applySizeScaleAndBias(&touchMinor);
2132 mCalibration.applySizeScaleAndBias(&toolMajor);
2133 mCalibration.applySizeScaleAndBias(&toolMinor);
2134 size *= mSizeScale;
2135 break;
2136 default:
2137 touchMajor = 0;
2138 touchMinor = 0;
2139 toolMajor = 0;
2140 toolMinor = 0;
2141 size = 0;
2142 break;
2143 }
2144
2145 // Pressure
2146 float pressure;
2147 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002148 case Calibration::PressureCalibration::PHYSICAL:
2149 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002150 pressure = in.pressure * mPressureScale;
2151 break;
2152 default:
2153 pressure = in.isHovering ? 0 : 1;
2154 break;
2155 }
2156
2157 // Tilt and Orientation
2158 float tilt;
2159 float orientation;
2160 if (mHaveTilt) {
2161 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2162 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2163 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2164 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2165 } else {
2166 tilt = 0;
2167
2168 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002169 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002170 orientation = in.orientation * mOrientationScale;
2171 break;
Michael Wright227c5542020-07-02 18:30:52 +01002172 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002173 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2174 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2175 if (c1 != 0 || c2 != 0) {
2176 orientation = atan2f(c1, c2) * 0.5f;
2177 float confidence = hypotf(c1, c2);
2178 float scale = 1.0f + confidence / 16.0f;
2179 touchMajor *= scale;
2180 touchMinor /= scale;
2181 toolMajor *= scale;
2182 toolMinor /= scale;
2183 } else {
2184 orientation = 0;
2185 }
2186 break;
2187 }
2188 default:
2189 orientation = 0;
2190 }
2191 }
2192
2193 // Distance
2194 float distance;
2195 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002196 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002197 distance = in.distance * mDistanceScale;
2198 break;
2199 default:
2200 distance = 0;
2201 }
2202
2203 // Coverage
2204 int32_t rawLeft, rawTop, rawRight, rawBottom;
2205 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002206 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002207 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2208 rawRight = in.toolMinor & 0x0000ffff;
2209 rawBottom = in.toolMajor & 0x0000ffff;
2210 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2211 break;
2212 default:
2213 rawLeft = rawTop = rawRight = rawBottom = 0;
2214 break;
2215 }
2216
2217 // Adjust X,Y coords for device calibration
2218 // TODO: Adjust coverage coords?
2219 float xTransformed = in.x, yTransformed = in.y;
2220 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002221 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002222
2223 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002224 float left, top, right, bottom;
2225
2226 switch (mSurfaceOrientation) {
2227 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002228 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2229 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2230 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2231 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2232 orientation -= M_PI_2;
2233 if (mOrientedRanges.haveOrientation &&
2234 orientation < mOrientedRanges.orientation.min) {
2235 orientation +=
2236 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2237 }
2238 break;
2239 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002240 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2241 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2242 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2243 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2244 orientation -= M_PI;
2245 if (mOrientedRanges.haveOrientation &&
2246 orientation < mOrientedRanges.orientation.min) {
2247 orientation +=
2248 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2249 }
2250 break;
2251 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002252 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2253 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2254 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2255 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2256 orientation += M_PI_2;
2257 if (mOrientedRanges.haveOrientation &&
2258 orientation > mOrientedRanges.orientation.max) {
2259 orientation -=
2260 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2261 }
2262 break;
2263 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002264 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2265 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2266 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2267 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2268 break;
2269 }
2270
2271 // Write output coords.
2272 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2273 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002274 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2275 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002276 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2277 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2278 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2279 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2280 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2281 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2282 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002283 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002284 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2285 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2286 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2287 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2288 } else {
2289 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2290 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2291 }
2292
Chris Ye364fdb52020-08-05 15:07:56 -07002293 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002294 uint32_t id = in.id;
2295 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2296 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2297 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2298 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2299 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2300 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2301 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2302 }
2303
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002304 // Write output properties.
2305 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002306 properties.clear();
2307 properties.id = id;
2308 properties.toolType = in.toolType;
2309
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002310 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002311 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002312 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002313 }
2314}
2315
2316void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2317 PointerUsage pointerUsage) {
2318 if (pointerUsage != mPointerUsage) {
2319 abortPointerUsage(when, policyFlags);
2320 mPointerUsage = pointerUsage;
2321 }
2322
2323 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002324 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002325 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2326 break;
Michael Wright227c5542020-07-02 18:30:52 +01002327 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002328 dispatchPointerStylus(when, policyFlags);
2329 break;
Michael Wright227c5542020-07-02 18:30:52 +01002330 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002331 dispatchPointerMouse(when, policyFlags);
2332 break;
Michael Wright227c5542020-07-02 18:30:52 +01002333 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002334 break;
2335 }
2336}
2337
2338void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2339 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002340 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002341 abortPointerGestures(when, policyFlags);
2342 break;
Michael Wright227c5542020-07-02 18:30:52 +01002343 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344 abortPointerStylus(when, policyFlags);
2345 break;
Michael Wright227c5542020-07-02 18:30:52 +01002346 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347 abortPointerMouse(when, policyFlags);
2348 break;
Michael Wright227c5542020-07-02 18:30:52 +01002349 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002350 break;
2351 }
2352
Michael Wright227c5542020-07-02 18:30:52 +01002353 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354}
2355
2356void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2357 // Update current gesture coordinates.
2358 bool cancelPreviousGesture, finishPreviousGesture;
2359 bool sendEvents =
2360 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2361 if (!sendEvents) {
2362 return;
2363 }
2364 if (finishPreviousGesture) {
2365 cancelPreviousGesture = false;
2366 }
2367
2368 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002369 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002370 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002371 if (finishPreviousGesture || cancelPreviousGesture) {
2372 mPointerController->clearSpots();
2373 }
2374
Michael Wright227c5542020-07-02 18:30:52 +01002375 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002376 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2377 mPointerGesture.currentGestureIdToIndex,
2378 mPointerGesture.currentGestureIdBits,
2379 mPointerController->getDisplayId());
2380 }
2381 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002382 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383 }
2384
2385 // Show or hide the pointer if needed.
2386 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002387 case PointerGesture::Mode::NEUTRAL:
2388 case PointerGesture::Mode::QUIET:
2389 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2390 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002392 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002393 }
2394 break;
Michael Wright227c5542020-07-02 18:30:52 +01002395 case PointerGesture::Mode::TAP:
2396 case PointerGesture::Mode::TAP_DRAG:
2397 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2398 case PointerGesture::Mode::HOVER:
2399 case PointerGesture::Mode::PRESS:
2400 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002401 // Unfade the pointer when the current gesture manipulates the
2402 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002403 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 break;
Michael Wright227c5542020-07-02 18:30:52 +01002405 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406 // Fade the pointer when the current gesture manipulates a different
2407 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002408 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002409 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002411 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002412 }
2413 break;
2414 }
2415
2416 // Send events!
2417 int32_t metaState = getContext()->getGlobalMetaState();
2418 int32_t buttonState = mCurrentCookedState.buttonState;
2419
2420 // Update last coordinates of pointers that have moved so that we observe the new
2421 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002422 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2423 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2424 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2425 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2426 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2427 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002428 bool moveNeeded = false;
2429 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2430 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2431 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2432 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2433 mPointerGesture.lastGestureIdBits.value);
2434 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2435 mPointerGesture.currentGestureCoords,
2436 mPointerGesture.currentGestureIdToIndex,
2437 mPointerGesture.lastGestureProperties,
2438 mPointerGesture.lastGestureCoords,
2439 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2440 if (buttonState != mLastCookedState.buttonState) {
2441 moveNeeded = true;
2442 }
2443 }
2444
2445 // Send motion events for all pointers that went up or were canceled.
2446 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2447 if (!dispatchedGestureIdBits.isEmpty()) {
2448 if (cancelPreviousGesture) {
2449 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2450 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2451 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2452 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2453 mPointerGesture.downTime);
2454
2455 dispatchedGestureIdBits.clear();
2456 } else {
2457 BitSet32 upGestureIdBits;
2458 if (finishPreviousGesture) {
2459 upGestureIdBits = dispatchedGestureIdBits;
2460 } else {
2461 upGestureIdBits.value =
2462 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2463 }
2464 while (!upGestureIdBits.isEmpty()) {
2465 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2466
2467 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2468 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2469 mPointerGesture.lastGestureProperties,
2470 mPointerGesture.lastGestureCoords,
2471 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2472 0, mPointerGesture.downTime);
2473
2474 dispatchedGestureIdBits.clearBit(id);
2475 }
2476 }
2477 }
2478
2479 // Send motion events for all pointers that moved.
2480 if (moveNeeded) {
2481 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2482 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2483 mPointerGesture.currentGestureProperties,
2484 mPointerGesture.currentGestureCoords,
2485 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2486 mPointerGesture.downTime);
2487 }
2488
2489 // Send motion events for all pointers that went down.
2490 if (down) {
2491 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2492 ~dispatchedGestureIdBits.value);
2493 while (!downGestureIdBits.isEmpty()) {
2494 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2495 dispatchedGestureIdBits.markBit(id);
2496
2497 if (dispatchedGestureIdBits.count() == 1) {
2498 mPointerGesture.downTime = when;
2499 }
2500
2501 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2502 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2503 mPointerGesture.currentGestureCoords,
2504 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2505 0, mPointerGesture.downTime);
2506 }
2507 }
2508
2509 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002510 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002511 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2512 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2513 mPointerGesture.currentGestureProperties,
2514 mPointerGesture.currentGestureCoords,
2515 mPointerGesture.currentGestureIdToIndex,
2516 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2517 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2518 // Synthesize a hover move event after all pointers go up to indicate that
2519 // the pointer is hovering again even if the user is not currently touching
2520 // the touch pad. This ensures that a view will receive a fresh hover enter
2521 // event after a tap.
2522 float x, y;
2523 mPointerController->getPosition(&x, &y);
2524
2525 PointerProperties pointerProperties;
2526 pointerProperties.clear();
2527 pointerProperties.id = 0;
2528 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2529
2530 PointerCoords pointerCoords;
2531 pointerCoords.clear();
2532 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2533 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2534
2535 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002536 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2537 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2538 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2539 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2540 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002541 getListener()->notifyMotion(&args);
2542 }
2543
2544 // Update state.
2545 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2546 if (!down) {
2547 mPointerGesture.lastGestureIdBits.clear();
2548 } else {
2549 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2550 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2551 uint32_t id = idBits.clearFirstMarkedBit();
2552 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2553 mPointerGesture.lastGestureProperties[index].copyFrom(
2554 mPointerGesture.currentGestureProperties[index]);
2555 mPointerGesture.lastGestureCoords[index].copyFrom(
2556 mPointerGesture.currentGestureCoords[index]);
2557 mPointerGesture.lastGestureIdToIndex[id] = index;
2558 }
2559 }
2560}
2561
2562void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2563 // Cancel previously dispatches pointers.
2564 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2565 int32_t metaState = getContext()->getGlobalMetaState();
2566 int32_t buttonState = mCurrentRawState.buttonState;
2567 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2568 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2569 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2570 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2571 0, 0, mPointerGesture.downTime);
2572 }
2573
2574 // Reset the current pointer gesture.
2575 mPointerGesture.reset();
2576 mPointerVelocityControl.reset();
2577
2578 // Remove any current spots.
2579 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002580 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002581 mPointerController->clearSpots();
2582 }
2583}
2584
2585bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2586 bool* outFinishPreviousGesture, bool isTimeout) {
2587 *outCancelPreviousGesture = false;
2588 *outFinishPreviousGesture = false;
2589
2590 // Handle TAP timeout.
2591 if (isTimeout) {
2592#if DEBUG_GESTURES
2593 ALOGD("Gestures: Processing timeout");
2594#endif
2595
Michael Wright227c5542020-07-02 18:30:52 +01002596 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002597 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2598 // The tap/drag timeout has not yet expired.
2599 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2600 mConfig.pointerGestureTapDragInterval);
2601 } else {
2602 // The tap is finished.
2603#if DEBUG_GESTURES
2604 ALOGD("Gestures: TAP finished");
2605#endif
2606 *outFinishPreviousGesture = true;
2607
2608 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002609 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002610 mPointerGesture.currentGestureIdBits.clear();
2611
2612 mPointerVelocityControl.reset();
2613 return true;
2614 }
2615 }
2616
2617 // We did not handle this timeout.
2618 return false;
2619 }
2620
2621 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2622 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2623
2624 // Update the velocity tracker.
2625 {
2626 VelocityTracker::Position positions[MAX_POINTERS];
2627 uint32_t count = 0;
2628 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
2629 uint32_t id = idBits.clearFirstMarkedBit();
2630 const RawPointerData::Pointer& pointer =
2631 mCurrentRawState.rawPointerData.pointerForId(id);
2632 positions[count].x = pointer.x * mPointerXMovementScale;
2633 positions[count].y = pointer.y * mPointerYMovementScale;
2634 }
2635 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2636 positions);
2637 }
2638
2639 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2640 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002641 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2642 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2643 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002644 mPointerGesture.resetTap();
2645 }
2646
2647 // Pick a new active touch id if needed.
2648 // Choose an arbitrary pointer that just went down, if there is one.
2649 // Otherwise choose an arbitrary remaining pointer.
2650 // This guarantees we always have an active touch id when there is at least one pointer.
2651 // We keep the same active touch id for as long as possible.
2652 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2653 int32_t activeTouchId = lastActiveTouchId;
2654 if (activeTouchId < 0) {
2655 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2656 activeTouchId = mPointerGesture.activeTouchId =
2657 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2658 mPointerGesture.firstTouchTime = when;
2659 }
2660 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2661 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2662 activeTouchId = mPointerGesture.activeTouchId =
2663 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2664 } else {
2665 activeTouchId = mPointerGesture.activeTouchId = -1;
2666 }
2667 }
2668
2669 // Determine whether we are in quiet time.
2670 bool isQuietTime = false;
2671 if (activeTouchId < 0) {
2672 mPointerGesture.resetQuietTime();
2673 } else {
2674 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2675 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002676 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2677 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2678 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002679 currentFingerCount < 2) {
2680 // Enter quiet time when exiting swipe or freeform state.
2681 // This is to prevent accidentally entering the hover state and flinging the
2682 // pointer when finishing a swipe and there is still one pointer left onscreen.
2683 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002684 } else if (mPointerGesture.lastGestureMode ==
2685 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002686 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2687 // Enter quiet time when releasing the button and there are still two or more
2688 // fingers down. This may indicate that one finger was used to press the button
2689 // but it has not gone up yet.
2690 isQuietTime = true;
2691 }
2692 if (isQuietTime) {
2693 mPointerGesture.quietTime = when;
2694 }
2695 }
2696 }
2697
2698 // Switch states based on button and pointer state.
2699 if (isQuietTime) {
2700 // Case 1: Quiet time. (QUIET)
2701#if DEBUG_GESTURES
2702 ALOGD("Gestures: QUIET for next %0.3fms",
2703 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2704#endif
Michael Wright227c5542020-07-02 18:30:52 +01002705 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002706 *outFinishPreviousGesture = true;
2707 }
2708
2709 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002710 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002711 mPointerGesture.currentGestureIdBits.clear();
2712
2713 mPointerVelocityControl.reset();
2714 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2715 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2716 // The pointer follows the active touch point.
2717 // Emit DOWN, MOVE, UP events at the pointer location.
2718 //
2719 // Only the active touch matters; other fingers are ignored. This policy helps
2720 // to handle the case where the user places a second finger on the touch pad
2721 // to apply the necessary force to depress an integrated button below the surface.
2722 // We don't want the second finger to be delivered to applications.
2723 //
2724 // For this to work well, we need to make sure to track the pointer that is really
2725 // active. If the user first puts one finger down to click then adds another
2726 // finger to drag then the active pointer should switch to the finger that is
2727 // being dragged.
2728#if DEBUG_GESTURES
2729 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2730 "currentFingerCount=%d",
2731 activeTouchId, currentFingerCount);
2732#endif
2733 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002734 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002735 *outFinishPreviousGesture = true;
2736 mPointerGesture.activeGestureId = 0;
2737 }
2738
2739 // Switch pointers if needed.
2740 // Find the fastest pointer and follow it.
2741 if (activeTouchId >= 0 && currentFingerCount > 1) {
2742 int32_t bestId = -1;
2743 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2744 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2745 uint32_t id = idBits.clearFirstMarkedBit();
2746 float vx, vy;
2747 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2748 float speed = hypotf(vx, vy);
2749 if (speed > bestSpeed) {
2750 bestId = id;
2751 bestSpeed = speed;
2752 }
2753 }
2754 }
2755 if (bestId >= 0 && bestId != activeTouchId) {
2756 mPointerGesture.activeTouchId = activeTouchId = bestId;
2757#if DEBUG_GESTURES
2758 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2759 "bestId=%d, bestSpeed=%0.3f",
2760 bestId, bestSpeed);
2761#endif
2762 }
2763 }
2764
2765 float deltaX = 0, deltaY = 0;
2766 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2767 const RawPointerData::Pointer& currentPointer =
2768 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2769 const RawPointerData::Pointer& lastPointer =
2770 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2771 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2772 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2773
2774 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2775 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2776
2777 // Move the pointer using a relative motion.
2778 // When using spots, the click will occur at the position of the anchor
2779 // spot and all other spots will move there.
2780 mPointerController->move(deltaX, deltaY);
2781 } else {
2782 mPointerVelocityControl.reset();
2783 }
2784
2785 float x, y;
2786 mPointerController->getPosition(&x, &y);
2787
Michael Wright227c5542020-07-02 18:30:52 +01002788 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002789 mPointerGesture.currentGestureIdBits.clear();
2790 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2791 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2792 mPointerGesture.currentGestureProperties[0].clear();
2793 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2794 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2795 mPointerGesture.currentGestureCoords[0].clear();
2796 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2797 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2798 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2799 } else if (currentFingerCount == 0) {
2800 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002801 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002802 *outFinishPreviousGesture = true;
2803 }
2804
2805 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2806 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2807 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002808 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2809 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002810 lastFingerCount == 1) {
2811 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2812 float x, y;
2813 mPointerController->getPosition(&x, &y);
2814 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2815 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2816#if DEBUG_GESTURES
2817 ALOGD("Gestures: TAP");
2818#endif
2819
2820 mPointerGesture.tapUpTime = when;
2821 getContext()->requestTimeoutAtTime(when +
2822 mConfig.pointerGestureTapDragInterval);
2823
2824 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002825 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002826 mPointerGesture.currentGestureIdBits.clear();
2827 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2828 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2829 mPointerGesture.currentGestureProperties[0].clear();
2830 mPointerGesture.currentGestureProperties[0].id =
2831 mPointerGesture.activeGestureId;
2832 mPointerGesture.currentGestureProperties[0].toolType =
2833 AMOTION_EVENT_TOOL_TYPE_FINGER;
2834 mPointerGesture.currentGestureCoords[0].clear();
2835 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2836 mPointerGesture.tapX);
2837 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2838 mPointerGesture.tapY);
2839 mPointerGesture.currentGestureCoords[0]
2840 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2841
2842 tapped = true;
2843 } else {
2844#if DEBUG_GESTURES
2845 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2846 y - mPointerGesture.tapY);
2847#endif
2848 }
2849 } else {
2850#if DEBUG_GESTURES
2851 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2852 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2853 (when - mPointerGesture.tapDownTime) * 0.000001f);
2854 } else {
2855 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2856 }
2857#endif
2858 }
2859 }
2860
2861 mPointerVelocityControl.reset();
2862
2863 if (!tapped) {
2864#if DEBUG_GESTURES
2865 ALOGD("Gestures: NEUTRAL");
2866#endif
2867 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002868 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002869 mPointerGesture.currentGestureIdBits.clear();
2870 }
2871 } else if (currentFingerCount == 1) {
2872 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2873 // The pointer follows the active touch point.
2874 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2875 // When in TAP_DRAG, emit MOVE events at the pointer location.
2876 ALOG_ASSERT(activeTouchId >= 0);
2877
Michael Wright227c5542020-07-02 18:30:52 +01002878 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2879 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002880 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2881 float x, y;
2882 mPointerController->getPosition(&x, &y);
2883 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2884 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002885 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002886 } else {
2887#if DEBUG_GESTURES
2888 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2889 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2890#endif
2891 }
2892 } else {
2893#if DEBUG_GESTURES
2894 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2895 (when - mPointerGesture.tapUpTime) * 0.000001f);
2896#endif
2897 }
Michael Wright227c5542020-07-02 18:30:52 +01002898 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2899 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002900 }
2901
2902 float deltaX = 0, deltaY = 0;
2903 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2904 const RawPointerData::Pointer& currentPointer =
2905 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2906 const RawPointerData::Pointer& lastPointer =
2907 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2908 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2909 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2910
2911 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2912 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2913
2914 // Move the pointer using a relative motion.
2915 // When using spots, the hover or drag will occur at the position of the anchor spot.
2916 mPointerController->move(deltaX, deltaY);
2917 } else {
2918 mPointerVelocityControl.reset();
2919 }
2920
2921 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002922 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002923#if DEBUG_GESTURES
2924 ALOGD("Gestures: TAP_DRAG");
2925#endif
2926 down = true;
2927 } else {
2928#if DEBUG_GESTURES
2929 ALOGD("Gestures: HOVER");
2930#endif
Michael Wright227c5542020-07-02 18:30:52 +01002931 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002932 *outFinishPreviousGesture = true;
2933 }
2934 mPointerGesture.activeGestureId = 0;
2935 down = false;
2936 }
2937
2938 float x, y;
2939 mPointerController->getPosition(&x, &y);
2940
2941 mPointerGesture.currentGestureIdBits.clear();
2942 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2943 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2944 mPointerGesture.currentGestureProperties[0].clear();
2945 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2946 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2947 mPointerGesture.currentGestureCoords[0].clear();
2948 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2949 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2950 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2951 down ? 1.0f : 0.0f);
2952
2953 if (lastFingerCount == 0 && currentFingerCount != 0) {
2954 mPointerGesture.resetTap();
2955 mPointerGesture.tapDownTime = when;
2956 mPointerGesture.tapX = x;
2957 mPointerGesture.tapY = y;
2958 }
2959 } else {
2960 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2961 // We need to provide feedback for each finger that goes down so we cannot wait
2962 // for the fingers to move before deciding what to do.
2963 //
2964 // The ambiguous case is deciding what to do when there are two fingers down but they
2965 // have not moved enough to determine whether they are part of a drag or part of a
2966 // freeform gesture, or just a press or long-press at the pointer location.
2967 //
2968 // When there are two fingers we start with the PRESS hypothesis and we generate a
2969 // down at the pointer location.
2970 //
2971 // When the two fingers move enough or when additional fingers are added, we make
2972 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2973 ALOG_ASSERT(activeTouchId >= 0);
2974
2975 bool settled = when >=
2976 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002977 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2978 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2979 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002980 *outFinishPreviousGesture = true;
2981 } else if (!settled && currentFingerCount > lastFingerCount) {
2982 // Additional pointers have gone down but not yet settled.
2983 // Reset the gesture.
2984#if DEBUG_GESTURES
2985 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2986 "settle time remaining %0.3fms",
2987 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2988 when) * 0.000001f);
2989#endif
2990 *outCancelPreviousGesture = true;
2991 } else {
2992 // Continue previous gesture.
2993 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2994 }
2995
2996 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01002997 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002998 mPointerGesture.activeGestureId = 0;
2999 mPointerGesture.referenceIdBits.clear();
3000 mPointerVelocityControl.reset();
3001
3002 // Use the centroid and pointer location as the reference points for the gesture.
3003#if DEBUG_GESTURES
3004 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3005 "settle time remaining %0.3fms",
3006 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3007 when) * 0.000001f);
3008#endif
3009 mCurrentRawState.rawPointerData
3010 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3011 &mPointerGesture.referenceTouchY);
3012 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3013 &mPointerGesture.referenceGestureY);
3014 }
3015
3016 // Clear the reference deltas for fingers not yet included in the reference calculation.
3017 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3018 ~mPointerGesture.referenceIdBits.value);
3019 !idBits.isEmpty();) {
3020 uint32_t id = idBits.clearFirstMarkedBit();
3021 mPointerGesture.referenceDeltas[id].dx = 0;
3022 mPointerGesture.referenceDeltas[id].dy = 0;
3023 }
3024 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3025
3026 // Add delta for all fingers and calculate a common movement delta.
3027 float commonDeltaX = 0, commonDeltaY = 0;
3028 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3029 mCurrentCookedState.fingerIdBits.value);
3030 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3031 bool first = (idBits == commonIdBits);
3032 uint32_t id = idBits.clearFirstMarkedBit();
3033 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3034 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3035 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3036 delta.dx += cpd.x - lpd.x;
3037 delta.dy += cpd.y - lpd.y;
3038
3039 if (first) {
3040 commonDeltaX = delta.dx;
3041 commonDeltaY = delta.dy;
3042 } else {
3043 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3044 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3045 }
3046 }
3047
3048 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003049 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003050 float dist[MAX_POINTER_ID + 1];
3051 int32_t distOverThreshold = 0;
3052 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3053 uint32_t id = idBits.clearFirstMarkedBit();
3054 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3055 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3056 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3057 distOverThreshold += 1;
3058 }
3059 }
3060
3061 // Only transition when at least two pointers have moved further than
3062 // the minimum distance threshold.
3063 if (distOverThreshold >= 2) {
3064 if (currentFingerCount > 2) {
3065 // There are more than two pointers, switch to FREEFORM.
3066#if DEBUG_GESTURES
3067 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3068 currentFingerCount);
3069#endif
3070 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003071 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003072 } else {
3073 // There are exactly two pointers.
3074 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3075 uint32_t id1 = idBits.clearFirstMarkedBit();
3076 uint32_t id2 = idBits.firstMarkedBit();
3077 const RawPointerData::Pointer& p1 =
3078 mCurrentRawState.rawPointerData.pointerForId(id1);
3079 const RawPointerData::Pointer& p2 =
3080 mCurrentRawState.rawPointerData.pointerForId(id2);
3081 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3082 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3083 // There are two pointers but they are too far apart for a SWIPE,
3084 // switch to FREEFORM.
3085#if DEBUG_GESTURES
3086 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3087 mutualDistance, mPointerGestureMaxSwipeWidth);
3088#endif
3089 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003090 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003091 } else {
3092 // There are two pointers. Wait for both pointers to start moving
3093 // before deciding whether this is a SWIPE or FREEFORM gesture.
3094 float dist1 = dist[id1];
3095 float dist2 = dist[id2];
3096 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3097 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3098 // Calculate the dot product of the displacement vectors.
3099 // When the vectors are oriented in approximately the same direction,
3100 // the angle betweeen them is near zero and the cosine of the angle
3101 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3102 // mag(v2).
3103 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3104 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3105 float dx1 = delta1.dx * mPointerXZoomScale;
3106 float dy1 = delta1.dy * mPointerYZoomScale;
3107 float dx2 = delta2.dx * mPointerXZoomScale;
3108 float dy2 = delta2.dy * mPointerYZoomScale;
3109 float dot = dx1 * dx2 + dy1 * dy2;
3110 float cosine = dot / (dist1 * dist2); // denominator always > 0
3111 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3112 // Pointers are moving in the same direction. Switch to SWIPE.
3113#if DEBUG_GESTURES
3114 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3115 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3116 "cosine %0.3f >= %0.3f",
3117 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3118 mConfig.pointerGestureMultitouchMinDistance, cosine,
3119 mConfig.pointerGestureSwipeTransitionAngleCosine);
3120#endif
Michael Wright227c5542020-07-02 18:30:52 +01003121 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003122 } else {
3123 // Pointers are moving in different directions. Switch to FREEFORM.
3124#if DEBUG_GESTURES
3125 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3126 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3127 "cosine %0.3f < %0.3f",
3128 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3129 mConfig.pointerGestureMultitouchMinDistance, cosine,
3130 mConfig.pointerGestureSwipeTransitionAngleCosine);
3131#endif
3132 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003133 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003134 }
3135 }
3136 }
3137 }
3138 }
Michael Wright227c5542020-07-02 18:30:52 +01003139 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003140 // Switch from SWIPE to FREEFORM if additional pointers go down.
3141 // Cancel previous gesture.
3142 if (currentFingerCount > 2) {
3143#if DEBUG_GESTURES
3144 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3145 currentFingerCount);
3146#endif
3147 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003148 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003149 }
3150 }
3151
3152 // Move the reference points based on the overall group motion of the fingers
3153 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003154 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003155 (commonDeltaX || commonDeltaY)) {
3156 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3157 uint32_t id = idBits.clearFirstMarkedBit();
3158 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3159 delta.dx = 0;
3160 delta.dy = 0;
3161 }
3162
3163 mPointerGesture.referenceTouchX += commonDeltaX;
3164 mPointerGesture.referenceTouchY += commonDeltaY;
3165
3166 commonDeltaX *= mPointerXMovementScale;
3167 commonDeltaY *= mPointerYMovementScale;
3168
3169 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3170 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3171
3172 mPointerGesture.referenceGestureX += commonDeltaX;
3173 mPointerGesture.referenceGestureY += commonDeltaY;
3174 }
3175
3176 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003177 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3178 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003179 // PRESS or SWIPE mode.
3180#if DEBUG_GESTURES
3181 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3182 "activeGestureId=%d, currentTouchPointerCount=%d",
3183 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3184#endif
3185 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3186
3187 mPointerGesture.currentGestureIdBits.clear();
3188 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3189 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3190 mPointerGesture.currentGestureProperties[0].clear();
3191 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3192 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3193 mPointerGesture.currentGestureCoords[0].clear();
3194 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3195 mPointerGesture.referenceGestureX);
3196 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3197 mPointerGesture.referenceGestureY);
3198 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003199 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003200 // FREEFORM mode.
3201#if DEBUG_GESTURES
3202 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3203 "activeGestureId=%d, currentTouchPointerCount=%d",
3204 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3205#endif
3206 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3207
3208 mPointerGesture.currentGestureIdBits.clear();
3209
3210 BitSet32 mappedTouchIdBits;
3211 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003212 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003213 // Initially, assign the active gesture id to the active touch point
3214 // if there is one. No other touch id bits are mapped yet.
3215 if (!*outCancelPreviousGesture) {
3216 mappedTouchIdBits.markBit(activeTouchId);
3217 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3218 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3219 mPointerGesture.activeGestureId;
3220 } else {
3221 mPointerGesture.activeGestureId = -1;
3222 }
3223 } else {
3224 // Otherwise, assume we mapped all touches from the previous frame.
3225 // Reuse all mappings that are still applicable.
3226 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3227 mCurrentCookedState.fingerIdBits.value;
3228 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3229
3230 // Check whether we need to choose a new active gesture id because the
3231 // current went went up.
3232 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3233 ~mCurrentCookedState.fingerIdBits.value);
3234 !upTouchIdBits.isEmpty();) {
3235 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3236 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3237 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3238 mPointerGesture.activeGestureId = -1;
3239 break;
3240 }
3241 }
3242 }
3243
3244#if DEBUG_GESTURES
3245 ALOGD("Gestures: FREEFORM follow up "
3246 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3247 "activeGestureId=%d",
3248 mappedTouchIdBits.value, usedGestureIdBits.value,
3249 mPointerGesture.activeGestureId);
3250#endif
3251
3252 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3253 for (uint32_t i = 0; i < currentFingerCount; i++) {
3254 uint32_t touchId = idBits.clearFirstMarkedBit();
3255 uint32_t gestureId;
3256 if (!mappedTouchIdBits.hasBit(touchId)) {
3257 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3258 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3259#if DEBUG_GESTURES
3260 ALOGD("Gestures: FREEFORM "
3261 "new mapping for touch id %d -> gesture id %d",
3262 touchId, gestureId);
3263#endif
3264 } else {
3265 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3266#if DEBUG_GESTURES
3267 ALOGD("Gestures: FREEFORM "
3268 "existing mapping for touch id %d -> gesture id %d",
3269 touchId, gestureId);
3270#endif
3271 }
3272 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3273 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3274
3275 const RawPointerData::Pointer& pointer =
3276 mCurrentRawState.rawPointerData.pointerForId(touchId);
3277 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3278 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3279 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3280
3281 mPointerGesture.currentGestureProperties[i].clear();
3282 mPointerGesture.currentGestureProperties[i].id = gestureId;
3283 mPointerGesture.currentGestureProperties[i].toolType =
3284 AMOTION_EVENT_TOOL_TYPE_FINGER;
3285 mPointerGesture.currentGestureCoords[i].clear();
3286 mPointerGesture.currentGestureCoords[i]
3287 .setAxisValue(AMOTION_EVENT_AXIS_X,
3288 mPointerGesture.referenceGestureX + deltaX);
3289 mPointerGesture.currentGestureCoords[i]
3290 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3291 mPointerGesture.referenceGestureY + deltaY);
3292 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3293 1.0f);
3294 }
3295
3296 if (mPointerGesture.activeGestureId < 0) {
3297 mPointerGesture.activeGestureId =
3298 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3299#if DEBUG_GESTURES
3300 ALOGD("Gestures: FREEFORM new "
3301 "activeGestureId=%d",
3302 mPointerGesture.activeGestureId);
3303#endif
3304 }
3305 }
3306 }
3307
3308 mPointerController->setButtonState(mCurrentRawState.buttonState);
3309
3310#if DEBUG_GESTURES
3311 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3312 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3313 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3314 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3315 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3316 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3317 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3318 uint32_t id = idBits.clearFirstMarkedBit();
3319 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3320 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3321 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3322 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3323 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3324 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3325 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3326 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3327 }
3328 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3329 uint32_t id = idBits.clearFirstMarkedBit();
3330 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3331 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3332 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3333 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3334 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3335 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3336 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3337 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3338 }
3339#endif
3340 return true;
3341}
3342
3343void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3344 mPointerSimple.currentCoords.clear();
3345 mPointerSimple.currentProperties.clear();
3346
3347 bool down, hovering;
3348 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3349 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3350 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3351 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3352 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3353 mPointerController->setPosition(x, y);
3354
3355 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3356 down = !hovering;
3357
3358 mPointerController->getPosition(&x, &y);
3359 mPointerSimple.currentCoords.copyFrom(
3360 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3361 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3362 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3363 mPointerSimple.currentProperties.id = 0;
3364 mPointerSimple.currentProperties.toolType =
3365 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3366 } else {
3367 down = false;
3368 hovering = false;
3369 }
3370
3371 dispatchPointerSimple(when, policyFlags, down, hovering);
3372}
3373
3374void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3375 abortPointerSimple(when, policyFlags);
3376}
3377
3378void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3379 mPointerSimple.currentCoords.clear();
3380 mPointerSimple.currentProperties.clear();
3381
3382 bool down, hovering;
3383 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3384 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3385 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3386 float deltaX = 0, deltaY = 0;
3387 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3388 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3389 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3390 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3391 mPointerXMovementScale;
3392 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3393 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3394 mPointerYMovementScale;
3395
3396 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3397 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3398
3399 mPointerController->move(deltaX, deltaY);
3400 } else {
3401 mPointerVelocityControl.reset();
3402 }
3403
3404 down = isPointerDown(mCurrentRawState.buttonState);
3405 hovering = !down;
3406
3407 float x, y;
3408 mPointerController->getPosition(&x, &y);
3409 mPointerSimple.currentCoords.copyFrom(
3410 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3411 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3412 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3413 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3414 hovering ? 0.0f : 1.0f);
3415 mPointerSimple.currentProperties.id = 0;
3416 mPointerSimple.currentProperties.toolType =
3417 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3418 } else {
3419 mPointerVelocityControl.reset();
3420
3421 down = false;
3422 hovering = false;
3423 }
3424
3425 dispatchPointerSimple(when, policyFlags, down, hovering);
3426}
3427
3428void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3429 abortPointerSimple(when, policyFlags);
3430
3431 mPointerVelocityControl.reset();
3432}
3433
3434void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3435 bool hovering) {
3436 int32_t metaState = getContext()->getGlobalMetaState();
3437 int32_t displayId = mViewport.displayId;
3438
3439 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003440 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003441 mPointerController->clearSpots();
3442 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003443 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003444 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003445 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003446 }
3447 displayId = mPointerController->getDisplayId();
3448
3449 float xCursorPosition;
3450 float yCursorPosition;
3451 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3452
3453 if (mPointerSimple.down && !down) {
3454 mPointerSimple.down = false;
3455
3456 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003457 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3458 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003459 mLastRawState.buttonState, MotionClassification::NONE,
3460 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3461 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3462 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3463 /* videoFrames */ {});
3464 getListener()->notifyMotion(&args);
3465 }
3466
3467 if (mPointerSimple.hovering && !hovering) {
3468 mPointerSimple.hovering = false;
3469
3470 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003471 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3472 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3473 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003474 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3475 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3476 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3477 /* videoFrames */ {});
3478 getListener()->notifyMotion(&args);
3479 }
3480
3481 if (down) {
3482 if (!mPointerSimple.down) {
3483 mPointerSimple.down = true;
3484 mPointerSimple.downTime = when;
3485
3486 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003487 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003488 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3489 metaState, mCurrentRawState.buttonState,
3490 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3491 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3492 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3493 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3494 getListener()->notifyMotion(&args);
3495 }
3496
3497 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003498 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3499 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003500 mCurrentRawState.buttonState, MotionClassification::NONE,
3501 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3502 &mPointerSimple.currentCoords, mOrientedXPrecision,
3503 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3504 mPointerSimple.downTime, /* videoFrames */ {});
3505 getListener()->notifyMotion(&args);
3506 }
3507
3508 if (hovering) {
3509 if (!mPointerSimple.hovering) {
3510 mPointerSimple.hovering = true;
3511
3512 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003513 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003514 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3515 metaState, mCurrentRawState.buttonState,
3516 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3517 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3518 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3519 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3520 getListener()->notifyMotion(&args);
3521 }
3522
3523 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003524 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3525 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3526 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3528 &mPointerSimple.currentCoords, mOrientedXPrecision,
3529 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3530 mPointerSimple.downTime, /* videoFrames */ {});
3531 getListener()->notifyMotion(&args);
3532 }
3533
3534 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3535 float vscroll = mCurrentRawState.rawVScroll;
3536 float hscroll = mCurrentRawState.rawHScroll;
3537 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3538 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3539
3540 // Send scroll.
3541 PointerCoords pointerCoords;
3542 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3543 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3544 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3545
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003546 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3547 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003548 mCurrentRawState.buttonState, MotionClassification::NONE,
3549 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3550 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3551 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3552 /* videoFrames */ {});
3553 getListener()->notifyMotion(&args);
3554 }
3555
3556 // Save state.
3557 if (down || hovering) {
3558 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3559 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3560 } else {
3561 mPointerSimple.reset();
3562 }
3563}
3564
3565void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3566 mPointerSimple.currentCoords.clear();
3567 mPointerSimple.currentProperties.clear();
3568
3569 dispatchPointerSimple(when, policyFlags, false, false);
3570}
3571
3572void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3573 int32_t action, int32_t actionButton, int32_t flags,
3574 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3575 const PointerProperties* properties,
3576 const PointerCoords* coords, const uint32_t* idToIndex,
3577 BitSet32 idBits, int32_t changedId, float xPrecision,
3578 float yPrecision, nsecs_t downTime) {
3579 PointerCoords pointerCoords[MAX_POINTERS];
3580 PointerProperties pointerProperties[MAX_POINTERS];
3581 uint32_t pointerCount = 0;
3582 while (!idBits.isEmpty()) {
3583 uint32_t id = idBits.clearFirstMarkedBit();
3584 uint32_t index = idToIndex[id];
3585 pointerProperties[pointerCount].copyFrom(properties[index]);
3586 pointerCoords[pointerCount].copyFrom(coords[index]);
3587
3588 if (changedId >= 0 && id == uint32_t(changedId)) {
3589 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3590 }
3591
3592 pointerCount += 1;
3593 }
3594
3595 ALOG_ASSERT(pointerCount != 0);
3596
3597 if (changedId >= 0 && pointerCount == 1) {
3598 // Replace initial down and final up action.
3599 // We can compare the action without masking off the changed pointer index
3600 // because we know the index is 0.
3601 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3602 action = AMOTION_EVENT_ACTION_DOWN;
3603 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003604 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3605 action = AMOTION_EVENT_ACTION_CANCEL;
3606 } else {
3607 action = AMOTION_EVENT_ACTION_UP;
3608 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003609 } else {
3610 // Can't happen.
3611 ALOG_ASSERT(false);
3612 }
3613 }
3614 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3615 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003616 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003617 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3618 }
3619 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3620 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003621 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003622 std::for_each(frames.begin(), frames.end(),
3623 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003624 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3625 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003626 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3627 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3628 downTime, std::move(frames));
3629 getListener()->notifyMotion(&args);
3630}
3631
3632bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3633 const PointerCoords* inCoords,
3634 const uint32_t* inIdToIndex,
3635 PointerProperties* outProperties,
3636 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3637 BitSet32 idBits) const {
3638 bool changed = false;
3639 while (!idBits.isEmpty()) {
3640 uint32_t id = idBits.clearFirstMarkedBit();
3641 uint32_t inIndex = inIdToIndex[id];
3642 uint32_t outIndex = outIdToIndex[id];
3643
3644 const PointerProperties& curInProperties = inProperties[inIndex];
3645 const PointerCoords& curInCoords = inCoords[inIndex];
3646 PointerProperties& curOutProperties = outProperties[outIndex];
3647 PointerCoords& curOutCoords = outCoords[outIndex];
3648
3649 if (curInProperties != curOutProperties) {
3650 curOutProperties.copyFrom(curInProperties);
3651 changed = true;
3652 }
3653
3654 if (curInCoords != curOutCoords) {
3655 curOutCoords.copyFrom(curInCoords);
3656 changed = true;
3657 }
3658 }
3659 return changed;
3660}
3661
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003662void TouchInputMapper::cancelTouch(nsecs_t when) {
3663 abortPointerUsage(when, 0 /*policyFlags*/);
3664 abortTouches(when, 0 /* policyFlags*/);
3665}
3666
Arthur Hung4197f6b2020-03-16 15:39:59 +08003667// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003668void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003669 // Scale to surface coordinate.
3670 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3671 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3672
3673 // Rotate to surface coordinate.
3674 // 0 - no swap and reverse.
3675 // 90 - swap x/y and reverse y.
3676 // 180 - reverse x, y.
3677 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003678 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003679 case DISPLAY_ORIENTATION_0:
3680 x = xScaled + mXTranslate;
3681 y = yScaled + mYTranslate;
3682 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003683 case DISPLAY_ORIENTATION_90:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003684 y = mSurfaceRight - xScaled;
3685 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003686 break;
3687 case DISPLAY_ORIENTATION_180:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003688 x = mSurfaceRight - xScaled;
3689 y = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003690 break;
3691 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003692 y = xScaled + mXTranslate;
3693 x = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003694 break;
3695 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003696 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003697 }
3698}
3699
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003700bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003701 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3702 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3703
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003704 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003705 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003706 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003707 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003708}
3709
3710const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3711 for (const VirtualKey& virtualKey : mVirtualKeys) {
3712#if DEBUG_VIRTUAL_KEYS
3713 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3714 "left=%d, top=%d, right=%d, bottom=%d",
3715 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3716 virtualKey.hitRight, virtualKey.hitBottom);
3717#endif
3718
3719 if (virtualKey.isHit(x, y)) {
3720 return &virtualKey;
3721 }
3722 }
3723
3724 return nullptr;
3725}
3726
3727void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3728 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3729 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3730
3731 current->rawPointerData.clearIdBits();
3732
3733 if (currentPointerCount == 0) {
3734 // No pointers to assign.
3735 return;
3736 }
3737
3738 if (lastPointerCount == 0) {
3739 // All pointers are new.
3740 for (uint32_t i = 0; i < currentPointerCount; i++) {
3741 uint32_t id = i;
3742 current->rawPointerData.pointers[i].id = id;
3743 current->rawPointerData.idToIndex[id] = i;
3744 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3745 }
3746 return;
3747 }
3748
3749 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3750 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3751 // Only one pointer and no change in count so it must have the same id as before.
3752 uint32_t id = last->rawPointerData.pointers[0].id;
3753 current->rawPointerData.pointers[0].id = id;
3754 current->rawPointerData.idToIndex[id] = 0;
3755 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3756 return;
3757 }
3758
3759 // General case.
3760 // We build a heap of squared euclidean distances between current and last pointers
3761 // associated with the current and last pointer indices. Then, we find the best
3762 // match (by distance) for each current pointer.
3763 // The pointers must have the same tool type but it is possible for them to
3764 // transition from hovering to touching or vice-versa while retaining the same id.
3765 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3766
3767 uint32_t heapSize = 0;
3768 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3769 currentPointerIndex++) {
3770 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3771 lastPointerIndex++) {
3772 const RawPointerData::Pointer& currentPointer =
3773 current->rawPointerData.pointers[currentPointerIndex];
3774 const RawPointerData::Pointer& lastPointer =
3775 last->rawPointerData.pointers[lastPointerIndex];
3776 if (currentPointer.toolType == lastPointer.toolType) {
3777 int64_t deltaX = currentPointer.x - lastPointer.x;
3778 int64_t deltaY = currentPointer.y - lastPointer.y;
3779
3780 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3781
3782 // Insert new element into the heap (sift up).
3783 heap[heapSize].currentPointerIndex = currentPointerIndex;
3784 heap[heapSize].lastPointerIndex = lastPointerIndex;
3785 heap[heapSize].distance = distance;
3786 heapSize += 1;
3787 }
3788 }
3789 }
3790
3791 // Heapify
3792 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3793 startIndex -= 1;
3794 for (uint32_t parentIndex = startIndex;;) {
3795 uint32_t childIndex = parentIndex * 2 + 1;
3796 if (childIndex >= heapSize) {
3797 break;
3798 }
3799
3800 if (childIndex + 1 < heapSize &&
3801 heap[childIndex + 1].distance < heap[childIndex].distance) {
3802 childIndex += 1;
3803 }
3804
3805 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3806 break;
3807 }
3808
3809 swap(heap[parentIndex], heap[childIndex]);
3810 parentIndex = childIndex;
3811 }
3812 }
3813
3814#if DEBUG_POINTER_ASSIGNMENT
3815 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3816 for (size_t i = 0; i < heapSize; i++) {
3817 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3818 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3819 }
3820#endif
3821
3822 // Pull matches out by increasing order of distance.
3823 // To avoid reassigning pointers that have already been matched, the loop keeps track
3824 // of which last and current pointers have been matched using the matchedXXXBits variables.
3825 // It also tracks the used pointer id bits.
3826 BitSet32 matchedLastBits(0);
3827 BitSet32 matchedCurrentBits(0);
3828 BitSet32 usedIdBits(0);
3829 bool first = true;
3830 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3831 while (heapSize > 0) {
3832 if (first) {
3833 // The first time through the loop, we just consume the root element of
3834 // the heap (the one with smallest distance).
3835 first = false;
3836 } else {
3837 // Previous iterations consumed the root element of the heap.
3838 // Pop root element off of the heap (sift down).
3839 heap[0] = heap[heapSize];
3840 for (uint32_t parentIndex = 0;;) {
3841 uint32_t childIndex = parentIndex * 2 + 1;
3842 if (childIndex >= heapSize) {
3843 break;
3844 }
3845
3846 if (childIndex + 1 < heapSize &&
3847 heap[childIndex + 1].distance < heap[childIndex].distance) {
3848 childIndex += 1;
3849 }
3850
3851 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3852 break;
3853 }
3854
3855 swap(heap[parentIndex], heap[childIndex]);
3856 parentIndex = childIndex;
3857 }
3858
3859#if DEBUG_POINTER_ASSIGNMENT
3860 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003861 for (size_t j = 0; j < heapSize; j++) {
3862 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3863 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003864 }
3865#endif
3866 }
3867
3868 heapSize -= 1;
3869
3870 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3871 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3872
3873 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3874 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3875
3876 matchedCurrentBits.markBit(currentPointerIndex);
3877 matchedLastBits.markBit(lastPointerIndex);
3878
3879 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3880 current->rawPointerData.pointers[currentPointerIndex].id = id;
3881 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3882 current->rawPointerData.markIdBit(id,
3883 current->rawPointerData.isHovering(
3884 currentPointerIndex));
3885 usedIdBits.markBit(id);
3886
3887#if DEBUG_POINTER_ASSIGNMENT
3888 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3889 ", distance=%" PRIu64,
3890 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3891#endif
3892 break;
3893 }
3894 }
3895
3896 // Assign fresh ids to pointers that were not matched in the process.
3897 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3898 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3899 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3900
3901 current->rawPointerData.pointers[currentPointerIndex].id = id;
3902 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3903 current->rawPointerData.markIdBit(id,
3904 current->rawPointerData.isHovering(currentPointerIndex));
3905
3906#if DEBUG_POINTER_ASSIGNMENT
3907 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3908#endif
3909 }
3910}
3911
3912int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3913 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3914 return AKEY_STATE_VIRTUAL;
3915 }
3916
3917 for (const VirtualKey& virtualKey : mVirtualKeys) {
3918 if (virtualKey.keyCode == keyCode) {
3919 return AKEY_STATE_UP;
3920 }
3921 }
3922
3923 return AKEY_STATE_UNKNOWN;
3924}
3925
3926int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3927 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3928 return AKEY_STATE_VIRTUAL;
3929 }
3930
3931 for (const VirtualKey& virtualKey : mVirtualKeys) {
3932 if (virtualKey.scanCode == scanCode) {
3933 return AKEY_STATE_UP;
3934 }
3935 }
3936
3937 return AKEY_STATE_UNKNOWN;
3938}
3939
3940bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3941 const int32_t* keyCodes, uint8_t* outFlags) {
3942 for (const VirtualKey& virtualKey : mVirtualKeys) {
3943 for (size_t i = 0; i < numCodes; i++) {
3944 if (virtualKey.keyCode == keyCodes[i]) {
3945 outFlags[i] = 1;
3946 }
3947 }
3948 }
3949
3950 return true;
3951}
3952
3953std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3954 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003955 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003956 return std::make_optional(mPointerController->getDisplayId());
3957 } else {
3958 return std::make_optional(mViewport.displayId);
3959 }
3960 }
3961 return std::nullopt;
3962}
3963
3964} // namespace android