blob: 86229f902fe57895697d9e625748d57385d4dbc2 [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);
Chris Ye364fdb52020-08-05 15:07:56 -07001783 // Exclude unscaled device for inside surface checking.
1784 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001785 // If exactly one pointer went down, check for virtual key hit.
1786 // Otherwise we will drop the entire stroke.
1787 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1788 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1789 if (virtualKey) {
1790 mCurrentVirtualKey.down = true;
1791 mCurrentVirtualKey.downTime = when;
1792 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1793 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1794 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001795 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1796 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001797
1798 if (!mCurrentVirtualKey.ignored) {
1799#if DEBUG_VIRTUAL_KEYS
1800 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1801 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1802#endif
1803 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1804 AKEY_EVENT_FLAG_FROM_SYSTEM |
1805 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1806 }
1807 }
1808 }
1809 return true;
1810 }
1811 }
1812
1813 // Disable all virtual key touches that happen within a short time interval of the
1814 // most recent touch within the screen area. The idea is to filter out stray
1815 // virtual key presses when interacting with the touch screen.
1816 //
1817 // Problems we're trying to solve:
1818 //
1819 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1820 // virtual key area that is implemented by a separate touch panel and accidentally
1821 // triggers a virtual key.
1822 //
1823 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1824 // area and accidentally triggers a virtual key. This often happens when virtual keys
1825 // are layed out below the screen near to where the on screen keyboard's space bar
1826 // is displayed.
1827 if (mConfig.virtualKeyQuietTime > 0 &&
1828 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001829 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001830 }
1831 return false;
1832}
1833
1834void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1835 int32_t keyEventAction, int32_t keyEventFlags) {
1836 int32_t keyCode = mCurrentVirtualKey.keyCode;
1837 int32_t scanCode = mCurrentVirtualKey.scanCode;
1838 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001839 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001840 policyFlags |= POLICY_FLAG_VIRTUAL;
1841
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001842 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1843 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1844 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001845 getListener()->notifyKey(&args);
1846}
1847
1848void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1849 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1850 if (!currentIdBits.isEmpty()) {
1851 int32_t metaState = getContext()->getGlobalMetaState();
1852 int32_t buttonState = mCurrentCookedState.buttonState;
1853 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1854 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1855 mCurrentCookedState.cookedPointerData.pointerProperties,
1856 mCurrentCookedState.cookedPointerData.pointerCoords,
1857 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1858 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1859 mCurrentMotionAborted = true;
1860 }
1861}
1862
1863void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1864 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1865 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1866 int32_t metaState = getContext()->getGlobalMetaState();
1867 int32_t buttonState = mCurrentCookedState.buttonState;
1868
1869 if (currentIdBits == lastIdBits) {
1870 if (!currentIdBits.isEmpty()) {
1871 // No pointer id changes so this is a move event.
1872 // The listener takes care of batching moves so we don't have to deal with that here.
1873 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1874 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1875 mCurrentCookedState.cookedPointerData.pointerProperties,
1876 mCurrentCookedState.cookedPointerData.pointerCoords,
1877 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1878 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1879 }
1880 } else {
1881 // There may be pointers going up and pointers going down and pointers moving
1882 // all at the same time.
1883 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1884 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1885 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1886 BitSet32 dispatchedIdBits(lastIdBits.value);
1887
1888 // Update last coordinates of pointers that have moved so that we observe the new
1889 // pointer positions at the same time as other pointers that have just gone up.
1890 bool moveNeeded =
1891 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1892 mCurrentCookedState.cookedPointerData.pointerCoords,
1893 mCurrentCookedState.cookedPointerData.idToIndex,
1894 mLastCookedState.cookedPointerData.pointerProperties,
1895 mLastCookedState.cookedPointerData.pointerCoords,
1896 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1897 if (buttonState != mLastCookedState.buttonState) {
1898 moveNeeded = true;
1899 }
1900
1901 // Dispatch pointer up events.
1902 while (!upIdBits.isEmpty()) {
1903 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001904 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1905 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1906 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001907 mLastCookedState.cookedPointerData.pointerProperties,
1908 mLastCookedState.cookedPointerData.pointerCoords,
1909 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1910 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1911 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001912 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001913 }
1914
1915 // Dispatch move events if any of the remaining pointers moved from their old locations.
1916 // Although applications receive new locations as part of individual pointer up
1917 // events, they do not generally handle them except when presented in a move event.
1918 if (moveNeeded && !moveIdBits.isEmpty()) {
1919 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1920 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1921 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1922 mCurrentCookedState.cookedPointerData.pointerCoords,
1923 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1924 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1925 }
1926
1927 // Dispatch pointer down events using the new pointer locations.
1928 while (!downIdBits.isEmpty()) {
1929 uint32_t downId = downIdBits.clearFirstMarkedBit();
1930 dispatchedIdBits.markBit(downId);
1931
1932 if (dispatchedIdBits.count() == 1) {
1933 // First pointer is going down. Set down time.
1934 mDownTime = when;
1935 }
1936
1937 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1938 metaState, buttonState, 0,
1939 mCurrentCookedState.cookedPointerData.pointerProperties,
1940 mCurrentCookedState.cookedPointerData.pointerCoords,
1941 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1942 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1943 }
1944 }
1945}
1946
1947void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1948 if (mSentHoverEnter &&
1949 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1950 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1951 int32_t metaState = getContext()->getGlobalMetaState();
1952 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1953 mLastCookedState.buttonState, 0,
1954 mLastCookedState.cookedPointerData.pointerProperties,
1955 mLastCookedState.cookedPointerData.pointerCoords,
1956 mLastCookedState.cookedPointerData.idToIndex,
1957 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1958 mOrientedYPrecision, mDownTime);
1959 mSentHoverEnter = false;
1960 }
1961}
1962
1963void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1964 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1965 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1966 int32_t metaState = getContext()->getGlobalMetaState();
1967 if (!mSentHoverEnter) {
1968 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1969 metaState, mCurrentRawState.buttonState, 0,
1970 mCurrentCookedState.cookedPointerData.pointerProperties,
1971 mCurrentCookedState.cookedPointerData.pointerCoords,
1972 mCurrentCookedState.cookedPointerData.idToIndex,
1973 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1974 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1975 mSentHoverEnter = true;
1976 }
1977
1978 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1979 mCurrentRawState.buttonState, 0,
1980 mCurrentCookedState.cookedPointerData.pointerProperties,
1981 mCurrentCookedState.cookedPointerData.pointerCoords,
1982 mCurrentCookedState.cookedPointerData.idToIndex,
1983 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1984 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1985 }
1986}
1987
1988void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
1989 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
1990 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
1991 const int32_t metaState = getContext()->getGlobalMetaState();
1992 int32_t buttonState = mLastCookedState.buttonState;
1993 while (!releasedButtons.isEmpty()) {
1994 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
1995 buttonState &= ~actionButton;
1996 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1997 actionButton, 0, metaState, buttonState, 0,
1998 mCurrentCookedState.cookedPointerData.pointerProperties,
1999 mCurrentCookedState.cookedPointerData.pointerCoords,
2000 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2001 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2002 }
2003}
2004
2005void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2006 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2007 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2008 const int32_t metaState = getContext()->getGlobalMetaState();
2009 int32_t buttonState = mLastCookedState.buttonState;
2010 while (!pressedButtons.isEmpty()) {
2011 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2012 buttonState |= actionButton;
2013 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2014 0, metaState, buttonState, 0,
2015 mCurrentCookedState.cookedPointerData.pointerProperties,
2016 mCurrentCookedState.cookedPointerData.pointerCoords,
2017 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2018 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2019 }
2020}
2021
2022const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2023 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2024 return cookedPointerData.touchingIdBits;
2025 }
2026 return cookedPointerData.hoveringIdBits;
2027}
2028
2029void TouchInputMapper::cookPointerData() {
2030 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2031
2032 mCurrentCookedState.cookedPointerData.clear();
2033 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2034 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2035 mCurrentRawState.rawPointerData.hoveringIdBits;
2036 mCurrentCookedState.cookedPointerData.touchingIdBits =
2037 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002038 mCurrentCookedState.cookedPointerData.canceledIdBits =
2039 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002040
2041 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2042 mCurrentCookedState.buttonState = 0;
2043 } else {
2044 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2045 }
2046
2047 // Walk through the the active pointers and map device coordinates onto
2048 // surface coordinates and adjust for display orientation.
2049 for (uint32_t i = 0; i < currentPointerCount; i++) {
2050 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2051
2052 // Size
2053 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2054 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002055 case Calibration::SizeCalibration::GEOMETRIC:
2056 case Calibration::SizeCalibration::DIAMETER:
2057 case Calibration::SizeCalibration::BOX:
2058 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002059 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2060 touchMajor = in.touchMajor;
2061 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2062 toolMajor = in.toolMajor;
2063 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2064 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2065 : in.touchMajor;
2066 } else if (mRawPointerAxes.touchMajor.valid) {
2067 toolMajor = touchMajor = in.touchMajor;
2068 toolMinor = touchMinor =
2069 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2070 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2071 : in.touchMajor;
2072 } else if (mRawPointerAxes.toolMajor.valid) {
2073 touchMajor = toolMajor = in.toolMajor;
2074 touchMinor = toolMinor =
2075 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2076 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2077 : in.toolMajor;
2078 } else {
2079 ALOG_ASSERT(false,
2080 "No touch or tool axes. "
2081 "Size calibration should have been resolved to NONE.");
2082 touchMajor = 0;
2083 touchMinor = 0;
2084 toolMajor = 0;
2085 toolMinor = 0;
2086 size = 0;
2087 }
2088
2089 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2090 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2091 if (touchingCount > 1) {
2092 touchMajor /= touchingCount;
2093 touchMinor /= touchingCount;
2094 toolMajor /= touchingCount;
2095 toolMinor /= touchingCount;
2096 size /= touchingCount;
2097 }
2098 }
2099
Michael Wright227c5542020-07-02 18:30:52 +01002100 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002101 touchMajor *= mGeometricScale;
2102 touchMinor *= mGeometricScale;
2103 toolMajor *= mGeometricScale;
2104 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002105 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002106 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2107 touchMinor = touchMajor;
2108 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2109 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002110 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002111 touchMinor = touchMajor;
2112 toolMinor = toolMajor;
2113 }
2114
2115 mCalibration.applySizeScaleAndBias(&touchMajor);
2116 mCalibration.applySizeScaleAndBias(&touchMinor);
2117 mCalibration.applySizeScaleAndBias(&toolMajor);
2118 mCalibration.applySizeScaleAndBias(&toolMinor);
2119 size *= mSizeScale;
2120 break;
2121 default:
2122 touchMajor = 0;
2123 touchMinor = 0;
2124 toolMajor = 0;
2125 toolMinor = 0;
2126 size = 0;
2127 break;
2128 }
2129
2130 // Pressure
2131 float pressure;
2132 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002133 case Calibration::PressureCalibration::PHYSICAL:
2134 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002135 pressure = in.pressure * mPressureScale;
2136 break;
2137 default:
2138 pressure = in.isHovering ? 0 : 1;
2139 break;
2140 }
2141
2142 // Tilt and Orientation
2143 float tilt;
2144 float orientation;
2145 if (mHaveTilt) {
2146 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2147 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2148 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2149 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2150 } else {
2151 tilt = 0;
2152
2153 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002154 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002155 orientation = in.orientation * mOrientationScale;
2156 break;
Michael Wright227c5542020-07-02 18:30:52 +01002157 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002158 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2159 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2160 if (c1 != 0 || c2 != 0) {
2161 orientation = atan2f(c1, c2) * 0.5f;
2162 float confidence = hypotf(c1, c2);
2163 float scale = 1.0f + confidence / 16.0f;
2164 touchMajor *= scale;
2165 touchMinor /= scale;
2166 toolMajor *= scale;
2167 toolMinor /= scale;
2168 } else {
2169 orientation = 0;
2170 }
2171 break;
2172 }
2173 default:
2174 orientation = 0;
2175 }
2176 }
2177
2178 // Distance
2179 float distance;
2180 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002181 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002182 distance = in.distance * mDistanceScale;
2183 break;
2184 default:
2185 distance = 0;
2186 }
2187
2188 // Coverage
2189 int32_t rawLeft, rawTop, rawRight, rawBottom;
2190 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002191 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002192 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2193 rawRight = in.toolMinor & 0x0000ffff;
2194 rawBottom = in.toolMajor & 0x0000ffff;
2195 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2196 break;
2197 default:
2198 rawLeft = rawTop = rawRight = rawBottom = 0;
2199 break;
2200 }
2201
2202 // Adjust X,Y coords for device calibration
2203 // TODO: Adjust coverage coords?
2204 float xTransformed = in.x, yTransformed = in.y;
2205 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002206 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002207
2208 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002209 float left, top, right, bottom;
2210
2211 switch (mSurfaceOrientation) {
2212 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002213 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2214 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2215 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2216 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2217 orientation -= M_PI_2;
2218 if (mOrientedRanges.haveOrientation &&
2219 orientation < mOrientedRanges.orientation.min) {
2220 orientation +=
2221 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2222 }
2223 break;
2224 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002225 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2226 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2227 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2228 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2229 orientation -= M_PI;
2230 if (mOrientedRanges.haveOrientation &&
2231 orientation < mOrientedRanges.orientation.min) {
2232 orientation +=
2233 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2234 }
2235 break;
2236 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002237 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2238 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2239 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2240 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2241 orientation += M_PI_2;
2242 if (mOrientedRanges.haveOrientation &&
2243 orientation > mOrientedRanges.orientation.max) {
2244 orientation -=
2245 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2246 }
2247 break;
2248 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002249 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2250 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2251 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2252 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2253 break;
2254 }
2255
2256 // Write output coords.
2257 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2258 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002259 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2260 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002261 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2262 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2263 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2264 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2265 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2266 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2267 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002268 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002269 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2270 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2271 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2272 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2273 } else {
2274 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2275 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2276 }
2277
Chris Ye364fdb52020-08-05 15:07:56 -07002278 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002279 uint32_t id = in.id;
2280 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2281 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2282 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2283 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2284 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2285 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2286 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2287 }
2288
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002289 // Write output properties.
2290 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002291 properties.clear();
2292 properties.id = id;
2293 properties.toolType = in.toolType;
2294
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002295 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002297 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002298 }
2299}
2300
2301void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2302 PointerUsage pointerUsage) {
2303 if (pointerUsage != mPointerUsage) {
2304 abortPointerUsage(when, policyFlags);
2305 mPointerUsage = pointerUsage;
2306 }
2307
2308 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002309 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002310 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2311 break;
Michael Wright227c5542020-07-02 18:30:52 +01002312 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002313 dispatchPointerStylus(when, policyFlags);
2314 break;
Michael Wright227c5542020-07-02 18:30:52 +01002315 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002316 dispatchPointerMouse(when, policyFlags);
2317 break;
Michael Wright227c5542020-07-02 18:30:52 +01002318 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002319 break;
2320 }
2321}
2322
2323void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2324 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002325 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002326 abortPointerGestures(when, policyFlags);
2327 break;
Michael Wright227c5542020-07-02 18:30:52 +01002328 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002329 abortPointerStylus(when, policyFlags);
2330 break;
Michael Wright227c5542020-07-02 18:30:52 +01002331 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002332 abortPointerMouse(when, policyFlags);
2333 break;
Michael Wright227c5542020-07-02 18:30:52 +01002334 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002335 break;
2336 }
2337
Michael Wright227c5542020-07-02 18:30:52 +01002338 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002339}
2340
2341void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2342 // Update current gesture coordinates.
2343 bool cancelPreviousGesture, finishPreviousGesture;
2344 bool sendEvents =
2345 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2346 if (!sendEvents) {
2347 return;
2348 }
2349 if (finishPreviousGesture) {
2350 cancelPreviousGesture = false;
2351 }
2352
2353 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002354 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002355 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 if (finishPreviousGesture || cancelPreviousGesture) {
2357 mPointerController->clearSpots();
2358 }
2359
Michael Wright227c5542020-07-02 18:30:52 +01002360 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2362 mPointerGesture.currentGestureIdToIndex,
2363 mPointerGesture.currentGestureIdBits,
2364 mPointerController->getDisplayId());
2365 }
2366 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002367 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 }
2369
2370 // Show or hide the pointer if needed.
2371 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002372 case PointerGesture::Mode::NEUTRAL:
2373 case PointerGesture::Mode::QUIET:
2374 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2375 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002376 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002377 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 }
2379 break;
Michael Wright227c5542020-07-02 18:30:52 +01002380 case PointerGesture::Mode::TAP:
2381 case PointerGesture::Mode::TAP_DRAG:
2382 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2383 case PointerGesture::Mode::HOVER:
2384 case PointerGesture::Mode::PRESS:
2385 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002386 // Unfade the pointer when the current gesture manipulates the
2387 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002388 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 break;
Michael Wright227c5542020-07-02 18:30:52 +01002390 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 // Fade the pointer when the current gesture manipulates a different
2392 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002393 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002394 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002395 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002396 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 }
2398 break;
2399 }
2400
2401 // Send events!
2402 int32_t metaState = getContext()->getGlobalMetaState();
2403 int32_t buttonState = mCurrentCookedState.buttonState;
2404
2405 // Update last coordinates of pointers that have moved so that we observe the new
2406 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002407 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2408 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2409 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2410 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2411 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2412 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002413 bool moveNeeded = false;
2414 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2415 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2416 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2417 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2418 mPointerGesture.lastGestureIdBits.value);
2419 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2420 mPointerGesture.currentGestureCoords,
2421 mPointerGesture.currentGestureIdToIndex,
2422 mPointerGesture.lastGestureProperties,
2423 mPointerGesture.lastGestureCoords,
2424 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2425 if (buttonState != mLastCookedState.buttonState) {
2426 moveNeeded = true;
2427 }
2428 }
2429
2430 // Send motion events for all pointers that went up or were canceled.
2431 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2432 if (!dispatchedGestureIdBits.isEmpty()) {
2433 if (cancelPreviousGesture) {
2434 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2435 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2436 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2437 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2438 mPointerGesture.downTime);
2439
2440 dispatchedGestureIdBits.clear();
2441 } else {
2442 BitSet32 upGestureIdBits;
2443 if (finishPreviousGesture) {
2444 upGestureIdBits = dispatchedGestureIdBits;
2445 } else {
2446 upGestureIdBits.value =
2447 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2448 }
2449 while (!upGestureIdBits.isEmpty()) {
2450 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2451
2452 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2453 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2454 mPointerGesture.lastGestureProperties,
2455 mPointerGesture.lastGestureCoords,
2456 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2457 0, mPointerGesture.downTime);
2458
2459 dispatchedGestureIdBits.clearBit(id);
2460 }
2461 }
2462 }
2463
2464 // Send motion events for all pointers that moved.
2465 if (moveNeeded) {
2466 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2467 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2468 mPointerGesture.currentGestureProperties,
2469 mPointerGesture.currentGestureCoords,
2470 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2471 mPointerGesture.downTime);
2472 }
2473
2474 // Send motion events for all pointers that went down.
2475 if (down) {
2476 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2477 ~dispatchedGestureIdBits.value);
2478 while (!downGestureIdBits.isEmpty()) {
2479 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2480 dispatchedGestureIdBits.markBit(id);
2481
2482 if (dispatchedGestureIdBits.count() == 1) {
2483 mPointerGesture.downTime = when;
2484 }
2485
2486 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2487 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2488 mPointerGesture.currentGestureCoords,
2489 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2490 0, mPointerGesture.downTime);
2491 }
2492 }
2493
2494 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002495 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002496 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2497 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2498 mPointerGesture.currentGestureProperties,
2499 mPointerGesture.currentGestureCoords,
2500 mPointerGesture.currentGestureIdToIndex,
2501 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2502 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2503 // Synthesize a hover move event after all pointers go up to indicate that
2504 // the pointer is hovering again even if the user is not currently touching
2505 // the touch pad. This ensures that a view will receive a fresh hover enter
2506 // event after a tap.
2507 float x, y;
2508 mPointerController->getPosition(&x, &y);
2509
2510 PointerProperties pointerProperties;
2511 pointerProperties.clear();
2512 pointerProperties.id = 0;
2513 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2514
2515 PointerCoords pointerCoords;
2516 pointerCoords.clear();
2517 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2518 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2519
2520 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002521 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2522 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2523 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2524 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2525 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002526 getListener()->notifyMotion(&args);
2527 }
2528
2529 // Update state.
2530 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2531 if (!down) {
2532 mPointerGesture.lastGestureIdBits.clear();
2533 } else {
2534 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2535 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2536 uint32_t id = idBits.clearFirstMarkedBit();
2537 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2538 mPointerGesture.lastGestureProperties[index].copyFrom(
2539 mPointerGesture.currentGestureProperties[index]);
2540 mPointerGesture.lastGestureCoords[index].copyFrom(
2541 mPointerGesture.currentGestureCoords[index]);
2542 mPointerGesture.lastGestureIdToIndex[id] = index;
2543 }
2544 }
2545}
2546
2547void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2548 // Cancel previously dispatches pointers.
2549 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2550 int32_t metaState = getContext()->getGlobalMetaState();
2551 int32_t buttonState = mCurrentRawState.buttonState;
2552 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2553 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2554 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2555 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2556 0, 0, mPointerGesture.downTime);
2557 }
2558
2559 // Reset the current pointer gesture.
2560 mPointerGesture.reset();
2561 mPointerVelocityControl.reset();
2562
2563 // Remove any current spots.
2564 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002565 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002566 mPointerController->clearSpots();
2567 }
2568}
2569
2570bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2571 bool* outFinishPreviousGesture, bool isTimeout) {
2572 *outCancelPreviousGesture = false;
2573 *outFinishPreviousGesture = false;
2574
2575 // Handle TAP timeout.
2576 if (isTimeout) {
2577#if DEBUG_GESTURES
2578 ALOGD("Gestures: Processing timeout");
2579#endif
2580
Michael Wright227c5542020-07-02 18:30:52 +01002581 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002582 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2583 // The tap/drag timeout has not yet expired.
2584 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2585 mConfig.pointerGestureTapDragInterval);
2586 } else {
2587 // The tap is finished.
2588#if DEBUG_GESTURES
2589 ALOGD("Gestures: TAP finished");
2590#endif
2591 *outFinishPreviousGesture = true;
2592
2593 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002594 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002595 mPointerGesture.currentGestureIdBits.clear();
2596
2597 mPointerVelocityControl.reset();
2598 return true;
2599 }
2600 }
2601
2602 // We did not handle this timeout.
2603 return false;
2604 }
2605
2606 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2607 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2608
2609 // Update the velocity tracker.
2610 {
2611 VelocityTracker::Position positions[MAX_POINTERS];
2612 uint32_t count = 0;
2613 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
2614 uint32_t id = idBits.clearFirstMarkedBit();
2615 const RawPointerData::Pointer& pointer =
2616 mCurrentRawState.rawPointerData.pointerForId(id);
2617 positions[count].x = pointer.x * mPointerXMovementScale;
2618 positions[count].y = pointer.y * mPointerYMovementScale;
2619 }
2620 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2621 positions);
2622 }
2623
2624 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2625 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002626 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2627 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2628 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002629 mPointerGesture.resetTap();
2630 }
2631
2632 // Pick a new active touch id if needed.
2633 // Choose an arbitrary pointer that just went down, if there is one.
2634 // Otherwise choose an arbitrary remaining pointer.
2635 // This guarantees we always have an active touch id when there is at least one pointer.
2636 // We keep the same active touch id for as long as possible.
2637 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2638 int32_t activeTouchId = lastActiveTouchId;
2639 if (activeTouchId < 0) {
2640 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2641 activeTouchId = mPointerGesture.activeTouchId =
2642 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2643 mPointerGesture.firstTouchTime = when;
2644 }
2645 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2646 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2647 activeTouchId = mPointerGesture.activeTouchId =
2648 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2649 } else {
2650 activeTouchId = mPointerGesture.activeTouchId = -1;
2651 }
2652 }
2653
2654 // Determine whether we are in quiet time.
2655 bool isQuietTime = false;
2656 if (activeTouchId < 0) {
2657 mPointerGesture.resetQuietTime();
2658 } else {
2659 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2660 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002661 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2662 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2663 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002664 currentFingerCount < 2) {
2665 // Enter quiet time when exiting swipe or freeform state.
2666 // This is to prevent accidentally entering the hover state and flinging the
2667 // pointer when finishing a swipe and there is still one pointer left onscreen.
2668 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002669 } else if (mPointerGesture.lastGestureMode ==
2670 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002671 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2672 // Enter quiet time when releasing the button and there are still two or more
2673 // fingers down. This may indicate that one finger was used to press the button
2674 // but it has not gone up yet.
2675 isQuietTime = true;
2676 }
2677 if (isQuietTime) {
2678 mPointerGesture.quietTime = when;
2679 }
2680 }
2681 }
2682
2683 // Switch states based on button and pointer state.
2684 if (isQuietTime) {
2685 // Case 1: Quiet time. (QUIET)
2686#if DEBUG_GESTURES
2687 ALOGD("Gestures: QUIET for next %0.3fms",
2688 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2689#endif
Michael Wright227c5542020-07-02 18:30:52 +01002690 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002691 *outFinishPreviousGesture = true;
2692 }
2693
2694 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002695 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002696 mPointerGesture.currentGestureIdBits.clear();
2697
2698 mPointerVelocityControl.reset();
2699 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2700 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2701 // The pointer follows the active touch point.
2702 // Emit DOWN, MOVE, UP events at the pointer location.
2703 //
2704 // Only the active touch matters; other fingers are ignored. This policy helps
2705 // to handle the case where the user places a second finger on the touch pad
2706 // to apply the necessary force to depress an integrated button below the surface.
2707 // We don't want the second finger to be delivered to applications.
2708 //
2709 // For this to work well, we need to make sure to track the pointer that is really
2710 // active. If the user first puts one finger down to click then adds another
2711 // finger to drag then the active pointer should switch to the finger that is
2712 // being dragged.
2713#if DEBUG_GESTURES
2714 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2715 "currentFingerCount=%d",
2716 activeTouchId, currentFingerCount);
2717#endif
2718 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002719 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002720 *outFinishPreviousGesture = true;
2721 mPointerGesture.activeGestureId = 0;
2722 }
2723
2724 // Switch pointers if needed.
2725 // Find the fastest pointer and follow it.
2726 if (activeTouchId >= 0 && currentFingerCount > 1) {
2727 int32_t bestId = -1;
2728 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2729 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2730 uint32_t id = idBits.clearFirstMarkedBit();
2731 float vx, vy;
2732 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2733 float speed = hypotf(vx, vy);
2734 if (speed > bestSpeed) {
2735 bestId = id;
2736 bestSpeed = speed;
2737 }
2738 }
2739 }
2740 if (bestId >= 0 && bestId != activeTouchId) {
2741 mPointerGesture.activeTouchId = activeTouchId = bestId;
2742#if DEBUG_GESTURES
2743 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2744 "bestId=%d, bestSpeed=%0.3f",
2745 bestId, bestSpeed);
2746#endif
2747 }
2748 }
2749
2750 float deltaX = 0, deltaY = 0;
2751 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2752 const RawPointerData::Pointer& currentPointer =
2753 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2754 const RawPointerData::Pointer& lastPointer =
2755 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2756 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2757 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2758
2759 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2760 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2761
2762 // Move the pointer using a relative motion.
2763 // When using spots, the click will occur at the position of the anchor
2764 // spot and all other spots will move there.
2765 mPointerController->move(deltaX, deltaY);
2766 } else {
2767 mPointerVelocityControl.reset();
2768 }
2769
2770 float x, y;
2771 mPointerController->getPosition(&x, &y);
2772
Michael Wright227c5542020-07-02 18:30:52 +01002773 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002774 mPointerGesture.currentGestureIdBits.clear();
2775 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2776 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2777 mPointerGesture.currentGestureProperties[0].clear();
2778 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2779 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2780 mPointerGesture.currentGestureCoords[0].clear();
2781 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2782 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2783 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2784 } else if (currentFingerCount == 0) {
2785 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002786 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002787 *outFinishPreviousGesture = true;
2788 }
2789
2790 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2791 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2792 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002793 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2794 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002795 lastFingerCount == 1) {
2796 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2797 float x, y;
2798 mPointerController->getPosition(&x, &y);
2799 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2800 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2801#if DEBUG_GESTURES
2802 ALOGD("Gestures: TAP");
2803#endif
2804
2805 mPointerGesture.tapUpTime = when;
2806 getContext()->requestTimeoutAtTime(when +
2807 mConfig.pointerGestureTapDragInterval);
2808
2809 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002810 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002811 mPointerGesture.currentGestureIdBits.clear();
2812 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2813 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2814 mPointerGesture.currentGestureProperties[0].clear();
2815 mPointerGesture.currentGestureProperties[0].id =
2816 mPointerGesture.activeGestureId;
2817 mPointerGesture.currentGestureProperties[0].toolType =
2818 AMOTION_EVENT_TOOL_TYPE_FINGER;
2819 mPointerGesture.currentGestureCoords[0].clear();
2820 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2821 mPointerGesture.tapX);
2822 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2823 mPointerGesture.tapY);
2824 mPointerGesture.currentGestureCoords[0]
2825 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2826
2827 tapped = true;
2828 } else {
2829#if DEBUG_GESTURES
2830 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2831 y - mPointerGesture.tapY);
2832#endif
2833 }
2834 } else {
2835#if DEBUG_GESTURES
2836 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2837 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2838 (when - mPointerGesture.tapDownTime) * 0.000001f);
2839 } else {
2840 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2841 }
2842#endif
2843 }
2844 }
2845
2846 mPointerVelocityControl.reset();
2847
2848 if (!tapped) {
2849#if DEBUG_GESTURES
2850 ALOGD("Gestures: NEUTRAL");
2851#endif
2852 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002853 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 mPointerGesture.currentGestureIdBits.clear();
2855 }
2856 } else if (currentFingerCount == 1) {
2857 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2858 // The pointer follows the active touch point.
2859 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2860 // When in TAP_DRAG, emit MOVE events at the pointer location.
2861 ALOG_ASSERT(activeTouchId >= 0);
2862
Michael Wright227c5542020-07-02 18:30:52 +01002863 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2864 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002865 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2866 float x, y;
2867 mPointerController->getPosition(&x, &y);
2868 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2869 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002870 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002871 } else {
2872#if DEBUG_GESTURES
2873 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2874 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2875#endif
2876 }
2877 } else {
2878#if DEBUG_GESTURES
2879 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2880 (when - mPointerGesture.tapUpTime) * 0.000001f);
2881#endif
2882 }
Michael Wright227c5542020-07-02 18:30:52 +01002883 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2884 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002885 }
2886
2887 float deltaX = 0, deltaY = 0;
2888 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2889 const RawPointerData::Pointer& currentPointer =
2890 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2891 const RawPointerData::Pointer& lastPointer =
2892 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2893 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2894 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2895
2896 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2897 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2898
2899 // Move the pointer using a relative motion.
2900 // When using spots, the hover or drag will occur at the position of the anchor spot.
2901 mPointerController->move(deltaX, deltaY);
2902 } else {
2903 mPointerVelocityControl.reset();
2904 }
2905
2906 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002907 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002908#if DEBUG_GESTURES
2909 ALOGD("Gestures: TAP_DRAG");
2910#endif
2911 down = true;
2912 } else {
2913#if DEBUG_GESTURES
2914 ALOGD("Gestures: HOVER");
2915#endif
Michael Wright227c5542020-07-02 18:30:52 +01002916 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002917 *outFinishPreviousGesture = true;
2918 }
2919 mPointerGesture.activeGestureId = 0;
2920 down = false;
2921 }
2922
2923 float x, y;
2924 mPointerController->getPosition(&x, &y);
2925
2926 mPointerGesture.currentGestureIdBits.clear();
2927 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2928 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2929 mPointerGesture.currentGestureProperties[0].clear();
2930 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2931 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2932 mPointerGesture.currentGestureCoords[0].clear();
2933 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2934 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2935 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2936 down ? 1.0f : 0.0f);
2937
2938 if (lastFingerCount == 0 && currentFingerCount != 0) {
2939 mPointerGesture.resetTap();
2940 mPointerGesture.tapDownTime = when;
2941 mPointerGesture.tapX = x;
2942 mPointerGesture.tapY = y;
2943 }
2944 } else {
2945 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2946 // We need to provide feedback for each finger that goes down so we cannot wait
2947 // for the fingers to move before deciding what to do.
2948 //
2949 // The ambiguous case is deciding what to do when there are two fingers down but they
2950 // have not moved enough to determine whether they are part of a drag or part of a
2951 // freeform gesture, or just a press or long-press at the pointer location.
2952 //
2953 // When there are two fingers we start with the PRESS hypothesis and we generate a
2954 // down at the pointer location.
2955 //
2956 // When the two fingers move enough or when additional fingers are added, we make
2957 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2958 ALOG_ASSERT(activeTouchId >= 0);
2959
2960 bool settled = when >=
2961 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002962 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2963 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2964 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002965 *outFinishPreviousGesture = true;
2966 } else if (!settled && currentFingerCount > lastFingerCount) {
2967 // Additional pointers have gone down but not yet settled.
2968 // Reset the gesture.
2969#if DEBUG_GESTURES
2970 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2971 "settle time remaining %0.3fms",
2972 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2973 when) * 0.000001f);
2974#endif
2975 *outCancelPreviousGesture = true;
2976 } else {
2977 // Continue previous gesture.
2978 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2979 }
2980
2981 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01002982 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002983 mPointerGesture.activeGestureId = 0;
2984 mPointerGesture.referenceIdBits.clear();
2985 mPointerVelocityControl.reset();
2986
2987 // Use the centroid and pointer location as the reference points for the gesture.
2988#if DEBUG_GESTURES
2989 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
2990 "settle time remaining %0.3fms",
2991 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2992 when) * 0.000001f);
2993#endif
2994 mCurrentRawState.rawPointerData
2995 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
2996 &mPointerGesture.referenceTouchY);
2997 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
2998 &mPointerGesture.referenceGestureY);
2999 }
3000
3001 // Clear the reference deltas for fingers not yet included in the reference calculation.
3002 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3003 ~mPointerGesture.referenceIdBits.value);
3004 !idBits.isEmpty();) {
3005 uint32_t id = idBits.clearFirstMarkedBit();
3006 mPointerGesture.referenceDeltas[id].dx = 0;
3007 mPointerGesture.referenceDeltas[id].dy = 0;
3008 }
3009 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3010
3011 // Add delta for all fingers and calculate a common movement delta.
3012 float commonDeltaX = 0, commonDeltaY = 0;
3013 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3014 mCurrentCookedState.fingerIdBits.value);
3015 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3016 bool first = (idBits == commonIdBits);
3017 uint32_t id = idBits.clearFirstMarkedBit();
3018 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3019 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3020 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3021 delta.dx += cpd.x - lpd.x;
3022 delta.dy += cpd.y - lpd.y;
3023
3024 if (first) {
3025 commonDeltaX = delta.dx;
3026 commonDeltaY = delta.dy;
3027 } else {
3028 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3029 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3030 }
3031 }
3032
3033 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003034 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003035 float dist[MAX_POINTER_ID + 1];
3036 int32_t distOverThreshold = 0;
3037 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3038 uint32_t id = idBits.clearFirstMarkedBit();
3039 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3040 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3041 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3042 distOverThreshold += 1;
3043 }
3044 }
3045
3046 // Only transition when at least two pointers have moved further than
3047 // the minimum distance threshold.
3048 if (distOverThreshold >= 2) {
3049 if (currentFingerCount > 2) {
3050 // There are more than two pointers, switch to FREEFORM.
3051#if DEBUG_GESTURES
3052 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3053 currentFingerCount);
3054#endif
3055 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003056 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003057 } else {
3058 // There are exactly two pointers.
3059 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3060 uint32_t id1 = idBits.clearFirstMarkedBit();
3061 uint32_t id2 = idBits.firstMarkedBit();
3062 const RawPointerData::Pointer& p1 =
3063 mCurrentRawState.rawPointerData.pointerForId(id1);
3064 const RawPointerData::Pointer& p2 =
3065 mCurrentRawState.rawPointerData.pointerForId(id2);
3066 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3067 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3068 // There are two pointers but they are too far apart for a SWIPE,
3069 // switch to FREEFORM.
3070#if DEBUG_GESTURES
3071 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3072 mutualDistance, mPointerGestureMaxSwipeWidth);
3073#endif
3074 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003075 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003076 } else {
3077 // There are two pointers. Wait for both pointers to start moving
3078 // before deciding whether this is a SWIPE or FREEFORM gesture.
3079 float dist1 = dist[id1];
3080 float dist2 = dist[id2];
3081 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3082 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3083 // Calculate the dot product of the displacement vectors.
3084 // When the vectors are oriented in approximately the same direction,
3085 // the angle betweeen them is near zero and the cosine of the angle
3086 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3087 // mag(v2).
3088 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3089 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3090 float dx1 = delta1.dx * mPointerXZoomScale;
3091 float dy1 = delta1.dy * mPointerYZoomScale;
3092 float dx2 = delta2.dx * mPointerXZoomScale;
3093 float dy2 = delta2.dy * mPointerYZoomScale;
3094 float dot = dx1 * dx2 + dy1 * dy2;
3095 float cosine = dot / (dist1 * dist2); // denominator always > 0
3096 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3097 // Pointers are moving in the same direction. Switch to SWIPE.
3098#if DEBUG_GESTURES
3099 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3100 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3101 "cosine %0.3f >= %0.3f",
3102 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3103 mConfig.pointerGestureMultitouchMinDistance, cosine,
3104 mConfig.pointerGestureSwipeTransitionAngleCosine);
3105#endif
Michael Wright227c5542020-07-02 18:30:52 +01003106 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003107 } else {
3108 // Pointers are moving in different directions. Switch to FREEFORM.
3109#if DEBUG_GESTURES
3110 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3111 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3112 "cosine %0.3f < %0.3f",
3113 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3114 mConfig.pointerGestureMultitouchMinDistance, cosine,
3115 mConfig.pointerGestureSwipeTransitionAngleCosine);
3116#endif
3117 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003118 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003119 }
3120 }
3121 }
3122 }
3123 }
Michael Wright227c5542020-07-02 18:30:52 +01003124 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003125 // Switch from SWIPE to FREEFORM if additional pointers go down.
3126 // Cancel previous gesture.
3127 if (currentFingerCount > 2) {
3128#if DEBUG_GESTURES
3129 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3130 currentFingerCount);
3131#endif
3132 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003133 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003134 }
3135 }
3136
3137 // Move the reference points based on the overall group motion of the fingers
3138 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003139 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003140 (commonDeltaX || commonDeltaY)) {
3141 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3142 uint32_t id = idBits.clearFirstMarkedBit();
3143 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3144 delta.dx = 0;
3145 delta.dy = 0;
3146 }
3147
3148 mPointerGesture.referenceTouchX += commonDeltaX;
3149 mPointerGesture.referenceTouchY += commonDeltaY;
3150
3151 commonDeltaX *= mPointerXMovementScale;
3152 commonDeltaY *= mPointerYMovementScale;
3153
3154 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3155 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3156
3157 mPointerGesture.referenceGestureX += commonDeltaX;
3158 mPointerGesture.referenceGestureY += commonDeltaY;
3159 }
3160
3161 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003162 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3163 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003164 // PRESS or SWIPE mode.
3165#if DEBUG_GESTURES
3166 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3167 "activeGestureId=%d, currentTouchPointerCount=%d",
3168 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3169#endif
3170 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3171
3172 mPointerGesture.currentGestureIdBits.clear();
3173 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3174 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3175 mPointerGesture.currentGestureProperties[0].clear();
3176 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3177 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3178 mPointerGesture.currentGestureCoords[0].clear();
3179 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3180 mPointerGesture.referenceGestureX);
3181 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3182 mPointerGesture.referenceGestureY);
3183 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003184 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003185 // FREEFORM mode.
3186#if DEBUG_GESTURES
3187 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3188 "activeGestureId=%d, currentTouchPointerCount=%d",
3189 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3190#endif
3191 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3192
3193 mPointerGesture.currentGestureIdBits.clear();
3194
3195 BitSet32 mappedTouchIdBits;
3196 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003197 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003198 // Initially, assign the active gesture id to the active touch point
3199 // if there is one. No other touch id bits are mapped yet.
3200 if (!*outCancelPreviousGesture) {
3201 mappedTouchIdBits.markBit(activeTouchId);
3202 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3203 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3204 mPointerGesture.activeGestureId;
3205 } else {
3206 mPointerGesture.activeGestureId = -1;
3207 }
3208 } else {
3209 // Otherwise, assume we mapped all touches from the previous frame.
3210 // Reuse all mappings that are still applicable.
3211 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3212 mCurrentCookedState.fingerIdBits.value;
3213 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3214
3215 // Check whether we need to choose a new active gesture id because the
3216 // current went went up.
3217 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3218 ~mCurrentCookedState.fingerIdBits.value);
3219 !upTouchIdBits.isEmpty();) {
3220 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3221 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3222 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3223 mPointerGesture.activeGestureId = -1;
3224 break;
3225 }
3226 }
3227 }
3228
3229#if DEBUG_GESTURES
3230 ALOGD("Gestures: FREEFORM follow up "
3231 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3232 "activeGestureId=%d",
3233 mappedTouchIdBits.value, usedGestureIdBits.value,
3234 mPointerGesture.activeGestureId);
3235#endif
3236
3237 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3238 for (uint32_t i = 0; i < currentFingerCount; i++) {
3239 uint32_t touchId = idBits.clearFirstMarkedBit();
3240 uint32_t gestureId;
3241 if (!mappedTouchIdBits.hasBit(touchId)) {
3242 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3243 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3244#if DEBUG_GESTURES
3245 ALOGD("Gestures: FREEFORM "
3246 "new mapping for touch id %d -> gesture id %d",
3247 touchId, gestureId);
3248#endif
3249 } else {
3250 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3251#if DEBUG_GESTURES
3252 ALOGD("Gestures: FREEFORM "
3253 "existing mapping for touch id %d -> gesture id %d",
3254 touchId, gestureId);
3255#endif
3256 }
3257 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3258 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3259
3260 const RawPointerData::Pointer& pointer =
3261 mCurrentRawState.rawPointerData.pointerForId(touchId);
3262 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3263 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3264 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3265
3266 mPointerGesture.currentGestureProperties[i].clear();
3267 mPointerGesture.currentGestureProperties[i].id = gestureId;
3268 mPointerGesture.currentGestureProperties[i].toolType =
3269 AMOTION_EVENT_TOOL_TYPE_FINGER;
3270 mPointerGesture.currentGestureCoords[i].clear();
3271 mPointerGesture.currentGestureCoords[i]
3272 .setAxisValue(AMOTION_EVENT_AXIS_X,
3273 mPointerGesture.referenceGestureX + deltaX);
3274 mPointerGesture.currentGestureCoords[i]
3275 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3276 mPointerGesture.referenceGestureY + deltaY);
3277 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3278 1.0f);
3279 }
3280
3281 if (mPointerGesture.activeGestureId < 0) {
3282 mPointerGesture.activeGestureId =
3283 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3284#if DEBUG_GESTURES
3285 ALOGD("Gestures: FREEFORM new "
3286 "activeGestureId=%d",
3287 mPointerGesture.activeGestureId);
3288#endif
3289 }
3290 }
3291 }
3292
3293 mPointerController->setButtonState(mCurrentRawState.buttonState);
3294
3295#if DEBUG_GESTURES
3296 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3297 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3298 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3299 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3300 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3301 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3302 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3303 uint32_t id = idBits.clearFirstMarkedBit();
3304 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3305 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3306 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3307 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3308 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3309 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3310 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3311 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3312 }
3313 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3314 uint32_t id = idBits.clearFirstMarkedBit();
3315 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3316 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3317 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3318 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3319 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3320 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3321 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3322 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3323 }
3324#endif
3325 return true;
3326}
3327
3328void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3329 mPointerSimple.currentCoords.clear();
3330 mPointerSimple.currentProperties.clear();
3331
3332 bool down, hovering;
3333 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3334 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3335 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3336 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3337 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3338 mPointerController->setPosition(x, y);
3339
3340 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3341 down = !hovering;
3342
3343 mPointerController->getPosition(&x, &y);
3344 mPointerSimple.currentCoords.copyFrom(
3345 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3346 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3347 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3348 mPointerSimple.currentProperties.id = 0;
3349 mPointerSimple.currentProperties.toolType =
3350 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3351 } else {
3352 down = false;
3353 hovering = false;
3354 }
3355
3356 dispatchPointerSimple(when, policyFlags, down, hovering);
3357}
3358
3359void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3360 abortPointerSimple(when, policyFlags);
3361}
3362
3363void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3364 mPointerSimple.currentCoords.clear();
3365 mPointerSimple.currentProperties.clear();
3366
3367 bool down, hovering;
3368 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3369 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3370 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3371 float deltaX = 0, deltaY = 0;
3372 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3373 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3374 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3375 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3376 mPointerXMovementScale;
3377 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3378 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3379 mPointerYMovementScale;
3380
3381 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3382 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3383
3384 mPointerController->move(deltaX, deltaY);
3385 } else {
3386 mPointerVelocityControl.reset();
3387 }
3388
3389 down = isPointerDown(mCurrentRawState.buttonState);
3390 hovering = !down;
3391
3392 float x, y;
3393 mPointerController->getPosition(&x, &y);
3394 mPointerSimple.currentCoords.copyFrom(
3395 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3396 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3397 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3398 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3399 hovering ? 0.0f : 1.0f);
3400 mPointerSimple.currentProperties.id = 0;
3401 mPointerSimple.currentProperties.toolType =
3402 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3403 } else {
3404 mPointerVelocityControl.reset();
3405
3406 down = false;
3407 hovering = false;
3408 }
3409
3410 dispatchPointerSimple(when, policyFlags, down, hovering);
3411}
3412
3413void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3414 abortPointerSimple(when, policyFlags);
3415
3416 mPointerVelocityControl.reset();
3417}
3418
3419void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3420 bool hovering) {
3421 int32_t metaState = getContext()->getGlobalMetaState();
3422 int32_t displayId = mViewport.displayId;
3423
3424 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003425 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003426 mPointerController->clearSpots();
3427 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003428 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003429 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003430 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003431 }
3432 displayId = mPointerController->getDisplayId();
3433
3434 float xCursorPosition;
3435 float yCursorPosition;
3436 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3437
3438 if (mPointerSimple.down && !down) {
3439 mPointerSimple.down = false;
3440
3441 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003442 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3443 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003444 mLastRawState.buttonState, MotionClassification::NONE,
3445 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3446 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3447 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3448 /* videoFrames */ {});
3449 getListener()->notifyMotion(&args);
3450 }
3451
3452 if (mPointerSimple.hovering && !hovering) {
3453 mPointerSimple.hovering = false;
3454
3455 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003456 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3457 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3458 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003459 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3460 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3461 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3462 /* videoFrames */ {});
3463 getListener()->notifyMotion(&args);
3464 }
3465
3466 if (down) {
3467 if (!mPointerSimple.down) {
3468 mPointerSimple.down = true;
3469 mPointerSimple.downTime = when;
3470
3471 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003472 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003473 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3474 metaState, mCurrentRawState.buttonState,
3475 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3476 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3477 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3478 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3479 getListener()->notifyMotion(&args);
3480 }
3481
3482 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003483 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3484 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003485 mCurrentRawState.buttonState, MotionClassification::NONE,
3486 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3487 &mPointerSimple.currentCoords, mOrientedXPrecision,
3488 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3489 mPointerSimple.downTime, /* videoFrames */ {});
3490 getListener()->notifyMotion(&args);
3491 }
3492
3493 if (hovering) {
3494 if (!mPointerSimple.hovering) {
3495 mPointerSimple.hovering = true;
3496
3497 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003498 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003499 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3500 metaState, mCurrentRawState.buttonState,
3501 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3502 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3503 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3504 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3505 getListener()->notifyMotion(&args);
3506 }
3507
3508 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003509 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3510 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3511 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003512 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3513 &mPointerSimple.currentCoords, mOrientedXPrecision,
3514 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3515 mPointerSimple.downTime, /* videoFrames */ {});
3516 getListener()->notifyMotion(&args);
3517 }
3518
3519 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3520 float vscroll = mCurrentRawState.rawVScroll;
3521 float hscroll = mCurrentRawState.rawHScroll;
3522 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3523 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3524
3525 // Send scroll.
3526 PointerCoords pointerCoords;
3527 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3528 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3529 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3530
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003531 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3532 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003533 mCurrentRawState.buttonState, MotionClassification::NONE,
3534 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3535 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3536 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3537 /* videoFrames */ {});
3538 getListener()->notifyMotion(&args);
3539 }
3540
3541 // Save state.
3542 if (down || hovering) {
3543 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3544 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3545 } else {
3546 mPointerSimple.reset();
3547 }
3548}
3549
3550void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3551 mPointerSimple.currentCoords.clear();
3552 mPointerSimple.currentProperties.clear();
3553
3554 dispatchPointerSimple(when, policyFlags, false, false);
3555}
3556
3557void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3558 int32_t action, int32_t actionButton, int32_t flags,
3559 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3560 const PointerProperties* properties,
3561 const PointerCoords* coords, const uint32_t* idToIndex,
3562 BitSet32 idBits, int32_t changedId, float xPrecision,
3563 float yPrecision, nsecs_t downTime) {
3564 PointerCoords pointerCoords[MAX_POINTERS];
3565 PointerProperties pointerProperties[MAX_POINTERS];
3566 uint32_t pointerCount = 0;
3567 while (!idBits.isEmpty()) {
3568 uint32_t id = idBits.clearFirstMarkedBit();
3569 uint32_t index = idToIndex[id];
3570 pointerProperties[pointerCount].copyFrom(properties[index]);
3571 pointerCoords[pointerCount].copyFrom(coords[index]);
3572
3573 if (changedId >= 0 && id == uint32_t(changedId)) {
3574 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3575 }
3576
3577 pointerCount += 1;
3578 }
3579
3580 ALOG_ASSERT(pointerCount != 0);
3581
3582 if (changedId >= 0 && pointerCount == 1) {
3583 // Replace initial down and final up action.
3584 // We can compare the action without masking off the changed pointer index
3585 // because we know the index is 0.
3586 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3587 action = AMOTION_EVENT_ACTION_DOWN;
3588 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003589 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3590 action = AMOTION_EVENT_ACTION_CANCEL;
3591 } else {
3592 action = AMOTION_EVENT_ACTION_UP;
3593 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003594 } else {
3595 // Can't happen.
3596 ALOG_ASSERT(false);
3597 }
3598 }
3599 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3600 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003601 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003602 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3603 }
3604 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3605 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003606 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003607 std::for_each(frames.begin(), frames.end(),
3608 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003609 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3610 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003611 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3612 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3613 downTime, std::move(frames));
3614 getListener()->notifyMotion(&args);
3615}
3616
3617bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3618 const PointerCoords* inCoords,
3619 const uint32_t* inIdToIndex,
3620 PointerProperties* outProperties,
3621 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3622 BitSet32 idBits) const {
3623 bool changed = false;
3624 while (!idBits.isEmpty()) {
3625 uint32_t id = idBits.clearFirstMarkedBit();
3626 uint32_t inIndex = inIdToIndex[id];
3627 uint32_t outIndex = outIdToIndex[id];
3628
3629 const PointerProperties& curInProperties = inProperties[inIndex];
3630 const PointerCoords& curInCoords = inCoords[inIndex];
3631 PointerProperties& curOutProperties = outProperties[outIndex];
3632 PointerCoords& curOutCoords = outCoords[outIndex];
3633
3634 if (curInProperties != curOutProperties) {
3635 curOutProperties.copyFrom(curInProperties);
3636 changed = true;
3637 }
3638
3639 if (curInCoords != curOutCoords) {
3640 curOutCoords.copyFrom(curInCoords);
3641 changed = true;
3642 }
3643 }
3644 return changed;
3645}
3646
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003647void TouchInputMapper::cancelTouch(nsecs_t when) {
3648 abortPointerUsage(when, 0 /*policyFlags*/);
3649 abortTouches(when, 0 /* policyFlags*/);
3650}
3651
Arthur Hung4197f6b2020-03-16 15:39:59 +08003652// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003653void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003654 // Scale to surface coordinate.
3655 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3656 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3657
3658 // Rotate to surface coordinate.
3659 // 0 - no swap and reverse.
3660 // 90 - swap x/y and reverse y.
3661 // 180 - reverse x, y.
3662 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003663 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003664 case DISPLAY_ORIENTATION_0:
3665 x = xScaled + mXTranslate;
3666 y = yScaled + mYTranslate;
3667 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003668 case DISPLAY_ORIENTATION_90:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003669 y = mSurfaceRight - xScaled;
3670 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003671 break;
3672 case DISPLAY_ORIENTATION_180:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003673 x = mSurfaceRight - xScaled;
3674 y = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003675 break;
3676 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003677 y = xScaled + mXTranslate;
3678 x = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003679 break;
3680 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003681 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003682 }
3683}
3684
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003685bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003686 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3687 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3688
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003689 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003690 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003691 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003692 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003693}
3694
3695const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3696 for (const VirtualKey& virtualKey : mVirtualKeys) {
3697#if DEBUG_VIRTUAL_KEYS
3698 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3699 "left=%d, top=%d, right=%d, bottom=%d",
3700 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3701 virtualKey.hitRight, virtualKey.hitBottom);
3702#endif
3703
3704 if (virtualKey.isHit(x, y)) {
3705 return &virtualKey;
3706 }
3707 }
3708
3709 return nullptr;
3710}
3711
3712void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3713 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3714 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3715
3716 current->rawPointerData.clearIdBits();
3717
3718 if (currentPointerCount == 0) {
3719 // No pointers to assign.
3720 return;
3721 }
3722
3723 if (lastPointerCount == 0) {
3724 // All pointers are new.
3725 for (uint32_t i = 0; i < currentPointerCount; i++) {
3726 uint32_t id = i;
3727 current->rawPointerData.pointers[i].id = id;
3728 current->rawPointerData.idToIndex[id] = i;
3729 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3730 }
3731 return;
3732 }
3733
3734 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3735 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3736 // Only one pointer and no change in count so it must have the same id as before.
3737 uint32_t id = last->rawPointerData.pointers[0].id;
3738 current->rawPointerData.pointers[0].id = id;
3739 current->rawPointerData.idToIndex[id] = 0;
3740 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3741 return;
3742 }
3743
3744 // General case.
3745 // We build a heap of squared euclidean distances between current and last pointers
3746 // associated with the current and last pointer indices. Then, we find the best
3747 // match (by distance) for each current pointer.
3748 // The pointers must have the same tool type but it is possible for them to
3749 // transition from hovering to touching or vice-versa while retaining the same id.
3750 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3751
3752 uint32_t heapSize = 0;
3753 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3754 currentPointerIndex++) {
3755 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3756 lastPointerIndex++) {
3757 const RawPointerData::Pointer& currentPointer =
3758 current->rawPointerData.pointers[currentPointerIndex];
3759 const RawPointerData::Pointer& lastPointer =
3760 last->rawPointerData.pointers[lastPointerIndex];
3761 if (currentPointer.toolType == lastPointer.toolType) {
3762 int64_t deltaX = currentPointer.x - lastPointer.x;
3763 int64_t deltaY = currentPointer.y - lastPointer.y;
3764
3765 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3766
3767 // Insert new element into the heap (sift up).
3768 heap[heapSize].currentPointerIndex = currentPointerIndex;
3769 heap[heapSize].lastPointerIndex = lastPointerIndex;
3770 heap[heapSize].distance = distance;
3771 heapSize += 1;
3772 }
3773 }
3774 }
3775
3776 // Heapify
3777 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3778 startIndex -= 1;
3779 for (uint32_t parentIndex = startIndex;;) {
3780 uint32_t childIndex = parentIndex * 2 + 1;
3781 if (childIndex >= heapSize) {
3782 break;
3783 }
3784
3785 if (childIndex + 1 < heapSize &&
3786 heap[childIndex + 1].distance < heap[childIndex].distance) {
3787 childIndex += 1;
3788 }
3789
3790 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3791 break;
3792 }
3793
3794 swap(heap[parentIndex], heap[childIndex]);
3795 parentIndex = childIndex;
3796 }
3797 }
3798
3799#if DEBUG_POINTER_ASSIGNMENT
3800 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3801 for (size_t i = 0; i < heapSize; i++) {
3802 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3803 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3804 }
3805#endif
3806
3807 // Pull matches out by increasing order of distance.
3808 // To avoid reassigning pointers that have already been matched, the loop keeps track
3809 // of which last and current pointers have been matched using the matchedXXXBits variables.
3810 // It also tracks the used pointer id bits.
3811 BitSet32 matchedLastBits(0);
3812 BitSet32 matchedCurrentBits(0);
3813 BitSet32 usedIdBits(0);
3814 bool first = true;
3815 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3816 while (heapSize > 0) {
3817 if (first) {
3818 // The first time through the loop, we just consume the root element of
3819 // the heap (the one with smallest distance).
3820 first = false;
3821 } else {
3822 // Previous iterations consumed the root element of the heap.
3823 // Pop root element off of the heap (sift down).
3824 heap[0] = heap[heapSize];
3825 for (uint32_t parentIndex = 0;;) {
3826 uint32_t childIndex = parentIndex * 2 + 1;
3827 if (childIndex >= heapSize) {
3828 break;
3829 }
3830
3831 if (childIndex + 1 < heapSize &&
3832 heap[childIndex + 1].distance < heap[childIndex].distance) {
3833 childIndex += 1;
3834 }
3835
3836 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3837 break;
3838 }
3839
3840 swap(heap[parentIndex], heap[childIndex]);
3841 parentIndex = childIndex;
3842 }
3843
3844#if DEBUG_POINTER_ASSIGNMENT
3845 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003846 for (size_t j = 0; j < heapSize; j++) {
3847 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3848 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003849 }
3850#endif
3851 }
3852
3853 heapSize -= 1;
3854
3855 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3856 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3857
3858 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3859 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3860
3861 matchedCurrentBits.markBit(currentPointerIndex);
3862 matchedLastBits.markBit(lastPointerIndex);
3863
3864 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3865 current->rawPointerData.pointers[currentPointerIndex].id = id;
3866 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3867 current->rawPointerData.markIdBit(id,
3868 current->rawPointerData.isHovering(
3869 currentPointerIndex));
3870 usedIdBits.markBit(id);
3871
3872#if DEBUG_POINTER_ASSIGNMENT
3873 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3874 ", distance=%" PRIu64,
3875 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3876#endif
3877 break;
3878 }
3879 }
3880
3881 // Assign fresh ids to pointers that were not matched in the process.
3882 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3883 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3884 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3885
3886 current->rawPointerData.pointers[currentPointerIndex].id = id;
3887 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3888 current->rawPointerData.markIdBit(id,
3889 current->rawPointerData.isHovering(currentPointerIndex));
3890
3891#if DEBUG_POINTER_ASSIGNMENT
3892 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3893#endif
3894 }
3895}
3896
3897int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3898 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3899 return AKEY_STATE_VIRTUAL;
3900 }
3901
3902 for (const VirtualKey& virtualKey : mVirtualKeys) {
3903 if (virtualKey.keyCode == keyCode) {
3904 return AKEY_STATE_UP;
3905 }
3906 }
3907
3908 return AKEY_STATE_UNKNOWN;
3909}
3910
3911int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3912 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3913 return AKEY_STATE_VIRTUAL;
3914 }
3915
3916 for (const VirtualKey& virtualKey : mVirtualKeys) {
3917 if (virtualKey.scanCode == scanCode) {
3918 return AKEY_STATE_UP;
3919 }
3920 }
3921
3922 return AKEY_STATE_UNKNOWN;
3923}
3924
3925bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3926 const int32_t* keyCodes, uint8_t* outFlags) {
3927 for (const VirtualKey& virtualKey : mVirtualKeys) {
3928 for (size_t i = 0; i < numCodes; i++) {
3929 if (virtualKey.keyCode == keyCodes[i]) {
3930 outFlags[i] = 1;
3931 }
3932 }
3933 }
3934
3935 return true;
3936}
3937
3938std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3939 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003940 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003941 return std::make_optional(mPointerController->getDisplayId());
3942 } else {
3943 return std::make_optional(mViewport.displayId);
3944 }
3945 }
3946 return std::nullopt;
3947}
3948
3949} // namespace android