blob: 528e937712073eb8536c983cc8799e14f4017918 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 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
17#define LOG_TAG "InputReader"
18
19//#define LOG_NDEBUG 0
20
21// Log debug messages for each raw event received from the EventHub.
22#define DEBUG_RAW_EVENTS 0
23
24// Log debug messages about touch screen filtering hacks.
25#define DEBUG_HACKS 0
26
27// Log debug messages about virtual key processing.
28#define DEBUG_VIRTUAL_KEYS 0
29
30// Log debug messages about pointers.
31#define DEBUG_POINTERS 0
32
33// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
36// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
39// Log debug messages about the vibrator.
40#define DEBUG_VIBRATOR 0
41
Michael Wright842500e2015-03-13 17:32:02 -070042// Log debug messages about fusing stylus data.
43#define DEBUG_STYLUS_FUSION 0
44
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include "InputReader.h"
46
Mark Salyzyna5e161b2016-09-29 08:08:05 -070047#include <errno.h>
Michael Wright842500e2015-03-13 17:32:02 -070048#include <inttypes.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070049#include <limits.h>
50#include <math.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <stddef.h>
52#include <stdlib.h>
53#include <unistd.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054
Mark Salyzyn7823e122016-09-29 08:08:05 -070055#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057#include <android-base/stringprintf.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <input/Keyboard.h>
59#include <input/VirtualKeyMap.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
61#define INDENT " "
62#define INDENT2 " "
63#define INDENT3 " "
64#define INDENT4 " "
65#define INDENT5 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
71// --- Constants ---
72
73// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
74static const size_t MAX_SLOTS = 32;
75
Michael Wright842500e2015-03-13 17:32:02 -070076// Maximum amount of latency to add to touch events while waiting for data from an
77// external stylus.
Michael Wright5e17a5d2015-04-21 22:45:13 +010078static const nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
Michael Wright842500e2015-03-13 17:32:02 -070079
Michael Wright43fd19f2015-04-21 19:02:58 +010080// Maximum amount of time to wait on touch data before pushing out new pressure data.
81static const nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
82
83// Artificial latency on synthetic events created from stylus data without corresponding touch
84// data.
85static const nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
86
Michael Wrightd02c5b62014-02-10 15:10:22 -080087// --- Static Functions ---
88
89template<typename T>
90inline static T abs(const T& value) {
91 return value < 0 ? - value : value;
92}
93
94template<typename T>
95inline static T min(const T& a, const T& b) {
96 return a < b ? a : b;
97}
98
99template<typename T>
100inline static void swap(T& a, T& b) {
101 T temp = a;
102 a = b;
103 b = temp;
104}
105
106inline static float avg(float x, float y) {
107 return (x + y) / 2;
108}
109
110inline static float distance(float x1, float y1, float x2, float y2) {
111 return hypotf(x1 - x2, y1 - y2);
112}
113
114inline static int32_t signExtendNybble(int32_t value) {
115 return value >= 8 ? value - 16 : value;
116}
117
118static inline const char* toString(bool value) {
119 return value ? "true" : "false";
120}
121
122static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
123 const int32_t map[][4], size_t mapSize) {
124 if (orientation != DISPLAY_ORIENTATION_0) {
125 for (size_t i = 0; i < mapSize; i++) {
126 if (value == map[i][0]) {
127 return map[i][orientation];
128 }
129 }
130 }
131 return value;
132}
133
134static const int32_t keyCodeRotationMap[][4] = {
135 // key codes enumerated counter-clockwise with the original (unrotated) key first
136 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
137 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
138 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
139 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
140 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jim Millere7a57d12016-06-22 15:58:31 -0700141 { AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
142 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT },
143 { AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
144 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN },
145 { AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
146 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT },
147 { AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
148 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP },
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149};
150static const size_t keyCodeRotationMapSize =
151 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
152
Ivan Podogovb9afef32017-02-13 15:34:32 +0000153static int32_t rotateStemKey(int32_t value, int32_t orientation,
154 const int32_t map[][2], size_t mapSize) {
155 if (orientation == DISPLAY_ORIENTATION_180) {
156 for (size_t i = 0; i < mapSize; i++) {
157 if (value == map[i][0]) {
158 return map[i][1];
159 }
160 }
161 }
162 return value;
163}
164
165// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
166static int32_t stemKeyRotationMap[][2] = {
167 // key codes enumerated with the original (unrotated) key first
168 // no rotation, 180 degree rotation
169 { AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
170 { AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
171 { AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
172 { AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
173};
174static const size_t stemKeyRotationMapSize =
175 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
176
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000178 keyCode = rotateStemKey(keyCode, orientation,
179 stemKeyRotationMap, stemKeyRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 return rotateValueUsingRotationMap(keyCode, orientation,
181 keyCodeRotationMap, keyCodeRotationMapSize);
182}
183
184static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
185 float temp;
186 switch (orientation) {
187 case DISPLAY_ORIENTATION_90:
188 temp = *deltaX;
189 *deltaX = *deltaY;
190 *deltaY = -temp;
191 break;
192
193 case DISPLAY_ORIENTATION_180:
194 *deltaX = -*deltaX;
195 *deltaY = -*deltaY;
196 break;
197
198 case DISPLAY_ORIENTATION_270:
199 temp = *deltaX;
200 *deltaX = -*deltaY;
201 *deltaY = temp;
202 break;
203 }
204}
205
206static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
207 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
208}
209
210// Returns true if the pointer should be reported as being down given the specified
211// button states. This determines whether the event is reported as a touch event.
212static bool isPointerDown(int32_t buttonState) {
213 return buttonState &
214 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
215 | AMOTION_EVENT_BUTTON_TERTIARY);
216}
217
218static float calculateCommonVector(float a, float b) {
219 if (a > 0 && b > 0) {
220 return a < b ? a : b;
221 } else if (a < 0 && b < 0) {
222 return a > b ? a : b;
223 } else {
224 return 0;
225 }
226}
227
228static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100229 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
231 int32_t buttonState, int32_t keyCode) {
232 if (
233 (action == AKEY_EVENT_ACTION_DOWN
234 && !(lastButtonState & buttonState)
235 && (currentButtonState & buttonState))
236 || (action == AKEY_EVENT_ACTION_UP
237 && (lastButtonState & buttonState)
238 && !(currentButtonState & buttonState))) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100239 NotifyKeyArgs args(when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240 action, 0, keyCode, 0, context->getGlobalMetaState(), when);
241 context->getListener()->notifyKey(&args);
242 }
243}
244
245static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100246 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100248 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 lastButtonState, currentButtonState,
250 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100251 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 lastButtonState, currentButtonState,
253 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
254}
255
256
257// --- InputReaderConfiguration ---
258
Santos Cordonfa5cf462017-04-05 10:37:00 -0700259bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100260 const std::string& uniqueDisplayId, DisplayViewport* outViewport) const {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +0100261 for (const DisplayViewport& currentViewport : mDisplays) {
262 // for virtual displays, uniqueId must match
263 if (viewportType == ViewportType::VIEWPORT_VIRTUAL) {
264 if (currentViewport.type == ViewportType::VIEWPORT_VIRTUAL
265 && currentViewport.uniqueId == uniqueDisplayId) {
266 *outViewport = currentViewport;
267 return true;
Santos Cordonfa5cf462017-04-05 10:37:00 -0700268 }
Siarhei Vishniakoud6343922018-07-06 23:33:37 +0100269 } else if (viewportType == currentViewport.type) {
270 // there can only be 1 internal or external viewport, for now
271 *outViewport = currentViewport;
272 return true;
Santos Cordonfa5cf462017-04-05 10:37:00 -0700273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800274 }
275 return false;
276}
277
Siarhei Vishniakoud6343922018-07-06 23:33:37 +0100278void InputReaderConfiguration::setDisplayViewports(const std::vector<DisplayViewport>& viewports) {
279 mDisplays = viewports;
Santos Cordonfa5cf462017-04-05 10:37:00 -0700280}
281
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800282void InputReaderConfiguration::dump(std::string& dump) const {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +0100283 for (const DisplayViewport& viewport : mDisplays) {
Santos Cordonfa5cf462017-04-05 10:37:00 -0700284 dumpViewport(dump, viewport);
285 }
286}
287
Siarhei Vishniakoud6343922018-07-06 23:33:37 +0100288void InputReaderConfiguration::dumpViewport(std::string& dump, const DisplayViewport& viewport)
289 const {
290 dump += StringPrintf(INDENT4 "%s\n", viewport.toString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291}
292
293
Jason Gereckeaf126fb2012-05-10 14:22:47 -0700294// -- TouchAffineTransformation --
295void TouchAffineTransformation::applyTo(float& x, float& y) const {
296 float newX, newY;
297 newX = x * x_scale + y * x_ymix + x_offset;
298 newY = x * y_xmix + y * y_scale + y_offset;
299
300 x = newX;
301 y = newY;
302}
303
304
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305// --- InputReader ---
306
307InputReader::InputReader(const sp<EventHubInterface>& eventHub,
308 const sp<InputReaderPolicyInterface>& policy,
309 const sp<InputListenerInterface>& listener) :
310 mContext(this), mEventHub(eventHub), mPolicy(policy),
311 mGlobalMetaState(0), mGeneration(1),
312 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
313 mConfigurationChangesToRefresh(0) {
314 mQueuedListener = new QueuedInputListener(listener);
315
316 { // acquire lock
317 AutoMutex _l(mLock);
318
319 refreshConfigurationLocked(0);
320 updateGlobalMetaStateLocked();
321 } // release lock
322}
323
324InputReader::~InputReader() {
325 for (size_t i = 0; i < mDevices.size(); i++) {
326 delete mDevices.valueAt(i);
327 }
328}
329
330void InputReader::loopOnce() {
331 int32_t oldGeneration;
332 int32_t timeoutMillis;
333 bool inputDevicesChanged = false;
334 Vector<InputDeviceInfo> inputDevices;
335 { // acquire lock
336 AutoMutex _l(mLock);
337
338 oldGeneration = mGeneration;
339 timeoutMillis = -1;
340
341 uint32_t changes = mConfigurationChangesToRefresh;
342 if (changes) {
343 mConfigurationChangesToRefresh = 0;
344 timeoutMillis = 0;
345 refreshConfigurationLocked(changes);
346 } else if (mNextTimeout != LLONG_MAX) {
347 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
348 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
349 }
350 } // release lock
351
352 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
353
354 { // acquire lock
355 AutoMutex _l(mLock);
356 mReaderIsAliveCondition.broadcast();
357
358 if (count) {
359 processEventsLocked(mEventBuffer, count);
360 }
361
362 if (mNextTimeout != LLONG_MAX) {
363 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
364 if (now >= mNextTimeout) {
365#if DEBUG_RAW_EVENTS
366 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
367#endif
368 mNextTimeout = LLONG_MAX;
369 timeoutExpiredLocked(now);
370 }
371 }
372
373 if (oldGeneration != mGeneration) {
374 inputDevicesChanged = true;
375 getInputDevicesLocked(inputDevices);
376 }
377 } // release lock
378
379 // Send out a message that the describes the changed input devices.
380 if (inputDevicesChanged) {
381 mPolicy->notifyInputDevicesChanged(inputDevices);
382 }
383
384 // Flush queued events out to the listener.
385 // This must happen outside of the lock because the listener could potentially call
386 // back into the InputReader's methods, such as getScanCodeState, or become blocked
387 // on another thread similarly waiting to acquire the InputReader lock thereby
388 // resulting in a deadlock. This situation is actually quite plausible because the
389 // listener is actually the input dispatcher, which calls into the window manager,
390 // which occasionally calls into the input reader.
391 mQueuedListener->flush();
392}
393
394void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
395 for (const RawEvent* rawEvent = rawEvents; count;) {
396 int32_t type = rawEvent->type;
397 size_t batchSize = 1;
398 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
399 int32_t deviceId = rawEvent->deviceId;
400 while (batchSize < count) {
401 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
402 || rawEvent[batchSize].deviceId != deviceId) {
403 break;
404 }
405 batchSize += 1;
406 }
407#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700408 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409#endif
410 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
411 } else {
412 switch (rawEvent->type) {
413 case EventHubInterface::DEVICE_ADDED:
414 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
415 break;
416 case EventHubInterface::DEVICE_REMOVED:
417 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
418 break;
419 case EventHubInterface::FINISHED_DEVICE_SCAN:
420 handleConfigurationChangedLocked(rawEvent->when);
421 break;
422 default:
423 ALOG_ASSERT(false); // can't happen
424 break;
425 }
426 }
427 count -= batchSize;
428 rawEvent += batchSize;
429 }
430}
431
432void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
433 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
434 if (deviceIndex >= 0) {
435 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
436 return;
437 }
438
439 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
440 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
441 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
442
443 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
444 device->configure(when, &mConfig, 0);
445 device->reset(when);
446
447 if (device->isIgnored()) {
448 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100449 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450 } else {
451 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100452 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453 }
454
455 mDevices.add(deviceId, device);
456 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700457
458 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
459 notifyExternalStylusPresenceChanged();
460 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461}
462
463void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700464 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
466 if (deviceIndex < 0) {
467 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
468 return;
469 }
470
471 device = mDevices.valueAt(deviceIndex);
472 mDevices.removeItemsAt(deviceIndex, 1);
473 bumpGenerationLocked();
474
475 if (device->isIgnored()) {
476 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100477 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478 } else {
479 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100480 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481 }
482
Michael Wright842500e2015-03-13 17:32:02 -0700483 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
484 notifyExternalStylusPresenceChanged();
485 }
486
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487 device->reset(when);
488 delete device;
489}
490
491InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
492 const InputDeviceIdentifier& identifier, uint32_t classes) {
493 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
494 controllerNumber, identifier, classes);
495
496 // External devices.
497 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
498 device->setExternal(true);
499 }
500
Tim Kilbourn063ff532015-04-08 10:26:18 -0700501 // Devices with mics.
502 if (classes & INPUT_DEVICE_CLASS_MIC) {
503 device->setMic(true);
504 }
505
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 // Switch-like devices.
507 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
508 device->addMapper(new SwitchInputMapper(device));
509 }
510
Prashant Malani1941ff52015-08-11 18:29:28 -0700511 // Scroll wheel-like devices.
512 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
513 device->addMapper(new RotaryEncoderInputMapper(device));
514 }
515
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516 // Vibrator-like devices.
517 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
518 device->addMapper(new VibratorInputMapper(device));
519 }
520
521 // Keyboard-like devices.
522 uint32_t keyboardSource = 0;
523 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
524 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
525 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
526 }
527 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
528 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
529 }
530 if (classes & INPUT_DEVICE_CLASS_DPAD) {
531 keyboardSource |= AINPUT_SOURCE_DPAD;
532 }
533 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
534 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
535 }
536
537 if (keyboardSource != 0) {
538 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
539 }
540
541 // Cursor-like devices.
542 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
543 device->addMapper(new CursorInputMapper(device));
544 }
545
546 // Touchscreens and touchpad devices.
547 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
548 device->addMapper(new MultiTouchInputMapper(device));
549 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
550 device->addMapper(new SingleTouchInputMapper(device));
551 }
552
553 // Joystick-like devices.
554 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
555 device->addMapper(new JoystickInputMapper(device));
556 }
557
Michael Wright842500e2015-03-13 17:32:02 -0700558 // External stylus-like devices.
559 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
560 device->addMapper(new ExternalStylusInputMapper(device));
561 }
562
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 return device;
564}
565
566void InputReader::processEventsForDeviceLocked(int32_t deviceId,
567 const RawEvent* rawEvents, size_t count) {
568 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
569 if (deviceIndex < 0) {
570 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
571 return;
572 }
573
574 InputDevice* device = mDevices.valueAt(deviceIndex);
575 if (device->isIgnored()) {
576 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
577 return;
578 }
579
580 device->process(rawEvents, count);
581}
582
583void InputReader::timeoutExpiredLocked(nsecs_t when) {
584 for (size_t i = 0; i < mDevices.size(); i++) {
585 InputDevice* device = mDevices.valueAt(i);
586 if (!device->isIgnored()) {
587 device->timeoutExpired(when);
588 }
589 }
590}
591
592void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
593 // Reset global meta state because it depends on the list of all configured devices.
594 updateGlobalMetaStateLocked();
595
596 // Enqueue configuration changed.
597 NotifyConfigurationChangedArgs args(when);
598 mQueuedListener->notifyConfigurationChanged(&args);
599}
600
601void InputReader::refreshConfigurationLocked(uint32_t changes) {
602 mPolicy->getReaderConfiguration(&mConfig);
603 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
604
605 if (changes) {
606 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
607 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
608
609 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
610 mEventHub->requestReopenDevices();
611 } else {
612 for (size_t i = 0; i < mDevices.size(); i++) {
613 InputDevice* device = mDevices.valueAt(i);
614 device->configure(now, &mConfig, changes);
615 }
616 }
617 }
618}
619
620void InputReader::updateGlobalMetaStateLocked() {
621 mGlobalMetaState = 0;
622
623 for (size_t i = 0; i < mDevices.size(); i++) {
624 InputDevice* device = mDevices.valueAt(i);
625 mGlobalMetaState |= device->getMetaState();
626 }
627}
628
629int32_t InputReader::getGlobalMetaStateLocked() {
630 return mGlobalMetaState;
631}
632
Michael Wright842500e2015-03-13 17:32:02 -0700633void InputReader::notifyExternalStylusPresenceChanged() {
634 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
635}
636
637void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
638 for (size_t i = 0; i < mDevices.size(); i++) {
639 InputDevice* device = mDevices.valueAt(i);
640 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
641 outDevices.push();
642 device->getDeviceInfo(&outDevices.editTop());
643 }
644 }
645}
646
647void InputReader::dispatchExternalStylusState(const StylusState& state) {
648 for (size_t i = 0; i < mDevices.size(); i++) {
649 InputDevice* device = mDevices.valueAt(i);
650 device->updateExternalStylusState(state);
651 }
652}
653
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
655 mDisableVirtualKeysTimeout = time;
656}
657
658bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
659 InputDevice* device, int32_t keyCode, int32_t scanCode) {
660 if (now < mDisableVirtualKeysTimeout) {
661 ALOGI("Dropping virtual key from device %s because virtual keys are "
662 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100663 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 (mDisableVirtualKeysTimeout - now) * 0.000001,
665 keyCode, scanCode);
666 return true;
667 } else {
668 return false;
669 }
670}
671
672void InputReader::fadePointerLocked() {
673 for (size_t i = 0; i < mDevices.size(); i++) {
674 InputDevice* device = mDevices.valueAt(i);
675 device->fadePointer();
676 }
677}
678
679void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
680 if (when < mNextTimeout) {
681 mNextTimeout = when;
682 mEventHub->wake();
683 }
684}
685
686int32_t InputReader::bumpGenerationLocked() {
687 return ++mGeneration;
688}
689
690void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
691 AutoMutex _l(mLock);
692 getInputDevicesLocked(outInputDevices);
693}
694
695void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
696 outInputDevices.clear();
697
698 size_t numDevices = mDevices.size();
699 for (size_t i = 0; i < numDevices; i++) {
700 InputDevice* device = mDevices.valueAt(i);
701 if (!device->isIgnored()) {
702 outInputDevices.push();
703 device->getDeviceInfo(&outInputDevices.editTop());
704 }
705 }
706}
707
708int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
709 int32_t keyCode) {
710 AutoMutex _l(mLock);
711
712 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
713}
714
715int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
716 int32_t scanCode) {
717 AutoMutex _l(mLock);
718
719 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
720}
721
722int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
723 AutoMutex _l(mLock);
724
725 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
726}
727
728int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
729 GetStateFunc getStateFunc) {
730 int32_t result = AKEY_STATE_UNKNOWN;
731 if (deviceId >= 0) {
732 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
733 if (deviceIndex >= 0) {
734 InputDevice* device = mDevices.valueAt(deviceIndex);
735 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
736 result = (device->*getStateFunc)(sourceMask, code);
737 }
738 }
739 } else {
740 size_t numDevices = mDevices.size();
741 for (size_t i = 0; i < numDevices; i++) {
742 InputDevice* device = mDevices.valueAt(i);
743 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
744 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
745 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
746 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
747 if (currentResult >= AKEY_STATE_DOWN) {
748 return currentResult;
749 } else if (currentResult == AKEY_STATE_UP) {
750 result = currentResult;
751 }
752 }
753 }
754 }
755 return result;
756}
757
Andrii Kulian763a3a42016-03-08 10:46:16 -0800758void InputReader::toggleCapsLockState(int32_t deviceId) {
759 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
760 if (deviceIndex < 0) {
761 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
762 return;
763 }
764
765 InputDevice* device = mDevices.valueAt(deviceIndex);
766 if (device->isIgnored()) {
767 return;
768 }
769
770 device->updateMetaState(AKEYCODE_CAPS_LOCK);
771}
772
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
774 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
775 AutoMutex _l(mLock);
776
777 memset(outFlags, 0, numCodes);
778 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
779}
780
781bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
782 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
783 bool result = false;
784 if (deviceId >= 0) {
785 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
786 if (deviceIndex >= 0) {
787 InputDevice* device = mDevices.valueAt(deviceIndex);
788 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
789 result = device->markSupportedKeyCodes(sourceMask,
790 numCodes, keyCodes, outFlags);
791 }
792 }
793 } else {
794 size_t numDevices = mDevices.size();
795 for (size_t i = 0; i < numDevices; i++) {
796 InputDevice* device = mDevices.valueAt(i);
797 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
798 result |= device->markSupportedKeyCodes(sourceMask,
799 numCodes, keyCodes, outFlags);
800 }
801 }
802 }
803 return result;
804}
805
806void InputReader::requestRefreshConfiguration(uint32_t changes) {
807 AutoMutex _l(mLock);
808
809 if (changes) {
810 bool needWake = !mConfigurationChangesToRefresh;
811 mConfigurationChangesToRefresh |= changes;
812
813 if (needWake) {
814 mEventHub->wake();
815 }
816 }
817}
818
819void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
820 ssize_t repeat, int32_t token) {
821 AutoMutex _l(mLock);
822
823 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
824 if (deviceIndex >= 0) {
825 InputDevice* device = mDevices.valueAt(deviceIndex);
826 device->vibrate(pattern, patternSize, repeat, token);
827 }
828}
829
830void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
831 AutoMutex _l(mLock);
832
833 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
834 if (deviceIndex >= 0) {
835 InputDevice* device = mDevices.valueAt(deviceIndex);
836 device->cancelVibrate(token);
837 }
838}
839
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700840bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
841 AutoMutex _l(mLock);
842
843 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
844 if (deviceIndex >= 0) {
845 InputDevice* device = mDevices.valueAt(deviceIndex);
846 return device->isEnabled();
847 }
848 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
849 return false;
850}
851
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800852void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 AutoMutex _l(mLock);
854
855 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800856 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800858 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859
860 for (size_t i = 0; i < mDevices.size(); i++) {
861 mDevices.valueAt(i)->dump(dump);
862 }
863
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800864 dump += INDENT "Configuration:\n";
865 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
867 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800868 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100870 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800872 dump += "]\n";
873 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 mConfig.virtualKeyQuietTime * 0.000001f);
875
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800876 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
878 mConfig.pointerVelocityControlParameters.scale,
879 mConfig.pointerVelocityControlParameters.lowThreshold,
880 mConfig.pointerVelocityControlParameters.highThreshold,
881 mConfig.pointerVelocityControlParameters.acceleration);
882
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800883 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
885 mConfig.wheelVelocityControlParameters.scale,
886 mConfig.wheelVelocityControlParameters.lowThreshold,
887 mConfig.wheelVelocityControlParameters.highThreshold,
888 mConfig.wheelVelocityControlParameters.acceleration);
889
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800890 dump += StringPrintf(INDENT2 "PointerGesture:\n");
891 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800893 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800895 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800897 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800899 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800901 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800903 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800905 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800907 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800909 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800911 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800913 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700915
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800916 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700917 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918}
919
920void InputReader::monitor() {
921 // Acquire and release the lock to ensure that the reader has not deadlocked.
922 mLock.lock();
923 mEventHub->wake();
924 mReaderIsAliveCondition.wait(mLock);
925 mLock.unlock();
926
927 // Check the EventHub
928 mEventHub->monitor();
929}
930
931
932// --- InputReader::ContextImpl ---
933
934InputReader::ContextImpl::ContextImpl(InputReader* reader) :
935 mReader(reader) {
936}
937
938void InputReader::ContextImpl::updateGlobalMetaState() {
939 // lock is already held by the input loop
940 mReader->updateGlobalMetaStateLocked();
941}
942
943int32_t InputReader::ContextImpl::getGlobalMetaState() {
944 // lock is already held by the input loop
945 return mReader->getGlobalMetaStateLocked();
946}
947
948void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
949 // lock is already held by the input loop
950 mReader->disableVirtualKeysUntilLocked(time);
951}
952
953bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
954 InputDevice* device, int32_t keyCode, int32_t scanCode) {
955 // lock is already held by the input loop
956 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
957}
958
959void InputReader::ContextImpl::fadePointer() {
960 // lock is already held by the input loop
961 mReader->fadePointerLocked();
962}
963
964void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
965 // lock is already held by the input loop
966 mReader->requestTimeoutAtTimeLocked(when);
967}
968
969int32_t InputReader::ContextImpl::bumpGeneration() {
970 // lock is already held by the input loop
971 return mReader->bumpGenerationLocked();
972}
973
Michael Wright842500e2015-03-13 17:32:02 -0700974void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
975 // lock is already held by whatever called refreshConfigurationLocked
976 mReader->getExternalStylusDevicesLocked(outDevices);
977}
978
979void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
980 mReader->dispatchExternalStylusState(state);
981}
982
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
984 return mReader->mPolicy.get();
985}
986
987InputListenerInterface* InputReader::ContextImpl::getListener() {
988 return mReader->mQueuedListener.get();
989}
990
991EventHubInterface* InputReader::ContextImpl::getEventHub() {
992 return mReader->mEventHub.get();
993}
994
995
996// --- InputReaderThread ---
997
998InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
999 Thread(/*canCallJava*/ true), mReader(reader) {
1000}
1001
1002InputReaderThread::~InputReaderThread() {
1003}
1004
1005bool InputReaderThread::threadLoop() {
1006 mReader->loopOnce();
1007 return true;
1008}
1009
1010
1011// --- InputDevice ---
1012
1013InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
1014 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
1015 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
1016 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -07001017 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018}
1019
1020InputDevice::~InputDevice() {
1021 size_t numMappers = mMappers.size();
1022 for (size_t i = 0; i < numMappers; i++) {
1023 delete mMappers[i];
1024 }
1025 mMappers.clear();
1026}
1027
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001028bool InputDevice::isEnabled() {
1029 return getEventHub()->isDeviceEnabled(mId);
1030}
1031
1032void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1033 if (isEnabled() == enabled) {
1034 return;
1035 }
1036
1037 if (enabled) {
1038 getEventHub()->enableDevice(mId);
1039 reset(when);
1040 } else {
1041 reset(when);
1042 getEventHub()->disableDevice(mId);
1043 }
1044 // Must change generation to flag this device as changed
1045 bumpGeneration();
1046}
1047
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001048void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 InputDeviceInfo deviceInfo;
1050 getDeviceInfo(& deviceInfo);
1051
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001052 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001053 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001054 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1055 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
1056 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1057 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1058 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059
1060 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1061 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001062 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 for (size_t i = 0; i < ranges.size(); i++) {
1064 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1065 const char* label = getAxisLabel(range.axis);
1066 char name[32];
1067 if (label) {
1068 strncpy(name, label, sizeof(name));
1069 name[sizeof(name) - 1] = '\0';
1070 } else {
1071 snprintf(name, sizeof(name), "%d", range.axis);
1072 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001073 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001074 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1075 name, range.source, range.min, range.max, range.flat, range.fuzz,
1076 range.resolution);
1077 }
1078 }
1079
1080 size_t numMappers = mMappers.size();
1081 for (size_t i = 0; i < numMappers; i++) {
1082 InputMapper* mapper = mMappers[i];
1083 mapper->dump(dump);
1084 }
1085}
1086
1087void InputDevice::addMapper(InputMapper* mapper) {
1088 mMappers.add(mapper);
1089}
1090
1091void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1092 mSources = 0;
1093
1094 if (!isIgnored()) {
1095 if (!changes) { // first time only
1096 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1097 }
1098
1099 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1100 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1101 sp<KeyCharacterMap> keyboardLayout =
1102 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1103 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1104 bumpGeneration();
1105 }
1106 }
1107 }
1108
1109 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1110 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001111 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 if (mAlias != alias) {
1113 mAlias = alias;
1114 bumpGeneration();
1115 }
1116 }
1117 }
1118
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001119 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1120 ssize_t index = config->disabledDevices.indexOf(mId);
1121 bool enabled = index < 0;
1122 setEnabled(enabled, when);
1123 }
1124
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 size_t numMappers = mMappers.size();
1126 for (size_t i = 0; i < numMappers; i++) {
1127 InputMapper* mapper = mMappers[i];
1128 mapper->configure(when, config, changes);
1129 mSources |= mapper->getSources();
1130 }
1131 }
1132}
1133
1134void InputDevice::reset(nsecs_t when) {
1135 size_t numMappers = mMappers.size();
1136 for (size_t i = 0; i < numMappers; i++) {
1137 InputMapper* mapper = mMappers[i];
1138 mapper->reset(when);
1139 }
1140
1141 mContext->updateGlobalMetaState();
1142
1143 notifyReset(when);
1144}
1145
1146void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1147 // Process all of the events in order for each mapper.
1148 // We cannot simply ask each mapper to process them in bulk because mappers may
1149 // have side-effects that must be interleaved. For example, joystick movement events and
1150 // gamepad button presses are handled by different mappers but they should be dispatched
1151 // in the order received.
1152 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001153 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001155 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1157 rawEvent->when);
1158#endif
1159
1160 if (mDropUntilNextSync) {
1161 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1162 mDropUntilNextSync = false;
1163#if DEBUG_RAW_EVENTS
1164 ALOGD("Recovered from input event buffer overrun.");
1165#endif
1166 } else {
1167#if DEBUG_RAW_EVENTS
1168 ALOGD("Dropped input event while waiting for next input sync.");
1169#endif
1170 }
1171 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001172 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 mDropUntilNextSync = true;
1174 reset(rawEvent->when);
1175 } else {
1176 for (size_t i = 0; i < numMappers; i++) {
1177 InputMapper* mapper = mMappers[i];
1178 mapper->process(rawEvent);
1179 }
1180 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001181 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182 }
1183}
1184
1185void InputDevice::timeoutExpired(nsecs_t when) {
1186 size_t numMappers = mMappers.size();
1187 for (size_t i = 0; i < numMappers; i++) {
1188 InputMapper* mapper = mMappers[i];
1189 mapper->timeoutExpired(when);
1190 }
1191}
1192
Michael Wright842500e2015-03-13 17:32:02 -07001193void InputDevice::updateExternalStylusState(const StylusState& state) {
1194 size_t numMappers = mMappers.size();
1195 for (size_t i = 0; i < numMappers; i++) {
1196 InputMapper* mapper = mMappers[i];
1197 mapper->updateExternalStylusState(state);
1198 }
1199}
1200
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1202 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001203 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 size_t numMappers = mMappers.size();
1205 for (size_t i = 0; i < numMappers; i++) {
1206 InputMapper* mapper = mMappers[i];
1207 mapper->populateDeviceInfo(outDeviceInfo);
1208 }
1209}
1210
1211int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1212 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1213}
1214
1215int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1216 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1217}
1218
1219int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1220 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1221}
1222
1223int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1224 int32_t result = AKEY_STATE_UNKNOWN;
1225 size_t numMappers = mMappers.size();
1226 for (size_t i = 0; i < numMappers; i++) {
1227 InputMapper* mapper = mMappers[i];
1228 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1229 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1230 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1231 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1232 if (currentResult >= AKEY_STATE_DOWN) {
1233 return currentResult;
1234 } else if (currentResult == AKEY_STATE_UP) {
1235 result = currentResult;
1236 }
1237 }
1238 }
1239 return result;
1240}
1241
1242bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1243 const int32_t* keyCodes, uint8_t* outFlags) {
1244 bool result = false;
1245 size_t numMappers = mMappers.size();
1246 for (size_t i = 0; i < numMappers; i++) {
1247 InputMapper* mapper = mMappers[i];
1248 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1249 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1250 }
1251 }
1252 return result;
1253}
1254
1255void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1256 int32_t token) {
1257 size_t numMappers = mMappers.size();
1258 for (size_t i = 0; i < numMappers; i++) {
1259 InputMapper* mapper = mMappers[i];
1260 mapper->vibrate(pattern, patternSize, repeat, token);
1261 }
1262}
1263
1264void InputDevice::cancelVibrate(int32_t token) {
1265 size_t numMappers = mMappers.size();
1266 for (size_t i = 0; i < numMappers; i++) {
1267 InputMapper* mapper = mMappers[i];
1268 mapper->cancelVibrate(token);
1269 }
1270}
1271
Jeff Brownc9aa6282015-02-11 19:03:28 -08001272void InputDevice::cancelTouch(nsecs_t when) {
1273 size_t numMappers = mMappers.size();
1274 for (size_t i = 0; i < numMappers; i++) {
1275 InputMapper* mapper = mMappers[i];
1276 mapper->cancelTouch(when);
1277 }
1278}
1279
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280int32_t InputDevice::getMetaState() {
1281 int32_t result = 0;
1282 size_t numMappers = mMappers.size();
1283 for (size_t i = 0; i < numMappers; i++) {
1284 InputMapper* mapper = mMappers[i];
1285 result |= mapper->getMetaState();
1286 }
1287 return result;
1288}
1289
Andrii Kulian763a3a42016-03-08 10:46:16 -08001290void InputDevice::updateMetaState(int32_t keyCode) {
1291 size_t numMappers = mMappers.size();
1292 for (size_t i = 0; i < numMappers; i++) {
1293 mMappers[i]->updateMetaState(keyCode);
1294 }
1295}
1296
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297void InputDevice::fadePointer() {
1298 size_t numMappers = mMappers.size();
1299 for (size_t i = 0; i < numMappers; i++) {
1300 InputMapper* mapper = mMappers[i];
1301 mapper->fadePointer();
1302 }
1303}
1304
1305void InputDevice::bumpGeneration() {
1306 mGeneration = mContext->bumpGeneration();
1307}
1308
1309void InputDevice::notifyReset(nsecs_t when) {
1310 NotifyDeviceResetArgs args(when, mId);
1311 mContext->getListener()->notifyDeviceReset(&args);
1312}
1313
1314
1315// --- CursorButtonAccumulator ---
1316
1317CursorButtonAccumulator::CursorButtonAccumulator() {
1318 clearButtons();
1319}
1320
1321void CursorButtonAccumulator::reset(InputDevice* device) {
1322 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1323 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1324 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1325 mBtnBack = device->isKeyPressed(BTN_BACK);
1326 mBtnSide = device->isKeyPressed(BTN_SIDE);
1327 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1328 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1329 mBtnTask = device->isKeyPressed(BTN_TASK);
1330}
1331
1332void CursorButtonAccumulator::clearButtons() {
1333 mBtnLeft = 0;
1334 mBtnRight = 0;
1335 mBtnMiddle = 0;
1336 mBtnBack = 0;
1337 mBtnSide = 0;
1338 mBtnForward = 0;
1339 mBtnExtra = 0;
1340 mBtnTask = 0;
1341}
1342
1343void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1344 if (rawEvent->type == EV_KEY) {
1345 switch (rawEvent->code) {
1346 case BTN_LEFT:
1347 mBtnLeft = rawEvent->value;
1348 break;
1349 case BTN_RIGHT:
1350 mBtnRight = rawEvent->value;
1351 break;
1352 case BTN_MIDDLE:
1353 mBtnMiddle = rawEvent->value;
1354 break;
1355 case BTN_BACK:
1356 mBtnBack = rawEvent->value;
1357 break;
1358 case BTN_SIDE:
1359 mBtnSide = rawEvent->value;
1360 break;
1361 case BTN_FORWARD:
1362 mBtnForward = rawEvent->value;
1363 break;
1364 case BTN_EXTRA:
1365 mBtnExtra = rawEvent->value;
1366 break;
1367 case BTN_TASK:
1368 mBtnTask = rawEvent->value;
1369 break;
1370 }
1371 }
1372}
1373
1374uint32_t CursorButtonAccumulator::getButtonState() const {
1375 uint32_t result = 0;
1376 if (mBtnLeft) {
1377 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1378 }
1379 if (mBtnRight) {
1380 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1381 }
1382 if (mBtnMiddle) {
1383 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1384 }
1385 if (mBtnBack || mBtnSide) {
1386 result |= AMOTION_EVENT_BUTTON_BACK;
1387 }
1388 if (mBtnForward || mBtnExtra) {
1389 result |= AMOTION_EVENT_BUTTON_FORWARD;
1390 }
1391 return result;
1392}
1393
1394
1395// --- CursorMotionAccumulator ---
1396
1397CursorMotionAccumulator::CursorMotionAccumulator() {
1398 clearRelativeAxes();
1399}
1400
1401void CursorMotionAccumulator::reset(InputDevice* device) {
1402 clearRelativeAxes();
1403}
1404
1405void CursorMotionAccumulator::clearRelativeAxes() {
1406 mRelX = 0;
1407 mRelY = 0;
1408}
1409
1410void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1411 if (rawEvent->type == EV_REL) {
1412 switch (rawEvent->code) {
1413 case REL_X:
1414 mRelX = rawEvent->value;
1415 break;
1416 case REL_Y:
1417 mRelY = rawEvent->value;
1418 break;
1419 }
1420 }
1421}
1422
1423void CursorMotionAccumulator::finishSync() {
1424 clearRelativeAxes();
1425}
1426
1427
1428// --- CursorScrollAccumulator ---
1429
1430CursorScrollAccumulator::CursorScrollAccumulator() :
1431 mHaveRelWheel(false), mHaveRelHWheel(false) {
1432 clearRelativeAxes();
1433}
1434
1435void CursorScrollAccumulator::configure(InputDevice* device) {
1436 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1437 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1438}
1439
1440void CursorScrollAccumulator::reset(InputDevice* device) {
1441 clearRelativeAxes();
1442}
1443
1444void CursorScrollAccumulator::clearRelativeAxes() {
1445 mRelWheel = 0;
1446 mRelHWheel = 0;
1447}
1448
1449void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1450 if (rawEvent->type == EV_REL) {
1451 switch (rawEvent->code) {
1452 case REL_WHEEL:
1453 mRelWheel = rawEvent->value;
1454 break;
1455 case REL_HWHEEL:
1456 mRelHWheel = rawEvent->value;
1457 break;
1458 }
1459 }
1460}
1461
1462void CursorScrollAccumulator::finishSync() {
1463 clearRelativeAxes();
1464}
1465
1466
1467// --- TouchButtonAccumulator ---
1468
1469TouchButtonAccumulator::TouchButtonAccumulator() :
1470 mHaveBtnTouch(false), mHaveStylus(false) {
1471 clearButtons();
1472}
1473
1474void TouchButtonAccumulator::configure(InputDevice* device) {
1475 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1476 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1477 || device->hasKey(BTN_TOOL_RUBBER)
1478 || device->hasKey(BTN_TOOL_BRUSH)
1479 || device->hasKey(BTN_TOOL_PENCIL)
1480 || device->hasKey(BTN_TOOL_AIRBRUSH);
1481}
1482
1483void TouchButtonAccumulator::reset(InputDevice* device) {
1484 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1485 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001486 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1487 mBtnStylus2 =
1488 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1490 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1491 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1492 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1493 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1494 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1495 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1496 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1497 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1498 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1499 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1500}
1501
1502void TouchButtonAccumulator::clearButtons() {
1503 mBtnTouch = 0;
1504 mBtnStylus = 0;
1505 mBtnStylus2 = 0;
1506 mBtnToolFinger = 0;
1507 mBtnToolPen = 0;
1508 mBtnToolRubber = 0;
1509 mBtnToolBrush = 0;
1510 mBtnToolPencil = 0;
1511 mBtnToolAirbrush = 0;
1512 mBtnToolMouse = 0;
1513 mBtnToolLens = 0;
1514 mBtnToolDoubleTap = 0;
1515 mBtnToolTripleTap = 0;
1516 mBtnToolQuadTap = 0;
1517}
1518
1519void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1520 if (rawEvent->type == EV_KEY) {
1521 switch (rawEvent->code) {
1522 case BTN_TOUCH:
1523 mBtnTouch = rawEvent->value;
1524 break;
1525 case BTN_STYLUS:
1526 mBtnStylus = rawEvent->value;
1527 break;
1528 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001529 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 mBtnStylus2 = rawEvent->value;
1531 break;
1532 case BTN_TOOL_FINGER:
1533 mBtnToolFinger = rawEvent->value;
1534 break;
1535 case BTN_TOOL_PEN:
1536 mBtnToolPen = rawEvent->value;
1537 break;
1538 case BTN_TOOL_RUBBER:
1539 mBtnToolRubber = rawEvent->value;
1540 break;
1541 case BTN_TOOL_BRUSH:
1542 mBtnToolBrush = rawEvent->value;
1543 break;
1544 case BTN_TOOL_PENCIL:
1545 mBtnToolPencil = rawEvent->value;
1546 break;
1547 case BTN_TOOL_AIRBRUSH:
1548 mBtnToolAirbrush = rawEvent->value;
1549 break;
1550 case BTN_TOOL_MOUSE:
1551 mBtnToolMouse = rawEvent->value;
1552 break;
1553 case BTN_TOOL_LENS:
1554 mBtnToolLens = rawEvent->value;
1555 break;
1556 case BTN_TOOL_DOUBLETAP:
1557 mBtnToolDoubleTap = rawEvent->value;
1558 break;
1559 case BTN_TOOL_TRIPLETAP:
1560 mBtnToolTripleTap = rawEvent->value;
1561 break;
1562 case BTN_TOOL_QUADTAP:
1563 mBtnToolQuadTap = rawEvent->value;
1564 break;
1565 }
1566 }
1567}
1568
1569uint32_t TouchButtonAccumulator::getButtonState() const {
1570 uint32_t result = 0;
1571 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001572 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 }
1574 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001575 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 }
1577 return result;
1578}
1579
1580int32_t TouchButtonAccumulator::getToolType() const {
1581 if (mBtnToolMouse || mBtnToolLens) {
1582 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1583 }
1584 if (mBtnToolRubber) {
1585 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1586 }
1587 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1588 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1589 }
1590 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1591 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1592 }
1593 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1594}
1595
1596bool TouchButtonAccumulator::isToolActive() const {
1597 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1598 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1599 || mBtnToolMouse || mBtnToolLens
1600 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1601}
1602
1603bool TouchButtonAccumulator::isHovering() const {
1604 return mHaveBtnTouch && !mBtnTouch;
1605}
1606
1607bool TouchButtonAccumulator::hasStylus() const {
1608 return mHaveStylus;
1609}
1610
1611
1612// --- RawPointerAxes ---
1613
1614RawPointerAxes::RawPointerAxes() {
1615 clear();
1616}
1617
1618void RawPointerAxes::clear() {
1619 x.clear();
1620 y.clear();
1621 pressure.clear();
1622 touchMajor.clear();
1623 touchMinor.clear();
1624 toolMajor.clear();
1625 toolMinor.clear();
1626 orientation.clear();
1627 distance.clear();
1628 tiltX.clear();
1629 tiltY.clear();
1630 trackingId.clear();
1631 slot.clear();
1632}
1633
1634
1635// --- RawPointerData ---
1636
1637RawPointerData::RawPointerData() {
1638 clear();
1639}
1640
1641void RawPointerData::clear() {
1642 pointerCount = 0;
1643 clearIdBits();
1644}
1645
1646void RawPointerData::copyFrom(const RawPointerData& other) {
1647 pointerCount = other.pointerCount;
1648 hoveringIdBits = other.hoveringIdBits;
1649 touchingIdBits = other.touchingIdBits;
1650
1651 for (uint32_t i = 0; i < pointerCount; i++) {
1652 pointers[i] = other.pointers[i];
1653
1654 int id = pointers[i].id;
1655 idToIndex[id] = other.idToIndex[id];
1656 }
1657}
1658
1659void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1660 float x = 0, y = 0;
1661 uint32_t count = touchingIdBits.count();
1662 if (count) {
1663 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1664 uint32_t id = idBits.clearFirstMarkedBit();
1665 const Pointer& pointer = pointerForId(id);
1666 x += pointer.x;
1667 y += pointer.y;
1668 }
1669 x /= count;
1670 y /= count;
1671 }
1672 *outX = x;
1673 *outY = y;
1674}
1675
1676
1677// --- CookedPointerData ---
1678
1679CookedPointerData::CookedPointerData() {
1680 clear();
1681}
1682
1683void CookedPointerData::clear() {
1684 pointerCount = 0;
1685 hoveringIdBits.clear();
1686 touchingIdBits.clear();
1687}
1688
1689void CookedPointerData::copyFrom(const CookedPointerData& other) {
1690 pointerCount = other.pointerCount;
1691 hoveringIdBits = other.hoveringIdBits;
1692 touchingIdBits = other.touchingIdBits;
1693
1694 for (uint32_t i = 0; i < pointerCount; i++) {
1695 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1696 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1697
1698 int id = pointerProperties[i].id;
1699 idToIndex[id] = other.idToIndex[id];
1700 }
1701}
1702
1703
1704// --- SingleTouchMotionAccumulator ---
1705
1706SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1707 clearAbsoluteAxes();
1708}
1709
1710void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1711 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1712 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1713 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1714 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1715 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1716 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1717 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1718}
1719
1720void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1721 mAbsX = 0;
1722 mAbsY = 0;
1723 mAbsPressure = 0;
1724 mAbsToolWidth = 0;
1725 mAbsDistance = 0;
1726 mAbsTiltX = 0;
1727 mAbsTiltY = 0;
1728}
1729
1730void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1731 if (rawEvent->type == EV_ABS) {
1732 switch (rawEvent->code) {
1733 case ABS_X:
1734 mAbsX = rawEvent->value;
1735 break;
1736 case ABS_Y:
1737 mAbsY = rawEvent->value;
1738 break;
1739 case ABS_PRESSURE:
1740 mAbsPressure = rawEvent->value;
1741 break;
1742 case ABS_TOOL_WIDTH:
1743 mAbsToolWidth = rawEvent->value;
1744 break;
1745 case ABS_DISTANCE:
1746 mAbsDistance = rawEvent->value;
1747 break;
1748 case ABS_TILT_X:
1749 mAbsTiltX = rawEvent->value;
1750 break;
1751 case ABS_TILT_Y:
1752 mAbsTiltY = rawEvent->value;
1753 break;
1754 }
1755 }
1756}
1757
1758
1759// --- MultiTouchMotionAccumulator ---
1760
1761MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001762 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001763 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764}
1765
1766MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1767 delete[] mSlots;
1768}
1769
1770void MultiTouchMotionAccumulator::configure(InputDevice* device,
1771 size_t slotCount, bool usingSlotsProtocol) {
1772 mSlotCount = slotCount;
1773 mUsingSlotsProtocol = usingSlotsProtocol;
1774 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1775
1776 delete[] mSlots;
1777 mSlots = new Slot[slotCount];
1778}
1779
1780void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1781 // Unfortunately there is no way to read the initial contents of the slots.
1782 // So when we reset the accumulator, we must assume they are all zeroes.
1783 if (mUsingSlotsProtocol) {
1784 // Query the driver for the current slot index and use it as the initial slot
1785 // before we start reading events from the device. It is possible that the
1786 // current slot index will not be the same as it was when the first event was
1787 // written into the evdev buffer, which means the input mapper could start
1788 // out of sync with the initial state of the events in the evdev buffer.
1789 // In the extremely unlikely case that this happens, the data from
1790 // two slots will be confused until the next ABS_MT_SLOT event is received.
1791 // This can cause the touch point to "jump", but at least there will be
1792 // no stuck touches.
1793 int32_t initialSlot;
1794 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1795 ABS_MT_SLOT, &initialSlot);
1796 if (status) {
1797 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1798 initialSlot = -1;
1799 }
1800 clearSlots(initialSlot);
1801 } else {
1802 clearSlots(-1);
1803 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001804 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805}
1806
1807void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1808 if (mSlots) {
1809 for (size_t i = 0; i < mSlotCount; i++) {
1810 mSlots[i].clear();
1811 }
1812 }
1813 mCurrentSlot = initialSlot;
1814}
1815
1816void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1817 if (rawEvent->type == EV_ABS) {
1818 bool newSlot = false;
1819 if (mUsingSlotsProtocol) {
1820 if (rawEvent->code == ABS_MT_SLOT) {
1821 mCurrentSlot = rawEvent->value;
1822 newSlot = true;
1823 }
1824 } else if (mCurrentSlot < 0) {
1825 mCurrentSlot = 0;
1826 }
1827
1828 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1829#if DEBUG_POINTERS
1830 if (newSlot) {
1831 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001832 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 mCurrentSlot, mSlotCount - 1);
1834 }
1835#endif
1836 } else {
1837 Slot* slot = &mSlots[mCurrentSlot];
1838
1839 switch (rawEvent->code) {
1840 case ABS_MT_POSITION_X:
1841 slot->mInUse = true;
1842 slot->mAbsMTPositionX = rawEvent->value;
1843 break;
1844 case ABS_MT_POSITION_Y:
1845 slot->mInUse = true;
1846 slot->mAbsMTPositionY = rawEvent->value;
1847 break;
1848 case ABS_MT_TOUCH_MAJOR:
1849 slot->mInUse = true;
1850 slot->mAbsMTTouchMajor = rawEvent->value;
1851 break;
1852 case ABS_MT_TOUCH_MINOR:
1853 slot->mInUse = true;
1854 slot->mAbsMTTouchMinor = rawEvent->value;
1855 slot->mHaveAbsMTTouchMinor = true;
1856 break;
1857 case ABS_MT_WIDTH_MAJOR:
1858 slot->mInUse = true;
1859 slot->mAbsMTWidthMajor = rawEvent->value;
1860 break;
1861 case ABS_MT_WIDTH_MINOR:
1862 slot->mInUse = true;
1863 slot->mAbsMTWidthMinor = rawEvent->value;
1864 slot->mHaveAbsMTWidthMinor = true;
1865 break;
1866 case ABS_MT_ORIENTATION:
1867 slot->mInUse = true;
1868 slot->mAbsMTOrientation = rawEvent->value;
1869 break;
1870 case ABS_MT_TRACKING_ID:
1871 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1872 // The slot is no longer in use but it retains its previous contents,
1873 // which may be reused for subsequent touches.
1874 slot->mInUse = false;
1875 } else {
1876 slot->mInUse = true;
1877 slot->mAbsMTTrackingId = rawEvent->value;
1878 }
1879 break;
1880 case ABS_MT_PRESSURE:
1881 slot->mInUse = true;
1882 slot->mAbsMTPressure = rawEvent->value;
1883 break;
1884 case ABS_MT_DISTANCE:
1885 slot->mInUse = true;
1886 slot->mAbsMTDistance = rawEvent->value;
1887 break;
1888 case ABS_MT_TOOL_TYPE:
1889 slot->mInUse = true;
1890 slot->mAbsMTToolType = rawEvent->value;
1891 slot->mHaveAbsMTToolType = true;
1892 break;
1893 }
1894 }
1895 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1896 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1897 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001898 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1899 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 }
1901}
1902
1903void MultiTouchMotionAccumulator::finishSync() {
1904 if (!mUsingSlotsProtocol) {
1905 clearSlots(-1);
1906 }
1907}
1908
1909bool MultiTouchMotionAccumulator::hasStylus() const {
1910 return mHaveStylus;
1911}
1912
1913
1914// --- MultiTouchMotionAccumulator::Slot ---
1915
1916MultiTouchMotionAccumulator::Slot::Slot() {
1917 clear();
1918}
1919
1920void MultiTouchMotionAccumulator::Slot::clear() {
1921 mInUse = false;
1922 mHaveAbsMTTouchMinor = false;
1923 mHaveAbsMTWidthMinor = false;
1924 mHaveAbsMTToolType = false;
1925 mAbsMTPositionX = 0;
1926 mAbsMTPositionY = 0;
1927 mAbsMTTouchMajor = 0;
1928 mAbsMTTouchMinor = 0;
1929 mAbsMTWidthMajor = 0;
1930 mAbsMTWidthMinor = 0;
1931 mAbsMTOrientation = 0;
1932 mAbsMTTrackingId = -1;
1933 mAbsMTPressure = 0;
1934 mAbsMTDistance = 0;
1935 mAbsMTToolType = 0;
1936}
1937
1938int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1939 if (mHaveAbsMTToolType) {
1940 switch (mAbsMTToolType) {
1941 case MT_TOOL_FINGER:
1942 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1943 case MT_TOOL_PEN:
1944 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1945 }
1946 }
1947 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1948}
1949
1950
1951// --- InputMapper ---
1952
1953InputMapper::InputMapper(InputDevice* device) :
1954 mDevice(device), mContext(device->getContext()) {
1955}
1956
1957InputMapper::~InputMapper() {
1958}
1959
1960void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1961 info->addSource(getSources());
1962}
1963
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001964void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965}
1966
1967void InputMapper::configure(nsecs_t when,
1968 const InputReaderConfiguration* config, uint32_t changes) {
1969}
1970
1971void InputMapper::reset(nsecs_t when) {
1972}
1973
1974void InputMapper::timeoutExpired(nsecs_t when) {
1975}
1976
1977int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1978 return AKEY_STATE_UNKNOWN;
1979}
1980
1981int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1982 return AKEY_STATE_UNKNOWN;
1983}
1984
1985int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1986 return AKEY_STATE_UNKNOWN;
1987}
1988
1989bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1990 const int32_t* keyCodes, uint8_t* outFlags) {
1991 return false;
1992}
1993
1994void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1995 int32_t token) {
1996}
1997
1998void InputMapper::cancelVibrate(int32_t token) {
1999}
2000
Jeff Brownc9aa6282015-02-11 19:03:28 -08002001void InputMapper::cancelTouch(nsecs_t when) {
2002}
2003
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004int32_t InputMapper::getMetaState() {
2005 return 0;
2006}
2007
Andrii Kulian763a3a42016-03-08 10:46:16 -08002008void InputMapper::updateMetaState(int32_t keyCode) {
2009}
2010
Michael Wright842500e2015-03-13 17:32:02 -07002011void InputMapper::updateExternalStylusState(const StylusState& state) {
2012
2013}
2014
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015void InputMapper::fadePointer() {
2016}
2017
2018status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2019 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2020}
2021
2022void InputMapper::bumpGeneration() {
2023 mDevice->bumpGeneration();
2024}
2025
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002026void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 const RawAbsoluteAxisInfo& axis, const char* name) {
2028 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002029 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2031 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002032 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 }
2034}
2035
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002036void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2037 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2038 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2039 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2040 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002041}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042
2043// --- SwitchInputMapper ---
2044
2045SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002046 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047}
2048
2049SwitchInputMapper::~SwitchInputMapper() {
2050}
2051
2052uint32_t SwitchInputMapper::getSources() {
2053 return AINPUT_SOURCE_SWITCH;
2054}
2055
2056void SwitchInputMapper::process(const RawEvent* rawEvent) {
2057 switch (rawEvent->type) {
2058 case EV_SW:
2059 processSwitch(rawEvent->code, rawEvent->value);
2060 break;
2061
2062 case EV_SYN:
2063 if (rawEvent->code == SYN_REPORT) {
2064 sync(rawEvent->when);
2065 }
2066 }
2067}
2068
2069void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2070 if (switchCode >= 0 && switchCode < 32) {
2071 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002072 mSwitchValues |= 1 << switchCode;
2073 } else {
2074 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 }
2076 mUpdatedSwitchMask |= 1 << switchCode;
2077 }
2078}
2079
2080void SwitchInputMapper::sync(nsecs_t when) {
2081 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002082 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002083 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 getListener()->notifySwitch(&args);
2085
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086 mUpdatedSwitchMask = 0;
2087 }
2088}
2089
2090int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2091 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2092}
2093
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002094void SwitchInputMapper::dump(std::string& dump) {
2095 dump += INDENT2 "Switch Input Mapper:\n";
2096 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002097}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002098
2099// --- VibratorInputMapper ---
2100
2101VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2102 InputMapper(device), mVibrating(false) {
2103}
2104
2105VibratorInputMapper::~VibratorInputMapper() {
2106}
2107
2108uint32_t VibratorInputMapper::getSources() {
2109 return 0;
2110}
2111
2112void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2113 InputMapper::populateDeviceInfo(info);
2114
2115 info->setVibrator(true);
2116}
2117
2118void VibratorInputMapper::process(const RawEvent* rawEvent) {
2119 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2120}
2121
2122void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2123 int32_t token) {
2124#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002125 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 for (size_t i = 0; i < patternSize; i++) {
2127 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002128 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002130 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002132 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002133 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134#endif
2135
2136 mVibrating = true;
2137 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2138 mPatternSize = patternSize;
2139 mRepeat = repeat;
2140 mToken = token;
2141 mIndex = -1;
2142
2143 nextStep();
2144}
2145
2146void VibratorInputMapper::cancelVibrate(int32_t token) {
2147#if DEBUG_VIBRATOR
2148 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2149#endif
2150
2151 if (mVibrating && mToken == token) {
2152 stopVibrating();
2153 }
2154}
2155
2156void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2157 if (mVibrating) {
2158 if (when >= mNextStepTime) {
2159 nextStep();
2160 } else {
2161 getContext()->requestTimeoutAtTime(mNextStepTime);
2162 }
2163 }
2164}
2165
2166void VibratorInputMapper::nextStep() {
2167 mIndex += 1;
2168 if (size_t(mIndex) >= mPatternSize) {
2169 if (mRepeat < 0) {
2170 // We are done.
2171 stopVibrating();
2172 return;
2173 }
2174 mIndex = mRepeat;
2175 }
2176
2177 bool vibratorOn = mIndex & 1;
2178 nsecs_t duration = mPattern[mIndex];
2179 if (vibratorOn) {
2180#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002181 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182#endif
2183 getEventHub()->vibrate(getDeviceId(), duration);
2184 } else {
2185#if DEBUG_VIBRATOR
2186 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2187#endif
2188 getEventHub()->cancelVibrate(getDeviceId());
2189 }
2190 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2191 mNextStepTime = now + duration;
2192 getContext()->requestTimeoutAtTime(mNextStepTime);
2193#if DEBUG_VIBRATOR
2194 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2195#endif
2196}
2197
2198void VibratorInputMapper::stopVibrating() {
2199 mVibrating = false;
2200#if DEBUG_VIBRATOR
2201 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2202#endif
2203 getEventHub()->cancelVibrate(getDeviceId());
2204}
2205
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002206void VibratorInputMapper::dump(std::string& dump) {
2207 dump += INDENT2 "Vibrator Input Mapper:\n";
2208 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209}
2210
2211
2212// --- KeyboardInputMapper ---
2213
2214KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2215 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002216 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217}
2218
2219KeyboardInputMapper::~KeyboardInputMapper() {
2220}
2221
2222uint32_t KeyboardInputMapper::getSources() {
2223 return mSource;
2224}
2225
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002226int32_t KeyboardInputMapper::getOrientation() {
2227 if (mViewport) {
2228 return mViewport->orientation;
2229 }
2230 return DISPLAY_ORIENTATION_0;
2231}
2232
2233int32_t KeyboardInputMapper::getDisplayId() {
2234 if (mViewport) {
2235 return mViewport->displayId;
2236 }
2237 return ADISPLAY_ID_NONE;
2238}
2239
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2241 InputMapper::populateDeviceInfo(info);
2242
2243 info->setKeyboardType(mKeyboardType);
2244 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2245}
2246
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002247void KeyboardInputMapper::dump(std::string& dump) {
2248 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002250 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002251 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002252 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2253 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2254 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255}
2256
2257
2258void KeyboardInputMapper::configure(nsecs_t when,
2259 const InputReaderConfiguration* config, uint32_t changes) {
2260 InputMapper::configure(when, config, changes);
2261
2262 if (!changes) { // first time only
2263 // Configure basic parameters.
2264 configureParameters();
2265 }
2266
2267 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002268 if (mParameters.orientationAware) {
2269 DisplayViewport dvp;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002270 config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "", &dvp);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002271 mViewport = dvp;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 }
2273 }
2274}
2275
Ivan Podogovb9afef32017-02-13 15:34:32 +00002276static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2277 int32_t mapped = 0;
2278 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2279 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2280 if (stemKeyRotationMap[i][0] == keyCode) {
2281 stemKeyRotationMap[i][1] = mapped;
2282 return;
2283 }
2284 }
2285 }
2286}
2287
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288void KeyboardInputMapper::configureParameters() {
2289 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002290 const PropertyMap& config = getDevice()->getConfiguration();
2291 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 mParameters.orientationAware);
2293
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002295 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2296 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2297 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2298 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002300
2301 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002302 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002303 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304}
2305
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002306void KeyboardInputMapper::dumpParameters(std::string& dump) {
2307 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002308 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002310 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002311 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312}
2313
2314void KeyboardInputMapper::reset(nsecs_t when) {
2315 mMetaState = AMETA_NONE;
2316 mDownTime = 0;
2317 mKeyDowns.clear();
2318 mCurrentHidUsage = 0;
2319
2320 resetLedState();
2321
2322 InputMapper::reset(when);
2323}
2324
2325void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2326 switch (rawEvent->type) {
2327 case EV_KEY: {
2328 int32_t scanCode = rawEvent->code;
2329 int32_t usageCode = mCurrentHidUsage;
2330 mCurrentHidUsage = 0;
2331
2332 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002333 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 }
2335 break;
2336 }
2337 case EV_MSC: {
2338 if (rawEvent->code == MSC_SCAN) {
2339 mCurrentHidUsage = rawEvent->value;
2340 }
2341 break;
2342 }
2343 case EV_SYN: {
2344 if (rawEvent->code == SYN_REPORT) {
2345 mCurrentHidUsage = 0;
2346 }
2347 }
2348 }
2349}
2350
2351bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2352 return scanCode < BTN_MOUSE
2353 || scanCode >= KEY_OK
2354 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2355 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2356}
2357
Michael Wright58ba9882017-07-26 16:19:11 +01002358bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2359 switch (keyCode) {
2360 case AKEYCODE_MEDIA_PLAY:
2361 case AKEYCODE_MEDIA_PAUSE:
2362 case AKEYCODE_MEDIA_PLAY_PAUSE:
2363 case AKEYCODE_MUTE:
2364 case AKEYCODE_HEADSETHOOK:
2365 case AKEYCODE_MEDIA_STOP:
2366 case AKEYCODE_MEDIA_NEXT:
2367 case AKEYCODE_MEDIA_PREVIOUS:
2368 case AKEYCODE_MEDIA_REWIND:
2369 case AKEYCODE_MEDIA_RECORD:
2370 case AKEYCODE_MEDIA_FAST_FORWARD:
2371 case AKEYCODE_MEDIA_SKIP_FORWARD:
2372 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2373 case AKEYCODE_MEDIA_STEP_FORWARD:
2374 case AKEYCODE_MEDIA_STEP_BACKWARD:
2375 case AKEYCODE_MEDIA_AUDIO_TRACK:
2376 case AKEYCODE_VOLUME_UP:
2377 case AKEYCODE_VOLUME_DOWN:
2378 case AKEYCODE_VOLUME_MUTE:
2379 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2380 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2381 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2382 return true;
2383 }
2384 return false;
2385}
2386
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002387void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2388 int32_t usageCode) {
2389 int32_t keyCode;
2390 int32_t keyMetaState;
2391 uint32_t policyFlags;
2392
2393 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2394 &keyCode, &keyMetaState, &policyFlags)) {
2395 keyCode = AKEYCODE_UNKNOWN;
2396 keyMetaState = mMetaState;
2397 policyFlags = 0;
2398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399
2400 if (down) {
2401 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002402 if (mParameters.orientationAware) {
2403 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 }
2405
2406 // Add key down.
2407 ssize_t keyDownIndex = findKeyDown(scanCode);
2408 if (keyDownIndex >= 0) {
2409 // key repeat, be sure to use same keycode as before in case of rotation
2410 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2411 } else {
2412 // key down
2413 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2414 && mContext->shouldDropVirtualKey(when,
2415 getDevice(), keyCode, scanCode)) {
2416 return;
2417 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002418 if (policyFlags & POLICY_FLAG_GESTURE) {
2419 mDevice->cancelTouch(when);
2420 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421
2422 mKeyDowns.push();
2423 KeyDown& keyDown = mKeyDowns.editTop();
2424 keyDown.keyCode = keyCode;
2425 keyDown.scanCode = scanCode;
2426 }
2427
2428 mDownTime = when;
2429 } else {
2430 // Remove key down.
2431 ssize_t keyDownIndex = findKeyDown(scanCode);
2432 if (keyDownIndex >= 0) {
2433 // key up, be sure to use same keycode as before in case of rotation
2434 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2435 mKeyDowns.removeAt(size_t(keyDownIndex));
2436 } else {
2437 // key was not actually down
2438 ALOGI("Dropping key up from device %s because the key was not down. "
2439 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002440 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 return;
2442 }
2443 }
2444
Andrii Kulian763a3a42016-03-08 10:46:16 -08002445 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002446 // If global meta state changed send it along with the key.
2447 // If it has not changed then we'll use what keymap gave us,
2448 // since key replacement logic might temporarily reset a few
2449 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002450 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 }
2452
2453 nsecs_t downTime = mDownTime;
2454
2455 // Key down on external an keyboard should wake the device.
2456 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2457 // For internal keyboards, the key layout file should specify the policy flags for
2458 // each wake key individually.
2459 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002460 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002461 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 }
2463
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002464 if (mParameters.handlesKeyRepeat) {
2465 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2466 }
2467
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002468 NotifyKeyArgs args(when, getDeviceId(), mSource, getDisplayId(), policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002470 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002471 getListener()->notifyKey(&args);
2472}
2473
2474ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2475 size_t n = mKeyDowns.size();
2476 for (size_t i = 0; i < n; i++) {
2477 if (mKeyDowns[i].scanCode == scanCode) {
2478 return i;
2479 }
2480 }
2481 return -1;
2482}
2483
2484int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2485 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2486}
2487
2488int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2489 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2490}
2491
2492bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2493 const int32_t* keyCodes, uint8_t* outFlags) {
2494 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2495}
2496
2497int32_t KeyboardInputMapper::getMetaState() {
2498 return mMetaState;
2499}
2500
Andrii Kulian763a3a42016-03-08 10:46:16 -08002501void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2502 updateMetaStateIfNeeded(keyCode, false);
2503}
2504
2505bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2506 int32_t oldMetaState = mMetaState;
2507 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2508 bool metaStateChanged = oldMetaState != newMetaState;
2509 if (metaStateChanged) {
2510 mMetaState = newMetaState;
2511 updateLedState(false);
2512
2513 getContext()->updateGlobalMetaState();
2514 }
2515
2516 return metaStateChanged;
2517}
2518
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519void KeyboardInputMapper::resetLedState() {
2520 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2521 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2522 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2523
2524 updateLedState(true);
2525}
2526
2527void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2528 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2529 ledState.on = false;
2530}
2531
2532void KeyboardInputMapper::updateLedState(bool reset) {
2533 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2534 AMETA_CAPS_LOCK_ON, reset);
2535 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2536 AMETA_NUM_LOCK_ON, reset);
2537 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2538 AMETA_SCROLL_LOCK_ON, reset);
2539}
2540
2541void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2542 int32_t led, int32_t modifier, bool reset) {
2543 if (ledState.avail) {
2544 bool desiredState = (mMetaState & modifier) != 0;
2545 if (reset || ledState.on != desiredState) {
2546 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2547 ledState.on = desiredState;
2548 }
2549 }
2550}
2551
2552
2553// --- CursorInputMapper ---
2554
2555CursorInputMapper::CursorInputMapper(InputDevice* device) :
2556 InputMapper(device) {
2557}
2558
2559CursorInputMapper::~CursorInputMapper() {
2560}
2561
2562uint32_t CursorInputMapper::getSources() {
2563 return mSource;
2564}
2565
2566void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2567 InputMapper::populateDeviceInfo(info);
2568
2569 if (mParameters.mode == Parameters::MODE_POINTER) {
2570 float minX, minY, maxX, maxY;
2571 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2572 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2573 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2574 }
2575 } else {
2576 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2577 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2578 }
2579 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2580
2581 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2582 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2583 }
2584 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2585 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2586 }
2587}
2588
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002589void CursorInputMapper::dump(std::string& dump) {
2590 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002592 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2593 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2594 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2595 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2596 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002598 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002600 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2601 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2602 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2603 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2604 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2605 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606}
2607
2608void CursorInputMapper::configure(nsecs_t when,
2609 const InputReaderConfiguration* config, uint32_t changes) {
2610 InputMapper::configure(when, config, changes);
2611
2612 if (!changes) { // first time only
2613 mCursorScrollAccumulator.configure(getDevice());
2614
2615 // Configure basic parameters.
2616 configureParameters();
2617
2618 // Configure device mode.
2619 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002620 case Parameters::MODE_POINTER_RELATIVE:
2621 // Should not happen during first time configuration.
2622 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2623 mParameters.mode = Parameters::MODE_POINTER;
2624 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 case Parameters::MODE_POINTER:
2626 mSource = AINPUT_SOURCE_MOUSE;
2627 mXPrecision = 1.0f;
2628 mYPrecision = 1.0f;
2629 mXScale = 1.0f;
2630 mYScale = 1.0f;
2631 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2632 break;
2633 case Parameters::MODE_NAVIGATION:
2634 mSource = AINPUT_SOURCE_TRACKBALL;
2635 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2636 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2637 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2638 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2639 break;
2640 }
2641
2642 mVWheelScale = 1.0f;
2643 mHWheelScale = 1.0f;
2644 }
2645
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002646 if ((!changes && config->pointerCapture)
2647 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2648 if (config->pointerCapture) {
2649 if (mParameters.mode == Parameters::MODE_POINTER) {
2650 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2651 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2652 // Keep PointerController around in order to preserve the pointer position.
2653 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2654 } else {
2655 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2656 }
2657 } else {
2658 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2659 mParameters.mode = Parameters::MODE_POINTER;
2660 mSource = AINPUT_SOURCE_MOUSE;
2661 } else {
2662 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2663 }
2664 }
2665 bumpGeneration();
2666 if (changes) {
2667 getDevice()->notifyReset(when);
2668 }
2669 }
2670
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2672 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2673 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2674 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2675 }
2676
2677 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002678 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2680 DisplayViewport v;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002681 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "", &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 mOrientation = v.orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 }
2685 bumpGeneration();
2686 }
2687}
2688
2689void CursorInputMapper::configureParameters() {
2690 mParameters.mode = Parameters::MODE_POINTER;
2691 String8 cursorModeString;
2692 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2693 if (cursorModeString == "navigation") {
2694 mParameters.mode = Parameters::MODE_NAVIGATION;
2695 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2696 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2697 }
2698 }
2699
2700 mParameters.orientationAware = false;
2701 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2702 mParameters.orientationAware);
2703
2704 mParameters.hasAssociatedDisplay = false;
2705 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2706 mParameters.hasAssociatedDisplay = true;
2707 }
2708}
2709
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002710void CursorInputMapper::dumpParameters(std::string& dump) {
2711 dump += INDENT3 "Parameters:\n";
2712 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 toString(mParameters.hasAssociatedDisplay));
2714
2715 switch (mParameters.mode) {
2716 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002717 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002719 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002720 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002721 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002723 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724 break;
2725 default:
2726 ALOG_ASSERT(false);
2727 }
2728
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002729 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 toString(mParameters.orientationAware));
2731}
2732
2733void CursorInputMapper::reset(nsecs_t when) {
2734 mButtonState = 0;
2735 mDownTime = 0;
2736
2737 mPointerVelocityControl.reset();
2738 mWheelXVelocityControl.reset();
2739 mWheelYVelocityControl.reset();
2740
2741 mCursorButtonAccumulator.reset(getDevice());
2742 mCursorMotionAccumulator.reset(getDevice());
2743 mCursorScrollAccumulator.reset(getDevice());
2744
2745 InputMapper::reset(when);
2746}
2747
2748void CursorInputMapper::process(const RawEvent* rawEvent) {
2749 mCursorButtonAccumulator.process(rawEvent);
2750 mCursorMotionAccumulator.process(rawEvent);
2751 mCursorScrollAccumulator.process(rawEvent);
2752
2753 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2754 sync(rawEvent->when);
2755 }
2756}
2757
2758void CursorInputMapper::sync(nsecs_t when) {
2759 int32_t lastButtonState = mButtonState;
2760 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2761 mButtonState = currentButtonState;
2762
2763 bool wasDown = isPointerDown(lastButtonState);
2764 bool down = isPointerDown(currentButtonState);
2765 bool downChanged;
2766 if (!wasDown && down) {
2767 mDownTime = when;
2768 downChanged = true;
2769 } else if (wasDown && !down) {
2770 downChanged = true;
2771 } else {
2772 downChanged = false;
2773 }
2774 nsecs_t downTime = mDownTime;
2775 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002776 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2777 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778
2779 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2780 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2781 bool moved = deltaX != 0 || deltaY != 0;
2782
2783 // Rotate delta according to orientation if needed.
2784 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2785 && (deltaX != 0.0f || deltaY != 0.0f)) {
2786 rotateDelta(mOrientation, &deltaX, &deltaY);
2787 }
2788
2789 // Move the pointer.
2790 PointerProperties pointerProperties;
2791 pointerProperties.clear();
2792 pointerProperties.id = 0;
2793 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2794
2795 PointerCoords pointerCoords;
2796 pointerCoords.clear();
2797
2798 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2799 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2800 bool scrolled = vscroll != 0 || hscroll != 0;
2801
Yi Kong9b14ac62018-07-17 13:48:38 -07002802 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2803 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804
2805 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2806
2807 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002808 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 if (moved || scrolled || buttonsChanged) {
2810 mPointerController->setPresentation(
2811 PointerControllerInterface::PRESENTATION_POINTER);
2812
2813 if (moved) {
2814 mPointerController->move(deltaX, deltaY);
2815 }
2816
2817 if (buttonsChanged) {
2818 mPointerController->setButtonState(currentButtonState);
2819 }
2820
2821 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2822 }
2823
2824 float x, y;
2825 mPointerController->getPosition(&x, &y);
2826 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2827 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002828 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2829 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 displayId = ADISPLAY_ID_DEFAULT;
2831 } else {
2832 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2833 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2834 displayId = ADISPLAY_ID_NONE;
2835 }
2836
2837 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2838
2839 // Moving an external trackball or mouse should wake the device.
2840 // We don't do this for internal cursor devices to prevent them from waking up
2841 // the device in your pocket.
2842 // TODO: Use the input device configuration to control this behavior more finely.
2843 uint32_t policyFlags = 0;
2844 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002845 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846 }
2847
2848 // Synthesize key down from buttons if needed.
2849 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002850 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851
2852 // Send motion event.
2853 if (downChanged || moved || scrolled || buttonsChanged) {
2854 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002855 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856 int32_t motionEventAction;
2857 if (downChanged) {
2858 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002859 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2861 } else {
2862 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2863 }
2864
Michael Wright7b159c92015-05-14 14:48:03 +01002865 if (buttonsReleased) {
2866 BitSet32 released(buttonsReleased);
2867 while (!released.isEmpty()) {
2868 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2869 buttonState &= ~actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002870 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002871 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2872 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002873 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002874 mXPrecision, mYPrecision, downTime);
2875 getListener()->notifyMotion(&releaseArgs);
2876 }
2877 }
2878
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002879 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002880 motionEventAction, 0, 0, metaState, currentButtonState,
2881 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002882 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883 mXPrecision, mYPrecision, downTime);
2884 getListener()->notifyMotion(&args);
2885
Michael Wright7b159c92015-05-14 14:48:03 +01002886 if (buttonsPressed) {
2887 BitSet32 pressed(buttonsPressed);
2888 while (!pressed.isEmpty()) {
2889 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2890 buttonState |= actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002891 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002892 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2893 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002894 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002895 mXPrecision, mYPrecision, downTime);
2896 getListener()->notifyMotion(&pressArgs);
2897 }
2898 }
2899
2900 ALOG_ASSERT(buttonState == currentButtonState);
2901
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 // Send hover move after UP to tell the application that the mouse is hovering now.
2903 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002904 && (mSource == AINPUT_SOURCE_MOUSE)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002905 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002906 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002908 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909 mXPrecision, mYPrecision, downTime);
2910 getListener()->notifyMotion(&hoverArgs);
2911 }
2912
2913 // Send scroll events.
2914 if (scrolled) {
2915 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2916 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2917
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002918 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002919 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002921 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 mXPrecision, mYPrecision, downTime);
2923 getListener()->notifyMotion(&scrollArgs);
2924 }
2925 }
2926
2927 // Synthesize key up from buttons if needed.
2928 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002929 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930
2931 mCursorMotionAccumulator.finishSync();
2932 mCursorScrollAccumulator.finishSync();
2933}
2934
2935int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2936 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2937 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2938 } else {
2939 return AKEY_STATE_UNKNOWN;
2940 }
2941}
2942
2943void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002944 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2946 }
2947}
2948
Prashant Malani1941ff52015-08-11 18:29:28 -07002949// --- RotaryEncoderInputMapper ---
2950
2951RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002952 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002953 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2954}
2955
2956RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2957}
2958
2959uint32_t RotaryEncoderInputMapper::getSources() {
2960 return mSource;
2961}
2962
2963void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2964 InputMapper::populateDeviceInfo(info);
2965
2966 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002967 float res = 0.0f;
2968 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2969 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2970 }
2971 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2972 mScalingFactor)) {
2973 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2974 "default to 1.0!\n");
2975 mScalingFactor = 1.0f;
2976 }
2977 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2978 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002979 }
2980}
2981
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002982void RotaryEncoderInputMapper::dump(std::string& dump) {
2983 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2984 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002985 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2986}
2987
2988void RotaryEncoderInputMapper::configure(nsecs_t when,
2989 const InputReaderConfiguration* config, uint32_t changes) {
2990 InputMapper::configure(when, config, changes);
2991 if (!changes) {
2992 mRotaryEncoderScrollAccumulator.configure(getDevice());
2993 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002994 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Ivan Podogovad437252016-09-29 16:29:55 +01002995 DisplayViewport v;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002996 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "", &v)) {
Ivan Podogovad437252016-09-29 16:29:55 +01002997 mOrientation = v.orientation;
2998 } else {
2999 mOrientation = DISPLAY_ORIENTATION_0;
3000 }
3001 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003002}
3003
3004void RotaryEncoderInputMapper::reset(nsecs_t when) {
3005 mRotaryEncoderScrollAccumulator.reset(getDevice());
3006
3007 InputMapper::reset(when);
3008}
3009
3010void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3011 mRotaryEncoderScrollAccumulator.process(rawEvent);
3012
3013 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3014 sync(rawEvent->when);
3015 }
3016}
3017
3018void RotaryEncoderInputMapper::sync(nsecs_t when) {
3019 PointerCoords pointerCoords;
3020 pointerCoords.clear();
3021
3022 PointerProperties pointerProperties;
3023 pointerProperties.clear();
3024 pointerProperties.id = 0;
3025 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3026
3027 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3028 bool scrolled = scroll != 0;
3029
3030 // This is not a pointer, so it's not associated with a display.
3031 int32_t displayId = ADISPLAY_ID_NONE;
3032
3033 // Moving the rotary encoder should wake the device (if specified).
3034 uint32_t policyFlags = 0;
3035 if (scrolled && getDevice()->isExternal()) {
3036 policyFlags |= POLICY_FLAG_WAKE;
3037 }
3038
Ivan Podogovad437252016-09-29 16:29:55 +01003039 if (mOrientation == DISPLAY_ORIENTATION_180) {
3040 scroll = -scroll;
3041 }
3042
Prashant Malani1941ff52015-08-11 18:29:28 -07003043 // Send motion event.
3044 if (scrolled) {
3045 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003046 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003047
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003048 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Prashant Malani1941ff52015-08-11 18:29:28 -07003049 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3050 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003051 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Prashant Malani1941ff52015-08-11 18:29:28 -07003052 0, 0, 0);
3053 getListener()->notifyMotion(&scrollArgs);
3054 }
3055
3056 mRotaryEncoderScrollAccumulator.finishSync();
3057}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003058
3059// --- TouchInputMapper ---
3060
3061TouchInputMapper::TouchInputMapper(InputDevice* device) :
3062 InputMapper(device),
3063 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3064 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003065 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3067}
3068
3069TouchInputMapper::~TouchInputMapper() {
3070}
3071
3072uint32_t TouchInputMapper::getSources() {
3073 return mSource;
3074}
3075
3076void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3077 InputMapper::populateDeviceInfo(info);
3078
3079 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3080 info->addMotionRange(mOrientedRanges.x);
3081 info->addMotionRange(mOrientedRanges.y);
3082 info->addMotionRange(mOrientedRanges.pressure);
3083
3084 if (mOrientedRanges.haveSize) {
3085 info->addMotionRange(mOrientedRanges.size);
3086 }
3087
3088 if (mOrientedRanges.haveTouchSize) {
3089 info->addMotionRange(mOrientedRanges.touchMajor);
3090 info->addMotionRange(mOrientedRanges.touchMinor);
3091 }
3092
3093 if (mOrientedRanges.haveToolSize) {
3094 info->addMotionRange(mOrientedRanges.toolMajor);
3095 info->addMotionRange(mOrientedRanges.toolMinor);
3096 }
3097
3098 if (mOrientedRanges.haveOrientation) {
3099 info->addMotionRange(mOrientedRanges.orientation);
3100 }
3101
3102 if (mOrientedRanges.haveDistance) {
3103 info->addMotionRange(mOrientedRanges.distance);
3104 }
3105
3106 if (mOrientedRanges.haveTilt) {
3107 info->addMotionRange(mOrientedRanges.tilt);
3108 }
3109
3110 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3111 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3112 0.0f);
3113 }
3114 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3115 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3116 0.0f);
3117 }
3118 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3119 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3120 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3121 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3122 x.fuzz, x.resolution);
3123 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3124 y.fuzz, y.resolution);
3125 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3126 x.fuzz, x.resolution);
3127 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3128 y.fuzz, y.resolution);
3129 }
3130 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3131 }
3132}
3133
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003134void TouchInputMapper::dump(std::string& dump) {
3135 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136 dumpParameters(dump);
3137 dumpVirtualKeys(dump);
3138 dumpRawPointerAxes(dump);
3139 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003140 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141 dumpSurface(dump);
3142
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003143 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3144 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3145 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3146 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3147 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3148 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3149 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3150 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3151 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3152 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3153 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3154 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3155 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3156 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3157 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3158 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3159 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003161 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3162 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003163 mLastRawState.rawPointerData.pointerCount);
3164 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3165 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003166 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3168 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3169 "toolType=%d, isHovering=%s\n", i,
3170 pointer.id, pointer.x, pointer.y, pointer.pressure,
3171 pointer.touchMajor, pointer.touchMinor,
3172 pointer.toolMajor, pointer.toolMinor,
3173 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3174 pointer.toolType, toString(pointer.isHovering));
3175 }
3176
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003177 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3178 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003179 mLastCookedState.cookedPointerData.pointerCount);
3180 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3181 const PointerProperties& pointerProperties =
3182 mLastCookedState.cookedPointerData.pointerProperties[i];
3183 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003184 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3186 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3187 "toolType=%d, isHovering=%s\n", i,
3188 pointerProperties.id,
3189 pointerCoords.getX(),
3190 pointerCoords.getY(),
3191 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3192 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3193 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3194 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3195 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3196 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3197 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3198 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3199 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003200 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 }
3202
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003203 dump += INDENT3 "Stylus Fusion:\n";
3204 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003205 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003206 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3207 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003208 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003209 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003210 dumpStylusState(dump, mExternalStylusState);
3211
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003213 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3214 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003216 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003218 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003220 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003222 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 mPointerGestureMaxSwipeWidth);
3224 }
3225}
3226
Santos Cordonfa5cf462017-04-05 10:37:00 -07003227const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3228 switch (deviceMode) {
3229 case DEVICE_MODE_DISABLED:
3230 return "disabled";
3231 case DEVICE_MODE_DIRECT:
3232 return "direct";
3233 case DEVICE_MODE_UNSCALED:
3234 return "unscaled";
3235 case DEVICE_MODE_NAVIGATION:
3236 return "navigation";
3237 case DEVICE_MODE_POINTER:
3238 return "pointer";
3239 }
3240 return "unknown";
3241}
3242
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243void TouchInputMapper::configure(nsecs_t when,
3244 const InputReaderConfiguration* config, uint32_t changes) {
3245 InputMapper::configure(when, config, changes);
3246
3247 mConfig = *config;
3248
3249 if (!changes) { // first time only
3250 // Configure basic parameters.
3251 configureParameters();
3252
3253 // Configure common accumulators.
3254 mCursorScrollAccumulator.configure(getDevice());
3255 mTouchButtonAccumulator.configure(getDevice());
3256
3257 // Configure absolute axis information.
3258 configureRawPointerAxes();
3259
3260 // Prepare input device calibration.
3261 parseCalibration();
3262 resolveCalibration();
3263 }
3264
Michael Wright842500e2015-03-13 17:32:02 -07003265 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003266 // Update location calibration to reflect current settings
3267 updateAffineTransformation();
3268 }
3269
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3271 // Update pointer speed.
3272 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3273 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3274 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3275 }
3276
3277 bool resetNeeded = false;
3278 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3279 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003280 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3281 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 // Configure device sources, surface dimensions, orientation and
3283 // scaling factors.
3284 configureSurface(when, &resetNeeded);
3285 }
3286
3287 if (changes && resetNeeded) {
3288 // Send reset, unless this is the first time the device has been configured,
3289 // in which case the reader will call reset itself after all mappers are ready.
3290 getDevice()->notifyReset(when);
3291 }
3292}
3293
Michael Wright842500e2015-03-13 17:32:02 -07003294void TouchInputMapper::resolveExternalStylusPresence() {
3295 Vector<InputDeviceInfo> devices;
3296 mContext->getExternalStylusDevices(devices);
3297 mExternalStylusConnected = !devices.isEmpty();
3298
3299 if (!mExternalStylusConnected) {
3300 resetExternalStylus();
3301 }
3302}
3303
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304void TouchInputMapper::configureParameters() {
3305 // Use the pointer presentation mode for devices that do not support distinct
3306 // multitouch. The spot-based presentation relies on being able to accurately
3307 // locate two or more fingers on the touch pad.
3308 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003309 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310
3311 String8 gestureModeString;
3312 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3313 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003314 if (gestureModeString == "single-touch") {
3315 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3316 } else if (gestureModeString == "multi-touch") {
3317 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318 } else if (gestureModeString != "default") {
3319 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3320 }
3321 }
3322
3323 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3324 // The device is a touch screen.
3325 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3326 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3327 // The device is a pointing device like a track pad.
3328 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3329 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3330 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3331 // The device is a cursor device with a touch pad attached.
3332 // By default don't use the touch pad to move the pointer.
3333 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3334 } else {
3335 // The device is a touch pad of unknown purpose.
3336 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3337 }
3338
3339 mParameters.hasButtonUnderPad=
3340 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3341
3342 String8 deviceTypeString;
3343 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3344 deviceTypeString)) {
3345 if (deviceTypeString == "touchScreen") {
3346 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3347 } else if (deviceTypeString == "touchPad") {
3348 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3349 } else if (deviceTypeString == "touchNavigation") {
3350 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3351 } else if (deviceTypeString == "pointer") {
3352 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3353 } else if (deviceTypeString != "default") {
3354 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3355 }
3356 }
3357
3358 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3359 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3360 mParameters.orientationAware);
3361
3362 mParameters.hasAssociatedDisplay = false;
3363 mParameters.associatedDisplayIsExternal = false;
3364 if (mParameters.orientationAware
3365 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3366 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3367 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003368 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3369 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003370 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003371 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003372 uniqueDisplayId);
3373 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003376
3377 // Initial downs on external touch devices should wake the device.
3378 // Normally we don't do this for internal touch screens to prevent them from waking
3379 // up in your pocket but you can enable it using the input device configuration.
3380 mParameters.wake = getDevice()->isExternal();
3381 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3382 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383}
3384
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003385void TouchInputMapper::dumpParameters(std::string& dump) {
3386 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387
3388 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003389 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003390 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003392 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003393 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 break;
3395 default:
3396 assert(false);
3397 }
3398
3399 switch (mParameters.deviceType) {
3400 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003401 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402 break;
3403 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003404 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 break;
3406 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003407 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 break;
3409 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003410 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 break;
3412 default:
3413 ALOG_ASSERT(false);
3414 }
3415
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003416 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003417 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003419 toString(mParameters.associatedDisplayIsExternal),
3420 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003421 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 toString(mParameters.orientationAware));
3423}
3424
3425void TouchInputMapper::configureRawPointerAxes() {
3426 mRawPointerAxes.clear();
3427}
3428
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003429void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3430 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3432 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3433 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3434 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3435 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3436 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3437 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3438 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3439 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3440 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3441 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3442 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3443 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3444}
3445
Michael Wright842500e2015-03-13 17:32:02 -07003446bool TouchInputMapper::hasExternalStylus() const {
3447 return mExternalStylusConnected;
3448}
3449
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3451 int32_t oldDeviceMode = mDeviceMode;
3452
Michael Wright842500e2015-03-13 17:32:02 -07003453 resolveExternalStylusPresence();
3454
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455 // Determine device mode.
3456 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3457 && mConfig.pointerGesturesEnabled) {
3458 mSource = AINPUT_SOURCE_MOUSE;
3459 mDeviceMode = DEVICE_MODE_POINTER;
3460 if (hasStylus()) {
3461 mSource |= AINPUT_SOURCE_STYLUS;
3462 }
3463 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3464 && mParameters.hasAssociatedDisplay) {
3465 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3466 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003467 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 mSource |= AINPUT_SOURCE_STYLUS;
3469 }
Michael Wright2f78b682015-06-12 15:25:08 +01003470 if (hasExternalStylus()) {
3471 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3472 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3474 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3475 mDeviceMode = DEVICE_MODE_NAVIGATION;
3476 } else {
3477 mSource = AINPUT_SOURCE_TOUCHPAD;
3478 mDeviceMode = DEVICE_MODE_UNSCALED;
3479 }
3480
3481 // Ensure we have valid X and Y axes.
3482 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3483 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003484 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485 mDeviceMode = DEVICE_MODE_DISABLED;
3486 return;
3487 }
3488
3489 // Raw width and height in the natural orientation.
3490 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3491 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3492
3493 // Get associated display dimensions.
3494 DisplayViewport newViewport;
3495 if (mParameters.hasAssociatedDisplay) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003496 std::string uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003497 ViewportType viewportTypeToUse;
3498
3499 if (mParameters.associatedDisplayIsExternal) {
3500 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003501 } else if (!mParameters.uniqueDisplayId.empty()) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003502 // If the IDC file specified a unique display Id, then it expects to be linked to a
3503 // virtual display with the same unique ID.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003504 uniqueDisplayId = mParameters.uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003505 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3506 } else {
3507 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3508 }
3509
3510 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3512 "display. The device will be inoperable until the display size "
3513 "becomes available.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003514 getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515 mDeviceMode = DEVICE_MODE_DISABLED;
3516 return;
3517 }
3518 } else {
3519 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3520 }
3521 bool viewportChanged = mViewport != newViewport;
3522 if (viewportChanged) {
3523 mViewport = newViewport;
3524
3525 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3526 // Convert rotated viewport to natural surface coordinates.
3527 int32_t naturalLogicalWidth, naturalLogicalHeight;
3528 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3529 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3530 int32_t naturalDeviceWidth, naturalDeviceHeight;
3531 switch (mViewport.orientation) {
3532 case DISPLAY_ORIENTATION_90:
3533 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3534 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3535 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3536 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3537 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3538 naturalPhysicalTop = mViewport.physicalLeft;
3539 naturalDeviceWidth = mViewport.deviceHeight;
3540 naturalDeviceHeight = mViewport.deviceWidth;
3541 break;
3542 case DISPLAY_ORIENTATION_180:
3543 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3544 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3545 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3546 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3547 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3548 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3549 naturalDeviceWidth = mViewport.deviceWidth;
3550 naturalDeviceHeight = mViewport.deviceHeight;
3551 break;
3552 case DISPLAY_ORIENTATION_270:
3553 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3554 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3555 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3556 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3557 naturalPhysicalLeft = mViewport.physicalTop;
3558 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3559 naturalDeviceWidth = mViewport.deviceHeight;
3560 naturalDeviceHeight = mViewport.deviceWidth;
3561 break;
3562 case DISPLAY_ORIENTATION_0:
3563 default:
3564 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3565 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3566 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3567 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3568 naturalPhysicalLeft = mViewport.physicalLeft;
3569 naturalPhysicalTop = mViewport.physicalTop;
3570 naturalDeviceWidth = mViewport.deviceWidth;
3571 naturalDeviceHeight = mViewport.deviceHeight;
3572 break;
3573 }
3574
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003575 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3576 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3577 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3578 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3579 }
3580
Michael Wright358bcc72018-08-21 04:01:07 +01003581 mPhysicalWidth = naturalPhysicalWidth;
3582 mPhysicalHeight = naturalPhysicalHeight;
3583 mPhysicalLeft = naturalPhysicalLeft;
3584 mPhysicalTop = naturalPhysicalTop;
3585
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3587 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3588 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3589 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3590
3591 mSurfaceOrientation = mParameters.orientationAware ?
3592 mViewport.orientation : DISPLAY_ORIENTATION_0;
3593 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003594 mPhysicalWidth = rawWidth;
3595 mPhysicalHeight = rawHeight;
3596 mPhysicalLeft = 0;
3597 mPhysicalTop = 0;
3598
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 mSurfaceWidth = rawWidth;
3600 mSurfaceHeight = rawHeight;
3601 mSurfaceLeft = 0;
3602 mSurfaceTop = 0;
3603 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3604 }
3605 }
3606
3607 // If moving between pointer modes, need to reset some state.
3608 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3609 if (deviceModeChanged) {
3610 mOrientedRanges.clear();
3611 }
3612
3613 // Create pointer controller if needed.
3614 if (mDeviceMode == DEVICE_MODE_POINTER ||
3615 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003616 if (mPointerController == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3618 }
3619 } else {
3620 mPointerController.clear();
3621 }
3622
3623 if (viewportChanged || deviceModeChanged) {
3624 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3625 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003626 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3628
3629 // Configure X and Y factors.
3630 mXScale = float(mSurfaceWidth) / rawWidth;
3631 mYScale = float(mSurfaceHeight) / rawHeight;
3632 mXTranslate = -mSurfaceLeft;
3633 mYTranslate = -mSurfaceTop;
3634 mXPrecision = 1.0f / mXScale;
3635 mYPrecision = 1.0f / mYScale;
3636
3637 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3638 mOrientedRanges.x.source = mSource;
3639 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3640 mOrientedRanges.y.source = mSource;
3641
3642 configureVirtualKeys();
3643
3644 // Scale factor for terms that are not oriented in a particular axis.
3645 // If the pixels are square then xScale == yScale otherwise we fake it
3646 // by choosing an average.
3647 mGeometricScale = avg(mXScale, mYScale);
3648
3649 // Size of diagonal axis.
3650 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3651
3652 // Size factors.
3653 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3654 if (mRawPointerAxes.touchMajor.valid
3655 && mRawPointerAxes.touchMajor.maxValue != 0) {
3656 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3657 } else if (mRawPointerAxes.toolMajor.valid
3658 && mRawPointerAxes.toolMajor.maxValue != 0) {
3659 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3660 } else {
3661 mSizeScale = 0.0f;
3662 }
3663
3664 mOrientedRanges.haveTouchSize = true;
3665 mOrientedRanges.haveToolSize = true;
3666 mOrientedRanges.haveSize = true;
3667
3668 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3669 mOrientedRanges.touchMajor.source = mSource;
3670 mOrientedRanges.touchMajor.min = 0;
3671 mOrientedRanges.touchMajor.max = diagonalSize;
3672 mOrientedRanges.touchMajor.flat = 0;
3673 mOrientedRanges.touchMajor.fuzz = 0;
3674 mOrientedRanges.touchMajor.resolution = 0;
3675
3676 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3677 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3678
3679 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3680 mOrientedRanges.toolMajor.source = mSource;
3681 mOrientedRanges.toolMajor.min = 0;
3682 mOrientedRanges.toolMajor.max = diagonalSize;
3683 mOrientedRanges.toolMajor.flat = 0;
3684 mOrientedRanges.toolMajor.fuzz = 0;
3685 mOrientedRanges.toolMajor.resolution = 0;
3686
3687 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3688 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3689
3690 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3691 mOrientedRanges.size.source = mSource;
3692 mOrientedRanges.size.min = 0;
3693 mOrientedRanges.size.max = 1.0;
3694 mOrientedRanges.size.flat = 0;
3695 mOrientedRanges.size.fuzz = 0;
3696 mOrientedRanges.size.resolution = 0;
3697 } else {
3698 mSizeScale = 0.0f;
3699 }
3700
3701 // Pressure factors.
3702 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003703 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3705 || mCalibration.pressureCalibration
3706 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3707 if (mCalibration.havePressureScale) {
3708 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003709 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 } else if (mRawPointerAxes.pressure.valid
3711 && mRawPointerAxes.pressure.maxValue != 0) {
3712 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3713 }
3714 }
3715
3716 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3717 mOrientedRanges.pressure.source = mSource;
3718 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003719 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720 mOrientedRanges.pressure.flat = 0;
3721 mOrientedRanges.pressure.fuzz = 0;
3722 mOrientedRanges.pressure.resolution = 0;
3723
3724 // Tilt
3725 mTiltXCenter = 0;
3726 mTiltXScale = 0;
3727 mTiltYCenter = 0;
3728 mTiltYScale = 0;
3729 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3730 if (mHaveTilt) {
3731 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3732 mRawPointerAxes.tiltX.maxValue);
3733 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3734 mRawPointerAxes.tiltY.maxValue);
3735 mTiltXScale = M_PI / 180;
3736 mTiltYScale = M_PI / 180;
3737
3738 mOrientedRanges.haveTilt = true;
3739
3740 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3741 mOrientedRanges.tilt.source = mSource;
3742 mOrientedRanges.tilt.min = 0;
3743 mOrientedRanges.tilt.max = M_PI_2;
3744 mOrientedRanges.tilt.flat = 0;
3745 mOrientedRanges.tilt.fuzz = 0;
3746 mOrientedRanges.tilt.resolution = 0;
3747 }
3748
3749 // Orientation
3750 mOrientationScale = 0;
3751 if (mHaveTilt) {
3752 mOrientedRanges.haveOrientation = true;
3753
3754 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3755 mOrientedRanges.orientation.source = mSource;
3756 mOrientedRanges.orientation.min = -M_PI;
3757 mOrientedRanges.orientation.max = M_PI;
3758 mOrientedRanges.orientation.flat = 0;
3759 mOrientedRanges.orientation.fuzz = 0;
3760 mOrientedRanges.orientation.resolution = 0;
3761 } else if (mCalibration.orientationCalibration !=
3762 Calibration::ORIENTATION_CALIBRATION_NONE) {
3763 if (mCalibration.orientationCalibration
3764 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3765 if (mRawPointerAxes.orientation.valid) {
3766 if (mRawPointerAxes.orientation.maxValue > 0) {
3767 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3768 } else if (mRawPointerAxes.orientation.minValue < 0) {
3769 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3770 } else {
3771 mOrientationScale = 0;
3772 }
3773 }
3774 }
3775
3776 mOrientedRanges.haveOrientation = true;
3777
3778 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3779 mOrientedRanges.orientation.source = mSource;
3780 mOrientedRanges.orientation.min = -M_PI_2;
3781 mOrientedRanges.orientation.max = M_PI_2;
3782 mOrientedRanges.orientation.flat = 0;
3783 mOrientedRanges.orientation.fuzz = 0;
3784 mOrientedRanges.orientation.resolution = 0;
3785 }
3786
3787 // Distance
3788 mDistanceScale = 0;
3789 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3790 if (mCalibration.distanceCalibration
3791 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3792 if (mCalibration.haveDistanceScale) {
3793 mDistanceScale = mCalibration.distanceScale;
3794 } else {
3795 mDistanceScale = 1.0f;
3796 }
3797 }
3798
3799 mOrientedRanges.haveDistance = true;
3800
3801 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3802 mOrientedRanges.distance.source = mSource;
3803 mOrientedRanges.distance.min =
3804 mRawPointerAxes.distance.minValue * mDistanceScale;
3805 mOrientedRanges.distance.max =
3806 mRawPointerAxes.distance.maxValue * mDistanceScale;
3807 mOrientedRanges.distance.flat = 0;
3808 mOrientedRanges.distance.fuzz =
3809 mRawPointerAxes.distance.fuzz * mDistanceScale;
3810 mOrientedRanges.distance.resolution = 0;
3811 }
3812
3813 // Compute oriented precision, scales and ranges.
3814 // Note that the maximum value reported is an inclusive maximum value so it is one
3815 // unit less than the total width or height of surface.
3816 switch (mSurfaceOrientation) {
3817 case DISPLAY_ORIENTATION_90:
3818 case DISPLAY_ORIENTATION_270:
3819 mOrientedXPrecision = mYPrecision;
3820 mOrientedYPrecision = mXPrecision;
3821
3822 mOrientedRanges.x.min = mYTranslate;
3823 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3824 mOrientedRanges.x.flat = 0;
3825 mOrientedRanges.x.fuzz = 0;
3826 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3827
3828 mOrientedRanges.y.min = mXTranslate;
3829 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3830 mOrientedRanges.y.flat = 0;
3831 mOrientedRanges.y.fuzz = 0;
3832 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3833 break;
3834
3835 default:
3836 mOrientedXPrecision = mXPrecision;
3837 mOrientedYPrecision = mYPrecision;
3838
3839 mOrientedRanges.x.min = mXTranslate;
3840 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3841 mOrientedRanges.x.flat = 0;
3842 mOrientedRanges.x.fuzz = 0;
3843 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3844
3845 mOrientedRanges.y.min = mYTranslate;
3846 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3847 mOrientedRanges.y.flat = 0;
3848 mOrientedRanges.y.fuzz = 0;
3849 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3850 break;
3851 }
3852
Jason Gerecke71b16e82014-03-10 09:47:59 -07003853 // Location
3854 updateAffineTransformation();
3855
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 if (mDeviceMode == DEVICE_MODE_POINTER) {
3857 // Compute pointer gesture detection parameters.
3858 float rawDiagonal = hypotf(rawWidth, rawHeight);
3859 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3860
3861 // Scale movements such that one whole swipe of the touch pad covers a
3862 // given area relative to the diagonal size of the display when no acceleration
3863 // is applied.
3864 // Assume that the touch pad has a square aspect ratio such that movements in
3865 // X and Y of the same number of raw units cover the same physical distance.
3866 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3867 * displayDiagonal / rawDiagonal;
3868 mPointerYMovementScale = mPointerXMovementScale;
3869
3870 // Scale zooms to cover a smaller range of the display than movements do.
3871 // This value determines the area around the pointer that is affected by freeform
3872 // pointer gestures.
3873 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3874 * displayDiagonal / rawDiagonal;
3875 mPointerYZoomScale = mPointerXZoomScale;
3876
3877 // Max width between pointers to detect a swipe gesture is more than some fraction
3878 // of the diagonal axis of the touch pad. Touches that are wider than this are
3879 // translated into freeform gestures.
3880 mPointerGestureMaxSwipeWidth =
3881 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3882
3883 // Abort current pointer usages because the state has changed.
3884 abortPointerUsage(when, 0 /*policyFlags*/);
3885 }
3886
3887 // Inform the dispatcher about the changes.
3888 *outResetNeeded = true;
3889 bumpGeneration();
3890 }
3891}
3892
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003893void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003894 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003895 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3896 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3897 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3898 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003899 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3900 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3901 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3902 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003903 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904}
3905
3906void TouchInputMapper::configureVirtualKeys() {
3907 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3908 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3909
3910 mVirtualKeys.clear();
3911
3912 if (virtualKeyDefinitions.size() == 0) {
3913 return;
3914 }
3915
3916 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3917
3918 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3919 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3920 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3921 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3922
3923 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3924 const VirtualKeyDefinition& virtualKeyDefinition =
3925 virtualKeyDefinitions[i];
3926
3927 mVirtualKeys.add();
3928 VirtualKey& virtualKey = mVirtualKeys.editTop();
3929
3930 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3931 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003932 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003934 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3935 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3937 virtualKey.scanCode);
3938 mVirtualKeys.pop(); // drop the key
3939 continue;
3940 }
3941
3942 virtualKey.keyCode = keyCode;
3943 virtualKey.flags = flags;
3944
3945 // convert the key definition's display coordinates into touch coordinates for a hit box
3946 int32_t halfWidth = virtualKeyDefinition.width / 2;
3947 int32_t halfHeight = virtualKeyDefinition.height / 2;
3948
3949 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3950 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3951 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3952 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3953 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3954 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3955 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3956 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3957 }
3958}
3959
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003960void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003962 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963
3964 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3965 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003966 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3968 i, virtualKey.scanCode, virtualKey.keyCode,
3969 virtualKey.hitLeft, virtualKey.hitRight,
3970 virtualKey.hitTop, virtualKey.hitBottom);
3971 }
3972 }
3973}
3974
3975void TouchInputMapper::parseCalibration() {
3976 const PropertyMap& in = getDevice()->getConfiguration();
3977 Calibration& out = mCalibration;
3978
3979 // Size
3980 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3981 String8 sizeCalibrationString;
3982 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3983 if (sizeCalibrationString == "none") {
3984 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3985 } else if (sizeCalibrationString == "geometric") {
3986 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3987 } else if (sizeCalibrationString == "diameter") {
3988 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3989 } else if (sizeCalibrationString == "box") {
3990 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3991 } else if (sizeCalibrationString == "area") {
3992 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3993 } else if (sizeCalibrationString != "default") {
3994 ALOGW("Invalid value for touch.size.calibration: '%s'",
3995 sizeCalibrationString.string());
3996 }
3997 }
3998
3999 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4000 out.sizeScale);
4001 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4002 out.sizeBias);
4003 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4004 out.sizeIsSummed);
4005
4006 // Pressure
4007 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4008 String8 pressureCalibrationString;
4009 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4010 if (pressureCalibrationString == "none") {
4011 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4012 } else if (pressureCalibrationString == "physical") {
4013 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4014 } else if (pressureCalibrationString == "amplitude") {
4015 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4016 } else if (pressureCalibrationString != "default") {
4017 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4018 pressureCalibrationString.string());
4019 }
4020 }
4021
4022 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4023 out.pressureScale);
4024
4025 // Orientation
4026 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4027 String8 orientationCalibrationString;
4028 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4029 if (orientationCalibrationString == "none") {
4030 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4031 } else if (orientationCalibrationString == "interpolated") {
4032 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4033 } else if (orientationCalibrationString == "vector") {
4034 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4035 } else if (orientationCalibrationString != "default") {
4036 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4037 orientationCalibrationString.string());
4038 }
4039 }
4040
4041 // Distance
4042 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4043 String8 distanceCalibrationString;
4044 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4045 if (distanceCalibrationString == "none") {
4046 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4047 } else if (distanceCalibrationString == "scaled") {
4048 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4049 } else if (distanceCalibrationString != "default") {
4050 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4051 distanceCalibrationString.string());
4052 }
4053 }
4054
4055 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4056 out.distanceScale);
4057
4058 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4059 String8 coverageCalibrationString;
4060 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4061 if (coverageCalibrationString == "none") {
4062 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4063 } else if (coverageCalibrationString == "box") {
4064 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4065 } else if (coverageCalibrationString != "default") {
4066 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4067 coverageCalibrationString.string());
4068 }
4069 }
4070}
4071
4072void TouchInputMapper::resolveCalibration() {
4073 // Size
4074 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4075 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4076 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4077 }
4078 } else {
4079 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4080 }
4081
4082 // Pressure
4083 if (mRawPointerAxes.pressure.valid) {
4084 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4085 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4086 }
4087 } else {
4088 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4089 }
4090
4091 // Orientation
4092 if (mRawPointerAxes.orientation.valid) {
4093 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4094 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4095 }
4096 } else {
4097 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4098 }
4099
4100 // Distance
4101 if (mRawPointerAxes.distance.valid) {
4102 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4103 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4104 }
4105 } else {
4106 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4107 }
4108
4109 // Coverage
4110 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4111 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4112 }
4113}
4114
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004115void TouchInputMapper::dumpCalibration(std::string& dump) {
4116 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117
4118 // Size
4119 switch (mCalibration.sizeCalibration) {
4120 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004121 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 break;
4123 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004124 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 break;
4126 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004127 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 break;
4129 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004130 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 break;
4132 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004133 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 break;
4135 default:
4136 ALOG_ASSERT(false);
4137 }
4138
4139 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004140 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 mCalibration.sizeScale);
4142 }
4143
4144 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004145 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 mCalibration.sizeBias);
4147 }
4148
4149 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004150 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 toString(mCalibration.sizeIsSummed));
4152 }
4153
4154 // Pressure
4155 switch (mCalibration.pressureCalibration) {
4156 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004157 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 break;
4159 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004160 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 break;
4162 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004163 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 break;
4165 default:
4166 ALOG_ASSERT(false);
4167 }
4168
4169 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004170 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 mCalibration.pressureScale);
4172 }
4173
4174 // Orientation
4175 switch (mCalibration.orientationCalibration) {
4176 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 break;
4179 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004180 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 break;
4182 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004183 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184 break;
4185 default:
4186 ALOG_ASSERT(false);
4187 }
4188
4189 // Distance
4190 switch (mCalibration.distanceCalibration) {
4191 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 break;
4194 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004195 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 break;
4197 default:
4198 ALOG_ASSERT(false);
4199 }
4200
4201 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004202 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 mCalibration.distanceScale);
4204 }
4205
4206 switch (mCalibration.coverageCalibration) {
4207 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004208 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209 break;
4210 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004211 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 break;
4213 default:
4214 ALOG_ASSERT(false);
4215 }
4216}
4217
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004218void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4219 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004220
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004221 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4222 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4223 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4224 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4225 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4226 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004227}
4228
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004229void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004230 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4231 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004232}
4233
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234void TouchInputMapper::reset(nsecs_t when) {
4235 mCursorButtonAccumulator.reset(getDevice());
4236 mCursorScrollAccumulator.reset(getDevice());
4237 mTouchButtonAccumulator.reset(getDevice());
4238
4239 mPointerVelocityControl.reset();
4240 mWheelXVelocityControl.reset();
4241 mWheelYVelocityControl.reset();
4242
Michael Wright842500e2015-03-13 17:32:02 -07004243 mRawStatesPending.clear();
4244 mCurrentRawState.clear();
4245 mCurrentCookedState.clear();
4246 mLastRawState.clear();
4247 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 mPointerUsage = POINTER_USAGE_NONE;
4249 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004250 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004251 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 mDownTime = 0;
4253
4254 mCurrentVirtualKey.down = false;
4255
4256 mPointerGesture.reset();
4257 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004258 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259
Yi Kong9b14ac62018-07-17 13:48:38 -07004260 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4262 mPointerController->clearSpots();
4263 }
4264
4265 InputMapper::reset(when);
4266}
4267
Michael Wright842500e2015-03-13 17:32:02 -07004268void TouchInputMapper::resetExternalStylus() {
4269 mExternalStylusState.clear();
4270 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004271 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004272 mExternalStylusDataPending = false;
4273}
4274
Michael Wright43fd19f2015-04-21 19:02:58 +01004275void TouchInputMapper::clearStylusDataPendingFlags() {
4276 mExternalStylusDataPending = false;
4277 mExternalStylusFusionTimeout = LLONG_MAX;
4278}
4279
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280void TouchInputMapper::process(const RawEvent* rawEvent) {
4281 mCursorButtonAccumulator.process(rawEvent);
4282 mCursorScrollAccumulator.process(rawEvent);
4283 mTouchButtonAccumulator.process(rawEvent);
4284
4285 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4286 sync(rawEvent->when);
4287 }
4288}
4289
4290void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004291 const RawState* last = mRawStatesPending.isEmpty() ?
4292 &mCurrentRawState : &mRawStatesPending.top();
4293
4294 // Push a new state.
4295 mRawStatesPending.push();
4296 RawState* next = &mRawStatesPending.editTop();
4297 next->clear();
4298 next->when = when;
4299
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004301 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 | mCursorButtonAccumulator.getButtonState();
4303
Michael Wright842500e2015-03-13 17:32:02 -07004304 // Sync scroll
4305 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4306 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 mCursorScrollAccumulator.finishSync();
4308
Michael Wright842500e2015-03-13 17:32:02 -07004309 // Sync touch
4310 syncTouch(when, next);
4311
4312 // Assign pointer ids.
4313 if (!mHavePointerIds) {
4314 assignPointerIds(last, next);
4315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316
4317#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004318 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4319 "hovering ids 0x%08x -> 0x%08x",
4320 last->rawPointerData.pointerCount,
4321 next->rawPointerData.pointerCount,
4322 last->rawPointerData.touchingIdBits.value,
4323 next->rawPointerData.touchingIdBits.value,
4324 last->rawPointerData.hoveringIdBits.value,
4325 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326#endif
4327
Michael Wright842500e2015-03-13 17:32:02 -07004328 processRawTouches(false /*timeout*/);
4329}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330
Michael Wright842500e2015-03-13 17:32:02 -07004331void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4333 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004334 mCurrentRawState.clear();
4335 mRawStatesPending.clear();
4336 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337 }
4338
Michael Wright842500e2015-03-13 17:32:02 -07004339 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4340 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4341 // touching the current state will only observe the events that have been dispatched to the
4342 // rest of the pipeline.
4343 const size_t N = mRawStatesPending.size();
4344 size_t count;
4345 for(count = 0; count < N; count++) {
4346 const RawState& next = mRawStatesPending[count];
4347
4348 // A failure to assign the stylus id means that we're waiting on stylus data
4349 // and so should defer the rest of the pipeline.
4350 if (assignExternalStylusId(next, timeout)) {
4351 break;
4352 }
4353
4354 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004355 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004356 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004357 if (mCurrentRawState.when < mLastRawState.when) {
4358 mCurrentRawState.when = mLastRawState.when;
4359 }
Michael Wright842500e2015-03-13 17:32:02 -07004360 cookAndDispatch(mCurrentRawState.when);
4361 }
4362 if (count != 0) {
4363 mRawStatesPending.removeItemsAt(0, count);
4364 }
4365
Michael Wright842500e2015-03-13 17:32:02 -07004366 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004367 if (timeout) {
4368 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4369 clearStylusDataPendingFlags();
4370 mCurrentRawState.copyFrom(mLastRawState);
4371#if DEBUG_STYLUS_FUSION
4372 ALOGD("Timeout expired, synthesizing event with new stylus data");
4373#endif
4374 cookAndDispatch(when);
4375 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4376 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4377 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4378 }
Michael Wright842500e2015-03-13 17:32:02 -07004379 }
4380}
4381
4382void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4383 // Always start with a clean state.
4384 mCurrentCookedState.clear();
4385
4386 // Apply stylus buttons to current raw state.
4387 applyExternalStylusButtonState(when);
4388
4389 // Handle policy on initial down or hover events.
4390 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4391 && mCurrentRawState.rawPointerData.pointerCount != 0;
4392
4393 uint32_t policyFlags = 0;
4394 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4395 if (initialDown || buttonsPressed) {
4396 // If this is a touch screen, hide the pointer on an initial down.
4397 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4398 getContext()->fadePointer();
4399 }
4400
4401 if (mParameters.wake) {
4402 policyFlags |= POLICY_FLAG_WAKE;
4403 }
4404 }
4405
4406 // Consume raw off-screen touches before cooking pointer data.
4407 // If touches are consumed, subsequent code will not receive any pointer data.
4408 if (consumeRawTouches(when, policyFlags)) {
4409 mCurrentRawState.rawPointerData.clear();
4410 }
4411
4412 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4413 // with cooked pointer data that has the same ids and indices as the raw data.
4414 // The following code can use either the raw or cooked data, as needed.
4415 cookPointerData();
4416
4417 // Apply stylus pressure to current cooked state.
4418 applyExternalStylusTouchState(when);
4419
4420 // Synthesize key down from raw buttons if needed.
4421 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004422 mViewport.displayId, policyFlags,
4423 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004424
4425 // Dispatch the touches either directly or by translation through a pointer on screen.
4426 if (mDeviceMode == DEVICE_MODE_POINTER) {
4427 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4428 !idBits.isEmpty(); ) {
4429 uint32_t id = idBits.clearFirstMarkedBit();
4430 const RawPointerData::Pointer& pointer =
4431 mCurrentRawState.rawPointerData.pointerForId(id);
4432 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4433 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4434 mCurrentCookedState.stylusIdBits.markBit(id);
4435 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4436 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4437 mCurrentCookedState.fingerIdBits.markBit(id);
4438 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4439 mCurrentCookedState.mouseIdBits.markBit(id);
4440 }
4441 }
4442 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4443 !idBits.isEmpty(); ) {
4444 uint32_t id = idBits.clearFirstMarkedBit();
4445 const RawPointerData::Pointer& pointer =
4446 mCurrentRawState.rawPointerData.pointerForId(id);
4447 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4448 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4449 mCurrentCookedState.stylusIdBits.markBit(id);
4450 }
4451 }
4452
4453 // Stylus takes precedence over all tools, then mouse, then finger.
4454 PointerUsage pointerUsage = mPointerUsage;
4455 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4456 mCurrentCookedState.mouseIdBits.clear();
4457 mCurrentCookedState.fingerIdBits.clear();
4458 pointerUsage = POINTER_USAGE_STYLUS;
4459 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4460 mCurrentCookedState.fingerIdBits.clear();
4461 pointerUsage = POINTER_USAGE_MOUSE;
4462 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4463 isPointerDown(mCurrentRawState.buttonState)) {
4464 pointerUsage = POINTER_USAGE_GESTURES;
4465 }
4466
4467 dispatchPointerUsage(when, policyFlags, pointerUsage);
4468 } else {
4469 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004470 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004471 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4472 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4473
4474 mPointerController->setButtonState(mCurrentRawState.buttonState);
4475 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4476 mCurrentCookedState.cookedPointerData.idToIndex,
4477 mCurrentCookedState.cookedPointerData.touchingIdBits);
4478 }
4479
Michael Wright8e812822015-06-22 16:18:21 +01004480 if (!mCurrentMotionAborted) {
4481 dispatchButtonRelease(when, policyFlags);
4482 dispatchHoverExit(when, policyFlags);
4483 dispatchTouches(when, policyFlags);
4484 dispatchHoverEnterAndMove(when, policyFlags);
4485 dispatchButtonPress(when, policyFlags);
4486 }
4487
4488 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4489 mCurrentMotionAborted = false;
4490 }
Michael Wright842500e2015-03-13 17:32:02 -07004491 }
4492
4493 // Synthesize key up from raw buttons if needed.
4494 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004495 mViewport.displayId, policyFlags,
4496 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004497
4498 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004499 mCurrentRawState.rawVScroll = 0;
4500 mCurrentRawState.rawHScroll = 0;
4501
4502 // Copy current touch to last touch in preparation for the next cycle.
4503 mLastRawState.copyFrom(mCurrentRawState);
4504 mLastCookedState.copyFrom(mCurrentCookedState);
4505}
4506
4507void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004508 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004509 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4510 }
4511}
4512
4513void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004514 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4515 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004516
Michael Wright53dca3a2015-04-23 17:39:53 +01004517 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4518 float pressure = mExternalStylusState.pressure;
4519 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4520 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4521 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4522 }
4523 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4524 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4525
4526 PointerProperties& properties =
4527 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004528 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4529 properties.toolType = mExternalStylusState.toolType;
4530 }
4531 }
4532}
4533
4534bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4535 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4536 return false;
4537 }
4538
4539 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4540 && state.rawPointerData.pointerCount != 0;
4541 if (initialDown) {
4542 if (mExternalStylusState.pressure != 0.0f) {
4543#if DEBUG_STYLUS_FUSION
4544 ALOGD("Have both stylus and touch data, beginning fusion");
4545#endif
4546 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4547 } else if (timeout) {
4548#if DEBUG_STYLUS_FUSION
4549 ALOGD("Timeout expired, assuming touch is not a stylus.");
4550#endif
4551 resetExternalStylus();
4552 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004553 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4554 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004555 }
4556#if DEBUG_STYLUS_FUSION
4557 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004558 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004559#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004560 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004561 return true;
4562 }
4563 }
4564
4565 // Check if the stylus pointer has gone up.
4566 if (mExternalStylusId != -1 &&
4567 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4568#if DEBUG_STYLUS_FUSION
4569 ALOGD("Stylus pointer is going up");
4570#endif
4571 mExternalStylusId = -1;
4572 }
4573
4574 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575}
4576
4577void TouchInputMapper::timeoutExpired(nsecs_t when) {
4578 if (mDeviceMode == DEVICE_MODE_POINTER) {
4579 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4580 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4581 }
Michael Wright842500e2015-03-13 17:32:02 -07004582 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004583 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004584 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004585 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4586 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004587 }
4588 }
4589}
4590
4591void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004592 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004593 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004594 // We're either in the middle of a fused stream of data or we're waiting on data before
4595 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4596 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004597 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004598 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599 }
4600}
4601
4602bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4603 // Check for release of a virtual key.
4604 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004605 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606 // Pointer went up while virtual key was down.
4607 mCurrentVirtualKey.down = false;
4608 if (!mCurrentVirtualKey.ignored) {
4609#if DEBUG_VIRTUAL_KEYS
4610 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4611 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4612#endif
4613 dispatchVirtualKey(when, policyFlags,
4614 AKEY_EVENT_ACTION_UP,
4615 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4616 }
4617 return true;
4618 }
4619
Michael Wright842500e2015-03-13 17:32:02 -07004620 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4621 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4622 const RawPointerData::Pointer& pointer =
4623 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4625 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4626 // Pointer is still within the space of the virtual key.
4627 return true;
4628 }
4629 }
4630
4631 // Pointer left virtual key area or another pointer also went down.
4632 // Send key cancellation but do not consume the touch yet.
4633 // This is useful when the user swipes through from the virtual key area
4634 // into the main display surface.
4635 mCurrentVirtualKey.down = false;
4636 if (!mCurrentVirtualKey.ignored) {
4637#if DEBUG_VIRTUAL_KEYS
4638 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4639 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4640#endif
4641 dispatchVirtualKey(when, policyFlags,
4642 AKEY_EVENT_ACTION_UP,
4643 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4644 | AKEY_EVENT_FLAG_CANCELED);
4645 }
4646 }
4647
Michael Wright842500e2015-03-13 17:32:02 -07004648 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4649 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004651 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4652 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4654 // If exactly one pointer went down, check for virtual key hit.
4655 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004656 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4658 if (virtualKey) {
4659 mCurrentVirtualKey.down = true;
4660 mCurrentVirtualKey.downTime = when;
4661 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4662 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4663 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4664 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4665
4666 if (!mCurrentVirtualKey.ignored) {
4667#if DEBUG_VIRTUAL_KEYS
4668 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4669 mCurrentVirtualKey.keyCode,
4670 mCurrentVirtualKey.scanCode);
4671#endif
4672 dispatchVirtualKey(when, policyFlags,
4673 AKEY_EVENT_ACTION_DOWN,
4674 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4675 }
4676 }
4677 }
4678 return true;
4679 }
4680 }
4681
4682 // Disable all virtual key touches that happen within a short time interval of the
4683 // most recent touch within the screen area. The idea is to filter out stray
4684 // virtual key presses when interacting with the touch screen.
4685 //
4686 // Problems we're trying to solve:
4687 //
4688 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4689 // virtual key area that is implemented by a separate touch panel and accidentally
4690 // triggers a virtual key.
4691 //
4692 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4693 // area and accidentally triggers a virtual key. This often happens when virtual keys
4694 // are layed out below the screen near to where the on screen keyboard's space bar
4695 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004696 if (mConfig.virtualKeyQuietTime > 0 &&
4697 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4699 }
4700 return false;
4701}
4702
4703void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4704 int32_t keyEventAction, int32_t keyEventFlags) {
4705 int32_t keyCode = mCurrentVirtualKey.keyCode;
4706 int32_t scanCode = mCurrentVirtualKey.scanCode;
4707 nsecs_t downTime = mCurrentVirtualKey.downTime;
4708 int32_t metaState = mContext->getGlobalMetaState();
4709 policyFlags |= POLICY_FLAG_VIRTUAL;
4710
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004711 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId,
4712 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 getListener()->notifyKey(&args);
4714}
4715
Michael Wright8e812822015-06-22 16:18:21 +01004716void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4717 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4718 if (!currentIdBits.isEmpty()) {
4719 int32_t metaState = getContext()->getGlobalMetaState();
4720 int32_t buttonState = mCurrentCookedState.buttonState;
4721 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4722 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004723 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004724 mCurrentCookedState.cookedPointerData.pointerProperties,
4725 mCurrentCookedState.cookedPointerData.pointerCoords,
4726 mCurrentCookedState.cookedPointerData.idToIndex,
4727 currentIdBits, -1,
4728 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4729 mCurrentMotionAborted = true;
4730 }
4731}
4732
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004734 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4735 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004737 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738
4739 if (currentIdBits == lastIdBits) {
4740 if (!currentIdBits.isEmpty()) {
4741 // No pointer id changes so this is a move event.
4742 // The listener takes care of batching moves so we don't have to deal with that here.
4743 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004744 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004746 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004747 mCurrentCookedState.cookedPointerData.pointerProperties,
4748 mCurrentCookedState.cookedPointerData.pointerCoords,
4749 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750 currentIdBits, -1,
4751 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4752 }
4753 } else {
4754 // There may be pointers going up and pointers going down and pointers moving
4755 // all at the same time.
4756 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4757 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4758 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4759 BitSet32 dispatchedIdBits(lastIdBits.value);
4760
4761 // Update last coordinates of pointers that have moved so that we observe the new
4762 // pointer positions at the same time as other pointers that have just gone up.
4763 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004764 mCurrentCookedState.cookedPointerData.pointerProperties,
4765 mCurrentCookedState.cookedPointerData.pointerCoords,
4766 mCurrentCookedState.cookedPointerData.idToIndex,
4767 mLastCookedState.cookedPointerData.pointerProperties,
4768 mLastCookedState.cookedPointerData.pointerCoords,
4769 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004771 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 moveNeeded = true;
4773 }
4774
4775 // Dispatch pointer up events.
4776 while (!upIdBits.isEmpty()) {
4777 uint32_t upId = upIdBits.clearFirstMarkedBit();
4778
4779 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004780 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004781 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004782 mLastCookedState.cookedPointerData.pointerProperties,
4783 mLastCookedState.cookedPointerData.pointerCoords,
4784 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004785 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786 dispatchedIdBits.clearBit(upId);
4787 }
4788
4789 // Dispatch move events if any of the remaining pointers moved from their old locations.
4790 // Although applications receive new locations as part of individual pointer up
4791 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004792 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4794 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004795 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004796 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004797 mCurrentCookedState.cookedPointerData.pointerProperties,
4798 mCurrentCookedState.cookedPointerData.pointerCoords,
4799 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004800 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 }
4802
4803 // Dispatch pointer down events using the new pointer locations.
4804 while (!downIdBits.isEmpty()) {
4805 uint32_t downId = downIdBits.clearFirstMarkedBit();
4806 dispatchedIdBits.markBit(downId);
4807
4808 if (dispatchedIdBits.count() == 1) {
4809 // First pointer is going down. Set down time.
4810 mDownTime = when;
4811 }
4812
4813 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004814 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004815 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004816 mCurrentCookedState.cookedPointerData.pointerProperties,
4817 mCurrentCookedState.cookedPointerData.pointerCoords,
4818 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004819 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 }
4821 }
4822}
4823
4824void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4825 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004826 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4827 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 int32_t metaState = getContext()->getGlobalMetaState();
4829 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004830 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004831 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004832 mLastCookedState.cookedPointerData.pointerProperties,
4833 mLastCookedState.cookedPointerData.pointerCoords,
4834 mLastCookedState.cookedPointerData.idToIndex,
4835 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4837 mSentHoverEnter = false;
4838 }
4839}
4840
4841void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004842 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4843 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004844 int32_t metaState = getContext()->getGlobalMetaState();
4845 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004846 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004847 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004848 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004849 mCurrentCookedState.cookedPointerData.pointerProperties,
4850 mCurrentCookedState.cookedPointerData.pointerCoords,
4851 mCurrentCookedState.cookedPointerData.idToIndex,
4852 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4854 mSentHoverEnter = true;
4855 }
4856
4857 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004858 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004859 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004860 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004861 mCurrentCookedState.cookedPointerData.pointerProperties,
4862 mCurrentCookedState.cookedPointerData.pointerCoords,
4863 mCurrentCookedState.cookedPointerData.idToIndex,
4864 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4866 }
4867}
4868
Michael Wright7b159c92015-05-14 14:48:03 +01004869void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4870 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4871 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4872 const int32_t metaState = getContext()->getGlobalMetaState();
4873 int32_t buttonState = mLastCookedState.buttonState;
4874 while (!releasedButtons.isEmpty()) {
4875 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4876 buttonState &= ~actionButton;
4877 dispatchMotion(when, policyFlags, mSource,
4878 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4879 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004880 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004881 mCurrentCookedState.cookedPointerData.pointerProperties,
4882 mCurrentCookedState.cookedPointerData.pointerCoords,
4883 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4884 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4885 }
4886}
4887
4888void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4889 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4890 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4891 const int32_t metaState = getContext()->getGlobalMetaState();
4892 int32_t buttonState = mLastCookedState.buttonState;
4893 while (!pressedButtons.isEmpty()) {
4894 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4895 buttonState |= actionButton;
4896 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4897 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004898 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004899 mCurrentCookedState.cookedPointerData.pointerProperties,
4900 mCurrentCookedState.cookedPointerData.pointerCoords,
4901 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4902 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4903 }
4904}
4905
4906const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4907 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4908 return cookedPointerData.touchingIdBits;
4909 }
4910 return cookedPointerData.hoveringIdBits;
4911}
4912
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004914 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915
Michael Wright842500e2015-03-13 17:32:02 -07004916 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004917 mCurrentCookedState.deviceTimestamp =
4918 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004919 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4920 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4921 mCurrentRawState.rawPointerData.hoveringIdBits;
4922 mCurrentCookedState.cookedPointerData.touchingIdBits =
4923 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924
Michael Wright7b159c92015-05-14 14:48:03 +01004925 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4926 mCurrentCookedState.buttonState = 0;
4927 } else {
4928 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4929 }
4930
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931 // Walk through the the active pointers and map device coordinates onto
4932 // surface coordinates and adjust for display orientation.
4933 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004934 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935
4936 // Size
4937 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4938 switch (mCalibration.sizeCalibration) {
4939 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4940 case Calibration::SIZE_CALIBRATION_DIAMETER:
4941 case Calibration::SIZE_CALIBRATION_BOX:
4942 case Calibration::SIZE_CALIBRATION_AREA:
4943 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4944 touchMajor = in.touchMajor;
4945 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4946 toolMajor = in.toolMajor;
4947 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4948 size = mRawPointerAxes.touchMinor.valid
4949 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4950 } else if (mRawPointerAxes.touchMajor.valid) {
4951 toolMajor = touchMajor = in.touchMajor;
4952 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4953 ? in.touchMinor : in.touchMajor;
4954 size = mRawPointerAxes.touchMinor.valid
4955 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4956 } else if (mRawPointerAxes.toolMajor.valid) {
4957 touchMajor = toolMajor = in.toolMajor;
4958 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4959 ? in.toolMinor : in.toolMajor;
4960 size = mRawPointerAxes.toolMinor.valid
4961 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4962 } else {
4963 ALOG_ASSERT(false, "No touch or tool axes. "
4964 "Size calibration should have been resolved to NONE.");
4965 touchMajor = 0;
4966 touchMinor = 0;
4967 toolMajor = 0;
4968 toolMinor = 0;
4969 size = 0;
4970 }
4971
4972 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004973 uint32_t touchingCount =
4974 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004975 if (touchingCount > 1) {
4976 touchMajor /= touchingCount;
4977 touchMinor /= touchingCount;
4978 toolMajor /= touchingCount;
4979 toolMinor /= touchingCount;
4980 size /= touchingCount;
4981 }
4982 }
4983
4984 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4985 touchMajor *= mGeometricScale;
4986 touchMinor *= mGeometricScale;
4987 toolMajor *= mGeometricScale;
4988 toolMinor *= mGeometricScale;
4989 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4990 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4991 touchMinor = touchMajor;
4992 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4993 toolMinor = toolMajor;
4994 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4995 touchMinor = touchMajor;
4996 toolMinor = toolMajor;
4997 }
4998
4999 mCalibration.applySizeScaleAndBias(&touchMajor);
5000 mCalibration.applySizeScaleAndBias(&touchMinor);
5001 mCalibration.applySizeScaleAndBias(&toolMajor);
5002 mCalibration.applySizeScaleAndBias(&toolMinor);
5003 size *= mSizeScale;
5004 break;
5005 default:
5006 touchMajor = 0;
5007 touchMinor = 0;
5008 toolMajor = 0;
5009 toolMinor = 0;
5010 size = 0;
5011 break;
5012 }
5013
5014 // Pressure
5015 float pressure;
5016 switch (mCalibration.pressureCalibration) {
5017 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5018 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5019 pressure = in.pressure * mPressureScale;
5020 break;
5021 default:
5022 pressure = in.isHovering ? 0 : 1;
5023 break;
5024 }
5025
5026 // Tilt and Orientation
5027 float tilt;
5028 float orientation;
5029 if (mHaveTilt) {
5030 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5031 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5032 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5033 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5034 } else {
5035 tilt = 0;
5036
5037 switch (mCalibration.orientationCalibration) {
5038 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5039 orientation = in.orientation * mOrientationScale;
5040 break;
5041 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5042 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5043 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5044 if (c1 != 0 || c2 != 0) {
5045 orientation = atan2f(c1, c2) * 0.5f;
5046 float confidence = hypotf(c1, c2);
5047 float scale = 1.0f + confidence / 16.0f;
5048 touchMajor *= scale;
5049 touchMinor /= scale;
5050 toolMajor *= scale;
5051 toolMinor /= scale;
5052 } else {
5053 orientation = 0;
5054 }
5055 break;
5056 }
5057 default:
5058 orientation = 0;
5059 }
5060 }
5061
5062 // Distance
5063 float distance;
5064 switch (mCalibration.distanceCalibration) {
5065 case Calibration::DISTANCE_CALIBRATION_SCALED:
5066 distance = in.distance * mDistanceScale;
5067 break;
5068 default:
5069 distance = 0;
5070 }
5071
5072 // Coverage
5073 int32_t rawLeft, rawTop, rawRight, rawBottom;
5074 switch (mCalibration.coverageCalibration) {
5075 case Calibration::COVERAGE_CALIBRATION_BOX:
5076 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5077 rawRight = in.toolMinor & 0x0000ffff;
5078 rawBottom = in.toolMajor & 0x0000ffff;
5079 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5080 break;
5081 default:
5082 rawLeft = rawTop = rawRight = rawBottom = 0;
5083 break;
5084 }
5085
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005086 // Adjust X,Y coords for device calibration
5087 // TODO: Adjust coverage coords?
5088 float xTransformed = in.x, yTransformed = in.y;
5089 mAffineTransform.applyTo(xTransformed, yTransformed);
5090
5091 // Adjust X, Y, and coverage coords for surface orientation.
5092 float x, y;
5093 float left, top, right, bottom;
5094
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095 switch (mSurfaceOrientation) {
5096 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005097 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5098 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5100 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5101 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5102 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5103 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005104 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5106 }
5107 break;
5108 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005109 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005110 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005111 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5112 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5114 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5115 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005116 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5118 }
5119 break;
5120 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005121 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005122 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005123 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5124 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5126 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5127 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005128 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5130 }
5131 break;
5132 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005133 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5134 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5136 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5137 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5138 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5139 break;
5140 }
5141
5142 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005143 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 out.clear();
5145 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5146 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5147 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5148 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5149 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5150 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5151 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5152 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5153 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5154 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5155 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5156 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5157 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5158 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5159 } else {
5160 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5161 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5162 }
5163
5164 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005165 PointerProperties& properties =
5166 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 uint32_t id = in.id;
5168 properties.clear();
5169 properties.id = id;
5170 properties.toolType = in.toolType;
5171
5172 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005173 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174 }
5175}
5176
5177void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5178 PointerUsage pointerUsage) {
5179 if (pointerUsage != mPointerUsage) {
5180 abortPointerUsage(when, policyFlags);
5181 mPointerUsage = pointerUsage;
5182 }
5183
5184 switch (mPointerUsage) {
5185 case POINTER_USAGE_GESTURES:
5186 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5187 break;
5188 case POINTER_USAGE_STYLUS:
5189 dispatchPointerStylus(when, policyFlags);
5190 break;
5191 case POINTER_USAGE_MOUSE:
5192 dispatchPointerMouse(when, policyFlags);
5193 break;
5194 default:
5195 break;
5196 }
5197}
5198
5199void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5200 switch (mPointerUsage) {
5201 case POINTER_USAGE_GESTURES:
5202 abortPointerGestures(when, policyFlags);
5203 break;
5204 case POINTER_USAGE_STYLUS:
5205 abortPointerStylus(when, policyFlags);
5206 break;
5207 case POINTER_USAGE_MOUSE:
5208 abortPointerMouse(when, policyFlags);
5209 break;
5210 default:
5211 break;
5212 }
5213
5214 mPointerUsage = POINTER_USAGE_NONE;
5215}
5216
5217void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5218 bool isTimeout) {
5219 // Update current gesture coordinates.
5220 bool cancelPreviousGesture, finishPreviousGesture;
5221 bool sendEvents = preparePointerGestures(when,
5222 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5223 if (!sendEvents) {
5224 return;
5225 }
5226 if (finishPreviousGesture) {
5227 cancelPreviousGesture = false;
5228 }
5229
5230 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005231 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5232 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233 if (finishPreviousGesture || cancelPreviousGesture) {
5234 mPointerController->clearSpots();
5235 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005236
5237 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5238 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5239 mPointerGesture.currentGestureIdToIndex,
5240 mPointerGesture.currentGestureIdBits);
5241 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005242 } else {
5243 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5244 }
5245
5246 // Show or hide the pointer if needed.
5247 switch (mPointerGesture.currentGestureMode) {
5248 case PointerGesture::NEUTRAL:
5249 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005250 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5251 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252 // Remind the user of where the pointer is after finishing a gesture with spots.
5253 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5254 }
5255 break;
5256 case PointerGesture::TAP:
5257 case PointerGesture::TAP_DRAG:
5258 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5259 case PointerGesture::HOVER:
5260 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005261 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 // Unfade the pointer when the current gesture manipulates the
5263 // area directly under the pointer.
5264 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5265 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 case PointerGesture::FREEFORM:
5267 // Fade the pointer when the current gesture manipulates a different
5268 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005269 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5271 } else {
5272 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5273 }
5274 break;
5275 }
5276
5277 // Send events!
5278 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005279 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280
5281 // Update last coordinates of pointers that have moved so that we observe the new
5282 // pointer positions at the same time as other pointers that have just gone up.
5283 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5284 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5285 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5286 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5287 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5288 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5289 bool moveNeeded = false;
5290 if (down && !cancelPreviousGesture && !finishPreviousGesture
5291 && !mPointerGesture.lastGestureIdBits.isEmpty()
5292 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5293 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5294 & mPointerGesture.lastGestureIdBits.value);
5295 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5296 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5297 mPointerGesture.lastGestureProperties,
5298 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5299 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005300 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005301 moveNeeded = true;
5302 }
5303 }
5304
5305 // Send motion events for all pointers that went up or were canceled.
5306 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5307 if (!dispatchedGestureIdBits.isEmpty()) {
5308 if (cancelPreviousGesture) {
5309 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005310 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005311 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312 mPointerGesture.lastGestureProperties,
5313 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005314 dispatchedGestureIdBits, -1, 0,
5315 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005316
5317 dispatchedGestureIdBits.clear();
5318 } else {
5319 BitSet32 upGestureIdBits;
5320 if (finishPreviousGesture) {
5321 upGestureIdBits = dispatchedGestureIdBits;
5322 } else {
5323 upGestureIdBits.value = dispatchedGestureIdBits.value
5324 & ~mPointerGesture.currentGestureIdBits.value;
5325 }
5326 while (!upGestureIdBits.isEmpty()) {
5327 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5328
5329 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005330 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005332 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333 mPointerGesture.lastGestureProperties,
5334 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5335 dispatchedGestureIdBits, id,
5336 0, 0, mPointerGesture.downTime);
5337
5338 dispatchedGestureIdBits.clearBit(id);
5339 }
5340 }
5341 }
5342
5343 // Send motion events for all pointers that moved.
5344 if (moveNeeded) {
5345 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005346 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005347 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348 mPointerGesture.currentGestureProperties,
5349 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5350 dispatchedGestureIdBits, -1,
5351 0, 0, mPointerGesture.downTime);
5352 }
5353
5354 // Send motion events for all pointers that went down.
5355 if (down) {
5356 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5357 & ~dispatchedGestureIdBits.value);
5358 while (!downGestureIdBits.isEmpty()) {
5359 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5360 dispatchedGestureIdBits.markBit(id);
5361
5362 if (dispatchedGestureIdBits.count() == 1) {
5363 mPointerGesture.downTime = when;
5364 }
5365
5366 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005367 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005368 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369 mPointerGesture.currentGestureProperties,
5370 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5371 dispatchedGestureIdBits, id,
5372 0, 0, mPointerGesture.downTime);
5373 }
5374 }
5375
5376 // Send motion events for hover.
5377 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5378 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005379 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005380 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381 mPointerGesture.currentGestureProperties,
5382 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5383 mPointerGesture.currentGestureIdBits, -1,
5384 0, 0, mPointerGesture.downTime);
5385 } else if (dispatchedGestureIdBits.isEmpty()
5386 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5387 // Synthesize a hover move event after all pointers go up to indicate that
5388 // the pointer is hovering again even if the user is not currently touching
5389 // the touch pad. This ensures that a view will receive a fresh hover enter
5390 // event after a tap.
5391 float x, y;
5392 mPointerController->getPosition(&x, &y);
5393
5394 PointerProperties pointerProperties;
5395 pointerProperties.clear();
5396 pointerProperties.id = 0;
5397 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5398
5399 PointerCoords pointerCoords;
5400 pointerCoords.clear();
5401 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5402 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5403
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005404 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005405 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005407 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 0, 0, mPointerGesture.downTime);
5409 getListener()->notifyMotion(&args);
5410 }
5411
5412 // Update state.
5413 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5414 if (!down) {
5415 mPointerGesture.lastGestureIdBits.clear();
5416 } else {
5417 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5418 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5419 uint32_t id = idBits.clearFirstMarkedBit();
5420 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5421 mPointerGesture.lastGestureProperties[index].copyFrom(
5422 mPointerGesture.currentGestureProperties[index]);
5423 mPointerGesture.lastGestureCoords[index].copyFrom(
5424 mPointerGesture.currentGestureCoords[index]);
5425 mPointerGesture.lastGestureIdToIndex[id] = index;
5426 }
5427 }
5428}
5429
5430void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5431 // Cancel previously dispatches pointers.
5432 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5433 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005434 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005436 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005437 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438 mPointerGesture.lastGestureProperties,
5439 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5440 mPointerGesture.lastGestureIdBits, -1,
5441 0, 0, mPointerGesture.downTime);
5442 }
5443
5444 // Reset the current pointer gesture.
5445 mPointerGesture.reset();
5446 mPointerVelocityControl.reset();
5447
5448 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005449 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5451 mPointerController->clearSpots();
5452 }
5453}
5454
5455bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5456 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5457 *outCancelPreviousGesture = false;
5458 *outFinishPreviousGesture = false;
5459
5460 // Handle TAP timeout.
5461 if (isTimeout) {
5462#if DEBUG_GESTURES
5463 ALOGD("Gestures: Processing timeout");
5464#endif
5465
5466 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5467 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5468 // The tap/drag timeout has not yet expired.
5469 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5470 + mConfig.pointerGestureTapDragInterval);
5471 } else {
5472 // The tap is finished.
5473#if DEBUG_GESTURES
5474 ALOGD("Gestures: TAP finished");
5475#endif
5476 *outFinishPreviousGesture = true;
5477
5478 mPointerGesture.activeGestureId = -1;
5479 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5480 mPointerGesture.currentGestureIdBits.clear();
5481
5482 mPointerVelocityControl.reset();
5483 return true;
5484 }
5485 }
5486
5487 // We did not handle this timeout.
5488 return false;
5489 }
5490
Michael Wright842500e2015-03-13 17:32:02 -07005491 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5492 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493
5494 // Update the velocity tracker.
5495 {
5496 VelocityTracker::Position positions[MAX_POINTERS];
5497 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005498 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005500 const RawPointerData::Pointer& pointer =
5501 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502 positions[count].x = pointer.x * mPointerXMovementScale;
5503 positions[count].y = pointer.y * mPointerYMovementScale;
5504 }
5505 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005506 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507 }
5508
5509 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5510 // to NEUTRAL, then we should not generate tap event.
5511 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5512 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5513 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5514 mPointerGesture.resetTap();
5515 }
5516
5517 // Pick a new active touch id if needed.
5518 // Choose an arbitrary pointer that just went down, if there is one.
5519 // Otherwise choose an arbitrary remaining pointer.
5520 // This guarantees we always have an active touch id when there is at least one pointer.
5521 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5523 int32_t activeTouchId = lastActiveTouchId;
5524 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005525 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005526 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005527 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528 mPointerGesture.firstTouchTime = when;
5529 }
Michael Wright842500e2015-03-13 17:32:02 -07005530 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005531 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005533 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 } else {
5535 activeTouchId = mPointerGesture.activeTouchId = -1;
5536 }
5537 }
5538
5539 // Determine whether we are in quiet time.
5540 bool isQuietTime = false;
5541 if (activeTouchId < 0) {
5542 mPointerGesture.resetQuietTime();
5543 } else {
5544 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5545 if (!isQuietTime) {
5546 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5547 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5548 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5549 && currentFingerCount < 2) {
5550 // Enter quiet time when exiting swipe or freeform state.
5551 // This is to prevent accidentally entering the hover state and flinging the
5552 // pointer when finishing a swipe and there is still one pointer left onscreen.
5553 isQuietTime = true;
5554 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5555 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005556 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 // Enter quiet time when releasing the button and there are still two or more
5558 // fingers down. This may indicate that one finger was used to press the button
5559 // but it has not gone up yet.
5560 isQuietTime = true;
5561 }
5562 if (isQuietTime) {
5563 mPointerGesture.quietTime = when;
5564 }
5565 }
5566 }
5567
5568 // Switch states based on button and pointer state.
5569 if (isQuietTime) {
5570 // Case 1: Quiet time. (QUIET)
5571#if DEBUG_GESTURES
5572 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5573 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5574#endif
5575 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5576 *outFinishPreviousGesture = true;
5577 }
5578
5579 mPointerGesture.activeGestureId = -1;
5580 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5581 mPointerGesture.currentGestureIdBits.clear();
5582
5583 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005584 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5586 // The pointer follows the active touch point.
5587 // Emit DOWN, MOVE, UP events at the pointer location.
5588 //
5589 // Only the active touch matters; other fingers are ignored. This policy helps
5590 // to handle the case where the user places a second finger on the touch pad
5591 // to apply the necessary force to depress an integrated button below the surface.
5592 // We don't want the second finger to be delivered to applications.
5593 //
5594 // For this to work well, we need to make sure to track the pointer that is really
5595 // active. If the user first puts one finger down to click then adds another
5596 // finger to drag then the active pointer should switch to the finger that is
5597 // being dragged.
5598#if DEBUG_GESTURES
5599 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5600 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5601#endif
5602 // Reset state when just starting.
5603 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5604 *outFinishPreviousGesture = true;
5605 mPointerGesture.activeGestureId = 0;
5606 }
5607
5608 // Switch pointers if needed.
5609 // Find the fastest pointer and follow it.
5610 if (activeTouchId >= 0 && currentFingerCount > 1) {
5611 int32_t bestId = -1;
5612 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005613 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614 uint32_t id = idBits.clearFirstMarkedBit();
5615 float vx, vy;
5616 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5617 float speed = hypotf(vx, vy);
5618 if (speed > bestSpeed) {
5619 bestId = id;
5620 bestSpeed = speed;
5621 }
5622 }
5623 }
5624 if (bestId >= 0 && bestId != activeTouchId) {
5625 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626#if DEBUG_GESTURES
5627 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5628 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5629#endif
5630 }
5631 }
5632
Jun Mukaifa1706a2015-12-03 01:14:46 -08005633 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005634 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005636 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005638 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005639 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5640 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641
5642 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5643 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5644
5645 // Move the pointer using a relative motion.
5646 // When using spots, the click will occur at the position of the anchor
5647 // spot and all other spots will move there.
5648 mPointerController->move(deltaX, deltaY);
5649 } else {
5650 mPointerVelocityControl.reset();
5651 }
5652
5653 float x, y;
5654 mPointerController->getPosition(&x, &y);
5655
5656 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5657 mPointerGesture.currentGestureIdBits.clear();
5658 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5659 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5660 mPointerGesture.currentGestureProperties[0].clear();
5661 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5662 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5663 mPointerGesture.currentGestureCoords[0].clear();
5664 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5665 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5666 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5667 } else if (currentFingerCount == 0) {
5668 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5669 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5670 *outFinishPreviousGesture = true;
5671 }
5672
5673 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5674 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5675 bool tapped = false;
5676 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5677 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5678 && lastFingerCount == 1) {
5679 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5680 float x, y;
5681 mPointerController->getPosition(&x, &y);
5682 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5683 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5684#if DEBUG_GESTURES
5685 ALOGD("Gestures: TAP");
5686#endif
5687
5688 mPointerGesture.tapUpTime = when;
5689 getContext()->requestTimeoutAtTime(when
5690 + mConfig.pointerGestureTapDragInterval);
5691
5692 mPointerGesture.activeGestureId = 0;
5693 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5694 mPointerGesture.currentGestureIdBits.clear();
5695 mPointerGesture.currentGestureIdBits.markBit(
5696 mPointerGesture.activeGestureId);
5697 mPointerGesture.currentGestureIdToIndex[
5698 mPointerGesture.activeGestureId] = 0;
5699 mPointerGesture.currentGestureProperties[0].clear();
5700 mPointerGesture.currentGestureProperties[0].id =
5701 mPointerGesture.activeGestureId;
5702 mPointerGesture.currentGestureProperties[0].toolType =
5703 AMOTION_EVENT_TOOL_TYPE_FINGER;
5704 mPointerGesture.currentGestureCoords[0].clear();
5705 mPointerGesture.currentGestureCoords[0].setAxisValue(
5706 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5707 mPointerGesture.currentGestureCoords[0].setAxisValue(
5708 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5709 mPointerGesture.currentGestureCoords[0].setAxisValue(
5710 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5711
5712 tapped = true;
5713 } else {
5714#if DEBUG_GESTURES
5715 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5716 x - mPointerGesture.tapX,
5717 y - mPointerGesture.tapY);
5718#endif
5719 }
5720 } else {
5721#if DEBUG_GESTURES
5722 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5723 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5724 (when - mPointerGesture.tapDownTime) * 0.000001f);
5725 } else {
5726 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5727 }
5728#endif
5729 }
5730 }
5731
5732 mPointerVelocityControl.reset();
5733
5734 if (!tapped) {
5735#if DEBUG_GESTURES
5736 ALOGD("Gestures: NEUTRAL");
5737#endif
5738 mPointerGesture.activeGestureId = -1;
5739 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5740 mPointerGesture.currentGestureIdBits.clear();
5741 }
5742 } else if (currentFingerCount == 1) {
5743 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5744 // The pointer follows the active touch point.
5745 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5746 // When in TAP_DRAG, emit MOVE events at the pointer location.
5747 ALOG_ASSERT(activeTouchId >= 0);
5748
5749 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5750 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5751 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5752 float x, y;
5753 mPointerController->getPosition(&x, &y);
5754 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5755 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5756 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5757 } else {
5758#if DEBUG_GESTURES
5759 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5760 x - mPointerGesture.tapX,
5761 y - mPointerGesture.tapY);
5762#endif
5763 }
5764 } else {
5765#if DEBUG_GESTURES
5766 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5767 (when - mPointerGesture.tapUpTime) * 0.000001f);
5768#endif
5769 }
5770 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5771 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5772 }
5773
Jun Mukaifa1706a2015-12-03 01:14:46 -08005774 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005775 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005776 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005777 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005778 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005779 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005780 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5781 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782
5783 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5784 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5785
5786 // Move the pointer using a relative motion.
5787 // When using spots, the hover or drag will occur at the position of the anchor spot.
5788 mPointerController->move(deltaX, deltaY);
5789 } else {
5790 mPointerVelocityControl.reset();
5791 }
5792
5793 bool down;
5794 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5795#if DEBUG_GESTURES
5796 ALOGD("Gestures: TAP_DRAG");
5797#endif
5798 down = true;
5799 } else {
5800#if DEBUG_GESTURES
5801 ALOGD("Gestures: HOVER");
5802#endif
5803 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5804 *outFinishPreviousGesture = true;
5805 }
5806 mPointerGesture.activeGestureId = 0;
5807 down = false;
5808 }
5809
5810 float x, y;
5811 mPointerController->getPosition(&x, &y);
5812
5813 mPointerGesture.currentGestureIdBits.clear();
5814 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5815 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5816 mPointerGesture.currentGestureProperties[0].clear();
5817 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5818 mPointerGesture.currentGestureProperties[0].toolType =
5819 AMOTION_EVENT_TOOL_TYPE_FINGER;
5820 mPointerGesture.currentGestureCoords[0].clear();
5821 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5822 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5823 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5824 down ? 1.0f : 0.0f);
5825
5826 if (lastFingerCount == 0 && currentFingerCount != 0) {
5827 mPointerGesture.resetTap();
5828 mPointerGesture.tapDownTime = when;
5829 mPointerGesture.tapX = x;
5830 mPointerGesture.tapY = y;
5831 }
5832 } else {
5833 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5834 // We need to provide feedback for each finger that goes down so we cannot wait
5835 // for the fingers to move before deciding what to do.
5836 //
5837 // The ambiguous case is deciding what to do when there are two fingers down but they
5838 // have not moved enough to determine whether they are part of a drag or part of a
5839 // freeform gesture, or just a press or long-press at the pointer location.
5840 //
5841 // When there are two fingers we start with the PRESS hypothesis and we generate a
5842 // down at the pointer location.
5843 //
5844 // When the two fingers move enough or when additional fingers are added, we make
5845 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5846 ALOG_ASSERT(activeTouchId >= 0);
5847
5848 bool settled = when >= mPointerGesture.firstTouchTime
5849 + mConfig.pointerGestureMultitouchSettleInterval;
5850 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5851 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5852 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5853 *outFinishPreviousGesture = true;
5854 } else if (!settled && currentFingerCount > lastFingerCount) {
5855 // Additional pointers have gone down but not yet settled.
5856 // Reset the gesture.
5857#if DEBUG_GESTURES
5858 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5859 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5860 + mConfig.pointerGestureMultitouchSettleInterval - when)
5861 * 0.000001f);
5862#endif
5863 *outCancelPreviousGesture = true;
5864 } else {
5865 // Continue previous gesture.
5866 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5867 }
5868
5869 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5870 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5871 mPointerGesture.activeGestureId = 0;
5872 mPointerGesture.referenceIdBits.clear();
5873 mPointerVelocityControl.reset();
5874
5875 // Use the centroid and pointer location as the reference points for the gesture.
5876#if DEBUG_GESTURES
5877 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5878 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5879 + mConfig.pointerGestureMultitouchSettleInterval - when)
5880 * 0.000001f);
5881#endif
Michael Wright842500e2015-03-13 17:32:02 -07005882 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005883 &mPointerGesture.referenceTouchX,
5884 &mPointerGesture.referenceTouchY);
5885 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5886 &mPointerGesture.referenceGestureY);
5887 }
5888
5889 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005890 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005891 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5892 uint32_t id = idBits.clearFirstMarkedBit();
5893 mPointerGesture.referenceDeltas[id].dx = 0;
5894 mPointerGesture.referenceDeltas[id].dy = 0;
5895 }
Michael Wright842500e2015-03-13 17:32:02 -07005896 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897
5898 // Add delta for all fingers and calculate a common movement delta.
5899 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005900 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5901 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5903 bool first = (idBits == commonIdBits);
5904 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005905 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5906 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005907 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5908 delta.dx += cpd.x - lpd.x;
5909 delta.dy += cpd.y - lpd.y;
5910
5911 if (first) {
5912 commonDeltaX = delta.dx;
5913 commonDeltaY = delta.dy;
5914 } else {
5915 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5916 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5917 }
5918 }
5919
5920 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5921 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5922 float dist[MAX_POINTER_ID + 1];
5923 int32_t distOverThreshold = 0;
5924 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5925 uint32_t id = idBits.clearFirstMarkedBit();
5926 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5927 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5928 delta.dy * mPointerYZoomScale);
5929 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5930 distOverThreshold += 1;
5931 }
5932 }
5933
5934 // Only transition when at least two pointers have moved further than
5935 // the minimum distance threshold.
5936 if (distOverThreshold >= 2) {
5937 if (currentFingerCount > 2) {
5938 // There are more than two pointers, switch to FREEFORM.
5939#if DEBUG_GESTURES
5940 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5941 currentFingerCount);
5942#endif
5943 *outCancelPreviousGesture = true;
5944 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5945 } else {
5946 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005947 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948 uint32_t id1 = idBits.clearFirstMarkedBit();
5949 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005950 const RawPointerData::Pointer& p1 =
5951 mCurrentRawState.rawPointerData.pointerForId(id1);
5952 const RawPointerData::Pointer& p2 =
5953 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5955 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5956 // There are two pointers but they are too far apart for a SWIPE,
5957 // switch to FREEFORM.
5958#if DEBUG_GESTURES
5959 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5960 mutualDistance, mPointerGestureMaxSwipeWidth);
5961#endif
5962 *outCancelPreviousGesture = true;
5963 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5964 } else {
5965 // There are two pointers. Wait for both pointers to start moving
5966 // before deciding whether this is a SWIPE or FREEFORM gesture.
5967 float dist1 = dist[id1];
5968 float dist2 = dist[id2];
5969 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5970 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5971 // Calculate the dot product of the displacement vectors.
5972 // When the vectors are oriented in approximately the same direction,
5973 // the angle betweeen them is near zero and the cosine of the angle
5974 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5975 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5976 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5977 float dx1 = delta1.dx * mPointerXZoomScale;
5978 float dy1 = delta1.dy * mPointerYZoomScale;
5979 float dx2 = delta2.dx * mPointerXZoomScale;
5980 float dy2 = delta2.dy * mPointerYZoomScale;
5981 float dot = dx1 * dx2 + dy1 * dy2;
5982 float cosine = dot / (dist1 * dist2); // denominator always > 0
5983 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5984 // Pointers are moving in the same direction. Switch to SWIPE.
5985#if DEBUG_GESTURES
5986 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5987 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5988 "cosine %0.3f >= %0.3f",
5989 dist1, mConfig.pointerGestureMultitouchMinDistance,
5990 dist2, mConfig.pointerGestureMultitouchMinDistance,
5991 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5992#endif
5993 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5994 } else {
5995 // Pointers are moving in different directions. Switch to FREEFORM.
5996#if DEBUG_GESTURES
5997 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5998 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5999 "cosine %0.3f < %0.3f",
6000 dist1, mConfig.pointerGestureMultitouchMinDistance,
6001 dist2, mConfig.pointerGestureMultitouchMinDistance,
6002 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6003#endif
6004 *outCancelPreviousGesture = true;
6005 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6006 }
6007 }
6008 }
6009 }
6010 }
6011 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6012 // Switch from SWIPE to FREEFORM if additional pointers go down.
6013 // Cancel previous gesture.
6014 if (currentFingerCount > 2) {
6015#if DEBUG_GESTURES
6016 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6017 currentFingerCount);
6018#endif
6019 *outCancelPreviousGesture = true;
6020 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6021 }
6022 }
6023
6024 // Move the reference points based on the overall group motion of the fingers
6025 // except in PRESS mode while waiting for a transition to occur.
6026 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6027 && (commonDeltaX || commonDeltaY)) {
6028 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6029 uint32_t id = idBits.clearFirstMarkedBit();
6030 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6031 delta.dx = 0;
6032 delta.dy = 0;
6033 }
6034
6035 mPointerGesture.referenceTouchX += commonDeltaX;
6036 mPointerGesture.referenceTouchY += commonDeltaY;
6037
6038 commonDeltaX *= mPointerXMovementScale;
6039 commonDeltaY *= mPointerYMovementScale;
6040
6041 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6042 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6043
6044 mPointerGesture.referenceGestureX += commonDeltaX;
6045 mPointerGesture.referenceGestureY += commonDeltaY;
6046 }
6047
6048 // Report gestures.
6049 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6050 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6051 // PRESS or SWIPE mode.
6052#if DEBUG_GESTURES
6053 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6054 "activeGestureId=%d, currentTouchPointerCount=%d",
6055 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6056#endif
6057 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6058
6059 mPointerGesture.currentGestureIdBits.clear();
6060 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6061 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6062 mPointerGesture.currentGestureProperties[0].clear();
6063 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6064 mPointerGesture.currentGestureProperties[0].toolType =
6065 AMOTION_EVENT_TOOL_TYPE_FINGER;
6066 mPointerGesture.currentGestureCoords[0].clear();
6067 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6068 mPointerGesture.referenceGestureX);
6069 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6070 mPointerGesture.referenceGestureY);
6071 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6072 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6073 // FREEFORM mode.
6074#if DEBUG_GESTURES
6075 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6076 "activeGestureId=%d, currentTouchPointerCount=%d",
6077 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6078#endif
6079 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6080
6081 mPointerGesture.currentGestureIdBits.clear();
6082
6083 BitSet32 mappedTouchIdBits;
6084 BitSet32 usedGestureIdBits;
6085 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6086 // Initially, assign the active gesture id to the active touch point
6087 // if there is one. No other touch id bits are mapped yet.
6088 if (!*outCancelPreviousGesture) {
6089 mappedTouchIdBits.markBit(activeTouchId);
6090 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6091 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6092 mPointerGesture.activeGestureId;
6093 } else {
6094 mPointerGesture.activeGestureId = -1;
6095 }
6096 } else {
6097 // Otherwise, assume we mapped all touches from the previous frame.
6098 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006099 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6100 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006101 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6102
6103 // Check whether we need to choose a new active gesture id because the
6104 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006105 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6106 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006107 !upTouchIdBits.isEmpty(); ) {
6108 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6109 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6110 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6111 mPointerGesture.activeGestureId = -1;
6112 break;
6113 }
6114 }
6115 }
6116
6117#if DEBUG_GESTURES
6118 ALOGD("Gestures: FREEFORM follow up "
6119 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6120 "activeGestureId=%d",
6121 mappedTouchIdBits.value, usedGestureIdBits.value,
6122 mPointerGesture.activeGestureId);
6123#endif
6124
Michael Wright842500e2015-03-13 17:32:02 -07006125 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006126 for (uint32_t i = 0; i < currentFingerCount; i++) {
6127 uint32_t touchId = idBits.clearFirstMarkedBit();
6128 uint32_t gestureId;
6129 if (!mappedTouchIdBits.hasBit(touchId)) {
6130 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6131 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6132#if DEBUG_GESTURES
6133 ALOGD("Gestures: FREEFORM "
6134 "new mapping for touch id %d -> gesture id %d",
6135 touchId, gestureId);
6136#endif
6137 } else {
6138 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6139#if DEBUG_GESTURES
6140 ALOGD("Gestures: FREEFORM "
6141 "existing mapping for touch id %d -> gesture id %d",
6142 touchId, gestureId);
6143#endif
6144 }
6145 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6146 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6147
6148 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006149 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006150 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6151 * mPointerXZoomScale;
6152 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6153 * mPointerYZoomScale;
6154 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6155
6156 mPointerGesture.currentGestureProperties[i].clear();
6157 mPointerGesture.currentGestureProperties[i].id = gestureId;
6158 mPointerGesture.currentGestureProperties[i].toolType =
6159 AMOTION_EVENT_TOOL_TYPE_FINGER;
6160 mPointerGesture.currentGestureCoords[i].clear();
6161 mPointerGesture.currentGestureCoords[i].setAxisValue(
6162 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6163 mPointerGesture.currentGestureCoords[i].setAxisValue(
6164 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6165 mPointerGesture.currentGestureCoords[i].setAxisValue(
6166 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6167 }
6168
6169 if (mPointerGesture.activeGestureId < 0) {
6170 mPointerGesture.activeGestureId =
6171 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6172#if DEBUG_GESTURES
6173 ALOGD("Gestures: FREEFORM new "
6174 "activeGestureId=%d", mPointerGesture.activeGestureId);
6175#endif
6176 }
6177 }
6178 }
6179
Michael Wright842500e2015-03-13 17:32:02 -07006180 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006181
6182#if DEBUG_GESTURES
6183 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6184 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6185 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6186 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6187 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6188 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6189 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6190 uint32_t id = idBits.clearFirstMarkedBit();
6191 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6192 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6193 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6194 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6195 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6196 id, index, properties.toolType,
6197 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6198 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6199 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6200 }
6201 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6202 uint32_t id = idBits.clearFirstMarkedBit();
6203 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6204 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6205 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6206 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6207 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6208 id, index, properties.toolType,
6209 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6210 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6211 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6212 }
6213#endif
6214 return true;
6215}
6216
6217void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6218 mPointerSimple.currentCoords.clear();
6219 mPointerSimple.currentProperties.clear();
6220
6221 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006222 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6223 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6224 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6225 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6226 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006227 mPointerController->setPosition(x, y);
6228
Michael Wright842500e2015-03-13 17:32:02 -07006229 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 down = !hovering;
6231
6232 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006233 mPointerSimple.currentCoords.copyFrom(
6234 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6236 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6237 mPointerSimple.currentProperties.id = 0;
6238 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006239 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006240 } else {
6241 down = false;
6242 hovering = false;
6243 }
6244
6245 dispatchPointerSimple(when, policyFlags, down, hovering);
6246}
6247
6248void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6249 abortPointerSimple(when, policyFlags);
6250}
6251
6252void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6253 mPointerSimple.currentCoords.clear();
6254 mPointerSimple.currentProperties.clear();
6255
6256 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006257 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6258 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6259 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006260 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006261 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6262 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006263 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006264 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006265 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006266 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006267 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006268 * mPointerYMovementScale;
6269
6270 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6271 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6272
6273 mPointerController->move(deltaX, deltaY);
6274 } else {
6275 mPointerVelocityControl.reset();
6276 }
6277
Michael Wright842500e2015-03-13 17:32:02 -07006278 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006279 hovering = !down;
6280
6281 float x, y;
6282 mPointerController->getPosition(&x, &y);
6283 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006284 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006285 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6286 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6287 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6288 hovering ? 0.0f : 1.0f);
6289 mPointerSimple.currentProperties.id = 0;
6290 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006291 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006292 } else {
6293 mPointerVelocityControl.reset();
6294
6295 down = false;
6296 hovering = false;
6297 }
6298
6299 dispatchPointerSimple(when, policyFlags, down, hovering);
6300}
6301
6302void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6303 abortPointerSimple(when, policyFlags);
6304
6305 mPointerVelocityControl.reset();
6306}
6307
6308void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6309 bool down, bool hovering) {
6310 int32_t metaState = getContext()->getGlobalMetaState();
6311
Yi Kong9b14ac62018-07-17 13:48:38 -07006312 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006313 if (down || hovering) {
6314 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6315 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006316 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006317 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6318 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6319 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6320 }
6321 }
6322
6323 if (mPointerSimple.down && !down) {
6324 mPointerSimple.down = false;
6325
6326 // Send up.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006327 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006328 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006329 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006330 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6331 mOrientedXPrecision, mOrientedYPrecision,
6332 mPointerSimple.downTime);
6333 getListener()->notifyMotion(&args);
6334 }
6335
6336 if (mPointerSimple.hovering && !hovering) {
6337 mPointerSimple.hovering = false;
6338
6339 // Send hover exit.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006340 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006341 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006342 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006343 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6344 mOrientedXPrecision, mOrientedYPrecision,
6345 mPointerSimple.downTime);
6346 getListener()->notifyMotion(&args);
6347 }
6348
6349 if (down) {
6350 if (!mPointerSimple.down) {
6351 mPointerSimple.down = true;
6352 mPointerSimple.downTime = when;
6353
6354 // Send down.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006355 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006356 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006357 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006358 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6359 mOrientedXPrecision, mOrientedYPrecision,
6360 mPointerSimple.downTime);
6361 getListener()->notifyMotion(&args);
6362 }
6363
6364 // Send move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006365 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006366 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006367 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006368 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6369 mOrientedXPrecision, mOrientedYPrecision,
6370 mPointerSimple.downTime);
6371 getListener()->notifyMotion(&args);
6372 }
6373
6374 if (hovering) {
6375 if (!mPointerSimple.hovering) {
6376 mPointerSimple.hovering = true;
6377
6378 // Send hover enter.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006379 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006380 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006381 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006382 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006383 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6384 mOrientedXPrecision, mOrientedYPrecision,
6385 mPointerSimple.downTime);
6386 getListener()->notifyMotion(&args);
6387 }
6388
6389 // Send hover move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006390 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006391 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006392 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006393 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006394 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6395 mOrientedXPrecision, mOrientedYPrecision,
6396 mPointerSimple.downTime);
6397 getListener()->notifyMotion(&args);
6398 }
6399
Michael Wright842500e2015-03-13 17:32:02 -07006400 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6401 float vscroll = mCurrentRawState.rawVScroll;
6402 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006403 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6404 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006405
6406 // Send scroll.
6407 PointerCoords pointerCoords;
6408 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6409 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6410 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6411
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006412 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006413 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006414 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415 1, &mPointerSimple.currentProperties, &pointerCoords,
6416 mOrientedXPrecision, mOrientedYPrecision,
6417 mPointerSimple.downTime);
6418 getListener()->notifyMotion(&args);
6419 }
6420
6421 // Save state.
6422 if (down || hovering) {
6423 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6424 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6425 } else {
6426 mPointerSimple.reset();
6427 }
6428}
6429
6430void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6431 mPointerSimple.currentCoords.clear();
6432 mPointerSimple.currentProperties.clear();
6433
6434 dispatchPointerSimple(when, policyFlags, false, false);
6435}
6436
6437void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006438 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006439 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006440 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006441 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6442 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006443 PointerCoords pointerCoords[MAX_POINTERS];
6444 PointerProperties pointerProperties[MAX_POINTERS];
6445 uint32_t pointerCount = 0;
6446 while (!idBits.isEmpty()) {
6447 uint32_t id = idBits.clearFirstMarkedBit();
6448 uint32_t index = idToIndex[id];
6449 pointerProperties[pointerCount].copyFrom(properties[index]);
6450 pointerCoords[pointerCount].copyFrom(coords[index]);
6451
6452 if (changedId >= 0 && id == uint32_t(changedId)) {
6453 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6454 }
6455
6456 pointerCount += 1;
6457 }
6458
6459 ALOG_ASSERT(pointerCount != 0);
6460
6461 if (changedId >= 0 && pointerCount == 1) {
6462 // Replace initial down and final up action.
6463 // We can compare the action without masking off the changed pointer index
6464 // because we know the index is 0.
6465 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6466 action = AMOTION_EVENT_ACTION_DOWN;
6467 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6468 action = AMOTION_EVENT_ACTION_UP;
6469 } else {
6470 // Can't happen.
6471 ALOG_ASSERT(false);
6472 }
6473 }
6474
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006475 NotifyMotionArgs args(when, getDeviceId(), source, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006476 action, actionButton, flags, metaState, buttonState, edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006477 deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006478 xPrecision, yPrecision, downTime);
6479 getListener()->notifyMotion(&args);
6480}
6481
6482bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6483 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6484 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6485 BitSet32 idBits) const {
6486 bool changed = false;
6487 while (!idBits.isEmpty()) {
6488 uint32_t id = idBits.clearFirstMarkedBit();
6489 uint32_t inIndex = inIdToIndex[id];
6490 uint32_t outIndex = outIdToIndex[id];
6491
6492 const PointerProperties& curInProperties = inProperties[inIndex];
6493 const PointerCoords& curInCoords = inCoords[inIndex];
6494 PointerProperties& curOutProperties = outProperties[outIndex];
6495 PointerCoords& curOutCoords = outCoords[outIndex];
6496
6497 if (curInProperties != curOutProperties) {
6498 curOutProperties.copyFrom(curInProperties);
6499 changed = true;
6500 }
6501
6502 if (curInCoords != curOutCoords) {
6503 curOutCoords.copyFrom(curInCoords);
6504 changed = true;
6505 }
6506 }
6507 return changed;
6508}
6509
6510void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006511 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006512 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6513 }
6514}
6515
Jeff Brownc9aa6282015-02-11 19:03:28 -08006516void TouchInputMapper::cancelTouch(nsecs_t when) {
6517 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006518 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006519}
6520
Michael Wrightd02c5b62014-02-10 15:10:22 -08006521bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006522 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006523 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006524 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006525 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6526 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6527 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006528}
6529
6530const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6531 int32_t x, int32_t y) {
6532 size_t numVirtualKeys = mVirtualKeys.size();
6533 for (size_t i = 0; i < numVirtualKeys; i++) {
6534 const VirtualKey& virtualKey = mVirtualKeys[i];
6535
6536#if DEBUG_VIRTUAL_KEYS
6537 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6538 "left=%d, top=%d, right=%d, bottom=%d",
6539 x, y,
6540 virtualKey.keyCode, virtualKey.scanCode,
6541 virtualKey.hitLeft, virtualKey.hitTop,
6542 virtualKey.hitRight, virtualKey.hitBottom);
6543#endif
6544
6545 if (virtualKey.isHit(x, y)) {
6546 return & virtualKey;
6547 }
6548 }
6549
Yi Kong9b14ac62018-07-17 13:48:38 -07006550 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006551}
6552
Michael Wright842500e2015-03-13 17:32:02 -07006553void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6554 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6555 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006556
Michael Wright842500e2015-03-13 17:32:02 -07006557 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006558
6559 if (currentPointerCount == 0) {
6560 // No pointers to assign.
6561 return;
6562 }
6563
6564 if (lastPointerCount == 0) {
6565 // All pointers are new.
6566 for (uint32_t i = 0; i < currentPointerCount; i++) {
6567 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006568 current->rawPointerData.pointers[i].id = id;
6569 current->rawPointerData.idToIndex[id] = i;
6570 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006571 }
6572 return;
6573 }
6574
6575 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006576 && current->rawPointerData.pointers[0].toolType
6577 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006578 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006579 uint32_t id = last->rawPointerData.pointers[0].id;
6580 current->rawPointerData.pointers[0].id = id;
6581 current->rawPointerData.idToIndex[id] = 0;
6582 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006583 return;
6584 }
6585
6586 // General case.
6587 // We build a heap of squared euclidean distances between current and last pointers
6588 // associated with the current and last pointer indices. Then, we find the best
6589 // match (by distance) for each current pointer.
6590 // The pointers must have the same tool type but it is possible for them to
6591 // transition from hovering to touching or vice-versa while retaining the same id.
6592 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6593
6594 uint32_t heapSize = 0;
6595 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6596 currentPointerIndex++) {
6597 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6598 lastPointerIndex++) {
6599 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006600 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006601 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006602 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006603 if (currentPointer.toolType == lastPointer.toolType) {
6604 int64_t deltaX = currentPointer.x - lastPointer.x;
6605 int64_t deltaY = currentPointer.y - lastPointer.y;
6606
6607 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6608
6609 // Insert new element into the heap (sift up).
6610 heap[heapSize].currentPointerIndex = currentPointerIndex;
6611 heap[heapSize].lastPointerIndex = lastPointerIndex;
6612 heap[heapSize].distance = distance;
6613 heapSize += 1;
6614 }
6615 }
6616 }
6617
6618 // Heapify
6619 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6620 startIndex -= 1;
6621 for (uint32_t parentIndex = startIndex; ;) {
6622 uint32_t childIndex = parentIndex * 2 + 1;
6623 if (childIndex >= heapSize) {
6624 break;
6625 }
6626
6627 if (childIndex + 1 < heapSize
6628 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6629 childIndex += 1;
6630 }
6631
6632 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6633 break;
6634 }
6635
6636 swap(heap[parentIndex], heap[childIndex]);
6637 parentIndex = childIndex;
6638 }
6639 }
6640
6641#if DEBUG_POINTER_ASSIGNMENT
6642 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6643 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006644 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006645 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6646 heap[i].distance);
6647 }
6648#endif
6649
6650 // Pull matches out by increasing order of distance.
6651 // To avoid reassigning pointers that have already been matched, the loop keeps track
6652 // of which last and current pointers have been matched using the matchedXXXBits variables.
6653 // It also tracks the used pointer id bits.
6654 BitSet32 matchedLastBits(0);
6655 BitSet32 matchedCurrentBits(0);
6656 BitSet32 usedIdBits(0);
6657 bool first = true;
6658 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6659 while (heapSize > 0) {
6660 if (first) {
6661 // The first time through the loop, we just consume the root element of
6662 // the heap (the one with smallest distance).
6663 first = false;
6664 } else {
6665 // Previous iterations consumed the root element of the heap.
6666 // Pop root element off of the heap (sift down).
6667 heap[0] = heap[heapSize];
6668 for (uint32_t parentIndex = 0; ;) {
6669 uint32_t childIndex = parentIndex * 2 + 1;
6670 if (childIndex >= heapSize) {
6671 break;
6672 }
6673
6674 if (childIndex + 1 < heapSize
6675 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6676 childIndex += 1;
6677 }
6678
6679 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6680 break;
6681 }
6682
6683 swap(heap[parentIndex], heap[childIndex]);
6684 parentIndex = childIndex;
6685 }
6686
6687#if DEBUG_POINTER_ASSIGNMENT
6688 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6689 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006690 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006691 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6692 heap[i].distance);
6693 }
6694#endif
6695 }
6696
6697 heapSize -= 1;
6698
6699 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6700 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6701
6702 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6703 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6704
6705 matchedCurrentBits.markBit(currentPointerIndex);
6706 matchedLastBits.markBit(lastPointerIndex);
6707
Michael Wright842500e2015-03-13 17:32:02 -07006708 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6709 current->rawPointerData.pointers[currentPointerIndex].id = id;
6710 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6711 current->rawPointerData.markIdBit(id,
6712 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006713 usedIdBits.markBit(id);
6714
6715#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006716 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6717 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006718 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6719#endif
6720 break;
6721 }
6722 }
6723
6724 // Assign fresh ids to pointers that were not matched in the process.
6725 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6726 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6727 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6728
Michael Wright842500e2015-03-13 17:32:02 -07006729 current->rawPointerData.pointers[currentPointerIndex].id = id;
6730 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6731 current->rawPointerData.markIdBit(id,
6732 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006733
6734#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006735 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006736#endif
6737 }
6738}
6739
6740int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6741 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6742 return AKEY_STATE_VIRTUAL;
6743 }
6744
6745 size_t numVirtualKeys = mVirtualKeys.size();
6746 for (size_t i = 0; i < numVirtualKeys; i++) {
6747 const VirtualKey& virtualKey = mVirtualKeys[i];
6748 if (virtualKey.keyCode == keyCode) {
6749 return AKEY_STATE_UP;
6750 }
6751 }
6752
6753 return AKEY_STATE_UNKNOWN;
6754}
6755
6756int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6757 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6758 return AKEY_STATE_VIRTUAL;
6759 }
6760
6761 size_t numVirtualKeys = mVirtualKeys.size();
6762 for (size_t i = 0; i < numVirtualKeys; i++) {
6763 const VirtualKey& virtualKey = mVirtualKeys[i];
6764 if (virtualKey.scanCode == scanCode) {
6765 return AKEY_STATE_UP;
6766 }
6767 }
6768
6769 return AKEY_STATE_UNKNOWN;
6770}
6771
6772bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6773 const int32_t* keyCodes, uint8_t* outFlags) {
6774 size_t numVirtualKeys = mVirtualKeys.size();
6775 for (size_t i = 0; i < numVirtualKeys; i++) {
6776 const VirtualKey& virtualKey = mVirtualKeys[i];
6777
6778 for (size_t i = 0; i < numCodes; i++) {
6779 if (virtualKey.keyCode == keyCodes[i]) {
6780 outFlags[i] = 1;
6781 }
6782 }
6783 }
6784
6785 return true;
6786}
6787
6788
6789// --- SingleTouchInputMapper ---
6790
6791SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6792 TouchInputMapper(device) {
6793}
6794
6795SingleTouchInputMapper::~SingleTouchInputMapper() {
6796}
6797
6798void SingleTouchInputMapper::reset(nsecs_t when) {
6799 mSingleTouchMotionAccumulator.reset(getDevice());
6800
6801 TouchInputMapper::reset(when);
6802}
6803
6804void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6805 TouchInputMapper::process(rawEvent);
6806
6807 mSingleTouchMotionAccumulator.process(rawEvent);
6808}
6809
Michael Wright842500e2015-03-13 17:32:02 -07006810void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006811 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006812 outState->rawPointerData.pointerCount = 1;
6813 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006814
6815 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6816 && (mTouchButtonAccumulator.isHovering()
6817 || (mRawPointerAxes.pressure.valid
6818 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006819 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006820
Michael Wright842500e2015-03-13 17:32:02 -07006821 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006822 outPointer.id = 0;
6823 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6824 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6825 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6826 outPointer.touchMajor = 0;
6827 outPointer.touchMinor = 0;
6828 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6829 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6830 outPointer.orientation = 0;
6831 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6832 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6833 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6834 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6835 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6836 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6837 }
6838 outPointer.isHovering = isHovering;
6839 }
6840}
6841
6842void SingleTouchInputMapper::configureRawPointerAxes() {
6843 TouchInputMapper::configureRawPointerAxes();
6844
6845 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6846 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6847 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6848 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6849 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6850 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6851 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6852}
6853
6854bool SingleTouchInputMapper::hasStylus() const {
6855 return mTouchButtonAccumulator.hasStylus();
6856}
6857
6858
6859// --- MultiTouchInputMapper ---
6860
6861MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6862 TouchInputMapper(device) {
6863}
6864
6865MultiTouchInputMapper::~MultiTouchInputMapper() {
6866}
6867
6868void MultiTouchInputMapper::reset(nsecs_t when) {
6869 mMultiTouchMotionAccumulator.reset(getDevice());
6870
6871 mPointerIdBits.clear();
6872
6873 TouchInputMapper::reset(when);
6874}
6875
6876void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6877 TouchInputMapper::process(rawEvent);
6878
6879 mMultiTouchMotionAccumulator.process(rawEvent);
6880}
6881
Michael Wright842500e2015-03-13 17:32:02 -07006882void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006883 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6884 size_t outCount = 0;
6885 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006886 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006887
6888 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6889 const MultiTouchMotionAccumulator::Slot* inSlot =
6890 mMultiTouchMotionAccumulator.getSlot(inIndex);
6891 if (!inSlot->isInUse()) {
6892 continue;
6893 }
6894
6895 if (outCount >= MAX_POINTERS) {
6896#if DEBUG_POINTERS
6897 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6898 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006899 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006900#endif
6901 break; // too many fingers!
6902 }
6903
Michael Wright842500e2015-03-13 17:32:02 -07006904 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006905 outPointer.x = inSlot->getX();
6906 outPointer.y = inSlot->getY();
6907 outPointer.pressure = inSlot->getPressure();
6908 outPointer.touchMajor = inSlot->getTouchMajor();
6909 outPointer.touchMinor = inSlot->getTouchMinor();
6910 outPointer.toolMajor = inSlot->getToolMajor();
6911 outPointer.toolMinor = inSlot->getToolMinor();
6912 outPointer.orientation = inSlot->getOrientation();
6913 outPointer.distance = inSlot->getDistance();
6914 outPointer.tiltX = 0;
6915 outPointer.tiltY = 0;
6916
6917 outPointer.toolType = inSlot->getToolType();
6918 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6919 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6920 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6921 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6922 }
6923 }
6924
6925 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6926 && (mTouchButtonAccumulator.isHovering()
6927 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6928 outPointer.isHovering = isHovering;
6929
6930 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006931 if (mHavePointerIds) {
6932 int32_t trackingId = inSlot->getTrackingId();
6933 int32_t id = -1;
6934 if (trackingId >= 0) {
6935 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6936 uint32_t n = idBits.clearFirstMarkedBit();
6937 if (mPointerTrackingIdMap[n] == trackingId) {
6938 id = n;
6939 }
6940 }
6941
6942 if (id < 0 && !mPointerIdBits.isFull()) {
6943 id = mPointerIdBits.markFirstUnmarkedBit();
6944 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006945 }
Michael Wright842500e2015-03-13 17:32:02 -07006946 }
gaoshang1a632de2016-08-24 10:23:50 +08006947 if (id < 0) {
6948 mHavePointerIds = false;
6949 outState->rawPointerData.clearIdBits();
6950 newPointerIdBits.clear();
6951 } else {
6952 outPointer.id = id;
6953 outState->rawPointerData.idToIndex[id] = outCount;
6954 outState->rawPointerData.markIdBit(id, isHovering);
6955 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006956 }
Michael Wright842500e2015-03-13 17:32:02 -07006957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006958 outCount += 1;
6959 }
6960
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006961 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006962 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006963 mPointerIdBits = newPointerIdBits;
6964
6965 mMultiTouchMotionAccumulator.finishSync();
6966}
6967
6968void MultiTouchInputMapper::configureRawPointerAxes() {
6969 TouchInputMapper::configureRawPointerAxes();
6970
6971 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6972 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6973 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6974 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6975 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6976 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6977 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6978 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6979 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6980 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6981 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6982
6983 if (mRawPointerAxes.trackingId.valid
6984 && mRawPointerAxes.slot.valid
6985 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6986 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6987 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006988 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6989 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006990 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006991 slotCount = MAX_SLOTS;
6992 }
6993 mMultiTouchMotionAccumulator.configure(getDevice(),
6994 slotCount, true /*usingSlotsProtocol*/);
6995 } else {
6996 mMultiTouchMotionAccumulator.configure(getDevice(),
6997 MAX_POINTERS, false /*usingSlotsProtocol*/);
6998 }
6999}
7000
7001bool MultiTouchInputMapper::hasStylus() const {
7002 return mMultiTouchMotionAccumulator.hasStylus()
7003 || mTouchButtonAccumulator.hasStylus();
7004}
7005
Michael Wright842500e2015-03-13 17:32:02 -07007006// --- ExternalStylusInputMapper
7007
7008ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7009 InputMapper(device) {
7010
7011}
7012
7013uint32_t ExternalStylusInputMapper::getSources() {
7014 return AINPUT_SOURCE_STYLUS;
7015}
7016
7017void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7018 InputMapper::populateDeviceInfo(info);
7019 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7020 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7021}
7022
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007023void ExternalStylusInputMapper::dump(std::string& dump) {
7024 dump += INDENT2 "External Stylus Input Mapper:\n";
7025 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007026 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007027 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007028 dumpStylusState(dump, mStylusState);
7029}
7030
7031void ExternalStylusInputMapper::configure(nsecs_t when,
7032 const InputReaderConfiguration* config, uint32_t changes) {
7033 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7034 mTouchButtonAccumulator.configure(getDevice());
7035}
7036
7037void ExternalStylusInputMapper::reset(nsecs_t when) {
7038 InputDevice* device = getDevice();
7039 mSingleTouchMotionAccumulator.reset(device);
7040 mTouchButtonAccumulator.reset(device);
7041 InputMapper::reset(when);
7042}
7043
7044void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7045 mSingleTouchMotionAccumulator.process(rawEvent);
7046 mTouchButtonAccumulator.process(rawEvent);
7047
7048 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7049 sync(rawEvent->when);
7050 }
7051}
7052
7053void ExternalStylusInputMapper::sync(nsecs_t when) {
7054 mStylusState.clear();
7055
7056 mStylusState.when = when;
7057
Michael Wright45ccacf2015-04-21 19:01:58 +01007058 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7059 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7060 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7061 }
7062
Michael Wright842500e2015-03-13 17:32:02 -07007063 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7064 if (mRawPressureAxis.valid) {
7065 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7066 } else if (mTouchButtonAccumulator.isToolActive()) {
7067 mStylusState.pressure = 1.0f;
7068 } else {
7069 mStylusState.pressure = 0.0f;
7070 }
7071
7072 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007073
7074 mContext->dispatchExternalStylusState(mStylusState);
7075}
7076
Michael Wrightd02c5b62014-02-10 15:10:22 -08007077
7078// --- JoystickInputMapper ---
7079
7080JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7081 InputMapper(device) {
7082}
7083
7084JoystickInputMapper::~JoystickInputMapper() {
7085}
7086
7087uint32_t JoystickInputMapper::getSources() {
7088 return AINPUT_SOURCE_JOYSTICK;
7089}
7090
7091void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7092 InputMapper::populateDeviceInfo(info);
7093
7094 for (size_t i = 0; i < mAxes.size(); i++) {
7095 const Axis& axis = mAxes.valueAt(i);
7096 addMotionRange(axis.axisInfo.axis, axis, info);
7097
7098 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7099 addMotionRange(axis.axisInfo.highAxis, axis, info);
7100
7101 }
7102 }
7103}
7104
7105void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7106 InputDeviceInfo* info) {
7107 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7108 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7109 /* In order to ease the transition for developers from using the old axes
7110 * to the newer, more semantically correct axes, we'll continue to register
7111 * the old axes as duplicates of their corresponding new ones. */
7112 int32_t compatAxis = getCompatAxis(axisId);
7113 if (compatAxis >= 0) {
7114 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7115 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7116 }
7117}
7118
7119/* A mapping from axes the joystick actually has to the axes that should be
7120 * artificially created for compatibility purposes.
7121 * Returns -1 if no compatibility axis is needed. */
7122int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7123 switch(axis) {
7124 case AMOTION_EVENT_AXIS_LTRIGGER:
7125 return AMOTION_EVENT_AXIS_BRAKE;
7126 case AMOTION_EVENT_AXIS_RTRIGGER:
7127 return AMOTION_EVENT_AXIS_GAS;
7128 }
7129 return -1;
7130}
7131
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007132void JoystickInputMapper::dump(std::string& dump) {
7133 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007134
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007135 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007136 size_t numAxes = mAxes.size();
7137 for (size_t i = 0; i < numAxes; i++) {
7138 const Axis& axis = mAxes.valueAt(i);
7139 const char* label = getAxisLabel(axis.axisInfo.axis);
7140 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007141 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007142 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007143 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007144 }
7145 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7146 label = getAxisLabel(axis.axisInfo.highAxis);
7147 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007148 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007149 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007150 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007151 axis.axisInfo.splitValue);
7152 }
7153 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007154 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007155 }
7156
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007157 dump += StringPrintf(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007158 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007159 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007160 "highScale=%0.5f, highOffset=%0.5f\n",
7161 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007162 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007163 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7164 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7165 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7166 }
7167}
7168
7169void JoystickInputMapper::configure(nsecs_t when,
7170 const InputReaderConfiguration* config, uint32_t changes) {
7171 InputMapper::configure(when, config, changes);
7172
7173 if (!changes) { // first time only
7174 // Collect all axes.
7175 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7176 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7177 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7178 continue; // axis must be claimed by a different device
7179 }
7180
7181 RawAbsoluteAxisInfo rawAxisInfo;
7182 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7183 if (rawAxisInfo.valid) {
7184 // Map axis.
7185 AxisInfo axisInfo;
7186 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7187 if (!explicitlyMapped) {
7188 // Axis is not explicitly mapped, will choose a generic axis later.
7189 axisInfo.mode = AxisInfo::MODE_NORMAL;
7190 axisInfo.axis = -1;
7191 }
7192
7193 // Apply flat override.
7194 int32_t rawFlat = axisInfo.flatOverride < 0
7195 ? rawAxisInfo.flat : axisInfo.flatOverride;
7196
7197 // Calculate scaling factors and limits.
7198 Axis axis;
7199 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7200 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7201 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7202 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7203 scale, 0.0f, highScale, 0.0f,
7204 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7205 rawAxisInfo.resolution * scale);
7206 } else if (isCenteredAxis(axisInfo.axis)) {
7207 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7208 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7209 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7210 scale, offset, scale, offset,
7211 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7212 rawAxisInfo.resolution * scale);
7213 } else {
7214 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7215 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7216 scale, 0.0f, scale, 0.0f,
7217 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7218 rawAxisInfo.resolution * scale);
7219 }
7220
7221 // To eliminate noise while the joystick is at rest, filter out small variations
7222 // in axis values up front.
7223 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7224
7225 mAxes.add(abs, axis);
7226 }
7227 }
7228
7229 // If there are too many axes, start dropping them.
7230 // Prefer to keep explicitly mapped axes.
7231 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007232 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007233 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007234 pruneAxes(true);
7235 pruneAxes(false);
7236 }
7237
7238 // Assign generic axis ids to remaining axes.
7239 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7240 size_t numAxes = mAxes.size();
7241 for (size_t i = 0; i < numAxes; i++) {
7242 Axis& axis = mAxes.editValueAt(i);
7243 if (axis.axisInfo.axis < 0) {
7244 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7245 && haveAxis(nextGenericAxisId)) {
7246 nextGenericAxisId += 1;
7247 }
7248
7249 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7250 axis.axisInfo.axis = nextGenericAxisId;
7251 nextGenericAxisId += 1;
7252 } else {
7253 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7254 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007255 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007256 mAxes.removeItemsAt(i--);
7257 numAxes -= 1;
7258 }
7259 }
7260 }
7261 }
7262}
7263
7264bool JoystickInputMapper::haveAxis(int32_t axisId) {
7265 size_t numAxes = mAxes.size();
7266 for (size_t i = 0; i < numAxes; i++) {
7267 const Axis& axis = mAxes.valueAt(i);
7268 if (axis.axisInfo.axis == axisId
7269 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7270 && axis.axisInfo.highAxis == axisId)) {
7271 return true;
7272 }
7273 }
7274 return false;
7275}
7276
7277void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7278 size_t i = mAxes.size();
7279 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7280 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7281 continue;
7282 }
7283 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007284 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007285 mAxes.removeItemsAt(i);
7286 }
7287}
7288
7289bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7290 switch (axis) {
7291 case AMOTION_EVENT_AXIS_X:
7292 case AMOTION_EVENT_AXIS_Y:
7293 case AMOTION_EVENT_AXIS_Z:
7294 case AMOTION_EVENT_AXIS_RX:
7295 case AMOTION_EVENT_AXIS_RY:
7296 case AMOTION_EVENT_AXIS_RZ:
7297 case AMOTION_EVENT_AXIS_HAT_X:
7298 case AMOTION_EVENT_AXIS_HAT_Y:
7299 case AMOTION_EVENT_AXIS_ORIENTATION:
7300 case AMOTION_EVENT_AXIS_RUDDER:
7301 case AMOTION_EVENT_AXIS_WHEEL:
7302 return true;
7303 default:
7304 return false;
7305 }
7306}
7307
7308void JoystickInputMapper::reset(nsecs_t when) {
7309 // Recenter all axes.
7310 size_t numAxes = mAxes.size();
7311 for (size_t i = 0; i < numAxes; i++) {
7312 Axis& axis = mAxes.editValueAt(i);
7313 axis.resetValue();
7314 }
7315
7316 InputMapper::reset(when);
7317}
7318
7319void JoystickInputMapper::process(const RawEvent* rawEvent) {
7320 switch (rawEvent->type) {
7321 case EV_ABS: {
7322 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7323 if (index >= 0) {
7324 Axis& axis = mAxes.editValueAt(index);
7325 float newValue, highNewValue;
7326 switch (axis.axisInfo.mode) {
7327 case AxisInfo::MODE_INVERT:
7328 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7329 * axis.scale + axis.offset;
7330 highNewValue = 0.0f;
7331 break;
7332 case AxisInfo::MODE_SPLIT:
7333 if (rawEvent->value < axis.axisInfo.splitValue) {
7334 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7335 * axis.scale + axis.offset;
7336 highNewValue = 0.0f;
7337 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7338 newValue = 0.0f;
7339 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7340 * axis.highScale + axis.highOffset;
7341 } else {
7342 newValue = 0.0f;
7343 highNewValue = 0.0f;
7344 }
7345 break;
7346 default:
7347 newValue = rawEvent->value * axis.scale + axis.offset;
7348 highNewValue = 0.0f;
7349 break;
7350 }
7351 axis.newValue = newValue;
7352 axis.highNewValue = highNewValue;
7353 }
7354 break;
7355 }
7356
7357 case EV_SYN:
7358 switch (rawEvent->code) {
7359 case SYN_REPORT:
7360 sync(rawEvent->when, false /*force*/);
7361 break;
7362 }
7363 break;
7364 }
7365}
7366
7367void JoystickInputMapper::sync(nsecs_t when, bool force) {
7368 if (!filterAxes(force)) {
7369 return;
7370 }
7371
7372 int32_t metaState = mContext->getGlobalMetaState();
7373 int32_t buttonState = 0;
7374
7375 PointerProperties pointerProperties;
7376 pointerProperties.clear();
7377 pointerProperties.id = 0;
7378 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7379
7380 PointerCoords pointerCoords;
7381 pointerCoords.clear();
7382
7383 size_t numAxes = mAxes.size();
7384 for (size_t i = 0; i < numAxes; i++) {
7385 const Axis& axis = mAxes.valueAt(i);
7386 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7387 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7388 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7389 axis.highCurrentValue);
7390 }
7391 }
7392
7393 // Moving a joystick axis should not wake the device because joysticks can
7394 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7395 // button will likely wake the device.
7396 // TODO: Use the input device configuration to control this behavior more finely.
7397 uint32_t policyFlags = 0;
7398
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007399 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE,
7400 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007401 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007402 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007403 0, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007404 getListener()->notifyMotion(&args);
7405}
7406
7407void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7408 int32_t axis, float value) {
7409 pointerCoords->setAxisValue(axis, value);
7410 /* In order to ease the transition for developers from using the old axes
7411 * to the newer, more semantically correct axes, we'll continue to produce
7412 * values for the old axes as mirrors of the value of their corresponding
7413 * new axes. */
7414 int32_t compatAxis = getCompatAxis(axis);
7415 if (compatAxis >= 0) {
7416 pointerCoords->setAxisValue(compatAxis, value);
7417 }
7418}
7419
7420bool JoystickInputMapper::filterAxes(bool force) {
7421 bool atLeastOneSignificantChange = force;
7422 size_t numAxes = mAxes.size();
7423 for (size_t i = 0; i < numAxes; i++) {
7424 Axis& axis = mAxes.editValueAt(i);
7425 if (force || hasValueChangedSignificantly(axis.filter,
7426 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7427 axis.currentValue = axis.newValue;
7428 atLeastOneSignificantChange = true;
7429 }
7430 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7431 if (force || hasValueChangedSignificantly(axis.filter,
7432 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7433 axis.highCurrentValue = axis.highNewValue;
7434 atLeastOneSignificantChange = true;
7435 }
7436 }
7437 }
7438 return atLeastOneSignificantChange;
7439}
7440
7441bool JoystickInputMapper::hasValueChangedSignificantly(
7442 float filter, float newValue, float currentValue, float min, float max) {
7443 if (newValue != currentValue) {
7444 // Filter out small changes in value unless the value is converging on the axis
7445 // bounds or center point. This is intended to reduce the amount of information
7446 // sent to applications by particularly noisy joysticks (such as PS3).
7447 if (fabs(newValue - currentValue) > filter
7448 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7449 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7450 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7451 return true;
7452 }
7453 }
7454 return false;
7455}
7456
7457bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7458 float filter, float newValue, float currentValue, float thresholdValue) {
7459 float newDistance = fabs(newValue - thresholdValue);
7460 if (newDistance < filter) {
7461 float oldDistance = fabs(currentValue - thresholdValue);
7462 if (newDistance < oldDistance) {
7463 return true;
7464 }
7465 }
7466 return false;
7467}
7468
7469} // namespace android