blob: afbec995527cf053ec667624cb42939565742541 [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),
173 mPhysicalWidth(-1),
174 mPhysicalHeight(-1),
175 mPhysicalLeft(0),
176 mPhysicalTop(0),
177 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
178
179TouchInputMapper::~TouchInputMapper() {}
180
181uint32_t TouchInputMapper::getSources() {
182 return mSource;
183}
184
185void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
186 InputMapper::populateDeviceInfo(info);
187
Michael Wright227c5542020-07-02 18:30:52 +0100188 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700189 info->addMotionRange(mOrientedRanges.x);
190 info->addMotionRange(mOrientedRanges.y);
191 info->addMotionRange(mOrientedRanges.pressure);
192
193 if (mOrientedRanges.haveSize) {
194 info->addMotionRange(mOrientedRanges.size);
195 }
196
197 if (mOrientedRanges.haveTouchSize) {
198 info->addMotionRange(mOrientedRanges.touchMajor);
199 info->addMotionRange(mOrientedRanges.touchMinor);
200 }
201
202 if (mOrientedRanges.haveToolSize) {
203 info->addMotionRange(mOrientedRanges.toolMajor);
204 info->addMotionRange(mOrientedRanges.toolMinor);
205 }
206
207 if (mOrientedRanges.haveOrientation) {
208 info->addMotionRange(mOrientedRanges.orientation);
209 }
210
211 if (mOrientedRanges.haveDistance) {
212 info->addMotionRange(mOrientedRanges.distance);
213 }
214
215 if (mOrientedRanges.haveTilt) {
216 info->addMotionRange(mOrientedRanges.tilt);
217 }
218
219 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
220 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
221 0.0f);
222 }
223 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
224 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
225 0.0f);
226 }
Michael Wright227c5542020-07-02 18:30:52 +0100227 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700228 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
229 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
230 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
231 x.fuzz, x.resolution);
232 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
233 y.fuzz, y.resolution);
234 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
235 x.fuzz, x.resolution);
236 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
237 y.fuzz, y.resolution);
238 }
239 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
240 }
241}
242
243void TouchInputMapper::dump(std::string& dump) {
244 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
245 dumpParameters(dump);
246 dumpVirtualKeys(dump);
247 dumpRawPointerAxes(dump);
248 dumpCalibration(dump);
249 dumpAffineTransformation(dump);
250 dumpSurface(dump);
251
252 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
253 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
254 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
255 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
256 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
257 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
258 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
259 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
260 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
261 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
262 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
263 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
264 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
265 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
266 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
267 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
268 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
269
270 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
271 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
272 mLastRawState.rawPointerData.pointerCount);
273 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
274 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
275 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
276 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
277 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
278 "toolType=%d, isHovering=%s\n",
279 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
280 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
281 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
282 pointer.distance, pointer.toolType, toString(pointer.isHovering));
283 }
284
285 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
286 mLastCookedState.buttonState);
287 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
288 mLastCookedState.cookedPointerData.pointerCount);
289 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
290 const PointerProperties& pointerProperties =
291 mLastCookedState.cookedPointerData.pointerProperties[i];
292 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000293 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
294 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
295 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700296 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
297 "toolType=%d, isHovering=%s\n",
298 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000299 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
300 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700301 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
302 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
303 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
304 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
305 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
306 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
307 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
308 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
309 pointerProperties.toolType,
310 toString(mLastCookedState.cookedPointerData.isHovering(i)));
311 }
312
313 dump += INDENT3 "Stylus Fusion:\n";
314 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
315 toString(mExternalStylusConnected));
316 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
317 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
318 mExternalStylusFusionTimeout);
319 dump += INDENT3 "External Stylus State:\n";
320 dumpStylusState(dump, mExternalStylusState);
321
Michael Wright227c5542020-07-02 18:30:52 +0100322 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700323 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
324 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
325 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
326 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
327 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
328 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
329 }
330}
331
332const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
333 switch (deviceMode) {
Michael Wright227c5542020-07-02 18:30:52 +0100334 case DeviceMode::DISABLED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700335 return "disabled";
Michael Wright227c5542020-07-02 18:30:52 +0100336 case DeviceMode::DIRECT:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337 return "direct";
Michael Wright227c5542020-07-02 18:30:52 +0100338 case DeviceMode::UNSCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700339 return "unscaled";
Michael Wright227c5542020-07-02 18:30:52 +0100340 case DeviceMode::NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 return "navigation";
Michael Wright227c5542020-07-02 18:30:52 +0100342 case DeviceMode::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700343 return "pointer";
344 }
345 return "unknown";
346}
347
348void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
349 uint32_t changes) {
350 InputMapper::configure(when, config, changes);
351
352 mConfig = *config;
353
354 if (!changes) { // first time only
355 // Configure basic parameters.
356 configureParameters();
357
358 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800359 mCursorScrollAccumulator.configure(getDeviceContext());
360 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700361
362 // Configure absolute axis information.
363 configureRawPointerAxes();
364
365 // Prepare input device calibration.
366 parseCalibration();
367 resolveCalibration();
368 }
369
370 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
371 // Update location calibration to reflect current settings
372 updateAffineTransformation();
373 }
374
375 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
376 // Update pointer speed.
377 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
378 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
379 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
380 }
381
382 bool resetNeeded = false;
383 if (!changes ||
384 (changes &
385 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800386 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700387 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
388 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
389 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
390 // Configure device sources, surface dimensions, orientation and
391 // scaling factors.
392 configureSurface(when, &resetNeeded);
393 }
394
395 if (changes && resetNeeded) {
396 // Send reset, unless this is the first time the device has been configured,
397 // in which case the reader will call reset itself after all mappers are ready.
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800398 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800399 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700400 }
401}
402
403void TouchInputMapper::resolveExternalStylusPresence() {
404 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800405 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700406 mExternalStylusConnected = !devices.empty();
407
408 if (!mExternalStylusConnected) {
409 resetExternalStylus();
410 }
411}
412
413void TouchInputMapper::configureParameters() {
414 // Use the pointer presentation mode for devices that do not support distinct
415 // multitouch. The spot-based presentation relies on being able to accurately
416 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800417 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100418 ? Parameters::GestureMode::SINGLE_TOUCH
419 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700420
421 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800422 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
423 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700424 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100425 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100427 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 } else if (gestureModeString != "default") {
429 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
430 }
431 }
432
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800433 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700434 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100435 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800436 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700437 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100438 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800439 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
440 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700441 // The device is a cursor device with a touch pad attached.
442 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100443 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700444 } else {
445 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100446 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700447 }
448
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800449 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700450
451 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800452 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
453 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700454 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100455 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100457 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100459 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100461 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700462 } else if (deviceTypeString != "default") {
463 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
464 }
465 }
466
Michael Wright227c5542020-07-02 18:30:52 +0100467 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800468 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
469 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700470
471 mParameters.hasAssociatedDisplay = false;
472 mParameters.associatedDisplayIsExternal = false;
473 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100474 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
475 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700476 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100477 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800478 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700479 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800480 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
481 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700482 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
483 }
484 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800485 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700486 mParameters.hasAssociatedDisplay = true;
487 }
488
489 // Initial downs on external touch devices should wake the device.
490 // Normally we don't do this for internal touch screens to prevent them from waking
491 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800492 mParameters.wake = getDeviceContext().isExternal();
493 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700494}
495
496void TouchInputMapper::dumpParameters(std::string& dump) {
497 dump += INDENT3 "Parameters:\n";
498
499 switch (mParameters.gestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +0100500 case Parameters::GestureMode::SINGLE_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700501 dump += INDENT4 "GestureMode: single-touch\n";
502 break;
Michael Wright227c5542020-07-02 18:30:52 +0100503 case Parameters::GestureMode::MULTI_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700504 dump += INDENT4 "GestureMode: multi-touch\n";
505 break;
506 default:
507 assert(false);
508 }
509
510 switch (mParameters.deviceType) {
Michael Wright227c5542020-07-02 18:30:52 +0100511 case Parameters::DeviceType::TOUCH_SCREEN:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700512 dump += INDENT4 "DeviceType: touchScreen\n";
513 break;
Michael Wright227c5542020-07-02 18:30:52 +0100514 case Parameters::DeviceType::TOUCH_PAD:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700515 dump += INDENT4 "DeviceType: touchPad\n";
516 break;
Michael Wright227c5542020-07-02 18:30:52 +0100517 case Parameters::DeviceType::TOUCH_NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700518 dump += INDENT4 "DeviceType: touchNavigation\n";
519 break;
Michael Wright227c5542020-07-02 18:30:52 +0100520 case Parameters::DeviceType::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700521 dump += INDENT4 "DeviceType: pointer\n";
522 break;
523 default:
524 ALOG_ASSERT(false);
525 }
526
527 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
528 "displayId='%s'\n",
529 toString(mParameters.hasAssociatedDisplay),
530 toString(mParameters.associatedDisplayIsExternal),
531 mParameters.uniqueDisplayId.c_str());
532 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
533}
534
535void TouchInputMapper::configureRawPointerAxes() {
536 mRawPointerAxes.clear();
537}
538
539void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
540 dump += INDENT3 "Raw Touch Axes:\n";
541 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
542 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
545 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
546 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
547 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
548 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
549 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
550 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
551 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
552 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
553 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
554}
555
556bool TouchInputMapper::hasExternalStylus() const {
557 return mExternalStylusConnected;
558}
559
560/**
561 * Determine which DisplayViewport to use.
562 * 1. If display port is specified, return the matching viewport. If matching viewport not
563 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800564 * 2. Always use the suggested viewport from WindowManagerService for pointers.
565 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800567 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700568 */
569std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800570 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800571 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700572 if (displayPort) {
573 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800574 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700575 }
576
Michael Wright227c5542020-07-02 18:30:52 +0100577 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800578 std::optional<DisplayViewport> viewport =
579 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
580 if (viewport) {
581 return viewport;
582 } else {
583 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
584 mConfig.defaultPointerDisplayId);
585 }
586 }
587
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700588 // Check if uniqueDisplayId is specified in idc file.
589 if (!mParameters.uniqueDisplayId.empty()) {
590 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
591 }
592
593 ViewportType viewportTypeToUse;
594 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100595 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700596 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100597 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700598 }
599
600 std::optional<DisplayViewport> viewport =
601 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100602 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700603 ALOGW("Input device %s should be associated with external display, "
604 "fallback to internal one for the external viewport is not found.",
605 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100606 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700607 }
608
609 return viewport;
610 }
611
612 // No associated display, return a non-display viewport.
613 DisplayViewport newViewport;
614 // Raw width and height in the natural orientation.
615 int32_t rawWidth = mRawPointerAxes.getRawWidth();
616 int32_t rawHeight = mRawPointerAxes.getRawHeight();
617 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
618 return std::make_optional(newViewport);
619}
620
621void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100622 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700623
624 resolveExternalStylusPresence();
625
626 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100627 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800628 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700629 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100630 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700631 if (hasStylus()) {
632 mSource |= AINPUT_SOURCE_STYLUS;
633 }
Michael Wright227c5542020-07-02 18:30:52 +0100634 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700635 mParameters.hasAssociatedDisplay) {
636 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100637 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700638 if (hasStylus()) {
639 mSource |= AINPUT_SOURCE_STYLUS;
640 }
641 if (hasExternalStylus()) {
642 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
643 }
Michael Wright227c5542020-07-02 18:30:52 +0100644 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700645 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100646 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700647 } else {
648 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100649 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700650 }
651
652 // Ensure we have valid X and Y axes.
653 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
654 ALOGW("Touch device '%s' did not report support for X or Y axis! "
655 "The device will be inoperable.",
656 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100657 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700658 return;
659 }
660
661 // Get associated display dimensions.
662 std::optional<DisplayViewport> newViewport = findViewport();
663 if (!newViewport) {
664 ALOGI("Touch device '%s' could not query the properties of its associated "
665 "display. The device will be inoperable until the display size "
666 "becomes available.",
667 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100668 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700669 return;
670 }
671
672 // Raw width and height in the natural orientation.
673 int32_t rawWidth = mRawPointerAxes.getRawWidth();
674 int32_t rawHeight = mRawPointerAxes.getRawHeight();
675
676 bool viewportChanged = mViewport != *newViewport;
677 if (viewportChanged) {
678 mViewport = *newViewport;
679
Michael Wright227c5542020-07-02 18:30:52 +0100680 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700681 // Convert rotated viewport to natural surface coordinates.
682 int32_t naturalLogicalWidth, naturalLogicalHeight;
683 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
684 int32_t naturalPhysicalLeft, naturalPhysicalTop;
685 int32_t naturalDeviceWidth, naturalDeviceHeight;
686 switch (mViewport.orientation) {
687 case DISPLAY_ORIENTATION_90:
688 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
689 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
690 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
691 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800692 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700693 naturalPhysicalTop = mViewport.physicalLeft;
694 naturalDeviceWidth = mViewport.deviceHeight;
695 naturalDeviceHeight = mViewport.deviceWidth;
696 break;
697 case DISPLAY_ORIENTATION_180:
698 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
699 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
700 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
701 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
702 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
703 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
704 naturalDeviceWidth = mViewport.deviceWidth;
705 naturalDeviceHeight = mViewport.deviceHeight;
706 break;
707 case DISPLAY_ORIENTATION_270:
708 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
709 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
710 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
711 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
712 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800713 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700714 naturalDeviceWidth = mViewport.deviceHeight;
715 naturalDeviceHeight = mViewport.deviceWidth;
716 break;
717 case DISPLAY_ORIENTATION_0:
718 default:
719 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
720 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
721 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
722 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
723 naturalPhysicalLeft = mViewport.physicalLeft;
724 naturalPhysicalTop = mViewport.physicalTop;
725 naturalDeviceWidth = mViewport.deviceWidth;
726 naturalDeviceHeight = mViewport.deviceHeight;
727 break;
728 }
729
730 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
731 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
732 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
733 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
734 }
735
736 mPhysicalWidth = naturalPhysicalWidth;
737 mPhysicalHeight = naturalPhysicalHeight;
738 mPhysicalLeft = naturalPhysicalLeft;
739 mPhysicalTop = naturalPhysicalTop;
740
Arthur Hung4197f6b2020-03-16 15:39:59 +0800741 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
742 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700743 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
744 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800745 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
746 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700747
748 mSurfaceOrientation =
749 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
750 } else {
751 mPhysicalWidth = rawWidth;
752 mPhysicalHeight = rawHeight;
753 mPhysicalLeft = 0;
754 mPhysicalTop = 0;
755
Arthur Hung4197f6b2020-03-16 15:39:59 +0800756 mRawSurfaceWidth = rawWidth;
757 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700758 mSurfaceLeft = 0;
759 mSurfaceTop = 0;
760 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
761 }
762 }
763
764 // If moving between pointer modes, need to reset some state.
765 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
766 if (deviceModeChanged) {
767 mOrientedRanges.clear();
768 }
769
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800770 // Create pointer controller if needed.
Michael Wright227c5542020-07-02 18:30:52 +0100771 if (mDeviceMode == DeviceMode::POINTER ||
772 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800773 if (mPointerController == nullptr) {
774 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700775 }
776 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100777 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700778 }
779
780 if (viewportChanged || deviceModeChanged) {
781 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
782 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800783 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700784 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
785
786 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800787 mXScale = float(mRawSurfaceWidth) / rawWidth;
788 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700789 mXTranslate = -mSurfaceLeft;
790 mYTranslate = -mSurfaceTop;
791 mXPrecision = 1.0f / mXScale;
792 mYPrecision = 1.0f / mYScale;
793
794 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
795 mOrientedRanges.x.source = mSource;
796 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
797 mOrientedRanges.y.source = mSource;
798
799 configureVirtualKeys();
800
801 // Scale factor for terms that are not oriented in a particular axis.
802 // If the pixels are square then xScale == yScale otherwise we fake it
803 // by choosing an average.
804 mGeometricScale = avg(mXScale, mYScale);
805
806 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800807 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700808
809 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100810 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700811 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
812 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
813 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
814 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
815 } else {
816 mSizeScale = 0.0f;
817 }
818
819 mOrientedRanges.haveTouchSize = true;
820 mOrientedRanges.haveToolSize = true;
821 mOrientedRanges.haveSize = true;
822
823 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
824 mOrientedRanges.touchMajor.source = mSource;
825 mOrientedRanges.touchMajor.min = 0;
826 mOrientedRanges.touchMajor.max = diagonalSize;
827 mOrientedRanges.touchMajor.flat = 0;
828 mOrientedRanges.touchMajor.fuzz = 0;
829 mOrientedRanges.touchMajor.resolution = 0;
830
831 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
832 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
833
834 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
835 mOrientedRanges.toolMajor.source = mSource;
836 mOrientedRanges.toolMajor.min = 0;
837 mOrientedRanges.toolMajor.max = diagonalSize;
838 mOrientedRanges.toolMajor.flat = 0;
839 mOrientedRanges.toolMajor.fuzz = 0;
840 mOrientedRanges.toolMajor.resolution = 0;
841
842 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
843 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
844
845 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
846 mOrientedRanges.size.source = mSource;
847 mOrientedRanges.size.min = 0;
848 mOrientedRanges.size.max = 1.0;
849 mOrientedRanges.size.flat = 0;
850 mOrientedRanges.size.fuzz = 0;
851 mOrientedRanges.size.resolution = 0;
852 } else {
853 mSizeScale = 0.0f;
854 }
855
856 // Pressure factors.
857 mPressureScale = 0;
858 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100859 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
860 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700861 if (mCalibration.havePressureScale) {
862 mPressureScale = mCalibration.pressureScale;
863 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
864 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
865 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
866 }
867 }
868
869 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
870 mOrientedRanges.pressure.source = mSource;
871 mOrientedRanges.pressure.min = 0;
872 mOrientedRanges.pressure.max = pressureMax;
873 mOrientedRanges.pressure.flat = 0;
874 mOrientedRanges.pressure.fuzz = 0;
875 mOrientedRanges.pressure.resolution = 0;
876
877 // Tilt
878 mTiltXCenter = 0;
879 mTiltXScale = 0;
880 mTiltYCenter = 0;
881 mTiltYScale = 0;
882 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
883 if (mHaveTilt) {
884 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
885 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
886 mTiltXScale = M_PI / 180;
887 mTiltYScale = M_PI / 180;
888
889 mOrientedRanges.haveTilt = true;
890
891 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
892 mOrientedRanges.tilt.source = mSource;
893 mOrientedRanges.tilt.min = 0;
894 mOrientedRanges.tilt.max = M_PI_2;
895 mOrientedRanges.tilt.flat = 0;
896 mOrientedRanges.tilt.fuzz = 0;
897 mOrientedRanges.tilt.resolution = 0;
898 }
899
900 // Orientation
901 mOrientationScale = 0;
902 if (mHaveTilt) {
903 mOrientedRanges.haveOrientation = true;
904
905 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
906 mOrientedRanges.orientation.source = mSource;
907 mOrientedRanges.orientation.min = -M_PI;
908 mOrientedRanges.orientation.max = M_PI;
909 mOrientedRanges.orientation.flat = 0;
910 mOrientedRanges.orientation.fuzz = 0;
911 mOrientedRanges.orientation.resolution = 0;
912 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100913 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700914 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100915 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700916 if (mRawPointerAxes.orientation.valid) {
917 if (mRawPointerAxes.orientation.maxValue > 0) {
918 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
919 } else if (mRawPointerAxes.orientation.minValue < 0) {
920 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
921 } else {
922 mOrientationScale = 0;
923 }
924 }
925 }
926
927 mOrientedRanges.haveOrientation = true;
928
929 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
930 mOrientedRanges.orientation.source = mSource;
931 mOrientedRanges.orientation.min = -M_PI_2;
932 mOrientedRanges.orientation.max = M_PI_2;
933 mOrientedRanges.orientation.flat = 0;
934 mOrientedRanges.orientation.fuzz = 0;
935 mOrientedRanges.orientation.resolution = 0;
936 }
937
938 // Distance
939 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100940 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
941 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700942 if (mCalibration.haveDistanceScale) {
943 mDistanceScale = mCalibration.distanceScale;
944 } else {
945 mDistanceScale = 1.0f;
946 }
947 }
948
949 mOrientedRanges.haveDistance = true;
950
951 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
952 mOrientedRanges.distance.source = mSource;
953 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
954 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
955 mOrientedRanges.distance.flat = 0;
956 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
957 mOrientedRanges.distance.resolution = 0;
958 }
959
960 // Compute oriented precision, scales and ranges.
961 // Note that the maximum value reported is an inclusive maximum value so it is one
962 // unit less than the total width or height of surface.
963 switch (mSurfaceOrientation) {
964 case DISPLAY_ORIENTATION_90:
965 case DISPLAY_ORIENTATION_270:
966 mOrientedXPrecision = mYPrecision;
967 mOrientedYPrecision = mXPrecision;
968
969 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800970 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700971 mOrientedRanges.x.flat = 0;
972 mOrientedRanges.x.fuzz = 0;
973 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
974
975 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800976 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700977 mOrientedRanges.y.flat = 0;
978 mOrientedRanges.y.fuzz = 0;
979 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
980 break;
981
982 default:
983 mOrientedXPrecision = mXPrecision;
984 mOrientedYPrecision = mYPrecision;
985
986 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800987 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700988 mOrientedRanges.x.flat = 0;
989 mOrientedRanges.x.fuzz = 0;
990 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
991
992 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800993 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700994 mOrientedRanges.y.flat = 0;
995 mOrientedRanges.y.fuzz = 0;
996 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
997 break;
998 }
999
1000 // Location
1001 updateAffineTransformation();
1002
Michael Wright227c5542020-07-02 18:30:52 +01001003 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001004 // Compute pointer gesture detection parameters.
1005 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001006 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001007
1008 // Scale movements such that one whole swipe of the touch pad covers a
1009 // given area relative to the diagonal size of the display when no acceleration
1010 // is applied.
1011 // Assume that the touch pad has a square aspect ratio such that movements in
1012 // X and Y of the same number of raw units cover the same physical distance.
1013 mPointerXMovementScale =
1014 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1015 mPointerYMovementScale = mPointerXMovementScale;
1016
1017 // Scale zooms to cover a smaller range of the display than movements do.
1018 // This value determines the area around the pointer that is affected by freeform
1019 // pointer gestures.
1020 mPointerXZoomScale =
1021 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1022 mPointerYZoomScale = mPointerXZoomScale;
1023
1024 // Max width between pointers to detect a swipe gesture is more than some fraction
1025 // of the diagonal axis of the touch pad. Touches that are wider than this are
1026 // translated into freeform gestures.
1027 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1028
1029 // Abort current pointer usages because the state has changed.
1030 abortPointerUsage(when, 0 /*policyFlags*/);
1031 }
1032
1033 // Inform the dispatcher about the changes.
1034 *outResetNeeded = true;
1035 bumpGeneration();
1036 }
1037}
1038
1039void TouchInputMapper::dumpSurface(std::string& dump) {
1040 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001041 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1042 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001043 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1044 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001045 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1046 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001047 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1048 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1049 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1050 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1051 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1052}
1053
1054void TouchInputMapper::configureVirtualKeys() {
1055 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001056 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057
1058 mVirtualKeys.clear();
1059
1060 if (virtualKeyDefinitions.size() == 0) {
1061 return;
1062 }
1063
1064 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1065 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1066 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1067 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1068
1069 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1070 VirtualKey virtualKey;
1071
1072 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1073 int32_t keyCode;
1074 int32_t dummyKeyMetaState;
1075 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001076 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1077 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001078 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1079 continue; // drop the key
1080 }
1081
1082 virtualKey.keyCode = keyCode;
1083 virtualKey.flags = flags;
1084
1085 // convert the key definition's display coordinates into touch coordinates for a hit box
1086 int32_t halfWidth = virtualKeyDefinition.width / 2;
1087 int32_t halfHeight = virtualKeyDefinition.height / 2;
1088
1089 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001090 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001091 touchScreenLeft;
1092 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001093 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001094 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001095 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1096 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001097 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001098 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1099 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001100 touchScreenTop;
1101 mVirtualKeys.push_back(virtualKey);
1102 }
1103}
1104
1105void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1106 if (!mVirtualKeys.empty()) {
1107 dump += INDENT3 "Virtual Keys:\n";
1108
1109 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1110 const VirtualKey& virtualKey = mVirtualKeys[i];
1111 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1112 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1113 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1114 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1115 }
1116 }
1117}
1118
1119void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001120 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001121 Calibration& out = mCalibration;
1122
1123 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001124 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001125 String8 sizeCalibrationString;
1126 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1127 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001128 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001129 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001130 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001131 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001132 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001134 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001136 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 } else if (sizeCalibrationString != "default") {
1138 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1139 }
1140 }
1141
1142 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1143 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1144 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1145
1146 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001147 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 String8 pressureCalibrationString;
1149 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1150 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001151 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001152 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001153 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001154 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001155 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001156 } else if (pressureCalibrationString != "default") {
1157 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1158 pressureCalibrationString.string());
1159 }
1160 }
1161
1162 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1163
1164 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001165 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 String8 orientationCalibrationString;
1167 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1168 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (orientationCalibrationString != "default") {
1175 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1176 orientationCalibrationString.string());
1177 }
1178 }
1179
1180 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 String8 distanceCalibrationString;
1183 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1184 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 } else if (distanceCalibrationString != "default") {
1189 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1190 distanceCalibrationString.string());
1191 }
1192 }
1193
1194 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1195
Michael Wright227c5542020-07-02 18:30:52 +01001196 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 String8 coverageCalibrationString;
1198 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1199 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001202 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 } else if (coverageCalibrationString != "default") {
1204 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1205 coverageCalibrationString.string());
1206 }
1207 }
1208}
1209
1210void TouchInputMapper::resolveCalibration() {
1211 // Size
1212 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001213 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1214 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 }
1216 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001217 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001218 }
1219
1220 // Pressure
1221 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001222 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1223 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001224 }
1225 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001226 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 }
1228
1229 // Orientation
1230 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001231 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1232 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 }
1234 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001235 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 }
1237
1238 // Distance
1239 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001240 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1241 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 }
1243 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001244 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 }
1246
1247 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001248 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1249 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251}
1252
1253void TouchInputMapper::dumpCalibration(std::string& dump) {
1254 dump += INDENT3 "Calibration:\n";
1255
1256 // Size
1257 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001258 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 dump += INDENT4 "touch.size.calibration: none\n";
1260 break;
Michael Wright227c5542020-07-02 18:30:52 +01001261 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 dump += INDENT4 "touch.size.calibration: geometric\n";
1263 break;
Michael Wright227c5542020-07-02 18:30:52 +01001264 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 dump += INDENT4 "touch.size.calibration: diameter\n";
1266 break;
Michael Wright227c5542020-07-02 18:30:52 +01001267 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 dump += INDENT4 "touch.size.calibration: box\n";
1269 break;
Michael Wright227c5542020-07-02 18:30:52 +01001270 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 dump += INDENT4 "touch.size.calibration: area\n";
1272 break;
1273 default:
1274 ALOG_ASSERT(false);
1275 }
1276
1277 if (mCalibration.haveSizeScale) {
1278 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1279 }
1280
1281 if (mCalibration.haveSizeBias) {
1282 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1283 }
1284
1285 if (mCalibration.haveSizeIsSummed) {
1286 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1287 toString(mCalibration.sizeIsSummed));
1288 }
1289
1290 // Pressure
1291 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001292 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293 dump += INDENT4 "touch.pressure.calibration: none\n";
1294 break;
Michael Wright227c5542020-07-02 18:30:52 +01001295 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001296 dump += INDENT4 "touch.pressure.calibration: physical\n";
1297 break;
Michael Wright227c5542020-07-02 18:30:52 +01001298 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001299 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1300 break;
1301 default:
1302 ALOG_ASSERT(false);
1303 }
1304
1305 if (mCalibration.havePressureScale) {
1306 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1307 }
1308
1309 // Orientation
1310 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001311 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 dump += INDENT4 "touch.orientation.calibration: none\n";
1313 break;
Michael Wright227c5542020-07-02 18:30:52 +01001314 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1316 break;
Michael Wright227c5542020-07-02 18:30:52 +01001317 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 dump += INDENT4 "touch.orientation.calibration: vector\n";
1319 break;
1320 default:
1321 ALOG_ASSERT(false);
1322 }
1323
1324 // Distance
1325 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001326 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001327 dump += INDENT4 "touch.distance.calibration: none\n";
1328 break;
Michael Wright227c5542020-07-02 18:30:52 +01001329 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 dump += INDENT4 "touch.distance.calibration: scaled\n";
1331 break;
1332 default:
1333 ALOG_ASSERT(false);
1334 }
1335
1336 if (mCalibration.haveDistanceScale) {
1337 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1338 }
1339
1340 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001341 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001342 dump += INDENT4 "touch.coverage.calibration: none\n";
1343 break;
Michael Wright227c5542020-07-02 18:30:52 +01001344 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001345 dump += INDENT4 "touch.coverage.calibration: box\n";
1346 break;
1347 default:
1348 ALOG_ASSERT(false);
1349 }
1350}
1351
1352void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1353 dump += INDENT3 "Affine Transformation:\n";
1354
1355 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1356 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1357 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1358 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1359 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1360 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1361}
1362
1363void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001364 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001365 mSurfaceOrientation);
1366}
1367
1368void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001369 mCursorButtonAccumulator.reset(getDeviceContext());
1370 mCursorScrollAccumulator.reset(getDeviceContext());
1371 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001372
1373 mPointerVelocityControl.reset();
1374 mWheelXVelocityControl.reset();
1375 mWheelYVelocityControl.reset();
1376
1377 mRawStatesPending.clear();
1378 mCurrentRawState.clear();
1379 mCurrentCookedState.clear();
1380 mLastRawState.clear();
1381 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001382 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001383 mSentHoverEnter = false;
1384 mHavePointerIds = false;
1385 mCurrentMotionAborted = false;
1386 mDownTime = 0;
1387
1388 mCurrentVirtualKey.down = false;
1389
1390 mPointerGesture.reset();
1391 mPointerSimple.reset();
1392 resetExternalStylus();
1393
1394 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001395 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001396 mPointerController->clearSpots();
1397 }
1398
1399 InputMapper::reset(when);
1400}
1401
1402void TouchInputMapper::resetExternalStylus() {
1403 mExternalStylusState.clear();
1404 mExternalStylusId = -1;
1405 mExternalStylusFusionTimeout = LLONG_MAX;
1406 mExternalStylusDataPending = false;
1407}
1408
1409void TouchInputMapper::clearStylusDataPendingFlags() {
1410 mExternalStylusDataPending = false;
1411 mExternalStylusFusionTimeout = LLONG_MAX;
1412}
1413
1414void TouchInputMapper::process(const RawEvent* rawEvent) {
1415 mCursorButtonAccumulator.process(rawEvent);
1416 mCursorScrollAccumulator.process(rawEvent);
1417 mTouchButtonAccumulator.process(rawEvent);
1418
1419 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1420 sync(rawEvent->when);
1421 }
1422}
1423
1424void TouchInputMapper::sync(nsecs_t when) {
1425 const RawState* last =
1426 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1427
1428 // Push a new state.
1429 mRawStatesPending.emplace_back();
1430
1431 RawState* next = &mRawStatesPending.back();
1432 next->clear();
1433 next->when = when;
1434
1435 // Sync button state.
1436 next->buttonState =
1437 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1438
1439 // Sync scroll
1440 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1441 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1442 mCursorScrollAccumulator.finishSync();
1443
1444 // Sync touch
1445 syncTouch(when, next);
1446
1447 // Assign pointer ids.
1448 if (!mHavePointerIds) {
1449 assignPointerIds(last, next);
1450 }
1451
1452#if DEBUG_RAW_EVENTS
1453 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001454 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1456 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhungcc7f9802020-04-30 17:55:40 +08001457 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1458 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001459#endif
1460
1461 processRawTouches(false /*timeout*/);
1462}
1463
1464void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001465 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001466 // Drop all input if the device is disabled.
1467 mCurrentRawState.clear();
1468 mRawStatesPending.clear();
1469 return;
1470 }
1471
1472 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1473 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1474 // touching the current state will only observe the events that have been dispatched to the
1475 // rest of the pipeline.
1476 const size_t N = mRawStatesPending.size();
1477 size_t count;
1478 for (count = 0; count < N; count++) {
1479 const RawState& next = mRawStatesPending[count];
1480
1481 // A failure to assign the stylus id means that we're waiting on stylus data
1482 // and so should defer the rest of the pipeline.
1483 if (assignExternalStylusId(next, timeout)) {
1484 break;
1485 }
1486
1487 // All ready to go.
1488 clearStylusDataPendingFlags();
1489 mCurrentRawState.copyFrom(next);
1490 if (mCurrentRawState.when < mLastRawState.when) {
1491 mCurrentRawState.when = mLastRawState.when;
1492 }
1493 cookAndDispatch(mCurrentRawState.when);
1494 }
1495 if (count != 0) {
1496 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1497 }
1498
1499 if (mExternalStylusDataPending) {
1500 if (timeout) {
1501 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1502 clearStylusDataPendingFlags();
1503 mCurrentRawState.copyFrom(mLastRawState);
1504#if DEBUG_STYLUS_FUSION
1505 ALOGD("Timeout expired, synthesizing event with new stylus data");
1506#endif
1507 cookAndDispatch(when);
1508 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1509 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1510 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1511 }
1512 }
1513}
1514
1515void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1516 // Always start with a clean state.
1517 mCurrentCookedState.clear();
1518
1519 // Apply stylus buttons to current raw state.
1520 applyExternalStylusButtonState(when);
1521
1522 // Handle policy on initial down or hover events.
1523 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1524 mCurrentRawState.rawPointerData.pointerCount != 0;
1525
1526 uint32_t policyFlags = 0;
1527 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1528 if (initialDown || buttonsPressed) {
1529 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001530 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001531 getContext()->fadePointer();
1532 }
1533
1534 if (mParameters.wake) {
1535 policyFlags |= POLICY_FLAG_WAKE;
1536 }
1537 }
1538
1539 // Consume raw off-screen touches before cooking pointer data.
1540 // If touches are consumed, subsequent code will not receive any pointer data.
1541 if (consumeRawTouches(when, policyFlags)) {
1542 mCurrentRawState.rawPointerData.clear();
1543 }
1544
1545 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1546 // with cooked pointer data that has the same ids and indices as the raw data.
1547 // The following code can use either the raw or cooked data, as needed.
1548 cookPointerData();
1549
1550 // Apply stylus pressure to current cooked state.
1551 applyExternalStylusTouchState(when);
1552
1553 // Synthesize key down from raw buttons if needed.
1554 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1555 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1556 mCurrentCookedState.buttonState);
1557
1558 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001559 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001560 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1561 uint32_t id = idBits.clearFirstMarkedBit();
1562 const RawPointerData::Pointer& pointer =
1563 mCurrentRawState.rawPointerData.pointerForId(id);
1564 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1565 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1566 mCurrentCookedState.stylusIdBits.markBit(id);
1567 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1568 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1569 mCurrentCookedState.fingerIdBits.markBit(id);
1570 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1571 mCurrentCookedState.mouseIdBits.markBit(id);
1572 }
1573 }
1574 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1575 uint32_t id = idBits.clearFirstMarkedBit();
1576 const RawPointerData::Pointer& pointer =
1577 mCurrentRawState.rawPointerData.pointerForId(id);
1578 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1579 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1580 mCurrentCookedState.stylusIdBits.markBit(id);
1581 }
1582 }
1583
1584 // Stylus takes precedence over all tools, then mouse, then finger.
1585 PointerUsage pointerUsage = mPointerUsage;
1586 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1587 mCurrentCookedState.mouseIdBits.clear();
1588 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001589 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001590 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1591 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001592 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001593 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1594 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001595 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596 }
1597
1598 dispatchPointerUsage(when, policyFlags, pointerUsage);
1599 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001600 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001601 mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001602 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1603 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001604
1605 mPointerController->setButtonState(mCurrentRawState.buttonState);
1606 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1607 mCurrentCookedState.cookedPointerData.idToIndex,
1608 mCurrentCookedState.cookedPointerData.touchingIdBits,
1609 mViewport.displayId);
1610 }
1611
1612 if (!mCurrentMotionAborted) {
1613 dispatchButtonRelease(when, policyFlags);
1614 dispatchHoverExit(when, policyFlags);
1615 dispatchTouches(when, policyFlags);
1616 dispatchHoverEnterAndMove(when, policyFlags);
1617 dispatchButtonPress(when, policyFlags);
1618 }
1619
1620 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1621 mCurrentMotionAborted = false;
1622 }
1623 }
1624
1625 // Synthesize key up from raw buttons if needed.
1626 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1627 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1628 mCurrentCookedState.buttonState);
1629
1630 // Clear some transient state.
1631 mCurrentRawState.rawVScroll = 0;
1632 mCurrentRawState.rawHScroll = 0;
1633
1634 // Copy current touch to last touch in preparation for the next cycle.
1635 mLastRawState.copyFrom(mCurrentRawState);
1636 mLastCookedState.copyFrom(mCurrentCookedState);
1637}
1638
1639void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001640 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001641 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1642 }
1643}
1644
1645void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1646 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1647 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1648
1649 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1650 float pressure = mExternalStylusState.pressure;
1651 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1652 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1653 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1654 }
1655 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1656 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1657
1658 PointerProperties& properties =
1659 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1660 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1661 properties.toolType = mExternalStylusState.toolType;
1662 }
1663 }
1664}
1665
1666bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001667 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001668 return false;
1669 }
1670
1671 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1672 state.rawPointerData.pointerCount != 0;
1673 if (initialDown) {
1674 if (mExternalStylusState.pressure != 0.0f) {
1675#if DEBUG_STYLUS_FUSION
1676 ALOGD("Have both stylus and touch data, beginning fusion");
1677#endif
1678 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1679 } else if (timeout) {
1680#if DEBUG_STYLUS_FUSION
1681 ALOGD("Timeout expired, assuming touch is not a stylus.");
1682#endif
1683 resetExternalStylus();
1684 } else {
1685 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1686 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1687 }
1688#if DEBUG_STYLUS_FUSION
1689 ALOGD("No stylus data but stylus is connected, requesting timeout "
1690 "(%" PRId64 "ms)",
1691 mExternalStylusFusionTimeout);
1692#endif
1693 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1694 return true;
1695 }
1696 }
1697
1698 // Check if the stylus pointer has gone up.
1699 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1700#if DEBUG_STYLUS_FUSION
1701 ALOGD("Stylus pointer is going up");
1702#endif
1703 mExternalStylusId = -1;
1704 }
1705
1706 return false;
1707}
1708
1709void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001710 if (mDeviceMode == DeviceMode::POINTER) {
1711 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001712 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1713 }
Michael Wright227c5542020-07-02 18:30:52 +01001714 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001715 if (mExternalStylusFusionTimeout < when) {
1716 processRawTouches(true /*timeout*/);
1717 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1718 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1719 }
1720 }
1721}
1722
1723void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1724 mExternalStylusState.copyFrom(state);
1725 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1726 // We're either in the middle of a fused stream of data or we're waiting on data before
1727 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1728 // data.
1729 mExternalStylusDataPending = true;
1730 processRawTouches(false /*timeout*/);
1731 }
1732}
1733
1734bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1735 // Check for release of a virtual key.
1736 if (mCurrentVirtualKey.down) {
1737 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1738 // Pointer went up while virtual key was down.
1739 mCurrentVirtualKey.down = false;
1740 if (!mCurrentVirtualKey.ignored) {
1741#if DEBUG_VIRTUAL_KEYS
1742 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1743 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1744#endif
1745 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1746 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1747 }
1748 return true;
1749 }
1750
1751 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1752 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1753 const RawPointerData::Pointer& pointer =
1754 mCurrentRawState.rawPointerData.pointerForId(id);
1755 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1756 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1757 // Pointer is still within the space of the virtual key.
1758 return true;
1759 }
1760 }
1761
1762 // Pointer left virtual key area or another pointer also went down.
1763 // Send key cancellation but do not consume the touch yet.
1764 // This is useful when the user swipes through from the virtual key area
1765 // into the main display surface.
1766 mCurrentVirtualKey.down = false;
1767 if (!mCurrentVirtualKey.ignored) {
1768#if DEBUG_VIRTUAL_KEYS
1769 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1770 mCurrentVirtualKey.scanCode);
1771#endif
1772 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1773 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1774 AKEY_EVENT_FLAG_CANCELED);
1775 }
1776 }
1777
1778 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1779 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1780 // Pointer just went down. Check for virtual key press or off-screen touches.
1781 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1782 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1783 if (!isPointInsideSurface(pointer.x, pointer.y)) {
1784 // If exactly one pointer went down, check for virtual key hit.
1785 // Otherwise we will drop the entire stroke.
1786 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1787 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1788 if (virtualKey) {
1789 mCurrentVirtualKey.down = true;
1790 mCurrentVirtualKey.downTime = when;
1791 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1792 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1793 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001794 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1795 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001796
1797 if (!mCurrentVirtualKey.ignored) {
1798#if DEBUG_VIRTUAL_KEYS
1799 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1800 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1801#endif
1802 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1803 AKEY_EVENT_FLAG_FROM_SYSTEM |
1804 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1805 }
1806 }
1807 }
1808 return true;
1809 }
1810 }
1811
1812 // Disable all virtual key touches that happen within a short time interval of the
1813 // most recent touch within the screen area. The idea is to filter out stray
1814 // virtual key presses when interacting with the touch screen.
1815 //
1816 // Problems we're trying to solve:
1817 //
1818 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1819 // virtual key area that is implemented by a separate touch panel and accidentally
1820 // triggers a virtual key.
1821 //
1822 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1823 // area and accidentally triggers a virtual key. This often happens when virtual keys
1824 // are layed out below the screen near to where the on screen keyboard's space bar
1825 // is displayed.
1826 if (mConfig.virtualKeyQuietTime > 0 &&
1827 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001828 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001829 }
1830 return false;
1831}
1832
1833void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1834 int32_t keyEventAction, int32_t keyEventFlags) {
1835 int32_t keyCode = mCurrentVirtualKey.keyCode;
1836 int32_t scanCode = mCurrentVirtualKey.scanCode;
1837 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001838 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001839 policyFlags |= POLICY_FLAG_VIRTUAL;
1840
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001841 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1842 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1843 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001844 getListener()->notifyKey(&args);
1845}
1846
1847void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1848 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1849 if (!currentIdBits.isEmpty()) {
1850 int32_t metaState = getContext()->getGlobalMetaState();
1851 int32_t buttonState = mCurrentCookedState.buttonState;
1852 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1853 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1854 mCurrentCookedState.cookedPointerData.pointerProperties,
1855 mCurrentCookedState.cookedPointerData.pointerCoords,
1856 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1857 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1858 mCurrentMotionAborted = true;
1859 }
1860}
1861
1862void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1863 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1864 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1865 int32_t metaState = getContext()->getGlobalMetaState();
1866 int32_t buttonState = mCurrentCookedState.buttonState;
1867
1868 if (currentIdBits == lastIdBits) {
1869 if (!currentIdBits.isEmpty()) {
1870 // No pointer id changes so this is a move event.
1871 // The listener takes care of batching moves so we don't have to deal with that here.
1872 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1873 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1874 mCurrentCookedState.cookedPointerData.pointerProperties,
1875 mCurrentCookedState.cookedPointerData.pointerCoords,
1876 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1877 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1878 }
1879 } else {
1880 // There may be pointers going up and pointers going down and pointers moving
1881 // all at the same time.
1882 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1883 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1884 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1885 BitSet32 dispatchedIdBits(lastIdBits.value);
1886
1887 // Update last coordinates of pointers that have moved so that we observe the new
1888 // pointer positions at the same time as other pointers that have just gone up.
1889 bool moveNeeded =
1890 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1891 mCurrentCookedState.cookedPointerData.pointerCoords,
1892 mCurrentCookedState.cookedPointerData.idToIndex,
1893 mLastCookedState.cookedPointerData.pointerProperties,
1894 mLastCookedState.cookedPointerData.pointerCoords,
1895 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1896 if (buttonState != mLastCookedState.buttonState) {
1897 moveNeeded = true;
1898 }
1899
1900 // Dispatch pointer up events.
1901 while (!upIdBits.isEmpty()) {
1902 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001903 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1904 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1905 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001906 mLastCookedState.cookedPointerData.pointerProperties,
1907 mLastCookedState.cookedPointerData.pointerCoords,
1908 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1909 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1910 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001911 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001912 }
1913
1914 // Dispatch move events if any of the remaining pointers moved from their old locations.
1915 // Although applications receive new locations as part of individual pointer up
1916 // events, they do not generally handle them except when presented in a move event.
1917 if (moveNeeded && !moveIdBits.isEmpty()) {
1918 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1919 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1920 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1921 mCurrentCookedState.cookedPointerData.pointerCoords,
1922 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1923 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1924 }
1925
1926 // Dispatch pointer down events using the new pointer locations.
1927 while (!downIdBits.isEmpty()) {
1928 uint32_t downId = downIdBits.clearFirstMarkedBit();
1929 dispatchedIdBits.markBit(downId);
1930
1931 if (dispatchedIdBits.count() == 1) {
1932 // First pointer is going down. Set down time.
1933 mDownTime = when;
1934 }
1935
1936 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1937 metaState, buttonState, 0,
1938 mCurrentCookedState.cookedPointerData.pointerProperties,
1939 mCurrentCookedState.cookedPointerData.pointerCoords,
1940 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1941 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1942 }
1943 }
1944}
1945
1946void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1947 if (mSentHoverEnter &&
1948 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1949 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1950 int32_t metaState = getContext()->getGlobalMetaState();
1951 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1952 mLastCookedState.buttonState, 0,
1953 mLastCookedState.cookedPointerData.pointerProperties,
1954 mLastCookedState.cookedPointerData.pointerCoords,
1955 mLastCookedState.cookedPointerData.idToIndex,
1956 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1957 mOrientedYPrecision, mDownTime);
1958 mSentHoverEnter = false;
1959 }
1960}
1961
1962void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1963 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1964 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1965 int32_t metaState = getContext()->getGlobalMetaState();
1966 if (!mSentHoverEnter) {
1967 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1968 metaState, mCurrentRawState.buttonState, 0,
1969 mCurrentCookedState.cookedPointerData.pointerProperties,
1970 mCurrentCookedState.cookedPointerData.pointerCoords,
1971 mCurrentCookedState.cookedPointerData.idToIndex,
1972 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1973 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1974 mSentHoverEnter = true;
1975 }
1976
1977 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1978 mCurrentRawState.buttonState, 0,
1979 mCurrentCookedState.cookedPointerData.pointerProperties,
1980 mCurrentCookedState.cookedPointerData.pointerCoords,
1981 mCurrentCookedState.cookedPointerData.idToIndex,
1982 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1983 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1984 }
1985}
1986
1987void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
1988 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
1989 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
1990 const int32_t metaState = getContext()->getGlobalMetaState();
1991 int32_t buttonState = mLastCookedState.buttonState;
1992 while (!releasedButtons.isEmpty()) {
1993 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
1994 buttonState &= ~actionButton;
1995 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1996 actionButton, 0, metaState, buttonState, 0,
1997 mCurrentCookedState.cookedPointerData.pointerProperties,
1998 mCurrentCookedState.cookedPointerData.pointerCoords,
1999 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2000 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2001 }
2002}
2003
2004void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2005 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2006 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2007 const int32_t metaState = getContext()->getGlobalMetaState();
2008 int32_t buttonState = mLastCookedState.buttonState;
2009 while (!pressedButtons.isEmpty()) {
2010 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2011 buttonState |= actionButton;
2012 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2013 0, metaState, buttonState, 0,
2014 mCurrentCookedState.cookedPointerData.pointerProperties,
2015 mCurrentCookedState.cookedPointerData.pointerCoords,
2016 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2017 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2018 }
2019}
2020
2021const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2022 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2023 return cookedPointerData.touchingIdBits;
2024 }
2025 return cookedPointerData.hoveringIdBits;
2026}
2027
2028void TouchInputMapper::cookPointerData() {
2029 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2030
2031 mCurrentCookedState.cookedPointerData.clear();
2032 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2033 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2034 mCurrentRawState.rawPointerData.hoveringIdBits;
2035 mCurrentCookedState.cookedPointerData.touchingIdBits =
2036 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002037 mCurrentCookedState.cookedPointerData.canceledIdBits =
2038 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002039
2040 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2041 mCurrentCookedState.buttonState = 0;
2042 } else {
2043 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2044 }
2045
2046 // Walk through the the active pointers and map device coordinates onto
2047 // surface coordinates and adjust for display orientation.
2048 for (uint32_t i = 0; i < currentPointerCount; i++) {
2049 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2050
2051 // Size
2052 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2053 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002054 case Calibration::SizeCalibration::GEOMETRIC:
2055 case Calibration::SizeCalibration::DIAMETER:
2056 case Calibration::SizeCalibration::BOX:
2057 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002058 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2059 touchMajor = in.touchMajor;
2060 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2061 toolMajor = in.toolMajor;
2062 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2063 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2064 : in.touchMajor;
2065 } else if (mRawPointerAxes.touchMajor.valid) {
2066 toolMajor = touchMajor = in.touchMajor;
2067 toolMinor = touchMinor =
2068 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2069 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2070 : in.touchMajor;
2071 } else if (mRawPointerAxes.toolMajor.valid) {
2072 touchMajor = toolMajor = in.toolMajor;
2073 touchMinor = toolMinor =
2074 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2075 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2076 : in.toolMajor;
2077 } else {
2078 ALOG_ASSERT(false,
2079 "No touch or tool axes. "
2080 "Size calibration should have been resolved to NONE.");
2081 touchMajor = 0;
2082 touchMinor = 0;
2083 toolMajor = 0;
2084 toolMinor = 0;
2085 size = 0;
2086 }
2087
2088 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2089 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2090 if (touchingCount > 1) {
2091 touchMajor /= touchingCount;
2092 touchMinor /= touchingCount;
2093 toolMajor /= touchingCount;
2094 toolMinor /= touchingCount;
2095 size /= touchingCount;
2096 }
2097 }
2098
Michael Wright227c5542020-07-02 18:30:52 +01002099 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002100 touchMajor *= mGeometricScale;
2101 touchMinor *= mGeometricScale;
2102 toolMajor *= mGeometricScale;
2103 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002104 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002105 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2106 touchMinor = touchMajor;
2107 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2108 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002109 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002110 touchMinor = touchMajor;
2111 toolMinor = toolMajor;
2112 }
2113
2114 mCalibration.applySizeScaleAndBias(&touchMajor);
2115 mCalibration.applySizeScaleAndBias(&touchMinor);
2116 mCalibration.applySizeScaleAndBias(&toolMajor);
2117 mCalibration.applySizeScaleAndBias(&toolMinor);
2118 size *= mSizeScale;
2119 break;
2120 default:
2121 touchMajor = 0;
2122 touchMinor = 0;
2123 toolMajor = 0;
2124 toolMinor = 0;
2125 size = 0;
2126 break;
2127 }
2128
2129 // Pressure
2130 float pressure;
2131 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002132 case Calibration::PressureCalibration::PHYSICAL:
2133 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002134 pressure = in.pressure * mPressureScale;
2135 break;
2136 default:
2137 pressure = in.isHovering ? 0 : 1;
2138 break;
2139 }
2140
2141 // Tilt and Orientation
2142 float tilt;
2143 float orientation;
2144 if (mHaveTilt) {
2145 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2146 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2147 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2148 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2149 } else {
2150 tilt = 0;
2151
2152 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002153 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002154 orientation = in.orientation * mOrientationScale;
2155 break;
Michael Wright227c5542020-07-02 18:30:52 +01002156 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002157 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2158 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2159 if (c1 != 0 || c2 != 0) {
2160 orientation = atan2f(c1, c2) * 0.5f;
2161 float confidence = hypotf(c1, c2);
2162 float scale = 1.0f + confidence / 16.0f;
2163 touchMajor *= scale;
2164 touchMinor /= scale;
2165 toolMajor *= scale;
2166 toolMinor /= scale;
2167 } else {
2168 orientation = 0;
2169 }
2170 break;
2171 }
2172 default:
2173 orientation = 0;
2174 }
2175 }
2176
2177 // Distance
2178 float distance;
2179 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002180 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002181 distance = in.distance * mDistanceScale;
2182 break;
2183 default:
2184 distance = 0;
2185 }
2186
2187 // Coverage
2188 int32_t rawLeft, rawTop, rawRight, rawBottom;
2189 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002190 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002191 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2192 rawRight = in.toolMinor & 0x0000ffff;
2193 rawBottom = in.toolMajor & 0x0000ffff;
2194 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2195 break;
2196 default:
2197 rawLeft = rawTop = rawRight = rawBottom = 0;
2198 break;
2199 }
2200
2201 // Adjust X,Y coords for device calibration
2202 // TODO: Adjust coverage coords?
2203 float xTransformed = in.x, yTransformed = in.y;
2204 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002205 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002206
2207 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002208 float left, top, right, bottom;
2209
2210 switch (mSurfaceOrientation) {
2211 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002212 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2213 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2214 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2215 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2216 orientation -= M_PI_2;
2217 if (mOrientedRanges.haveOrientation &&
2218 orientation < mOrientedRanges.orientation.min) {
2219 orientation +=
2220 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2221 }
2222 break;
2223 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002224 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2225 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2226 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2227 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2228 orientation -= M_PI;
2229 if (mOrientedRanges.haveOrientation &&
2230 orientation < mOrientedRanges.orientation.min) {
2231 orientation +=
2232 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2233 }
2234 break;
2235 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002236 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2237 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2238 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2239 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2240 orientation += M_PI_2;
2241 if (mOrientedRanges.haveOrientation &&
2242 orientation > mOrientedRanges.orientation.max) {
2243 orientation -=
2244 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2245 }
2246 break;
2247 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002248 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2249 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2250 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2251 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2252 break;
2253 }
2254
2255 // Write output coords.
2256 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2257 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002258 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2259 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002260 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2261 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2262 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2263 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2264 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2265 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2266 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002267 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002268 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2269 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2270 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2271 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2272 } else {
2273 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2274 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2275 }
2276
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002277 // Write output relative fieldis if applicable.
2278 uint32_t id = in.id;
2279 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2280 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2281 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2282 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2283 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2284 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2285 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2286 }
2287
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002288 // Write output properties.
2289 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002290 properties.clear();
2291 properties.id = id;
2292 properties.toolType = in.toolType;
2293
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002294 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002295 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002296 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297 }
2298}
2299
2300void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2301 PointerUsage pointerUsage) {
2302 if (pointerUsage != mPointerUsage) {
2303 abortPointerUsage(when, policyFlags);
2304 mPointerUsage = pointerUsage;
2305 }
2306
2307 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002308 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002309 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2310 break;
Michael Wright227c5542020-07-02 18:30:52 +01002311 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002312 dispatchPointerStylus(when, policyFlags);
2313 break;
Michael Wright227c5542020-07-02 18:30:52 +01002314 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 dispatchPointerMouse(when, policyFlags);
2316 break;
Michael Wright227c5542020-07-02 18:30:52 +01002317 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002318 break;
2319 }
2320}
2321
2322void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2323 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002324 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002325 abortPointerGestures(when, policyFlags);
2326 break;
Michael Wright227c5542020-07-02 18:30:52 +01002327 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002328 abortPointerStylus(when, policyFlags);
2329 break;
Michael Wright227c5542020-07-02 18:30:52 +01002330 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002331 abortPointerMouse(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
Michael Wright227c5542020-07-02 18:30:52 +01002337 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002338}
2339
2340void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2341 // Update current gesture coordinates.
2342 bool cancelPreviousGesture, finishPreviousGesture;
2343 bool sendEvents =
2344 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2345 if (!sendEvents) {
2346 return;
2347 }
2348 if (finishPreviousGesture) {
2349 cancelPreviousGesture = false;
2350 }
2351
2352 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002353 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002354 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 if (finishPreviousGesture || cancelPreviousGesture) {
2356 mPointerController->clearSpots();
2357 }
2358
Michael Wright227c5542020-07-02 18:30:52 +01002359 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002360 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2361 mPointerGesture.currentGestureIdToIndex,
2362 mPointerGesture.currentGestureIdBits,
2363 mPointerController->getDisplayId());
2364 }
2365 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002366 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002367 }
2368
2369 // Show or hide the pointer if needed.
2370 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002371 case PointerGesture::Mode::NEUTRAL:
2372 case PointerGesture::Mode::QUIET:
2373 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2374 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002376 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 }
2378 break;
Michael Wright227c5542020-07-02 18:30:52 +01002379 case PointerGesture::Mode::TAP:
2380 case PointerGesture::Mode::TAP_DRAG:
2381 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2382 case PointerGesture::Mode::HOVER:
2383 case PointerGesture::Mode::PRESS:
2384 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 // Unfade the pointer when the current gesture manipulates the
2386 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002387 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 break;
Michael Wright227c5542020-07-02 18:30:52 +01002389 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390 // Fade the pointer when the current gesture manipulates a different
2391 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002392 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002393 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002395 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 }
2397 break;
2398 }
2399
2400 // Send events!
2401 int32_t metaState = getContext()->getGlobalMetaState();
2402 int32_t buttonState = mCurrentCookedState.buttonState;
2403
2404 // Update last coordinates of pointers that have moved so that we observe the new
2405 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002406 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2407 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2408 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2409 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2410 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2411 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002412 bool moveNeeded = false;
2413 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2414 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2415 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2416 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2417 mPointerGesture.lastGestureIdBits.value);
2418 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2419 mPointerGesture.currentGestureCoords,
2420 mPointerGesture.currentGestureIdToIndex,
2421 mPointerGesture.lastGestureProperties,
2422 mPointerGesture.lastGestureCoords,
2423 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2424 if (buttonState != mLastCookedState.buttonState) {
2425 moveNeeded = true;
2426 }
2427 }
2428
2429 // Send motion events for all pointers that went up or were canceled.
2430 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2431 if (!dispatchedGestureIdBits.isEmpty()) {
2432 if (cancelPreviousGesture) {
2433 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2434 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2435 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2436 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2437 mPointerGesture.downTime);
2438
2439 dispatchedGestureIdBits.clear();
2440 } else {
2441 BitSet32 upGestureIdBits;
2442 if (finishPreviousGesture) {
2443 upGestureIdBits = dispatchedGestureIdBits;
2444 } else {
2445 upGestureIdBits.value =
2446 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2447 }
2448 while (!upGestureIdBits.isEmpty()) {
2449 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2450
2451 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2452 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2453 mPointerGesture.lastGestureProperties,
2454 mPointerGesture.lastGestureCoords,
2455 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2456 0, mPointerGesture.downTime);
2457
2458 dispatchedGestureIdBits.clearBit(id);
2459 }
2460 }
2461 }
2462
2463 // Send motion events for all pointers that moved.
2464 if (moveNeeded) {
2465 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2466 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2467 mPointerGesture.currentGestureProperties,
2468 mPointerGesture.currentGestureCoords,
2469 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2470 mPointerGesture.downTime);
2471 }
2472
2473 // Send motion events for all pointers that went down.
2474 if (down) {
2475 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2476 ~dispatchedGestureIdBits.value);
2477 while (!downGestureIdBits.isEmpty()) {
2478 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2479 dispatchedGestureIdBits.markBit(id);
2480
2481 if (dispatchedGestureIdBits.count() == 1) {
2482 mPointerGesture.downTime = when;
2483 }
2484
2485 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2486 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2487 mPointerGesture.currentGestureCoords,
2488 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2489 0, mPointerGesture.downTime);
2490 }
2491 }
2492
2493 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002494 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002495 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2496 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2497 mPointerGesture.currentGestureProperties,
2498 mPointerGesture.currentGestureCoords,
2499 mPointerGesture.currentGestureIdToIndex,
2500 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2501 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2502 // Synthesize a hover move event after all pointers go up to indicate that
2503 // the pointer is hovering again even if the user is not currently touching
2504 // the touch pad. This ensures that a view will receive a fresh hover enter
2505 // event after a tap.
2506 float x, y;
2507 mPointerController->getPosition(&x, &y);
2508
2509 PointerProperties pointerProperties;
2510 pointerProperties.clear();
2511 pointerProperties.id = 0;
2512 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2513
2514 PointerCoords pointerCoords;
2515 pointerCoords.clear();
2516 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2517 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2518
2519 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002520 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2521 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2522 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2523 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2524 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002525 getListener()->notifyMotion(&args);
2526 }
2527
2528 // Update state.
2529 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2530 if (!down) {
2531 mPointerGesture.lastGestureIdBits.clear();
2532 } else {
2533 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2534 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2535 uint32_t id = idBits.clearFirstMarkedBit();
2536 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2537 mPointerGesture.lastGestureProperties[index].copyFrom(
2538 mPointerGesture.currentGestureProperties[index]);
2539 mPointerGesture.lastGestureCoords[index].copyFrom(
2540 mPointerGesture.currentGestureCoords[index]);
2541 mPointerGesture.lastGestureIdToIndex[id] = index;
2542 }
2543 }
2544}
2545
2546void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2547 // Cancel previously dispatches pointers.
2548 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2549 int32_t metaState = getContext()->getGlobalMetaState();
2550 int32_t buttonState = mCurrentRawState.buttonState;
2551 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2552 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2553 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2554 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2555 0, 0, mPointerGesture.downTime);
2556 }
2557
2558 // Reset the current pointer gesture.
2559 mPointerGesture.reset();
2560 mPointerVelocityControl.reset();
2561
2562 // Remove any current spots.
2563 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002564 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002565 mPointerController->clearSpots();
2566 }
2567}
2568
2569bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2570 bool* outFinishPreviousGesture, bool isTimeout) {
2571 *outCancelPreviousGesture = false;
2572 *outFinishPreviousGesture = false;
2573
2574 // Handle TAP timeout.
2575 if (isTimeout) {
2576#if DEBUG_GESTURES
2577 ALOGD("Gestures: Processing timeout");
2578#endif
2579
Michael Wright227c5542020-07-02 18:30:52 +01002580 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002581 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2582 // The tap/drag timeout has not yet expired.
2583 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2584 mConfig.pointerGestureTapDragInterval);
2585 } else {
2586 // The tap is finished.
2587#if DEBUG_GESTURES
2588 ALOGD("Gestures: TAP finished");
2589#endif
2590 *outFinishPreviousGesture = true;
2591
2592 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002593 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002594 mPointerGesture.currentGestureIdBits.clear();
2595
2596 mPointerVelocityControl.reset();
2597 return true;
2598 }
2599 }
2600
2601 // We did not handle this timeout.
2602 return false;
2603 }
2604
2605 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2606 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2607
2608 // Update the velocity tracker.
2609 {
2610 VelocityTracker::Position positions[MAX_POINTERS];
2611 uint32_t count = 0;
2612 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
2613 uint32_t id = idBits.clearFirstMarkedBit();
2614 const RawPointerData::Pointer& pointer =
2615 mCurrentRawState.rawPointerData.pointerForId(id);
2616 positions[count].x = pointer.x * mPointerXMovementScale;
2617 positions[count].y = pointer.y * mPointerYMovementScale;
2618 }
2619 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2620 positions);
2621 }
2622
2623 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2624 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002625 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2626 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2627 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002628 mPointerGesture.resetTap();
2629 }
2630
2631 // Pick a new active touch id if needed.
2632 // Choose an arbitrary pointer that just went down, if there is one.
2633 // Otherwise choose an arbitrary remaining pointer.
2634 // This guarantees we always have an active touch id when there is at least one pointer.
2635 // We keep the same active touch id for as long as possible.
2636 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2637 int32_t activeTouchId = lastActiveTouchId;
2638 if (activeTouchId < 0) {
2639 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2640 activeTouchId = mPointerGesture.activeTouchId =
2641 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2642 mPointerGesture.firstTouchTime = when;
2643 }
2644 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2645 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2646 activeTouchId = mPointerGesture.activeTouchId =
2647 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2648 } else {
2649 activeTouchId = mPointerGesture.activeTouchId = -1;
2650 }
2651 }
2652
2653 // Determine whether we are in quiet time.
2654 bool isQuietTime = false;
2655 if (activeTouchId < 0) {
2656 mPointerGesture.resetQuietTime();
2657 } else {
2658 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2659 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002660 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2661 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2662 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002663 currentFingerCount < 2) {
2664 // Enter quiet time when exiting swipe or freeform state.
2665 // This is to prevent accidentally entering the hover state and flinging the
2666 // pointer when finishing a swipe and there is still one pointer left onscreen.
2667 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002668 } else if (mPointerGesture.lastGestureMode ==
2669 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002670 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2671 // Enter quiet time when releasing the button and there are still two or more
2672 // fingers down. This may indicate that one finger was used to press the button
2673 // but it has not gone up yet.
2674 isQuietTime = true;
2675 }
2676 if (isQuietTime) {
2677 mPointerGesture.quietTime = when;
2678 }
2679 }
2680 }
2681
2682 // Switch states based on button and pointer state.
2683 if (isQuietTime) {
2684 // Case 1: Quiet time. (QUIET)
2685#if DEBUG_GESTURES
2686 ALOGD("Gestures: QUIET for next %0.3fms",
2687 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2688#endif
Michael Wright227c5542020-07-02 18:30:52 +01002689 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002690 *outFinishPreviousGesture = true;
2691 }
2692
2693 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002694 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002695 mPointerGesture.currentGestureIdBits.clear();
2696
2697 mPointerVelocityControl.reset();
2698 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2699 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2700 // The pointer follows the active touch point.
2701 // Emit DOWN, MOVE, UP events at the pointer location.
2702 //
2703 // Only the active touch matters; other fingers are ignored. This policy helps
2704 // to handle the case where the user places a second finger on the touch pad
2705 // to apply the necessary force to depress an integrated button below the surface.
2706 // We don't want the second finger to be delivered to applications.
2707 //
2708 // For this to work well, we need to make sure to track the pointer that is really
2709 // active. If the user first puts one finger down to click then adds another
2710 // finger to drag then the active pointer should switch to the finger that is
2711 // being dragged.
2712#if DEBUG_GESTURES
2713 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2714 "currentFingerCount=%d",
2715 activeTouchId, currentFingerCount);
2716#endif
2717 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002718 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002719 *outFinishPreviousGesture = true;
2720 mPointerGesture.activeGestureId = 0;
2721 }
2722
2723 // Switch pointers if needed.
2724 // Find the fastest pointer and follow it.
2725 if (activeTouchId >= 0 && currentFingerCount > 1) {
2726 int32_t bestId = -1;
2727 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2728 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2729 uint32_t id = idBits.clearFirstMarkedBit();
2730 float vx, vy;
2731 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2732 float speed = hypotf(vx, vy);
2733 if (speed > bestSpeed) {
2734 bestId = id;
2735 bestSpeed = speed;
2736 }
2737 }
2738 }
2739 if (bestId >= 0 && bestId != activeTouchId) {
2740 mPointerGesture.activeTouchId = activeTouchId = bestId;
2741#if DEBUG_GESTURES
2742 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2743 "bestId=%d, bestSpeed=%0.3f",
2744 bestId, bestSpeed);
2745#endif
2746 }
2747 }
2748
2749 float deltaX = 0, deltaY = 0;
2750 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2751 const RawPointerData::Pointer& currentPointer =
2752 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2753 const RawPointerData::Pointer& lastPointer =
2754 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2755 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2756 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2757
2758 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2759 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2760
2761 // Move the pointer using a relative motion.
2762 // When using spots, the click will occur at the position of the anchor
2763 // spot and all other spots will move there.
2764 mPointerController->move(deltaX, deltaY);
2765 } else {
2766 mPointerVelocityControl.reset();
2767 }
2768
2769 float x, y;
2770 mPointerController->getPosition(&x, &y);
2771
Michael Wright227c5542020-07-02 18:30:52 +01002772 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002773 mPointerGesture.currentGestureIdBits.clear();
2774 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2775 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2776 mPointerGesture.currentGestureProperties[0].clear();
2777 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2778 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2779 mPointerGesture.currentGestureCoords[0].clear();
2780 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2781 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2782 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2783 } else if (currentFingerCount == 0) {
2784 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002785 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002786 *outFinishPreviousGesture = true;
2787 }
2788
2789 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2790 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2791 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002792 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2793 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002794 lastFingerCount == 1) {
2795 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2796 float x, y;
2797 mPointerController->getPosition(&x, &y);
2798 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2799 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2800#if DEBUG_GESTURES
2801 ALOGD("Gestures: TAP");
2802#endif
2803
2804 mPointerGesture.tapUpTime = when;
2805 getContext()->requestTimeoutAtTime(when +
2806 mConfig.pointerGestureTapDragInterval);
2807
2808 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002809 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002810 mPointerGesture.currentGestureIdBits.clear();
2811 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2812 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2813 mPointerGesture.currentGestureProperties[0].clear();
2814 mPointerGesture.currentGestureProperties[0].id =
2815 mPointerGesture.activeGestureId;
2816 mPointerGesture.currentGestureProperties[0].toolType =
2817 AMOTION_EVENT_TOOL_TYPE_FINGER;
2818 mPointerGesture.currentGestureCoords[0].clear();
2819 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2820 mPointerGesture.tapX);
2821 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2822 mPointerGesture.tapY);
2823 mPointerGesture.currentGestureCoords[0]
2824 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2825
2826 tapped = true;
2827 } else {
2828#if DEBUG_GESTURES
2829 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2830 y - mPointerGesture.tapY);
2831#endif
2832 }
2833 } else {
2834#if DEBUG_GESTURES
2835 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2836 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2837 (when - mPointerGesture.tapDownTime) * 0.000001f);
2838 } else {
2839 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2840 }
2841#endif
2842 }
2843 }
2844
2845 mPointerVelocityControl.reset();
2846
2847 if (!tapped) {
2848#if DEBUG_GESTURES
2849 ALOGD("Gestures: NEUTRAL");
2850#endif
2851 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002852 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002853 mPointerGesture.currentGestureIdBits.clear();
2854 }
2855 } else if (currentFingerCount == 1) {
2856 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2857 // The pointer follows the active touch point.
2858 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2859 // When in TAP_DRAG, emit MOVE events at the pointer location.
2860 ALOG_ASSERT(activeTouchId >= 0);
2861
Michael Wright227c5542020-07-02 18:30:52 +01002862 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2863 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002864 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2865 float x, y;
2866 mPointerController->getPosition(&x, &y);
2867 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2868 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002869 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002870 } else {
2871#if DEBUG_GESTURES
2872 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2873 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2874#endif
2875 }
2876 } else {
2877#if DEBUG_GESTURES
2878 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2879 (when - mPointerGesture.tapUpTime) * 0.000001f);
2880#endif
2881 }
Michael Wright227c5542020-07-02 18:30:52 +01002882 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2883 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884 }
2885
2886 float deltaX = 0, deltaY = 0;
2887 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2888 const RawPointerData::Pointer& currentPointer =
2889 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2890 const RawPointerData::Pointer& lastPointer =
2891 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2892 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2893 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2894
2895 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2896 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2897
2898 // Move the pointer using a relative motion.
2899 // When using spots, the hover or drag will occur at the position of the anchor spot.
2900 mPointerController->move(deltaX, deltaY);
2901 } else {
2902 mPointerVelocityControl.reset();
2903 }
2904
2905 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002906 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907#if DEBUG_GESTURES
2908 ALOGD("Gestures: TAP_DRAG");
2909#endif
2910 down = true;
2911 } else {
2912#if DEBUG_GESTURES
2913 ALOGD("Gestures: HOVER");
2914#endif
Michael Wright227c5542020-07-02 18:30:52 +01002915 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002916 *outFinishPreviousGesture = true;
2917 }
2918 mPointerGesture.activeGestureId = 0;
2919 down = false;
2920 }
2921
2922 float x, y;
2923 mPointerController->getPosition(&x, &y);
2924
2925 mPointerGesture.currentGestureIdBits.clear();
2926 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2927 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2928 mPointerGesture.currentGestureProperties[0].clear();
2929 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2930 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2931 mPointerGesture.currentGestureCoords[0].clear();
2932 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2933 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2934 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2935 down ? 1.0f : 0.0f);
2936
2937 if (lastFingerCount == 0 && currentFingerCount != 0) {
2938 mPointerGesture.resetTap();
2939 mPointerGesture.tapDownTime = when;
2940 mPointerGesture.tapX = x;
2941 mPointerGesture.tapY = y;
2942 }
2943 } else {
2944 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2945 // We need to provide feedback for each finger that goes down so we cannot wait
2946 // for the fingers to move before deciding what to do.
2947 //
2948 // The ambiguous case is deciding what to do when there are two fingers down but they
2949 // have not moved enough to determine whether they are part of a drag or part of a
2950 // freeform gesture, or just a press or long-press at the pointer location.
2951 //
2952 // When there are two fingers we start with the PRESS hypothesis and we generate a
2953 // down at the pointer location.
2954 //
2955 // When the two fingers move enough or when additional fingers are added, we make
2956 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2957 ALOG_ASSERT(activeTouchId >= 0);
2958
2959 bool settled = when >=
2960 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002961 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2962 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2963 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002964 *outFinishPreviousGesture = true;
2965 } else if (!settled && currentFingerCount > lastFingerCount) {
2966 // Additional pointers have gone down but not yet settled.
2967 // Reset the gesture.
2968#if DEBUG_GESTURES
2969 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2970 "settle time remaining %0.3fms",
2971 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2972 when) * 0.000001f);
2973#endif
2974 *outCancelPreviousGesture = true;
2975 } else {
2976 // Continue previous gesture.
2977 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2978 }
2979
2980 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01002981 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002982 mPointerGesture.activeGestureId = 0;
2983 mPointerGesture.referenceIdBits.clear();
2984 mPointerVelocityControl.reset();
2985
2986 // Use the centroid and pointer location as the reference points for the gesture.
2987#if DEBUG_GESTURES
2988 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
2989 "settle time remaining %0.3fms",
2990 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2991 when) * 0.000001f);
2992#endif
2993 mCurrentRawState.rawPointerData
2994 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
2995 &mPointerGesture.referenceTouchY);
2996 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
2997 &mPointerGesture.referenceGestureY);
2998 }
2999
3000 // Clear the reference deltas for fingers not yet included in the reference calculation.
3001 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3002 ~mPointerGesture.referenceIdBits.value);
3003 !idBits.isEmpty();) {
3004 uint32_t id = idBits.clearFirstMarkedBit();
3005 mPointerGesture.referenceDeltas[id].dx = 0;
3006 mPointerGesture.referenceDeltas[id].dy = 0;
3007 }
3008 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3009
3010 // Add delta for all fingers and calculate a common movement delta.
3011 float commonDeltaX = 0, commonDeltaY = 0;
3012 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3013 mCurrentCookedState.fingerIdBits.value);
3014 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3015 bool first = (idBits == commonIdBits);
3016 uint32_t id = idBits.clearFirstMarkedBit();
3017 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3018 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3019 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3020 delta.dx += cpd.x - lpd.x;
3021 delta.dy += cpd.y - lpd.y;
3022
3023 if (first) {
3024 commonDeltaX = delta.dx;
3025 commonDeltaY = delta.dy;
3026 } else {
3027 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3028 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3029 }
3030 }
3031
3032 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003033 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003034 float dist[MAX_POINTER_ID + 1];
3035 int32_t distOverThreshold = 0;
3036 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3037 uint32_t id = idBits.clearFirstMarkedBit();
3038 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3039 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3040 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3041 distOverThreshold += 1;
3042 }
3043 }
3044
3045 // Only transition when at least two pointers have moved further than
3046 // the minimum distance threshold.
3047 if (distOverThreshold >= 2) {
3048 if (currentFingerCount > 2) {
3049 // There are more than two pointers, switch to FREEFORM.
3050#if DEBUG_GESTURES
3051 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3052 currentFingerCount);
3053#endif
3054 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003055 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003056 } else {
3057 // There are exactly two pointers.
3058 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3059 uint32_t id1 = idBits.clearFirstMarkedBit();
3060 uint32_t id2 = idBits.firstMarkedBit();
3061 const RawPointerData::Pointer& p1 =
3062 mCurrentRawState.rawPointerData.pointerForId(id1);
3063 const RawPointerData::Pointer& p2 =
3064 mCurrentRawState.rawPointerData.pointerForId(id2);
3065 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3066 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3067 // There are two pointers but they are too far apart for a SWIPE,
3068 // switch to FREEFORM.
3069#if DEBUG_GESTURES
3070 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3071 mutualDistance, mPointerGestureMaxSwipeWidth);
3072#endif
3073 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003074 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003075 } else {
3076 // There are two pointers. Wait for both pointers to start moving
3077 // before deciding whether this is a SWIPE or FREEFORM gesture.
3078 float dist1 = dist[id1];
3079 float dist2 = dist[id2];
3080 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3081 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3082 // Calculate the dot product of the displacement vectors.
3083 // When the vectors are oriented in approximately the same direction,
3084 // the angle betweeen them is near zero and the cosine of the angle
3085 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3086 // mag(v2).
3087 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3088 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3089 float dx1 = delta1.dx * mPointerXZoomScale;
3090 float dy1 = delta1.dy * mPointerYZoomScale;
3091 float dx2 = delta2.dx * mPointerXZoomScale;
3092 float dy2 = delta2.dy * mPointerYZoomScale;
3093 float dot = dx1 * dx2 + dy1 * dy2;
3094 float cosine = dot / (dist1 * dist2); // denominator always > 0
3095 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3096 // Pointers are moving in the same direction. Switch to SWIPE.
3097#if DEBUG_GESTURES
3098 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3099 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3100 "cosine %0.3f >= %0.3f",
3101 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3102 mConfig.pointerGestureMultitouchMinDistance, cosine,
3103 mConfig.pointerGestureSwipeTransitionAngleCosine);
3104#endif
Michael Wright227c5542020-07-02 18:30:52 +01003105 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003106 } else {
3107 // Pointers are moving in different directions. Switch to FREEFORM.
3108#if DEBUG_GESTURES
3109 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3110 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3111 "cosine %0.3f < %0.3f",
3112 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3113 mConfig.pointerGestureMultitouchMinDistance, cosine,
3114 mConfig.pointerGestureSwipeTransitionAngleCosine);
3115#endif
3116 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003117 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003118 }
3119 }
3120 }
3121 }
3122 }
Michael Wright227c5542020-07-02 18:30:52 +01003123 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003124 // Switch from SWIPE to FREEFORM if additional pointers go down.
3125 // Cancel previous gesture.
3126 if (currentFingerCount > 2) {
3127#if DEBUG_GESTURES
3128 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3129 currentFingerCount);
3130#endif
3131 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003132 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003133 }
3134 }
3135
3136 // Move the reference points based on the overall group motion of the fingers
3137 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003138 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003139 (commonDeltaX || commonDeltaY)) {
3140 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3141 uint32_t id = idBits.clearFirstMarkedBit();
3142 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3143 delta.dx = 0;
3144 delta.dy = 0;
3145 }
3146
3147 mPointerGesture.referenceTouchX += commonDeltaX;
3148 mPointerGesture.referenceTouchY += commonDeltaY;
3149
3150 commonDeltaX *= mPointerXMovementScale;
3151 commonDeltaY *= mPointerYMovementScale;
3152
3153 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3154 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3155
3156 mPointerGesture.referenceGestureX += commonDeltaX;
3157 mPointerGesture.referenceGestureY += commonDeltaY;
3158 }
3159
3160 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003161 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3162 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003163 // PRESS or SWIPE mode.
3164#if DEBUG_GESTURES
3165 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3166 "activeGestureId=%d, currentTouchPointerCount=%d",
3167 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3168#endif
3169 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3170
3171 mPointerGesture.currentGestureIdBits.clear();
3172 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3173 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3174 mPointerGesture.currentGestureProperties[0].clear();
3175 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3176 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3177 mPointerGesture.currentGestureCoords[0].clear();
3178 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3179 mPointerGesture.referenceGestureX);
3180 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3181 mPointerGesture.referenceGestureY);
3182 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003183 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003184 // FREEFORM mode.
3185#if DEBUG_GESTURES
3186 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3187 "activeGestureId=%d, currentTouchPointerCount=%d",
3188 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3189#endif
3190 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3191
3192 mPointerGesture.currentGestureIdBits.clear();
3193
3194 BitSet32 mappedTouchIdBits;
3195 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003196 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003197 // Initially, assign the active gesture id to the active touch point
3198 // if there is one. No other touch id bits are mapped yet.
3199 if (!*outCancelPreviousGesture) {
3200 mappedTouchIdBits.markBit(activeTouchId);
3201 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3202 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3203 mPointerGesture.activeGestureId;
3204 } else {
3205 mPointerGesture.activeGestureId = -1;
3206 }
3207 } else {
3208 // Otherwise, assume we mapped all touches from the previous frame.
3209 // Reuse all mappings that are still applicable.
3210 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3211 mCurrentCookedState.fingerIdBits.value;
3212 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3213
3214 // Check whether we need to choose a new active gesture id because the
3215 // current went went up.
3216 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3217 ~mCurrentCookedState.fingerIdBits.value);
3218 !upTouchIdBits.isEmpty();) {
3219 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3220 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3221 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3222 mPointerGesture.activeGestureId = -1;
3223 break;
3224 }
3225 }
3226 }
3227
3228#if DEBUG_GESTURES
3229 ALOGD("Gestures: FREEFORM follow up "
3230 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3231 "activeGestureId=%d",
3232 mappedTouchIdBits.value, usedGestureIdBits.value,
3233 mPointerGesture.activeGestureId);
3234#endif
3235
3236 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3237 for (uint32_t i = 0; i < currentFingerCount; i++) {
3238 uint32_t touchId = idBits.clearFirstMarkedBit();
3239 uint32_t gestureId;
3240 if (!mappedTouchIdBits.hasBit(touchId)) {
3241 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3242 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3243#if DEBUG_GESTURES
3244 ALOGD("Gestures: FREEFORM "
3245 "new mapping for touch id %d -> gesture id %d",
3246 touchId, gestureId);
3247#endif
3248 } else {
3249 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3250#if DEBUG_GESTURES
3251 ALOGD("Gestures: FREEFORM "
3252 "existing mapping for touch id %d -> gesture id %d",
3253 touchId, gestureId);
3254#endif
3255 }
3256 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3257 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3258
3259 const RawPointerData::Pointer& pointer =
3260 mCurrentRawState.rawPointerData.pointerForId(touchId);
3261 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3262 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3263 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3264
3265 mPointerGesture.currentGestureProperties[i].clear();
3266 mPointerGesture.currentGestureProperties[i].id = gestureId;
3267 mPointerGesture.currentGestureProperties[i].toolType =
3268 AMOTION_EVENT_TOOL_TYPE_FINGER;
3269 mPointerGesture.currentGestureCoords[i].clear();
3270 mPointerGesture.currentGestureCoords[i]
3271 .setAxisValue(AMOTION_EVENT_AXIS_X,
3272 mPointerGesture.referenceGestureX + deltaX);
3273 mPointerGesture.currentGestureCoords[i]
3274 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3275 mPointerGesture.referenceGestureY + deltaY);
3276 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3277 1.0f);
3278 }
3279
3280 if (mPointerGesture.activeGestureId < 0) {
3281 mPointerGesture.activeGestureId =
3282 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3283#if DEBUG_GESTURES
3284 ALOGD("Gestures: FREEFORM new "
3285 "activeGestureId=%d",
3286 mPointerGesture.activeGestureId);
3287#endif
3288 }
3289 }
3290 }
3291
3292 mPointerController->setButtonState(mCurrentRawState.buttonState);
3293
3294#if DEBUG_GESTURES
3295 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3296 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3297 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3298 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3299 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3300 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3301 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3302 uint32_t id = idBits.clearFirstMarkedBit();
3303 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3304 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3305 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3306 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3307 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3308 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3309 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3310 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3311 }
3312 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3313 uint32_t id = idBits.clearFirstMarkedBit();
3314 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3315 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3316 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3317 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3318 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3319 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3320 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3321 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3322 }
3323#endif
3324 return true;
3325}
3326
3327void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3328 mPointerSimple.currentCoords.clear();
3329 mPointerSimple.currentProperties.clear();
3330
3331 bool down, hovering;
3332 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3333 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3334 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3335 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3336 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3337 mPointerController->setPosition(x, y);
3338
3339 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3340 down = !hovering;
3341
3342 mPointerController->getPosition(&x, &y);
3343 mPointerSimple.currentCoords.copyFrom(
3344 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3345 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3346 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3347 mPointerSimple.currentProperties.id = 0;
3348 mPointerSimple.currentProperties.toolType =
3349 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3350 } else {
3351 down = false;
3352 hovering = false;
3353 }
3354
3355 dispatchPointerSimple(when, policyFlags, down, hovering);
3356}
3357
3358void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3359 abortPointerSimple(when, policyFlags);
3360}
3361
3362void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3363 mPointerSimple.currentCoords.clear();
3364 mPointerSimple.currentProperties.clear();
3365
3366 bool down, hovering;
3367 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3368 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3369 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3370 float deltaX = 0, deltaY = 0;
3371 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3372 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3373 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3374 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3375 mPointerXMovementScale;
3376 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3377 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3378 mPointerYMovementScale;
3379
3380 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3381 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3382
3383 mPointerController->move(deltaX, deltaY);
3384 } else {
3385 mPointerVelocityControl.reset();
3386 }
3387
3388 down = isPointerDown(mCurrentRawState.buttonState);
3389 hovering = !down;
3390
3391 float x, y;
3392 mPointerController->getPosition(&x, &y);
3393 mPointerSimple.currentCoords.copyFrom(
3394 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3395 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3396 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3397 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3398 hovering ? 0.0f : 1.0f);
3399 mPointerSimple.currentProperties.id = 0;
3400 mPointerSimple.currentProperties.toolType =
3401 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3402 } else {
3403 mPointerVelocityControl.reset();
3404
3405 down = false;
3406 hovering = false;
3407 }
3408
3409 dispatchPointerSimple(when, policyFlags, down, hovering);
3410}
3411
3412void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3413 abortPointerSimple(when, policyFlags);
3414
3415 mPointerVelocityControl.reset();
3416}
3417
3418void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3419 bool hovering) {
3420 int32_t metaState = getContext()->getGlobalMetaState();
3421 int32_t displayId = mViewport.displayId;
3422
3423 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003424 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003425 mPointerController->clearSpots();
3426 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003427 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003428 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003429 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003430 }
3431 displayId = mPointerController->getDisplayId();
3432
3433 float xCursorPosition;
3434 float yCursorPosition;
3435 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3436
3437 if (mPointerSimple.down && !down) {
3438 mPointerSimple.down = false;
3439
3440 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003441 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3442 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003443 mLastRawState.buttonState, MotionClassification::NONE,
3444 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3445 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3446 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3447 /* videoFrames */ {});
3448 getListener()->notifyMotion(&args);
3449 }
3450
3451 if (mPointerSimple.hovering && !hovering) {
3452 mPointerSimple.hovering = false;
3453
3454 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003455 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3456 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3457 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003458 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3459 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3460 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3461 /* videoFrames */ {});
3462 getListener()->notifyMotion(&args);
3463 }
3464
3465 if (down) {
3466 if (!mPointerSimple.down) {
3467 mPointerSimple.down = true;
3468 mPointerSimple.downTime = when;
3469
3470 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003471 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003472 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3473 metaState, mCurrentRawState.buttonState,
3474 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3475 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3476 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3477 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3478 getListener()->notifyMotion(&args);
3479 }
3480
3481 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003482 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3483 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003484 mCurrentRawState.buttonState, MotionClassification::NONE,
3485 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3486 &mPointerSimple.currentCoords, mOrientedXPrecision,
3487 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3488 mPointerSimple.downTime, /* videoFrames */ {});
3489 getListener()->notifyMotion(&args);
3490 }
3491
3492 if (hovering) {
3493 if (!mPointerSimple.hovering) {
3494 mPointerSimple.hovering = true;
3495
3496 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003497 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003498 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3499 metaState, mCurrentRawState.buttonState,
3500 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3501 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3502 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3503 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3504 getListener()->notifyMotion(&args);
3505 }
3506
3507 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003508 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3509 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3510 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003511 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3512 &mPointerSimple.currentCoords, mOrientedXPrecision,
3513 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3514 mPointerSimple.downTime, /* videoFrames */ {});
3515 getListener()->notifyMotion(&args);
3516 }
3517
3518 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3519 float vscroll = mCurrentRawState.rawVScroll;
3520 float hscroll = mCurrentRawState.rawHScroll;
3521 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3522 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3523
3524 // Send scroll.
3525 PointerCoords pointerCoords;
3526 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3527 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3528 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3529
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003530 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3531 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003532 mCurrentRawState.buttonState, MotionClassification::NONE,
3533 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3534 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3535 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3536 /* videoFrames */ {});
3537 getListener()->notifyMotion(&args);
3538 }
3539
3540 // Save state.
3541 if (down || hovering) {
3542 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3543 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3544 } else {
3545 mPointerSimple.reset();
3546 }
3547}
3548
3549void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3550 mPointerSimple.currentCoords.clear();
3551 mPointerSimple.currentProperties.clear();
3552
3553 dispatchPointerSimple(when, policyFlags, false, false);
3554}
3555
3556void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3557 int32_t action, int32_t actionButton, int32_t flags,
3558 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3559 const PointerProperties* properties,
3560 const PointerCoords* coords, const uint32_t* idToIndex,
3561 BitSet32 idBits, int32_t changedId, float xPrecision,
3562 float yPrecision, nsecs_t downTime) {
3563 PointerCoords pointerCoords[MAX_POINTERS];
3564 PointerProperties pointerProperties[MAX_POINTERS];
3565 uint32_t pointerCount = 0;
3566 while (!idBits.isEmpty()) {
3567 uint32_t id = idBits.clearFirstMarkedBit();
3568 uint32_t index = idToIndex[id];
3569 pointerProperties[pointerCount].copyFrom(properties[index]);
3570 pointerCoords[pointerCount].copyFrom(coords[index]);
3571
3572 if (changedId >= 0 && id == uint32_t(changedId)) {
3573 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3574 }
3575
3576 pointerCount += 1;
3577 }
3578
3579 ALOG_ASSERT(pointerCount != 0);
3580
3581 if (changedId >= 0 && pointerCount == 1) {
3582 // Replace initial down and final up action.
3583 // We can compare the action without masking off the changed pointer index
3584 // because we know the index is 0.
3585 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3586 action = AMOTION_EVENT_ACTION_DOWN;
3587 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003588 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3589 action = AMOTION_EVENT_ACTION_CANCEL;
3590 } else {
3591 action = AMOTION_EVENT_ACTION_UP;
3592 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593 } else {
3594 // Can't happen.
3595 ALOG_ASSERT(false);
3596 }
3597 }
3598 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3599 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003600 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003601 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3602 }
3603 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3604 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003605 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003606 std::for_each(frames.begin(), frames.end(),
3607 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003608 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3609 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003610 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3611 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3612 downTime, std::move(frames));
3613 getListener()->notifyMotion(&args);
3614}
3615
3616bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3617 const PointerCoords* inCoords,
3618 const uint32_t* inIdToIndex,
3619 PointerProperties* outProperties,
3620 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3621 BitSet32 idBits) const {
3622 bool changed = false;
3623 while (!idBits.isEmpty()) {
3624 uint32_t id = idBits.clearFirstMarkedBit();
3625 uint32_t inIndex = inIdToIndex[id];
3626 uint32_t outIndex = outIdToIndex[id];
3627
3628 const PointerProperties& curInProperties = inProperties[inIndex];
3629 const PointerCoords& curInCoords = inCoords[inIndex];
3630 PointerProperties& curOutProperties = outProperties[outIndex];
3631 PointerCoords& curOutCoords = outCoords[outIndex];
3632
3633 if (curInProperties != curOutProperties) {
3634 curOutProperties.copyFrom(curInProperties);
3635 changed = true;
3636 }
3637
3638 if (curInCoords != curOutCoords) {
3639 curOutCoords.copyFrom(curInCoords);
3640 changed = true;
3641 }
3642 }
3643 return changed;
3644}
3645
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003646void TouchInputMapper::cancelTouch(nsecs_t when) {
3647 abortPointerUsage(when, 0 /*policyFlags*/);
3648 abortTouches(when, 0 /* policyFlags*/);
3649}
3650
Arthur Hung4197f6b2020-03-16 15:39:59 +08003651// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003652void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003653 // Scale to surface coordinate.
3654 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3655 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3656
3657 // Rotate to surface coordinate.
3658 // 0 - no swap and reverse.
3659 // 90 - swap x/y and reverse y.
3660 // 180 - reverse x, y.
3661 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003662 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003663 case DISPLAY_ORIENTATION_0:
3664 x = xScaled + mXTranslate;
3665 y = yScaled + mYTranslate;
3666 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003667 case DISPLAY_ORIENTATION_90:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003668 y = mSurfaceRight - xScaled;
3669 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003670 break;
3671 case DISPLAY_ORIENTATION_180:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003672 x = mSurfaceRight - xScaled;
3673 y = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003674 break;
3675 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003676 y = xScaled + mXTranslate;
3677 x = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003678 break;
3679 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003680 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003681 }
3682}
3683
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003684bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003685 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3686 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3687
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003688 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003689 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003690 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003691 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003692}
3693
3694const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3695 for (const VirtualKey& virtualKey : mVirtualKeys) {
3696#if DEBUG_VIRTUAL_KEYS
3697 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3698 "left=%d, top=%d, right=%d, bottom=%d",
3699 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3700 virtualKey.hitRight, virtualKey.hitBottom);
3701#endif
3702
3703 if (virtualKey.isHit(x, y)) {
3704 return &virtualKey;
3705 }
3706 }
3707
3708 return nullptr;
3709}
3710
3711void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3712 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3713 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3714
3715 current->rawPointerData.clearIdBits();
3716
3717 if (currentPointerCount == 0) {
3718 // No pointers to assign.
3719 return;
3720 }
3721
3722 if (lastPointerCount == 0) {
3723 // All pointers are new.
3724 for (uint32_t i = 0; i < currentPointerCount; i++) {
3725 uint32_t id = i;
3726 current->rawPointerData.pointers[i].id = id;
3727 current->rawPointerData.idToIndex[id] = i;
3728 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3729 }
3730 return;
3731 }
3732
3733 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3734 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3735 // Only one pointer and no change in count so it must have the same id as before.
3736 uint32_t id = last->rawPointerData.pointers[0].id;
3737 current->rawPointerData.pointers[0].id = id;
3738 current->rawPointerData.idToIndex[id] = 0;
3739 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3740 return;
3741 }
3742
3743 // General case.
3744 // We build a heap of squared euclidean distances between current and last pointers
3745 // associated with the current and last pointer indices. Then, we find the best
3746 // match (by distance) for each current pointer.
3747 // The pointers must have the same tool type but it is possible for them to
3748 // transition from hovering to touching or vice-versa while retaining the same id.
3749 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3750
3751 uint32_t heapSize = 0;
3752 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3753 currentPointerIndex++) {
3754 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3755 lastPointerIndex++) {
3756 const RawPointerData::Pointer& currentPointer =
3757 current->rawPointerData.pointers[currentPointerIndex];
3758 const RawPointerData::Pointer& lastPointer =
3759 last->rawPointerData.pointers[lastPointerIndex];
3760 if (currentPointer.toolType == lastPointer.toolType) {
3761 int64_t deltaX = currentPointer.x - lastPointer.x;
3762 int64_t deltaY = currentPointer.y - lastPointer.y;
3763
3764 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3765
3766 // Insert new element into the heap (sift up).
3767 heap[heapSize].currentPointerIndex = currentPointerIndex;
3768 heap[heapSize].lastPointerIndex = lastPointerIndex;
3769 heap[heapSize].distance = distance;
3770 heapSize += 1;
3771 }
3772 }
3773 }
3774
3775 // Heapify
3776 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3777 startIndex -= 1;
3778 for (uint32_t parentIndex = startIndex;;) {
3779 uint32_t childIndex = parentIndex * 2 + 1;
3780 if (childIndex >= heapSize) {
3781 break;
3782 }
3783
3784 if (childIndex + 1 < heapSize &&
3785 heap[childIndex + 1].distance < heap[childIndex].distance) {
3786 childIndex += 1;
3787 }
3788
3789 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3790 break;
3791 }
3792
3793 swap(heap[parentIndex], heap[childIndex]);
3794 parentIndex = childIndex;
3795 }
3796 }
3797
3798#if DEBUG_POINTER_ASSIGNMENT
3799 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3800 for (size_t i = 0; i < heapSize; i++) {
3801 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3802 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3803 }
3804#endif
3805
3806 // Pull matches out by increasing order of distance.
3807 // To avoid reassigning pointers that have already been matched, the loop keeps track
3808 // of which last and current pointers have been matched using the matchedXXXBits variables.
3809 // It also tracks the used pointer id bits.
3810 BitSet32 matchedLastBits(0);
3811 BitSet32 matchedCurrentBits(0);
3812 BitSet32 usedIdBits(0);
3813 bool first = true;
3814 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3815 while (heapSize > 0) {
3816 if (first) {
3817 // The first time through the loop, we just consume the root element of
3818 // the heap (the one with smallest distance).
3819 first = false;
3820 } else {
3821 // Previous iterations consumed the root element of the heap.
3822 // Pop root element off of the heap (sift down).
3823 heap[0] = heap[heapSize];
3824 for (uint32_t parentIndex = 0;;) {
3825 uint32_t childIndex = parentIndex * 2 + 1;
3826 if (childIndex >= heapSize) {
3827 break;
3828 }
3829
3830 if (childIndex + 1 < heapSize &&
3831 heap[childIndex + 1].distance < heap[childIndex].distance) {
3832 childIndex += 1;
3833 }
3834
3835 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3836 break;
3837 }
3838
3839 swap(heap[parentIndex], heap[childIndex]);
3840 parentIndex = childIndex;
3841 }
3842
3843#if DEBUG_POINTER_ASSIGNMENT
3844 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3845 for (size_t i = 0; i < heapSize; i++) {
3846 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3847 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3848 }
3849#endif
3850 }
3851
3852 heapSize -= 1;
3853
3854 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3855 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3856
3857 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3858 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3859
3860 matchedCurrentBits.markBit(currentPointerIndex);
3861 matchedLastBits.markBit(lastPointerIndex);
3862
3863 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3864 current->rawPointerData.pointers[currentPointerIndex].id = id;
3865 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3866 current->rawPointerData.markIdBit(id,
3867 current->rawPointerData.isHovering(
3868 currentPointerIndex));
3869 usedIdBits.markBit(id);
3870
3871#if DEBUG_POINTER_ASSIGNMENT
3872 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3873 ", distance=%" PRIu64,
3874 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3875#endif
3876 break;
3877 }
3878 }
3879
3880 // Assign fresh ids to pointers that were not matched in the process.
3881 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3882 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3883 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3884
3885 current->rawPointerData.pointers[currentPointerIndex].id = id;
3886 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3887 current->rawPointerData.markIdBit(id,
3888 current->rawPointerData.isHovering(currentPointerIndex));
3889
3890#if DEBUG_POINTER_ASSIGNMENT
3891 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3892#endif
3893 }
3894}
3895
3896int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3897 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3898 return AKEY_STATE_VIRTUAL;
3899 }
3900
3901 for (const VirtualKey& virtualKey : mVirtualKeys) {
3902 if (virtualKey.keyCode == keyCode) {
3903 return AKEY_STATE_UP;
3904 }
3905 }
3906
3907 return AKEY_STATE_UNKNOWN;
3908}
3909
3910int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3911 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3912 return AKEY_STATE_VIRTUAL;
3913 }
3914
3915 for (const VirtualKey& virtualKey : mVirtualKeys) {
3916 if (virtualKey.scanCode == scanCode) {
3917 return AKEY_STATE_UP;
3918 }
3919 }
3920
3921 return AKEY_STATE_UNKNOWN;
3922}
3923
3924bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3925 const int32_t* keyCodes, uint8_t* outFlags) {
3926 for (const VirtualKey& virtualKey : mVirtualKeys) {
3927 for (size_t i = 0; i < numCodes; i++) {
3928 if (virtualKey.keyCode == keyCodes[i]) {
3929 outFlags[i] = 1;
3930 }
3931 }
3932 }
3933
3934 return true;
3935}
3936
3937std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3938 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003939 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003940 return std::make_optional(mPointerController->getDisplayId());
3941 } else {
3942 return std::make_optional(mViewport.displayId);
3943 }
3944 }
3945 return std::nullopt;
3946}
3947
3948} // namespace android