blob: 8f121294559de16564451e5d1dc397acd49e370e [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 {
Yi Kong9b14ac62018-07-17 13:48:38 -0700261 const DisplayViewport* viewport = nullptr;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100262 if (viewportType == ViewportType::VIEWPORT_VIRTUAL && !uniqueDisplayId.empty()) {
263
Michael Spangf88ea9b2017-09-05 20:17:16 -0400264 for (const DisplayViewport& currentViewport : mVirtualDisplays) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100265 if (currentViewport.uniqueId == uniqueDisplayId) {
Santos Cordonfa5cf462017-04-05 10:37:00 -0700266 viewport = &currentViewport;
267 break;
268 }
269 }
270 } else if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
271 viewport = &mExternalDisplay;
272 } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
273 viewport = &mInternalDisplay;
274 }
275
Yi Kong9b14ac62018-07-17 13:48:38 -0700276 if (viewport != nullptr && viewport->displayId >= 0) {
Santos Cordonfa5cf462017-04-05 10:37:00 -0700277 *outViewport = *viewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800278 return true;
279 }
280 return false;
281}
282
Santos Cordonfa5cf462017-04-05 10:37:00 -0700283void InputReaderConfiguration::setPhysicalDisplayViewport(ViewportType viewportType,
284 const DisplayViewport& viewport) {
285 if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
286 mExternalDisplay = viewport;
287 } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
288 mInternalDisplay = viewport;
289 }
290}
291
292void InputReaderConfiguration::setVirtualDisplayViewports(
293 const Vector<DisplayViewport>& viewports) {
294 mVirtualDisplays = viewports;
295}
296
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800297void InputReaderConfiguration::dump(std::string& dump) const {
298 dump += INDENT4 "ViewportInternal:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700299 dumpViewport(dump, mInternalDisplay);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800300 dump += INDENT4 "ViewportExternal:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700301 dumpViewport(dump, mExternalDisplay);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800302 dump += INDENT4 "ViewportVirtual:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700303 for (const DisplayViewport& viewport : mVirtualDisplays) {
304 dumpViewport(dump, viewport);
305 }
306}
307
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800308void InputReaderConfiguration::dumpViewport(std::string& dump, const DisplayViewport& viewport) const {
309 dump += StringPrintf(INDENT5 "Viewport: displayId=%d, orientation=%d, uniqueId='%s', "
Santos Cordonfa5cf462017-04-05 10:37:00 -0700310 "logicalFrame=[%d, %d, %d, %d], "
311 "physicalFrame=[%d, %d, %d, %d], "
312 "deviceSize=[%d, %d]\n",
313 viewport.displayId, viewport.orientation, viewport.uniqueId.c_str(),
314 viewport.logicalLeft, viewport.logicalTop,
315 viewport.logicalRight, viewport.logicalBottom,
316 viewport.physicalLeft, viewport.physicalTop,
317 viewport.physicalRight, viewport.physicalBottom,
318 viewport.deviceWidth, viewport.deviceHeight);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800319}
320
321
Jason Gereckeaf126fb2012-05-10 14:22:47 -0700322// -- TouchAffineTransformation --
323void TouchAffineTransformation::applyTo(float& x, float& y) const {
324 float newX, newY;
325 newX = x * x_scale + y * x_ymix + x_offset;
326 newY = x * y_xmix + y * y_scale + y_offset;
327
328 x = newX;
329 y = newY;
330}
331
332
Michael Wrightd02c5b62014-02-10 15:10:22 -0800333// --- InputReader ---
334
335InputReader::InputReader(const sp<EventHubInterface>& eventHub,
336 const sp<InputReaderPolicyInterface>& policy,
337 const sp<InputListenerInterface>& listener) :
338 mContext(this), mEventHub(eventHub), mPolicy(policy),
339 mGlobalMetaState(0), mGeneration(1),
340 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
341 mConfigurationChangesToRefresh(0) {
342 mQueuedListener = new QueuedInputListener(listener);
343
344 { // acquire lock
345 AutoMutex _l(mLock);
346
347 refreshConfigurationLocked(0);
348 updateGlobalMetaStateLocked();
349 } // release lock
350}
351
352InputReader::~InputReader() {
353 for (size_t i = 0; i < mDevices.size(); i++) {
354 delete mDevices.valueAt(i);
355 }
356}
357
358void InputReader::loopOnce() {
359 int32_t oldGeneration;
360 int32_t timeoutMillis;
361 bool inputDevicesChanged = false;
362 Vector<InputDeviceInfo> inputDevices;
363 { // acquire lock
364 AutoMutex _l(mLock);
365
366 oldGeneration = mGeneration;
367 timeoutMillis = -1;
368
369 uint32_t changes = mConfigurationChangesToRefresh;
370 if (changes) {
371 mConfigurationChangesToRefresh = 0;
372 timeoutMillis = 0;
373 refreshConfigurationLocked(changes);
374 } else if (mNextTimeout != LLONG_MAX) {
375 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
376 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
377 }
378 } // release lock
379
380 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
381
382 { // acquire lock
383 AutoMutex _l(mLock);
384 mReaderIsAliveCondition.broadcast();
385
386 if (count) {
387 processEventsLocked(mEventBuffer, count);
388 }
389
390 if (mNextTimeout != LLONG_MAX) {
391 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
392 if (now >= mNextTimeout) {
393#if DEBUG_RAW_EVENTS
394 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
395#endif
396 mNextTimeout = LLONG_MAX;
397 timeoutExpiredLocked(now);
398 }
399 }
400
401 if (oldGeneration != mGeneration) {
402 inputDevicesChanged = true;
403 getInputDevicesLocked(inputDevices);
404 }
405 } // release lock
406
407 // Send out a message that the describes the changed input devices.
408 if (inputDevicesChanged) {
409 mPolicy->notifyInputDevicesChanged(inputDevices);
410 }
411
412 // Flush queued events out to the listener.
413 // This must happen outside of the lock because the listener could potentially call
414 // back into the InputReader's methods, such as getScanCodeState, or become blocked
415 // on another thread similarly waiting to acquire the InputReader lock thereby
416 // resulting in a deadlock. This situation is actually quite plausible because the
417 // listener is actually the input dispatcher, which calls into the window manager,
418 // which occasionally calls into the input reader.
419 mQueuedListener->flush();
420}
421
422void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
423 for (const RawEvent* rawEvent = rawEvents; count;) {
424 int32_t type = rawEvent->type;
425 size_t batchSize = 1;
426 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
427 int32_t deviceId = rawEvent->deviceId;
428 while (batchSize < count) {
429 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
430 || rawEvent[batchSize].deviceId != deviceId) {
431 break;
432 }
433 batchSize += 1;
434 }
435#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700436 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437#endif
438 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
439 } else {
440 switch (rawEvent->type) {
441 case EventHubInterface::DEVICE_ADDED:
442 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
443 break;
444 case EventHubInterface::DEVICE_REMOVED:
445 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
446 break;
447 case EventHubInterface::FINISHED_DEVICE_SCAN:
448 handleConfigurationChangedLocked(rawEvent->when);
449 break;
450 default:
451 ALOG_ASSERT(false); // can't happen
452 break;
453 }
454 }
455 count -= batchSize;
456 rawEvent += batchSize;
457 }
458}
459
460void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
461 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
462 if (deviceIndex >= 0) {
463 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
464 return;
465 }
466
467 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
468 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
469 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
470
471 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
472 device->configure(when, &mConfig, 0);
473 device->reset(when);
474
475 if (device->isIgnored()) {
476 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100477 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478 } else {
479 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100480 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481 }
482
483 mDevices.add(deviceId, device);
484 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700485
486 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
487 notifyExternalStylusPresenceChanged();
488 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489}
490
491void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700492 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
494 if (deviceIndex < 0) {
495 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
496 return;
497 }
498
499 device = mDevices.valueAt(deviceIndex);
500 mDevices.removeItemsAt(deviceIndex, 1);
501 bumpGenerationLocked();
502
503 if (device->isIgnored()) {
504 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100505 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 } else {
507 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100508 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509 }
510
Michael Wright842500e2015-03-13 17:32:02 -0700511 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
512 notifyExternalStylusPresenceChanged();
513 }
514
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 device->reset(when);
516 delete device;
517}
518
519InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
520 const InputDeviceIdentifier& identifier, uint32_t classes) {
521 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
522 controllerNumber, identifier, classes);
523
524 // External devices.
525 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
526 device->setExternal(true);
527 }
528
Tim Kilbourn063ff532015-04-08 10:26:18 -0700529 // Devices with mics.
530 if (classes & INPUT_DEVICE_CLASS_MIC) {
531 device->setMic(true);
532 }
533
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534 // Switch-like devices.
535 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
536 device->addMapper(new SwitchInputMapper(device));
537 }
538
Prashant Malani1941ff52015-08-11 18:29:28 -0700539 // Scroll wheel-like devices.
540 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
541 device->addMapper(new RotaryEncoderInputMapper(device));
542 }
543
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 // Vibrator-like devices.
545 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
546 device->addMapper(new VibratorInputMapper(device));
547 }
548
549 // Keyboard-like devices.
550 uint32_t keyboardSource = 0;
551 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
552 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
553 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
554 }
555 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
556 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
557 }
558 if (classes & INPUT_DEVICE_CLASS_DPAD) {
559 keyboardSource |= AINPUT_SOURCE_DPAD;
560 }
561 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
562 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
563 }
564
565 if (keyboardSource != 0) {
566 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
567 }
568
569 // Cursor-like devices.
570 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
571 device->addMapper(new CursorInputMapper(device));
572 }
573
574 // Touchscreens and touchpad devices.
575 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
576 device->addMapper(new MultiTouchInputMapper(device));
577 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
578 device->addMapper(new SingleTouchInputMapper(device));
579 }
580
581 // Joystick-like devices.
582 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
583 device->addMapper(new JoystickInputMapper(device));
584 }
585
Michael Wright842500e2015-03-13 17:32:02 -0700586 // External stylus-like devices.
587 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
588 device->addMapper(new ExternalStylusInputMapper(device));
589 }
590
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591 return device;
592}
593
594void InputReader::processEventsForDeviceLocked(int32_t deviceId,
595 const RawEvent* rawEvents, size_t count) {
596 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
597 if (deviceIndex < 0) {
598 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
599 return;
600 }
601
602 InputDevice* device = mDevices.valueAt(deviceIndex);
603 if (device->isIgnored()) {
604 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
605 return;
606 }
607
608 device->process(rawEvents, count);
609}
610
611void InputReader::timeoutExpiredLocked(nsecs_t when) {
612 for (size_t i = 0; i < mDevices.size(); i++) {
613 InputDevice* device = mDevices.valueAt(i);
614 if (!device->isIgnored()) {
615 device->timeoutExpired(when);
616 }
617 }
618}
619
620void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
621 // Reset global meta state because it depends on the list of all configured devices.
622 updateGlobalMetaStateLocked();
623
624 // Enqueue configuration changed.
625 NotifyConfigurationChangedArgs args(when);
626 mQueuedListener->notifyConfigurationChanged(&args);
627}
628
629void InputReader::refreshConfigurationLocked(uint32_t changes) {
630 mPolicy->getReaderConfiguration(&mConfig);
631 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
632
633 if (changes) {
634 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
635 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
636
637 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
638 mEventHub->requestReopenDevices();
639 } else {
640 for (size_t i = 0; i < mDevices.size(); i++) {
641 InputDevice* device = mDevices.valueAt(i);
642 device->configure(now, &mConfig, changes);
643 }
644 }
645 }
646}
647
648void InputReader::updateGlobalMetaStateLocked() {
649 mGlobalMetaState = 0;
650
651 for (size_t i = 0; i < mDevices.size(); i++) {
652 InputDevice* device = mDevices.valueAt(i);
653 mGlobalMetaState |= device->getMetaState();
654 }
655}
656
657int32_t InputReader::getGlobalMetaStateLocked() {
658 return mGlobalMetaState;
659}
660
Michael Wright842500e2015-03-13 17:32:02 -0700661void InputReader::notifyExternalStylusPresenceChanged() {
662 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
663}
664
665void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
666 for (size_t i = 0; i < mDevices.size(); i++) {
667 InputDevice* device = mDevices.valueAt(i);
668 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
669 outDevices.push();
670 device->getDeviceInfo(&outDevices.editTop());
671 }
672 }
673}
674
675void InputReader::dispatchExternalStylusState(const StylusState& state) {
676 for (size_t i = 0; i < mDevices.size(); i++) {
677 InputDevice* device = mDevices.valueAt(i);
678 device->updateExternalStylusState(state);
679 }
680}
681
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
683 mDisableVirtualKeysTimeout = time;
684}
685
686bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
687 InputDevice* device, int32_t keyCode, int32_t scanCode) {
688 if (now < mDisableVirtualKeysTimeout) {
689 ALOGI("Dropping virtual key from device %s because virtual keys are "
690 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100691 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 (mDisableVirtualKeysTimeout - now) * 0.000001,
693 keyCode, scanCode);
694 return true;
695 } else {
696 return false;
697 }
698}
699
700void InputReader::fadePointerLocked() {
701 for (size_t i = 0; i < mDevices.size(); i++) {
702 InputDevice* device = mDevices.valueAt(i);
703 device->fadePointer();
704 }
705}
706
707void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
708 if (when < mNextTimeout) {
709 mNextTimeout = when;
710 mEventHub->wake();
711 }
712}
713
714int32_t InputReader::bumpGenerationLocked() {
715 return ++mGeneration;
716}
717
718void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
719 AutoMutex _l(mLock);
720 getInputDevicesLocked(outInputDevices);
721}
722
723void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
724 outInputDevices.clear();
725
726 size_t numDevices = mDevices.size();
727 for (size_t i = 0; i < numDevices; i++) {
728 InputDevice* device = mDevices.valueAt(i);
729 if (!device->isIgnored()) {
730 outInputDevices.push();
731 device->getDeviceInfo(&outInputDevices.editTop());
732 }
733 }
734}
735
736int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
737 int32_t keyCode) {
738 AutoMutex _l(mLock);
739
740 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
741}
742
743int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
744 int32_t scanCode) {
745 AutoMutex _l(mLock);
746
747 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
748}
749
750int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
751 AutoMutex _l(mLock);
752
753 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
754}
755
756int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
757 GetStateFunc getStateFunc) {
758 int32_t result = AKEY_STATE_UNKNOWN;
759 if (deviceId >= 0) {
760 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
761 if (deviceIndex >= 0) {
762 InputDevice* device = mDevices.valueAt(deviceIndex);
763 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
764 result = (device->*getStateFunc)(sourceMask, code);
765 }
766 }
767 } else {
768 size_t numDevices = mDevices.size();
769 for (size_t i = 0; i < numDevices; i++) {
770 InputDevice* device = mDevices.valueAt(i);
771 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
772 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
773 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
774 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
775 if (currentResult >= AKEY_STATE_DOWN) {
776 return currentResult;
777 } else if (currentResult == AKEY_STATE_UP) {
778 result = currentResult;
779 }
780 }
781 }
782 }
783 return result;
784}
785
Andrii Kulian763a3a42016-03-08 10:46:16 -0800786void InputReader::toggleCapsLockState(int32_t deviceId) {
787 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
788 if (deviceIndex < 0) {
789 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
790 return;
791 }
792
793 InputDevice* device = mDevices.valueAt(deviceIndex);
794 if (device->isIgnored()) {
795 return;
796 }
797
798 device->updateMetaState(AKEYCODE_CAPS_LOCK);
799}
800
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
802 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
803 AutoMutex _l(mLock);
804
805 memset(outFlags, 0, numCodes);
806 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
807}
808
809bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
810 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
811 bool result = false;
812 if (deviceId >= 0) {
813 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
814 if (deviceIndex >= 0) {
815 InputDevice* device = mDevices.valueAt(deviceIndex);
816 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
817 result = device->markSupportedKeyCodes(sourceMask,
818 numCodes, keyCodes, outFlags);
819 }
820 }
821 } else {
822 size_t numDevices = mDevices.size();
823 for (size_t i = 0; i < numDevices; i++) {
824 InputDevice* device = mDevices.valueAt(i);
825 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
826 result |= device->markSupportedKeyCodes(sourceMask,
827 numCodes, keyCodes, outFlags);
828 }
829 }
830 }
831 return result;
832}
833
834void InputReader::requestRefreshConfiguration(uint32_t changes) {
835 AutoMutex _l(mLock);
836
837 if (changes) {
838 bool needWake = !mConfigurationChangesToRefresh;
839 mConfigurationChangesToRefresh |= changes;
840
841 if (needWake) {
842 mEventHub->wake();
843 }
844 }
845}
846
847void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
848 ssize_t repeat, int32_t token) {
849 AutoMutex _l(mLock);
850
851 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
852 if (deviceIndex >= 0) {
853 InputDevice* device = mDevices.valueAt(deviceIndex);
854 device->vibrate(pattern, patternSize, repeat, token);
855 }
856}
857
858void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
859 AutoMutex _l(mLock);
860
861 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
862 if (deviceIndex >= 0) {
863 InputDevice* device = mDevices.valueAt(deviceIndex);
864 device->cancelVibrate(token);
865 }
866}
867
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700868bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
869 AutoMutex _l(mLock);
870
871 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
872 if (deviceIndex >= 0) {
873 InputDevice* device = mDevices.valueAt(deviceIndex);
874 return device->isEnabled();
875 }
876 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
877 return false;
878}
879
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800880void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 AutoMutex _l(mLock);
882
883 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800884 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800886 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887
888 for (size_t i = 0; i < mDevices.size(); i++) {
889 mDevices.valueAt(i)->dump(dump);
890 }
891
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800892 dump += INDENT "Configuration:\n";
893 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
895 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800896 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100898 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800900 dump += "]\n";
901 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 mConfig.virtualKeyQuietTime * 0.000001f);
903
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800904 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
906 mConfig.pointerVelocityControlParameters.scale,
907 mConfig.pointerVelocityControlParameters.lowThreshold,
908 mConfig.pointerVelocityControlParameters.highThreshold,
909 mConfig.pointerVelocityControlParameters.acceleration);
910
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800911 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
913 mConfig.wheelVelocityControlParameters.scale,
914 mConfig.wheelVelocityControlParameters.lowThreshold,
915 mConfig.wheelVelocityControlParameters.highThreshold,
916 mConfig.wheelVelocityControlParameters.acceleration);
917
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800918 dump += StringPrintf(INDENT2 "PointerGesture:\n");
919 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800921 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800923 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800925 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800927 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800929 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800931 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800933 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800935 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800937 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800939 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800941 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700943
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800944 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700945 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946}
947
948void InputReader::monitor() {
949 // Acquire and release the lock to ensure that the reader has not deadlocked.
950 mLock.lock();
951 mEventHub->wake();
952 mReaderIsAliveCondition.wait(mLock);
953 mLock.unlock();
954
955 // Check the EventHub
956 mEventHub->monitor();
957}
958
959
960// --- InputReader::ContextImpl ---
961
962InputReader::ContextImpl::ContextImpl(InputReader* reader) :
963 mReader(reader) {
964}
965
966void InputReader::ContextImpl::updateGlobalMetaState() {
967 // lock is already held by the input loop
968 mReader->updateGlobalMetaStateLocked();
969}
970
971int32_t InputReader::ContextImpl::getGlobalMetaState() {
972 // lock is already held by the input loop
973 return mReader->getGlobalMetaStateLocked();
974}
975
976void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
977 // lock is already held by the input loop
978 mReader->disableVirtualKeysUntilLocked(time);
979}
980
981bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
982 InputDevice* device, int32_t keyCode, int32_t scanCode) {
983 // lock is already held by the input loop
984 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
985}
986
987void InputReader::ContextImpl::fadePointer() {
988 // lock is already held by the input loop
989 mReader->fadePointerLocked();
990}
991
992void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
993 // lock is already held by the input loop
994 mReader->requestTimeoutAtTimeLocked(when);
995}
996
997int32_t InputReader::ContextImpl::bumpGeneration() {
998 // lock is already held by the input loop
999 return mReader->bumpGenerationLocked();
1000}
1001
Michael Wright842500e2015-03-13 17:32:02 -07001002void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
1003 // lock is already held by whatever called refreshConfigurationLocked
1004 mReader->getExternalStylusDevicesLocked(outDevices);
1005}
1006
1007void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
1008 mReader->dispatchExternalStylusState(state);
1009}
1010
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
1012 return mReader->mPolicy.get();
1013}
1014
1015InputListenerInterface* InputReader::ContextImpl::getListener() {
1016 return mReader->mQueuedListener.get();
1017}
1018
1019EventHubInterface* InputReader::ContextImpl::getEventHub() {
1020 return mReader->mEventHub.get();
1021}
1022
1023
1024// --- InputReaderThread ---
1025
1026InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
1027 Thread(/*canCallJava*/ true), mReader(reader) {
1028}
1029
1030InputReaderThread::~InputReaderThread() {
1031}
1032
1033bool InputReaderThread::threadLoop() {
1034 mReader->loopOnce();
1035 return true;
1036}
1037
1038
1039// --- InputDevice ---
1040
1041InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
1042 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
1043 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
1044 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -07001045 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046}
1047
1048InputDevice::~InputDevice() {
1049 size_t numMappers = mMappers.size();
1050 for (size_t i = 0; i < numMappers; i++) {
1051 delete mMappers[i];
1052 }
1053 mMappers.clear();
1054}
1055
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001056bool InputDevice::isEnabled() {
1057 return getEventHub()->isDeviceEnabled(mId);
1058}
1059
1060void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1061 if (isEnabled() == enabled) {
1062 return;
1063 }
1064
1065 if (enabled) {
1066 getEventHub()->enableDevice(mId);
1067 reset(when);
1068 } else {
1069 reset(when);
1070 getEventHub()->disableDevice(mId);
1071 }
1072 // Must change generation to flag this device as changed
1073 bumpGeneration();
1074}
1075
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001076void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 InputDeviceInfo deviceInfo;
1078 getDeviceInfo(& deviceInfo);
1079
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001080 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001081 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001082 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1083 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
1084 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1085 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1086 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001087
1088 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1089 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001090 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 for (size_t i = 0; i < ranges.size(); i++) {
1092 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1093 const char* label = getAxisLabel(range.axis);
1094 char name[32];
1095 if (label) {
1096 strncpy(name, label, sizeof(name));
1097 name[sizeof(name) - 1] = '\0';
1098 } else {
1099 snprintf(name, sizeof(name), "%d", range.axis);
1100 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001101 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1103 name, range.source, range.min, range.max, range.flat, range.fuzz,
1104 range.resolution);
1105 }
1106 }
1107
1108 size_t numMappers = mMappers.size();
1109 for (size_t i = 0; i < numMappers; i++) {
1110 InputMapper* mapper = mMappers[i];
1111 mapper->dump(dump);
1112 }
1113}
1114
1115void InputDevice::addMapper(InputMapper* mapper) {
1116 mMappers.add(mapper);
1117}
1118
1119void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1120 mSources = 0;
1121
1122 if (!isIgnored()) {
1123 if (!changes) { // first time only
1124 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1125 }
1126
1127 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1128 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1129 sp<KeyCharacterMap> keyboardLayout =
1130 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1131 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1132 bumpGeneration();
1133 }
1134 }
1135 }
1136
1137 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1138 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001139 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 if (mAlias != alias) {
1141 mAlias = alias;
1142 bumpGeneration();
1143 }
1144 }
1145 }
1146
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001147 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1148 ssize_t index = config->disabledDevices.indexOf(mId);
1149 bool enabled = index < 0;
1150 setEnabled(enabled, when);
1151 }
1152
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153 size_t numMappers = mMappers.size();
1154 for (size_t i = 0; i < numMappers; i++) {
1155 InputMapper* mapper = mMappers[i];
1156 mapper->configure(when, config, changes);
1157 mSources |= mapper->getSources();
1158 }
1159 }
1160}
1161
1162void InputDevice::reset(nsecs_t when) {
1163 size_t numMappers = mMappers.size();
1164 for (size_t i = 0; i < numMappers; i++) {
1165 InputMapper* mapper = mMappers[i];
1166 mapper->reset(when);
1167 }
1168
1169 mContext->updateGlobalMetaState();
1170
1171 notifyReset(when);
1172}
1173
1174void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1175 // Process all of the events in order for each mapper.
1176 // We cannot simply ask each mapper to process them in bulk because mappers may
1177 // have side-effects that must be interleaved. For example, joystick movement events and
1178 // gamepad button presses are handled by different mappers but they should be dispatched
1179 // in the order received.
1180 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001181 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001183 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1185 rawEvent->when);
1186#endif
1187
1188 if (mDropUntilNextSync) {
1189 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1190 mDropUntilNextSync = false;
1191#if DEBUG_RAW_EVENTS
1192 ALOGD("Recovered from input event buffer overrun.");
1193#endif
1194 } else {
1195#if DEBUG_RAW_EVENTS
1196 ALOGD("Dropped input event while waiting for next input sync.");
1197#endif
1198 }
1199 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001200 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 mDropUntilNextSync = true;
1202 reset(rawEvent->when);
1203 } else {
1204 for (size_t i = 0; i < numMappers; i++) {
1205 InputMapper* mapper = mMappers[i];
1206 mapper->process(rawEvent);
1207 }
1208 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001209 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 }
1211}
1212
1213void InputDevice::timeoutExpired(nsecs_t when) {
1214 size_t numMappers = mMappers.size();
1215 for (size_t i = 0; i < numMappers; i++) {
1216 InputMapper* mapper = mMappers[i];
1217 mapper->timeoutExpired(when);
1218 }
1219}
1220
Michael Wright842500e2015-03-13 17:32:02 -07001221void InputDevice::updateExternalStylusState(const StylusState& state) {
1222 size_t numMappers = mMappers.size();
1223 for (size_t i = 0; i < numMappers; i++) {
1224 InputMapper* mapper = mMappers[i];
1225 mapper->updateExternalStylusState(state);
1226 }
1227}
1228
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1230 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001231 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 size_t numMappers = mMappers.size();
1233 for (size_t i = 0; i < numMappers; i++) {
1234 InputMapper* mapper = mMappers[i];
1235 mapper->populateDeviceInfo(outDeviceInfo);
1236 }
1237}
1238
1239int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1240 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1241}
1242
1243int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1244 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1245}
1246
1247int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1248 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1249}
1250
1251int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1252 int32_t result = AKEY_STATE_UNKNOWN;
1253 size_t numMappers = mMappers.size();
1254 for (size_t i = 0; i < numMappers; i++) {
1255 InputMapper* mapper = mMappers[i];
1256 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1257 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1258 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1259 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1260 if (currentResult >= AKEY_STATE_DOWN) {
1261 return currentResult;
1262 } else if (currentResult == AKEY_STATE_UP) {
1263 result = currentResult;
1264 }
1265 }
1266 }
1267 return result;
1268}
1269
1270bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1271 const int32_t* keyCodes, uint8_t* outFlags) {
1272 bool result = false;
1273 size_t numMappers = mMappers.size();
1274 for (size_t i = 0; i < numMappers; i++) {
1275 InputMapper* mapper = mMappers[i];
1276 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1277 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1278 }
1279 }
1280 return result;
1281}
1282
1283void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1284 int32_t token) {
1285 size_t numMappers = mMappers.size();
1286 for (size_t i = 0; i < numMappers; i++) {
1287 InputMapper* mapper = mMappers[i];
1288 mapper->vibrate(pattern, patternSize, repeat, token);
1289 }
1290}
1291
1292void InputDevice::cancelVibrate(int32_t token) {
1293 size_t numMappers = mMappers.size();
1294 for (size_t i = 0; i < numMappers; i++) {
1295 InputMapper* mapper = mMappers[i];
1296 mapper->cancelVibrate(token);
1297 }
1298}
1299
Jeff Brownc9aa6282015-02-11 19:03:28 -08001300void InputDevice::cancelTouch(nsecs_t when) {
1301 size_t numMappers = mMappers.size();
1302 for (size_t i = 0; i < numMappers; i++) {
1303 InputMapper* mapper = mMappers[i];
1304 mapper->cancelTouch(when);
1305 }
1306}
1307
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308int32_t InputDevice::getMetaState() {
1309 int32_t result = 0;
1310 size_t numMappers = mMappers.size();
1311 for (size_t i = 0; i < numMappers; i++) {
1312 InputMapper* mapper = mMappers[i];
1313 result |= mapper->getMetaState();
1314 }
1315 return result;
1316}
1317
Andrii Kulian763a3a42016-03-08 10:46:16 -08001318void InputDevice::updateMetaState(int32_t keyCode) {
1319 size_t numMappers = mMappers.size();
1320 for (size_t i = 0; i < numMappers; i++) {
1321 mMappers[i]->updateMetaState(keyCode);
1322 }
1323}
1324
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325void InputDevice::fadePointer() {
1326 size_t numMappers = mMappers.size();
1327 for (size_t i = 0; i < numMappers; i++) {
1328 InputMapper* mapper = mMappers[i];
1329 mapper->fadePointer();
1330 }
1331}
1332
1333void InputDevice::bumpGeneration() {
1334 mGeneration = mContext->bumpGeneration();
1335}
1336
1337void InputDevice::notifyReset(nsecs_t when) {
1338 NotifyDeviceResetArgs args(when, mId);
1339 mContext->getListener()->notifyDeviceReset(&args);
1340}
1341
1342
1343// --- CursorButtonAccumulator ---
1344
1345CursorButtonAccumulator::CursorButtonAccumulator() {
1346 clearButtons();
1347}
1348
1349void CursorButtonAccumulator::reset(InputDevice* device) {
1350 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1351 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1352 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1353 mBtnBack = device->isKeyPressed(BTN_BACK);
1354 mBtnSide = device->isKeyPressed(BTN_SIDE);
1355 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1356 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1357 mBtnTask = device->isKeyPressed(BTN_TASK);
1358}
1359
1360void CursorButtonAccumulator::clearButtons() {
1361 mBtnLeft = 0;
1362 mBtnRight = 0;
1363 mBtnMiddle = 0;
1364 mBtnBack = 0;
1365 mBtnSide = 0;
1366 mBtnForward = 0;
1367 mBtnExtra = 0;
1368 mBtnTask = 0;
1369}
1370
1371void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1372 if (rawEvent->type == EV_KEY) {
1373 switch (rawEvent->code) {
1374 case BTN_LEFT:
1375 mBtnLeft = rawEvent->value;
1376 break;
1377 case BTN_RIGHT:
1378 mBtnRight = rawEvent->value;
1379 break;
1380 case BTN_MIDDLE:
1381 mBtnMiddle = rawEvent->value;
1382 break;
1383 case BTN_BACK:
1384 mBtnBack = rawEvent->value;
1385 break;
1386 case BTN_SIDE:
1387 mBtnSide = rawEvent->value;
1388 break;
1389 case BTN_FORWARD:
1390 mBtnForward = rawEvent->value;
1391 break;
1392 case BTN_EXTRA:
1393 mBtnExtra = rawEvent->value;
1394 break;
1395 case BTN_TASK:
1396 mBtnTask = rawEvent->value;
1397 break;
1398 }
1399 }
1400}
1401
1402uint32_t CursorButtonAccumulator::getButtonState() const {
1403 uint32_t result = 0;
1404 if (mBtnLeft) {
1405 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1406 }
1407 if (mBtnRight) {
1408 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1409 }
1410 if (mBtnMiddle) {
1411 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1412 }
1413 if (mBtnBack || mBtnSide) {
1414 result |= AMOTION_EVENT_BUTTON_BACK;
1415 }
1416 if (mBtnForward || mBtnExtra) {
1417 result |= AMOTION_EVENT_BUTTON_FORWARD;
1418 }
1419 return result;
1420}
1421
1422
1423// --- CursorMotionAccumulator ---
1424
1425CursorMotionAccumulator::CursorMotionAccumulator() {
1426 clearRelativeAxes();
1427}
1428
1429void CursorMotionAccumulator::reset(InputDevice* device) {
1430 clearRelativeAxes();
1431}
1432
1433void CursorMotionAccumulator::clearRelativeAxes() {
1434 mRelX = 0;
1435 mRelY = 0;
1436}
1437
1438void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1439 if (rawEvent->type == EV_REL) {
1440 switch (rawEvent->code) {
1441 case REL_X:
1442 mRelX = rawEvent->value;
1443 break;
1444 case REL_Y:
1445 mRelY = rawEvent->value;
1446 break;
1447 }
1448 }
1449}
1450
1451void CursorMotionAccumulator::finishSync() {
1452 clearRelativeAxes();
1453}
1454
1455
1456// --- CursorScrollAccumulator ---
1457
1458CursorScrollAccumulator::CursorScrollAccumulator() :
1459 mHaveRelWheel(false), mHaveRelHWheel(false) {
1460 clearRelativeAxes();
1461}
1462
1463void CursorScrollAccumulator::configure(InputDevice* device) {
1464 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1465 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1466}
1467
1468void CursorScrollAccumulator::reset(InputDevice* device) {
1469 clearRelativeAxes();
1470}
1471
1472void CursorScrollAccumulator::clearRelativeAxes() {
1473 mRelWheel = 0;
1474 mRelHWheel = 0;
1475}
1476
1477void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1478 if (rawEvent->type == EV_REL) {
1479 switch (rawEvent->code) {
1480 case REL_WHEEL:
1481 mRelWheel = rawEvent->value;
1482 break;
1483 case REL_HWHEEL:
1484 mRelHWheel = rawEvent->value;
1485 break;
1486 }
1487 }
1488}
1489
1490void CursorScrollAccumulator::finishSync() {
1491 clearRelativeAxes();
1492}
1493
1494
1495// --- TouchButtonAccumulator ---
1496
1497TouchButtonAccumulator::TouchButtonAccumulator() :
1498 mHaveBtnTouch(false), mHaveStylus(false) {
1499 clearButtons();
1500}
1501
1502void TouchButtonAccumulator::configure(InputDevice* device) {
1503 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1504 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1505 || device->hasKey(BTN_TOOL_RUBBER)
1506 || device->hasKey(BTN_TOOL_BRUSH)
1507 || device->hasKey(BTN_TOOL_PENCIL)
1508 || device->hasKey(BTN_TOOL_AIRBRUSH);
1509}
1510
1511void TouchButtonAccumulator::reset(InputDevice* device) {
1512 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1513 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001514 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1515 mBtnStylus2 =
1516 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1518 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1519 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1520 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1521 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1522 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1523 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1524 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1525 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1526 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1527 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1528}
1529
1530void TouchButtonAccumulator::clearButtons() {
1531 mBtnTouch = 0;
1532 mBtnStylus = 0;
1533 mBtnStylus2 = 0;
1534 mBtnToolFinger = 0;
1535 mBtnToolPen = 0;
1536 mBtnToolRubber = 0;
1537 mBtnToolBrush = 0;
1538 mBtnToolPencil = 0;
1539 mBtnToolAirbrush = 0;
1540 mBtnToolMouse = 0;
1541 mBtnToolLens = 0;
1542 mBtnToolDoubleTap = 0;
1543 mBtnToolTripleTap = 0;
1544 mBtnToolQuadTap = 0;
1545}
1546
1547void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1548 if (rawEvent->type == EV_KEY) {
1549 switch (rawEvent->code) {
1550 case BTN_TOUCH:
1551 mBtnTouch = rawEvent->value;
1552 break;
1553 case BTN_STYLUS:
1554 mBtnStylus = rawEvent->value;
1555 break;
1556 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001557 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 mBtnStylus2 = rawEvent->value;
1559 break;
1560 case BTN_TOOL_FINGER:
1561 mBtnToolFinger = rawEvent->value;
1562 break;
1563 case BTN_TOOL_PEN:
1564 mBtnToolPen = rawEvent->value;
1565 break;
1566 case BTN_TOOL_RUBBER:
1567 mBtnToolRubber = rawEvent->value;
1568 break;
1569 case BTN_TOOL_BRUSH:
1570 mBtnToolBrush = rawEvent->value;
1571 break;
1572 case BTN_TOOL_PENCIL:
1573 mBtnToolPencil = rawEvent->value;
1574 break;
1575 case BTN_TOOL_AIRBRUSH:
1576 mBtnToolAirbrush = rawEvent->value;
1577 break;
1578 case BTN_TOOL_MOUSE:
1579 mBtnToolMouse = rawEvent->value;
1580 break;
1581 case BTN_TOOL_LENS:
1582 mBtnToolLens = rawEvent->value;
1583 break;
1584 case BTN_TOOL_DOUBLETAP:
1585 mBtnToolDoubleTap = rawEvent->value;
1586 break;
1587 case BTN_TOOL_TRIPLETAP:
1588 mBtnToolTripleTap = rawEvent->value;
1589 break;
1590 case BTN_TOOL_QUADTAP:
1591 mBtnToolQuadTap = rawEvent->value;
1592 break;
1593 }
1594 }
1595}
1596
1597uint32_t TouchButtonAccumulator::getButtonState() const {
1598 uint32_t result = 0;
1599 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001600 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601 }
1602 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001603 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 }
1605 return result;
1606}
1607
1608int32_t TouchButtonAccumulator::getToolType() const {
1609 if (mBtnToolMouse || mBtnToolLens) {
1610 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1611 }
1612 if (mBtnToolRubber) {
1613 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1614 }
1615 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1616 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1617 }
1618 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1619 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1620 }
1621 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1622}
1623
1624bool TouchButtonAccumulator::isToolActive() const {
1625 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1626 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1627 || mBtnToolMouse || mBtnToolLens
1628 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1629}
1630
1631bool TouchButtonAccumulator::isHovering() const {
1632 return mHaveBtnTouch && !mBtnTouch;
1633}
1634
1635bool TouchButtonAccumulator::hasStylus() const {
1636 return mHaveStylus;
1637}
1638
1639
1640// --- RawPointerAxes ---
1641
1642RawPointerAxes::RawPointerAxes() {
1643 clear();
1644}
1645
1646void RawPointerAxes::clear() {
1647 x.clear();
1648 y.clear();
1649 pressure.clear();
1650 touchMajor.clear();
1651 touchMinor.clear();
1652 toolMajor.clear();
1653 toolMinor.clear();
1654 orientation.clear();
1655 distance.clear();
1656 tiltX.clear();
1657 tiltY.clear();
1658 trackingId.clear();
1659 slot.clear();
1660}
1661
1662
1663// --- RawPointerData ---
1664
1665RawPointerData::RawPointerData() {
1666 clear();
1667}
1668
1669void RawPointerData::clear() {
1670 pointerCount = 0;
1671 clearIdBits();
1672}
1673
1674void RawPointerData::copyFrom(const RawPointerData& other) {
1675 pointerCount = other.pointerCount;
1676 hoveringIdBits = other.hoveringIdBits;
1677 touchingIdBits = other.touchingIdBits;
1678
1679 for (uint32_t i = 0; i < pointerCount; i++) {
1680 pointers[i] = other.pointers[i];
1681
1682 int id = pointers[i].id;
1683 idToIndex[id] = other.idToIndex[id];
1684 }
1685}
1686
1687void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1688 float x = 0, y = 0;
1689 uint32_t count = touchingIdBits.count();
1690 if (count) {
1691 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1692 uint32_t id = idBits.clearFirstMarkedBit();
1693 const Pointer& pointer = pointerForId(id);
1694 x += pointer.x;
1695 y += pointer.y;
1696 }
1697 x /= count;
1698 y /= count;
1699 }
1700 *outX = x;
1701 *outY = y;
1702}
1703
1704
1705// --- CookedPointerData ---
1706
1707CookedPointerData::CookedPointerData() {
1708 clear();
1709}
1710
1711void CookedPointerData::clear() {
1712 pointerCount = 0;
1713 hoveringIdBits.clear();
1714 touchingIdBits.clear();
1715}
1716
1717void CookedPointerData::copyFrom(const CookedPointerData& other) {
1718 pointerCount = other.pointerCount;
1719 hoveringIdBits = other.hoveringIdBits;
1720 touchingIdBits = other.touchingIdBits;
1721
1722 for (uint32_t i = 0; i < pointerCount; i++) {
1723 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1724 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1725
1726 int id = pointerProperties[i].id;
1727 idToIndex[id] = other.idToIndex[id];
1728 }
1729}
1730
1731
1732// --- SingleTouchMotionAccumulator ---
1733
1734SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1735 clearAbsoluteAxes();
1736}
1737
1738void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1739 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1740 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1741 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1742 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1743 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1744 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1745 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1746}
1747
1748void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1749 mAbsX = 0;
1750 mAbsY = 0;
1751 mAbsPressure = 0;
1752 mAbsToolWidth = 0;
1753 mAbsDistance = 0;
1754 mAbsTiltX = 0;
1755 mAbsTiltY = 0;
1756}
1757
1758void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1759 if (rawEvent->type == EV_ABS) {
1760 switch (rawEvent->code) {
1761 case ABS_X:
1762 mAbsX = rawEvent->value;
1763 break;
1764 case ABS_Y:
1765 mAbsY = rawEvent->value;
1766 break;
1767 case ABS_PRESSURE:
1768 mAbsPressure = rawEvent->value;
1769 break;
1770 case ABS_TOOL_WIDTH:
1771 mAbsToolWidth = rawEvent->value;
1772 break;
1773 case ABS_DISTANCE:
1774 mAbsDistance = rawEvent->value;
1775 break;
1776 case ABS_TILT_X:
1777 mAbsTiltX = rawEvent->value;
1778 break;
1779 case ABS_TILT_Y:
1780 mAbsTiltY = rawEvent->value;
1781 break;
1782 }
1783 }
1784}
1785
1786
1787// --- MultiTouchMotionAccumulator ---
1788
1789MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001790 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001791 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792}
1793
1794MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1795 delete[] mSlots;
1796}
1797
1798void MultiTouchMotionAccumulator::configure(InputDevice* device,
1799 size_t slotCount, bool usingSlotsProtocol) {
1800 mSlotCount = slotCount;
1801 mUsingSlotsProtocol = usingSlotsProtocol;
1802 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1803
1804 delete[] mSlots;
1805 mSlots = new Slot[slotCount];
1806}
1807
1808void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1809 // Unfortunately there is no way to read the initial contents of the slots.
1810 // So when we reset the accumulator, we must assume they are all zeroes.
1811 if (mUsingSlotsProtocol) {
1812 // Query the driver for the current slot index and use it as the initial slot
1813 // before we start reading events from the device. It is possible that the
1814 // current slot index will not be the same as it was when the first event was
1815 // written into the evdev buffer, which means the input mapper could start
1816 // out of sync with the initial state of the events in the evdev buffer.
1817 // In the extremely unlikely case that this happens, the data from
1818 // two slots will be confused until the next ABS_MT_SLOT event is received.
1819 // This can cause the touch point to "jump", but at least there will be
1820 // no stuck touches.
1821 int32_t initialSlot;
1822 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1823 ABS_MT_SLOT, &initialSlot);
1824 if (status) {
1825 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1826 initialSlot = -1;
1827 }
1828 clearSlots(initialSlot);
1829 } else {
1830 clearSlots(-1);
1831 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001832 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833}
1834
1835void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1836 if (mSlots) {
1837 for (size_t i = 0; i < mSlotCount; i++) {
1838 mSlots[i].clear();
1839 }
1840 }
1841 mCurrentSlot = initialSlot;
1842}
1843
1844void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1845 if (rawEvent->type == EV_ABS) {
1846 bool newSlot = false;
1847 if (mUsingSlotsProtocol) {
1848 if (rawEvent->code == ABS_MT_SLOT) {
1849 mCurrentSlot = rawEvent->value;
1850 newSlot = true;
1851 }
1852 } else if (mCurrentSlot < 0) {
1853 mCurrentSlot = 0;
1854 }
1855
1856 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1857#if DEBUG_POINTERS
1858 if (newSlot) {
1859 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001860 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 mCurrentSlot, mSlotCount - 1);
1862 }
1863#endif
1864 } else {
1865 Slot* slot = &mSlots[mCurrentSlot];
1866
1867 switch (rawEvent->code) {
1868 case ABS_MT_POSITION_X:
1869 slot->mInUse = true;
1870 slot->mAbsMTPositionX = rawEvent->value;
1871 break;
1872 case ABS_MT_POSITION_Y:
1873 slot->mInUse = true;
1874 slot->mAbsMTPositionY = rawEvent->value;
1875 break;
1876 case ABS_MT_TOUCH_MAJOR:
1877 slot->mInUse = true;
1878 slot->mAbsMTTouchMajor = rawEvent->value;
1879 break;
1880 case ABS_MT_TOUCH_MINOR:
1881 slot->mInUse = true;
1882 slot->mAbsMTTouchMinor = rawEvent->value;
1883 slot->mHaveAbsMTTouchMinor = true;
1884 break;
1885 case ABS_MT_WIDTH_MAJOR:
1886 slot->mInUse = true;
1887 slot->mAbsMTWidthMajor = rawEvent->value;
1888 break;
1889 case ABS_MT_WIDTH_MINOR:
1890 slot->mInUse = true;
1891 slot->mAbsMTWidthMinor = rawEvent->value;
1892 slot->mHaveAbsMTWidthMinor = true;
1893 break;
1894 case ABS_MT_ORIENTATION:
1895 slot->mInUse = true;
1896 slot->mAbsMTOrientation = rawEvent->value;
1897 break;
1898 case ABS_MT_TRACKING_ID:
1899 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1900 // The slot is no longer in use but it retains its previous contents,
1901 // which may be reused for subsequent touches.
1902 slot->mInUse = false;
1903 } else {
1904 slot->mInUse = true;
1905 slot->mAbsMTTrackingId = rawEvent->value;
1906 }
1907 break;
1908 case ABS_MT_PRESSURE:
1909 slot->mInUse = true;
1910 slot->mAbsMTPressure = rawEvent->value;
1911 break;
1912 case ABS_MT_DISTANCE:
1913 slot->mInUse = true;
1914 slot->mAbsMTDistance = rawEvent->value;
1915 break;
1916 case ABS_MT_TOOL_TYPE:
1917 slot->mInUse = true;
1918 slot->mAbsMTToolType = rawEvent->value;
1919 slot->mHaveAbsMTToolType = true;
1920 break;
1921 }
1922 }
1923 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1924 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1925 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001926 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1927 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 }
1929}
1930
1931void MultiTouchMotionAccumulator::finishSync() {
1932 if (!mUsingSlotsProtocol) {
1933 clearSlots(-1);
1934 }
1935}
1936
1937bool MultiTouchMotionAccumulator::hasStylus() const {
1938 return mHaveStylus;
1939}
1940
1941
1942// --- MultiTouchMotionAccumulator::Slot ---
1943
1944MultiTouchMotionAccumulator::Slot::Slot() {
1945 clear();
1946}
1947
1948void MultiTouchMotionAccumulator::Slot::clear() {
1949 mInUse = false;
1950 mHaveAbsMTTouchMinor = false;
1951 mHaveAbsMTWidthMinor = false;
1952 mHaveAbsMTToolType = false;
1953 mAbsMTPositionX = 0;
1954 mAbsMTPositionY = 0;
1955 mAbsMTTouchMajor = 0;
1956 mAbsMTTouchMinor = 0;
1957 mAbsMTWidthMajor = 0;
1958 mAbsMTWidthMinor = 0;
1959 mAbsMTOrientation = 0;
1960 mAbsMTTrackingId = -1;
1961 mAbsMTPressure = 0;
1962 mAbsMTDistance = 0;
1963 mAbsMTToolType = 0;
1964}
1965
1966int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1967 if (mHaveAbsMTToolType) {
1968 switch (mAbsMTToolType) {
1969 case MT_TOOL_FINGER:
1970 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1971 case MT_TOOL_PEN:
1972 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1973 }
1974 }
1975 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1976}
1977
1978
1979// --- InputMapper ---
1980
1981InputMapper::InputMapper(InputDevice* device) :
1982 mDevice(device), mContext(device->getContext()) {
1983}
1984
1985InputMapper::~InputMapper() {
1986}
1987
1988void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1989 info->addSource(getSources());
1990}
1991
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001992void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993}
1994
1995void InputMapper::configure(nsecs_t when,
1996 const InputReaderConfiguration* config, uint32_t changes) {
1997}
1998
1999void InputMapper::reset(nsecs_t when) {
2000}
2001
2002void InputMapper::timeoutExpired(nsecs_t when) {
2003}
2004
2005int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2006 return AKEY_STATE_UNKNOWN;
2007}
2008
2009int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2010 return AKEY_STATE_UNKNOWN;
2011}
2012
2013int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2014 return AKEY_STATE_UNKNOWN;
2015}
2016
2017bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2018 const int32_t* keyCodes, uint8_t* outFlags) {
2019 return false;
2020}
2021
2022void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2023 int32_t token) {
2024}
2025
2026void InputMapper::cancelVibrate(int32_t token) {
2027}
2028
Jeff Brownc9aa6282015-02-11 19:03:28 -08002029void InputMapper::cancelTouch(nsecs_t when) {
2030}
2031
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032int32_t InputMapper::getMetaState() {
2033 return 0;
2034}
2035
Andrii Kulian763a3a42016-03-08 10:46:16 -08002036void InputMapper::updateMetaState(int32_t keyCode) {
2037}
2038
Michael Wright842500e2015-03-13 17:32:02 -07002039void InputMapper::updateExternalStylusState(const StylusState& state) {
2040
2041}
2042
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043void InputMapper::fadePointer() {
2044}
2045
2046status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2047 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2048}
2049
2050void InputMapper::bumpGeneration() {
2051 mDevice->bumpGeneration();
2052}
2053
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002054void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 const RawAbsoluteAxisInfo& axis, const char* name) {
2056 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002057 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2059 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002060 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 }
2062}
2063
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002064void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2065 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2066 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2067 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2068 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002069}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070
2071// --- SwitchInputMapper ---
2072
2073SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002074 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075}
2076
2077SwitchInputMapper::~SwitchInputMapper() {
2078}
2079
2080uint32_t SwitchInputMapper::getSources() {
2081 return AINPUT_SOURCE_SWITCH;
2082}
2083
2084void SwitchInputMapper::process(const RawEvent* rawEvent) {
2085 switch (rawEvent->type) {
2086 case EV_SW:
2087 processSwitch(rawEvent->code, rawEvent->value);
2088 break;
2089
2090 case EV_SYN:
2091 if (rawEvent->code == SYN_REPORT) {
2092 sync(rawEvent->when);
2093 }
2094 }
2095}
2096
2097void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2098 if (switchCode >= 0 && switchCode < 32) {
2099 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002100 mSwitchValues |= 1 << switchCode;
2101 } else {
2102 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103 }
2104 mUpdatedSwitchMask |= 1 << switchCode;
2105 }
2106}
2107
2108void SwitchInputMapper::sync(nsecs_t when) {
2109 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002110 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002111 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112 getListener()->notifySwitch(&args);
2113
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 mUpdatedSwitchMask = 0;
2115 }
2116}
2117
2118int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2119 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2120}
2121
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002122void SwitchInputMapper::dump(std::string& dump) {
2123 dump += INDENT2 "Switch Input Mapper:\n";
2124 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002125}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126
2127// --- VibratorInputMapper ---
2128
2129VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2130 InputMapper(device), mVibrating(false) {
2131}
2132
2133VibratorInputMapper::~VibratorInputMapper() {
2134}
2135
2136uint32_t VibratorInputMapper::getSources() {
2137 return 0;
2138}
2139
2140void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2141 InputMapper::populateDeviceInfo(info);
2142
2143 info->setVibrator(true);
2144}
2145
2146void VibratorInputMapper::process(const RawEvent* rawEvent) {
2147 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2148}
2149
2150void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2151 int32_t token) {
2152#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002153 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 for (size_t i = 0; i < patternSize; i++) {
2155 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002156 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002158 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002160 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002161 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162#endif
2163
2164 mVibrating = true;
2165 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2166 mPatternSize = patternSize;
2167 mRepeat = repeat;
2168 mToken = token;
2169 mIndex = -1;
2170
2171 nextStep();
2172}
2173
2174void VibratorInputMapper::cancelVibrate(int32_t token) {
2175#if DEBUG_VIBRATOR
2176 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2177#endif
2178
2179 if (mVibrating && mToken == token) {
2180 stopVibrating();
2181 }
2182}
2183
2184void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2185 if (mVibrating) {
2186 if (when >= mNextStepTime) {
2187 nextStep();
2188 } else {
2189 getContext()->requestTimeoutAtTime(mNextStepTime);
2190 }
2191 }
2192}
2193
2194void VibratorInputMapper::nextStep() {
2195 mIndex += 1;
2196 if (size_t(mIndex) >= mPatternSize) {
2197 if (mRepeat < 0) {
2198 // We are done.
2199 stopVibrating();
2200 return;
2201 }
2202 mIndex = mRepeat;
2203 }
2204
2205 bool vibratorOn = mIndex & 1;
2206 nsecs_t duration = mPattern[mIndex];
2207 if (vibratorOn) {
2208#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002209 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210#endif
2211 getEventHub()->vibrate(getDeviceId(), duration);
2212 } else {
2213#if DEBUG_VIBRATOR
2214 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2215#endif
2216 getEventHub()->cancelVibrate(getDeviceId());
2217 }
2218 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2219 mNextStepTime = now + duration;
2220 getContext()->requestTimeoutAtTime(mNextStepTime);
2221#if DEBUG_VIBRATOR
2222 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2223#endif
2224}
2225
2226void VibratorInputMapper::stopVibrating() {
2227 mVibrating = false;
2228#if DEBUG_VIBRATOR
2229 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2230#endif
2231 getEventHub()->cancelVibrate(getDeviceId());
2232}
2233
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002234void VibratorInputMapper::dump(std::string& dump) {
2235 dump += INDENT2 "Vibrator Input Mapper:\n";
2236 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237}
2238
2239
2240// --- KeyboardInputMapper ---
2241
2242KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2243 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002244 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245}
2246
2247KeyboardInputMapper::~KeyboardInputMapper() {
2248}
2249
2250uint32_t KeyboardInputMapper::getSources() {
2251 return mSource;
2252}
2253
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002254int32_t KeyboardInputMapper::getOrientation() {
2255 if (mViewport) {
2256 return mViewport->orientation;
2257 }
2258 return DISPLAY_ORIENTATION_0;
2259}
2260
2261int32_t KeyboardInputMapper::getDisplayId() {
2262 if (mViewport) {
2263 return mViewport->displayId;
2264 }
2265 return ADISPLAY_ID_NONE;
2266}
2267
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2269 InputMapper::populateDeviceInfo(info);
2270
2271 info->setKeyboardType(mKeyboardType);
2272 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2273}
2274
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002275void KeyboardInputMapper::dump(std::string& dump) {
2276 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002278 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002279 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002280 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2281 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2282 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283}
2284
2285
2286void KeyboardInputMapper::configure(nsecs_t when,
2287 const InputReaderConfiguration* config, uint32_t changes) {
2288 InputMapper::configure(when, config, changes);
2289
2290 if (!changes) { // first time only
2291 // Configure basic parameters.
2292 configureParameters();
2293 }
2294
2295 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002296 if (mParameters.orientationAware) {
2297 DisplayViewport dvp;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002298 config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "", &dvp);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002299 mViewport = dvp;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 }
2301 }
2302}
2303
Ivan Podogovb9afef32017-02-13 15:34:32 +00002304static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2305 int32_t mapped = 0;
2306 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2307 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2308 if (stemKeyRotationMap[i][0] == keyCode) {
2309 stemKeyRotationMap[i][1] = mapped;
2310 return;
2311 }
2312 }
2313 }
2314}
2315
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316void KeyboardInputMapper::configureParameters() {
2317 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002318 const PropertyMap& config = getDevice()->getConfiguration();
2319 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 mParameters.orientationAware);
2321
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002323 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2324 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2325 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2326 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002328
2329 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002330 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002331 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332}
2333
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002334void KeyboardInputMapper::dumpParameters(std::string& dump) {
2335 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002336 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002338 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002339 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340}
2341
2342void KeyboardInputMapper::reset(nsecs_t when) {
2343 mMetaState = AMETA_NONE;
2344 mDownTime = 0;
2345 mKeyDowns.clear();
2346 mCurrentHidUsage = 0;
2347
2348 resetLedState();
2349
2350 InputMapper::reset(when);
2351}
2352
2353void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2354 switch (rawEvent->type) {
2355 case EV_KEY: {
2356 int32_t scanCode = rawEvent->code;
2357 int32_t usageCode = mCurrentHidUsage;
2358 mCurrentHidUsage = 0;
2359
2360 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002361 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 }
2363 break;
2364 }
2365 case EV_MSC: {
2366 if (rawEvent->code == MSC_SCAN) {
2367 mCurrentHidUsage = rawEvent->value;
2368 }
2369 break;
2370 }
2371 case EV_SYN: {
2372 if (rawEvent->code == SYN_REPORT) {
2373 mCurrentHidUsage = 0;
2374 }
2375 }
2376 }
2377}
2378
2379bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2380 return scanCode < BTN_MOUSE
2381 || scanCode >= KEY_OK
2382 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2383 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2384}
2385
Michael Wright58ba9882017-07-26 16:19:11 +01002386bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2387 switch (keyCode) {
2388 case AKEYCODE_MEDIA_PLAY:
2389 case AKEYCODE_MEDIA_PAUSE:
2390 case AKEYCODE_MEDIA_PLAY_PAUSE:
2391 case AKEYCODE_MUTE:
2392 case AKEYCODE_HEADSETHOOK:
2393 case AKEYCODE_MEDIA_STOP:
2394 case AKEYCODE_MEDIA_NEXT:
2395 case AKEYCODE_MEDIA_PREVIOUS:
2396 case AKEYCODE_MEDIA_REWIND:
2397 case AKEYCODE_MEDIA_RECORD:
2398 case AKEYCODE_MEDIA_FAST_FORWARD:
2399 case AKEYCODE_MEDIA_SKIP_FORWARD:
2400 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2401 case AKEYCODE_MEDIA_STEP_FORWARD:
2402 case AKEYCODE_MEDIA_STEP_BACKWARD:
2403 case AKEYCODE_MEDIA_AUDIO_TRACK:
2404 case AKEYCODE_VOLUME_UP:
2405 case AKEYCODE_VOLUME_DOWN:
2406 case AKEYCODE_VOLUME_MUTE:
2407 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2408 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2409 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2410 return true;
2411 }
2412 return false;
2413}
2414
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002415void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2416 int32_t usageCode) {
2417 int32_t keyCode;
2418 int32_t keyMetaState;
2419 uint32_t policyFlags;
2420
2421 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2422 &keyCode, &keyMetaState, &policyFlags)) {
2423 keyCode = AKEYCODE_UNKNOWN;
2424 keyMetaState = mMetaState;
2425 policyFlags = 0;
2426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427
2428 if (down) {
2429 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002430 if (mParameters.orientationAware) {
2431 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432 }
2433
2434 // Add key down.
2435 ssize_t keyDownIndex = findKeyDown(scanCode);
2436 if (keyDownIndex >= 0) {
2437 // key repeat, be sure to use same keycode as before in case of rotation
2438 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2439 } else {
2440 // key down
2441 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2442 && mContext->shouldDropVirtualKey(when,
2443 getDevice(), keyCode, scanCode)) {
2444 return;
2445 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002446 if (policyFlags & POLICY_FLAG_GESTURE) {
2447 mDevice->cancelTouch(when);
2448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449
2450 mKeyDowns.push();
2451 KeyDown& keyDown = mKeyDowns.editTop();
2452 keyDown.keyCode = keyCode;
2453 keyDown.scanCode = scanCode;
2454 }
2455
2456 mDownTime = when;
2457 } else {
2458 // Remove key down.
2459 ssize_t keyDownIndex = findKeyDown(scanCode);
2460 if (keyDownIndex >= 0) {
2461 // key up, be sure to use same keycode as before in case of rotation
2462 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2463 mKeyDowns.removeAt(size_t(keyDownIndex));
2464 } else {
2465 // key was not actually down
2466 ALOGI("Dropping key up from device %s because the key was not down. "
2467 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002468 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 return;
2470 }
2471 }
2472
Andrii Kulian763a3a42016-03-08 10:46:16 -08002473 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002474 // If global meta state changed send it along with the key.
2475 // If it has not changed then we'll use what keymap gave us,
2476 // since key replacement logic might temporarily reset a few
2477 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002478 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 }
2480
2481 nsecs_t downTime = mDownTime;
2482
2483 // Key down on external an keyboard should wake the device.
2484 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2485 // For internal keyboards, the key layout file should specify the policy flags for
2486 // each wake key individually.
2487 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002488 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002489 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 }
2491
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002492 if (mParameters.handlesKeyRepeat) {
2493 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2494 }
2495
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002496 NotifyKeyArgs args(when, getDeviceId(), mSource, getDisplayId(), policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002498 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 getListener()->notifyKey(&args);
2500}
2501
2502ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2503 size_t n = mKeyDowns.size();
2504 for (size_t i = 0; i < n; i++) {
2505 if (mKeyDowns[i].scanCode == scanCode) {
2506 return i;
2507 }
2508 }
2509 return -1;
2510}
2511
2512int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2513 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2514}
2515
2516int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2517 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2518}
2519
2520bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2521 const int32_t* keyCodes, uint8_t* outFlags) {
2522 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2523}
2524
2525int32_t KeyboardInputMapper::getMetaState() {
2526 return mMetaState;
2527}
2528
Andrii Kulian763a3a42016-03-08 10:46:16 -08002529void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2530 updateMetaStateIfNeeded(keyCode, false);
2531}
2532
2533bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2534 int32_t oldMetaState = mMetaState;
2535 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2536 bool metaStateChanged = oldMetaState != newMetaState;
2537 if (metaStateChanged) {
2538 mMetaState = newMetaState;
2539 updateLedState(false);
2540
2541 getContext()->updateGlobalMetaState();
2542 }
2543
2544 return metaStateChanged;
2545}
2546
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547void KeyboardInputMapper::resetLedState() {
2548 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2549 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2550 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2551
2552 updateLedState(true);
2553}
2554
2555void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2556 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2557 ledState.on = false;
2558}
2559
2560void KeyboardInputMapper::updateLedState(bool reset) {
2561 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2562 AMETA_CAPS_LOCK_ON, reset);
2563 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2564 AMETA_NUM_LOCK_ON, reset);
2565 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2566 AMETA_SCROLL_LOCK_ON, reset);
2567}
2568
2569void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2570 int32_t led, int32_t modifier, bool reset) {
2571 if (ledState.avail) {
2572 bool desiredState = (mMetaState & modifier) != 0;
2573 if (reset || ledState.on != desiredState) {
2574 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2575 ledState.on = desiredState;
2576 }
2577 }
2578}
2579
2580
2581// --- CursorInputMapper ---
2582
2583CursorInputMapper::CursorInputMapper(InputDevice* device) :
2584 InputMapper(device) {
2585}
2586
2587CursorInputMapper::~CursorInputMapper() {
2588}
2589
2590uint32_t CursorInputMapper::getSources() {
2591 return mSource;
2592}
2593
2594void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2595 InputMapper::populateDeviceInfo(info);
2596
2597 if (mParameters.mode == Parameters::MODE_POINTER) {
2598 float minX, minY, maxX, maxY;
2599 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2600 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2601 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2602 }
2603 } else {
2604 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2605 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2606 }
2607 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2608
2609 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2610 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2611 }
2612 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2613 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2614 }
2615}
2616
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002617void CursorInputMapper::dump(std::string& dump) {
2618 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002620 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2621 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2622 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2623 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2624 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002626 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002628 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2629 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2630 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2631 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2632 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2633 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634}
2635
2636void CursorInputMapper::configure(nsecs_t when,
2637 const InputReaderConfiguration* config, uint32_t changes) {
2638 InputMapper::configure(when, config, changes);
2639
2640 if (!changes) { // first time only
2641 mCursorScrollAccumulator.configure(getDevice());
2642
2643 // Configure basic parameters.
2644 configureParameters();
2645
2646 // Configure device mode.
2647 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002648 case Parameters::MODE_POINTER_RELATIVE:
2649 // Should not happen during first time configuration.
2650 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2651 mParameters.mode = Parameters::MODE_POINTER;
2652 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 case Parameters::MODE_POINTER:
2654 mSource = AINPUT_SOURCE_MOUSE;
2655 mXPrecision = 1.0f;
2656 mYPrecision = 1.0f;
2657 mXScale = 1.0f;
2658 mYScale = 1.0f;
2659 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2660 break;
2661 case Parameters::MODE_NAVIGATION:
2662 mSource = AINPUT_SOURCE_TRACKBALL;
2663 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2664 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2665 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2666 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2667 break;
2668 }
2669
2670 mVWheelScale = 1.0f;
2671 mHWheelScale = 1.0f;
2672 }
2673
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002674 if ((!changes && config->pointerCapture)
2675 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2676 if (config->pointerCapture) {
2677 if (mParameters.mode == Parameters::MODE_POINTER) {
2678 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2679 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2680 // Keep PointerController around in order to preserve the pointer position.
2681 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2682 } else {
2683 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2684 }
2685 } else {
2686 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2687 mParameters.mode = Parameters::MODE_POINTER;
2688 mSource = AINPUT_SOURCE_MOUSE;
2689 } else {
2690 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2691 }
2692 }
2693 bumpGeneration();
2694 if (changes) {
2695 getDevice()->notifyReset(when);
2696 }
2697 }
2698
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2700 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2701 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2702 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2703 }
2704
2705 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002706 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2708 DisplayViewport v;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002709 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "", &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 mOrientation = v.orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 }
2713 bumpGeneration();
2714 }
2715}
2716
2717void CursorInputMapper::configureParameters() {
2718 mParameters.mode = Parameters::MODE_POINTER;
2719 String8 cursorModeString;
2720 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2721 if (cursorModeString == "navigation") {
2722 mParameters.mode = Parameters::MODE_NAVIGATION;
2723 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2724 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2725 }
2726 }
2727
2728 mParameters.orientationAware = false;
2729 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2730 mParameters.orientationAware);
2731
2732 mParameters.hasAssociatedDisplay = false;
2733 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2734 mParameters.hasAssociatedDisplay = true;
2735 }
2736}
2737
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002738void CursorInputMapper::dumpParameters(std::string& dump) {
2739 dump += INDENT3 "Parameters:\n";
2740 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 toString(mParameters.hasAssociatedDisplay));
2742
2743 switch (mParameters.mode) {
2744 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002745 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002747 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002748 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002749 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002751 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 break;
2753 default:
2754 ALOG_ASSERT(false);
2755 }
2756
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002757 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 toString(mParameters.orientationAware));
2759}
2760
2761void CursorInputMapper::reset(nsecs_t when) {
2762 mButtonState = 0;
2763 mDownTime = 0;
2764
2765 mPointerVelocityControl.reset();
2766 mWheelXVelocityControl.reset();
2767 mWheelYVelocityControl.reset();
2768
2769 mCursorButtonAccumulator.reset(getDevice());
2770 mCursorMotionAccumulator.reset(getDevice());
2771 mCursorScrollAccumulator.reset(getDevice());
2772
2773 InputMapper::reset(when);
2774}
2775
2776void CursorInputMapper::process(const RawEvent* rawEvent) {
2777 mCursorButtonAccumulator.process(rawEvent);
2778 mCursorMotionAccumulator.process(rawEvent);
2779 mCursorScrollAccumulator.process(rawEvent);
2780
2781 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2782 sync(rawEvent->when);
2783 }
2784}
2785
2786void CursorInputMapper::sync(nsecs_t when) {
2787 int32_t lastButtonState = mButtonState;
2788 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2789 mButtonState = currentButtonState;
2790
2791 bool wasDown = isPointerDown(lastButtonState);
2792 bool down = isPointerDown(currentButtonState);
2793 bool downChanged;
2794 if (!wasDown && down) {
2795 mDownTime = when;
2796 downChanged = true;
2797 } else if (wasDown && !down) {
2798 downChanged = true;
2799 } else {
2800 downChanged = false;
2801 }
2802 nsecs_t downTime = mDownTime;
2803 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002804 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2805 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806
2807 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2808 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2809 bool moved = deltaX != 0 || deltaY != 0;
2810
2811 // Rotate delta according to orientation if needed.
2812 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2813 && (deltaX != 0.0f || deltaY != 0.0f)) {
2814 rotateDelta(mOrientation, &deltaX, &deltaY);
2815 }
2816
2817 // Move the pointer.
2818 PointerProperties pointerProperties;
2819 pointerProperties.clear();
2820 pointerProperties.id = 0;
2821 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2822
2823 PointerCoords pointerCoords;
2824 pointerCoords.clear();
2825
2826 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2827 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2828 bool scrolled = vscroll != 0 || hscroll != 0;
2829
Yi Kong9b14ac62018-07-17 13:48:38 -07002830 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2831 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832
2833 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2834
2835 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002836 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 if (moved || scrolled || buttonsChanged) {
2838 mPointerController->setPresentation(
2839 PointerControllerInterface::PRESENTATION_POINTER);
2840
2841 if (moved) {
2842 mPointerController->move(deltaX, deltaY);
2843 }
2844
2845 if (buttonsChanged) {
2846 mPointerController->setButtonState(currentButtonState);
2847 }
2848
2849 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2850 }
2851
2852 float x, y;
2853 mPointerController->getPosition(&x, &y);
2854 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2855 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002856 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2857 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 displayId = ADISPLAY_ID_DEFAULT;
2859 } else {
2860 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2861 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2862 displayId = ADISPLAY_ID_NONE;
2863 }
2864
2865 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2866
2867 // Moving an external trackball or mouse should wake the device.
2868 // We don't do this for internal cursor devices to prevent them from waking up
2869 // the device in your pocket.
2870 // TODO: Use the input device configuration to control this behavior more finely.
2871 uint32_t policyFlags = 0;
2872 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002873 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874 }
2875
2876 // Synthesize key down from buttons if needed.
2877 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002878 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879
2880 // Send motion event.
2881 if (downChanged || moved || scrolled || buttonsChanged) {
2882 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002883 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884 int32_t motionEventAction;
2885 if (downChanged) {
2886 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002887 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2889 } else {
2890 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2891 }
2892
Michael Wright7b159c92015-05-14 14:48:03 +01002893 if (buttonsReleased) {
2894 BitSet32 released(buttonsReleased);
2895 while (!released.isEmpty()) {
2896 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2897 buttonState &= ~actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002898 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002899 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2900 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002901 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002902 mXPrecision, mYPrecision, downTime);
2903 getListener()->notifyMotion(&releaseArgs);
2904 }
2905 }
2906
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002907 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002908 motionEventAction, 0, 0, metaState, currentButtonState,
2909 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002910 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911 mXPrecision, mYPrecision, downTime);
2912 getListener()->notifyMotion(&args);
2913
Michael Wright7b159c92015-05-14 14:48:03 +01002914 if (buttonsPressed) {
2915 BitSet32 pressed(buttonsPressed);
2916 while (!pressed.isEmpty()) {
2917 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2918 buttonState |= actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002919 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002920 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2921 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002922 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002923 mXPrecision, mYPrecision, downTime);
2924 getListener()->notifyMotion(&pressArgs);
2925 }
2926 }
2927
2928 ALOG_ASSERT(buttonState == currentButtonState);
2929
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 // Send hover move after UP to tell the application that the mouse is hovering now.
2931 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002932 && (mSource == AINPUT_SOURCE_MOUSE)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002933 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002934 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002936 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 mXPrecision, mYPrecision, downTime);
2938 getListener()->notifyMotion(&hoverArgs);
2939 }
2940
2941 // Send scroll events.
2942 if (scrolled) {
2943 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2944 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2945
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002946 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002947 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002949 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950 mXPrecision, mYPrecision, downTime);
2951 getListener()->notifyMotion(&scrollArgs);
2952 }
2953 }
2954
2955 // Synthesize key up from buttons if needed.
2956 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002957 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958
2959 mCursorMotionAccumulator.finishSync();
2960 mCursorScrollAccumulator.finishSync();
2961}
2962
2963int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2964 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2965 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2966 } else {
2967 return AKEY_STATE_UNKNOWN;
2968 }
2969}
2970
2971void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002972 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2974 }
2975}
2976
Prashant Malani1941ff52015-08-11 18:29:28 -07002977// --- RotaryEncoderInputMapper ---
2978
2979RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002980 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002981 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2982}
2983
2984RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2985}
2986
2987uint32_t RotaryEncoderInputMapper::getSources() {
2988 return mSource;
2989}
2990
2991void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2992 InputMapper::populateDeviceInfo(info);
2993
2994 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002995 float res = 0.0f;
2996 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2997 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2998 }
2999 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
3000 mScalingFactor)) {
3001 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
3002 "default to 1.0!\n");
3003 mScalingFactor = 1.0f;
3004 }
3005 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3006 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003007 }
3008}
3009
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003010void RotaryEncoderInputMapper::dump(std::string& dump) {
3011 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
3012 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07003013 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
3014}
3015
3016void RotaryEncoderInputMapper::configure(nsecs_t when,
3017 const InputReaderConfiguration* config, uint32_t changes) {
3018 InputMapper::configure(when, config, changes);
3019 if (!changes) {
3020 mRotaryEncoderScrollAccumulator.configure(getDevice());
3021 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07003022 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Ivan Podogovad437252016-09-29 16:29:55 +01003023 DisplayViewport v;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003024 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "", &v)) {
Ivan Podogovad437252016-09-29 16:29:55 +01003025 mOrientation = v.orientation;
3026 } else {
3027 mOrientation = DISPLAY_ORIENTATION_0;
3028 }
3029 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003030}
3031
3032void RotaryEncoderInputMapper::reset(nsecs_t when) {
3033 mRotaryEncoderScrollAccumulator.reset(getDevice());
3034
3035 InputMapper::reset(when);
3036}
3037
3038void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3039 mRotaryEncoderScrollAccumulator.process(rawEvent);
3040
3041 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3042 sync(rawEvent->when);
3043 }
3044}
3045
3046void RotaryEncoderInputMapper::sync(nsecs_t when) {
3047 PointerCoords pointerCoords;
3048 pointerCoords.clear();
3049
3050 PointerProperties pointerProperties;
3051 pointerProperties.clear();
3052 pointerProperties.id = 0;
3053 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3054
3055 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3056 bool scrolled = scroll != 0;
3057
3058 // This is not a pointer, so it's not associated with a display.
3059 int32_t displayId = ADISPLAY_ID_NONE;
3060
3061 // Moving the rotary encoder should wake the device (if specified).
3062 uint32_t policyFlags = 0;
3063 if (scrolled && getDevice()->isExternal()) {
3064 policyFlags |= POLICY_FLAG_WAKE;
3065 }
3066
Ivan Podogovad437252016-09-29 16:29:55 +01003067 if (mOrientation == DISPLAY_ORIENTATION_180) {
3068 scroll = -scroll;
3069 }
3070
Prashant Malani1941ff52015-08-11 18:29:28 -07003071 // Send motion event.
3072 if (scrolled) {
3073 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003074 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003075
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003076 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Prashant Malani1941ff52015-08-11 18:29:28 -07003077 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3078 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003079 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Prashant Malani1941ff52015-08-11 18:29:28 -07003080 0, 0, 0);
3081 getListener()->notifyMotion(&scrollArgs);
3082 }
3083
3084 mRotaryEncoderScrollAccumulator.finishSync();
3085}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086
3087// --- TouchInputMapper ---
3088
3089TouchInputMapper::TouchInputMapper(InputDevice* device) :
3090 InputMapper(device),
3091 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3092 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003093 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3095}
3096
3097TouchInputMapper::~TouchInputMapper() {
3098}
3099
3100uint32_t TouchInputMapper::getSources() {
3101 return mSource;
3102}
3103
3104void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3105 InputMapper::populateDeviceInfo(info);
3106
3107 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3108 info->addMotionRange(mOrientedRanges.x);
3109 info->addMotionRange(mOrientedRanges.y);
3110 info->addMotionRange(mOrientedRanges.pressure);
3111
3112 if (mOrientedRanges.haveSize) {
3113 info->addMotionRange(mOrientedRanges.size);
3114 }
3115
3116 if (mOrientedRanges.haveTouchSize) {
3117 info->addMotionRange(mOrientedRanges.touchMajor);
3118 info->addMotionRange(mOrientedRanges.touchMinor);
3119 }
3120
3121 if (mOrientedRanges.haveToolSize) {
3122 info->addMotionRange(mOrientedRanges.toolMajor);
3123 info->addMotionRange(mOrientedRanges.toolMinor);
3124 }
3125
3126 if (mOrientedRanges.haveOrientation) {
3127 info->addMotionRange(mOrientedRanges.orientation);
3128 }
3129
3130 if (mOrientedRanges.haveDistance) {
3131 info->addMotionRange(mOrientedRanges.distance);
3132 }
3133
3134 if (mOrientedRanges.haveTilt) {
3135 info->addMotionRange(mOrientedRanges.tilt);
3136 }
3137
3138 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3139 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3140 0.0f);
3141 }
3142 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3143 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3144 0.0f);
3145 }
3146 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3147 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3148 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3149 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3150 x.fuzz, x.resolution);
3151 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3152 y.fuzz, y.resolution);
3153 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3154 x.fuzz, x.resolution);
3155 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3156 y.fuzz, y.resolution);
3157 }
3158 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3159 }
3160}
3161
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003162void TouchInputMapper::dump(std::string& dump) {
3163 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 dumpParameters(dump);
3165 dumpVirtualKeys(dump);
3166 dumpRawPointerAxes(dump);
3167 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003168 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 dumpSurface(dump);
3170
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003171 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3172 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3173 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3174 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3175 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3176 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3177 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3178 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3179 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3180 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3181 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3182 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3183 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3184 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3185 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3186 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3187 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003189 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3190 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003191 mLastRawState.rawPointerData.pointerCount);
3192 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3193 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003194 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3196 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3197 "toolType=%d, isHovering=%s\n", i,
3198 pointer.id, pointer.x, pointer.y, pointer.pressure,
3199 pointer.touchMajor, pointer.touchMinor,
3200 pointer.toolMajor, pointer.toolMinor,
3201 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3202 pointer.toolType, toString(pointer.isHovering));
3203 }
3204
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003205 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3206 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003207 mLastCookedState.cookedPointerData.pointerCount);
3208 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3209 const PointerProperties& pointerProperties =
3210 mLastCookedState.cookedPointerData.pointerProperties[i];
3211 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003212 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3214 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3215 "toolType=%d, isHovering=%s\n", i,
3216 pointerProperties.id,
3217 pointerCoords.getX(),
3218 pointerCoords.getY(),
3219 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3220 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3221 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3222 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3223 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3224 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3225 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3226 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3227 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003228 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229 }
3230
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003231 dump += INDENT3 "Stylus Fusion:\n";
3232 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003233 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003234 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3235 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003236 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003237 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003238 dumpStylusState(dump, mExternalStylusState);
3239
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003241 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3242 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003244 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003246 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003248 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003250 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251 mPointerGestureMaxSwipeWidth);
3252 }
3253}
3254
Santos Cordonfa5cf462017-04-05 10:37:00 -07003255const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3256 switch (deviceMode) {
3257 case DEVICE_MODE_DISABLED:
3258 return "disabled";
3259 case DEVICE_MODE_DIRECT:
3260 return "direct";
3261 case DEVICE_MODE_UNSCALED:
3262 return "unscaled";
3263 case DEVICE_MODE_NAVIGATION:
3264 return "navigation";
3265 case DEVICE_MODE_POINTER:
3266 return "pointer";
3267 }
3268 return "unknown";
3269}
3270
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271void TouchInputMapper::configure(nsecs_t when,
3272 const InputReaderConfiguration* config, uint32_t changes) {
3273 InputMapper::configure(when, config, changes);
3274
3275 mConfig = *config;
3276
3277 if (!changes) { // first time only
3278 // Configure basic parameters.
3279 configureParameters();
3280
3281 // Configure common accumulators.
3282 mCursorScrollAccumulator.configure(getDevice());
3283 mTouchButtonAccumulator.configure(getDevice());
3284
3285 // Configure absolute axis information.
3286 configureRawPointerAxes();
3287
3288 // Prepare input device calibration.
3289 parseCalibration();
3290 resolveCalibration();
3291 }
3292
Michael Wright842500e2015-03-13 17:32:02 -07003293 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003294 // Update location calibration to reflect current settings
3295 updateAffineTransformation();
3296 }
3297
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3299 // Update pointer speed.
3300 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3301 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3302 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3303 }
3304
3305 bool resetNeeded = false;
3306 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3307 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003308 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3309 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 // Configure device sources, surface dimensions, orientation and
3311 // scaling factors.
3312 configureSurface(when, &resetNeeded);
3313 }
3314
3315 if (changes && resetNeeded) {
3316 // Send reset, unless this is the first time the device has been configured,
3317 // in which case the reader will call reset itself after all mappers are ready.
3318 getDevice()->notifyReset(when);
3319 }
3320}
3321
Michael Wright842500e2015-03-13 17:32:02 -07003322void TouchInputMapper::resolveExternalStylusPresence() {
3323 Vector<InputDeviceInfo> devices;
3324 mContext->getExternalStylusDevices(devices);
3325 mExternalStylusConnected = !devices.isEmpty();
3326
3327 if (!mExternalStylusConnected) {
3328 resetExternalStylus();
3329 }
3330}
3331
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332void TouchInputMapper::configureParameters() {
3333 // Use the pointer presentation mode for devices that do not support distinct
3334 // multitouch. The spot-based presentation relies on being able to accurately
3335 // locate two or more fingers on the touch pad.
3336 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003337 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338
3339 String8 gestureModeString;
3340 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3341 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003342 if (gestureModeString == "single-touch") {
3343 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3344 } else if (gestureModeString == "multi-touch") {
3345 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346 } else if (gestureModeString != "default") {
3347 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3348 }
3349 }
3350
3351 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3352 // The device is a touch screen.
3353 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3354 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3355 // The device is a pointing device like a track pad.
3356 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3357 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3358 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3359 // The device is a cursor device with a touch pad attached.
3360 // By default don't use the touch pad to move the pointer.
3361 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3362 } else {
3363 // The device is a touch pad of unknown purpose.
3364 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3365 }
3366
3367 mParameters.hasButtonUnderPad=
3368 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3369
3370 String8 deviceTypeString;
3371 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3372 deviceTypeString)) {
3373 if (deviceTypeString == "touchScreen") {
3374 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3375 } else if (deviceTypeString == "touchPad") {
3376 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3377 } else if (deviceTypeString == "touchNavigation") {
3378 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3379 } else if (deviceTypeString == "pointer") {
3380 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3381 } else if (deviceTypeString != "default") {
3382 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3383 }
3384 }
3385
3386 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3387 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3388 mParameters.orientationAware);
3389
3390 mParameters.hasAssociatedDisplay = false;
3391 mParameters.associatedDisplayIsExternal = false;
3392 if (mParameters.orientationAware
3393 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3394 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3395 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003396 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3397 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003398 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003399 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003400 uniqueDisplayId);
3401 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003404
3405 // Initial downs on external touch devices should wake the device.
3406 // Normally we don't do this for internal touch screens to prevent them from waking
3407 // up in your pocket but you can enable it using the input device configuration.
3408 mParameters.wake = getDevice()->isExternal();
3409 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3410 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411}
3412
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003413void TouchInputMapper::dumpParameters(std::string& dump) {
3414 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415
3416 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003417 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003418 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003420 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003421 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 break;
3423 default:
3424 assert(false);
3425 }
3426
3427 switch (mParameters.deviceType) {
3428 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003429 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 break;
3431 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003432 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 break;
3434 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003435 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 break;
3437 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003438 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 break;
3440 default:
3441 ALOG_ASSERT(false);
3442 }
3443
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003444 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003445 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003447 toString(mParameters.associatedDisplayIsExternal),
3448 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003449 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 toString(mParameters.orientationAware));
3451}
3452
3453void TouchInputMapper::configureRawPointerAxes() {
3454 mRawPointerAxes.clear();
3455}
3456
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003457void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3458 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3460 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3461 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3462 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3463 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3464 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3465 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3466 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3467 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3468 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3469 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3470 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3471 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3472}
3473
Michael Wright842500e2015-03-13 17:32:02 -07003474bool TouchInputMapper::hasExternalStylus() const {
3475 return mExternalStylusConnected;
3476}
3477
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3479 int32_t oldDeviceMode = mDeviceMode;
3480
Michael Wright842500e2015-03-13 17:32:02 -07003481 resolveExternalStylusPresence();
3482
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 // Determine device mode.
3484 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3485 && mConfig.pointerGesturesEnabled) {
3486 mSource = AINPUT_SOURCE_MOUSE;
3487 mDeviceMode = DEVICE_MODE_POINTER;
3488 if (hasStylus()) {
3489 mSource |= AINPUT_SOURCE_STYLUS;
3490 }
3491 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3492 && mParameters.hasAssociatedDisplay) {
3493 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3494 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003495 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 mSource |= AINPUT_SOURCE_STYLUS;
3497 }
Michael Wright2f78b682015-06-12 15:25:08 +01003498 if (hasExternalStylus()) {
3499 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3502 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3503 mDeviceMode = DEVICE_MODE_NAVIGATION;
3504 } else {
3505 mSource = AINPUT_SOURCE_TOUCHPAD;
3506 mDeviceMode = DEVICE_MODE_UNSCALED;
3507 }
3508
3509 // Ensure we have valid X and Y axes.
3510 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3511 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003512 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 mDeviceMode = DEVICE_MODE_DISABLED;
3514 return;
3515 }
3516
3517 // Raw width and height in the natural orientation.
3518 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3519 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3520
3521 // Get associated display dimensions.
3522 DisplayViewport newViewport;
3523 if (mParameters.hasAssociatedDisplay) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003524 std::string uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003525 ViewportType viewportTypeToUse;
3526
3527 if (mParameters.associatedDisplayIsExternal) {
3528 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003529 } else if (!mParameters.uniqueDisplayId.empty()) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003530 // If the IDC file specified a unique display Id, then it expects to be linked to a
3531 // virtual display with the same unique ID.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003532 uniqueDisplayId = mParameters.uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003533 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3534 } else {
3535 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3536 }
3537
3538 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3540 "display. The device will be inoperable until the display size "
3541 "becomes available.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003542 getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 mDeviceMode = DEVICE_MODE_DISABLED;
3544 return;
3545 }
3546 } else {
3547 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3548 }
3549 bool viewportChanged = mViewport != newViewport;
3550 if (viewportChanged) {
3551 mViewport = newViewport;
3552
3553 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3554 // Convert rotated viewport to natural surface coordinates.
3555 int32_t naturalLogicalWidth, naturalLogicalHeight;
3556 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3557 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3558 int32_t naturalDeviceWidth, naturalDeviceHeight;
3559 switch (mViewport.orientation) {
3560 case DISPLAY_ORIENTATION_90:
3561 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3562 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3563 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3564 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3565 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3566 naturalPhysicalTop = mViewport.physicalLeft;
3567 naturalDeviceWidth = mViewport.deviceHeight;
3568 naturalDeviceHeight = mViewport.deviceWidth;
3569 break;
3570 case DISPLAY_ORIENTATION_180:
3571 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3572 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3573 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3574 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3575 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3576 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3577 naturalDeviceWidth = mViewport.deviceWidth;
3578 naturalDeviceHeight = mViewport.deviceHeight;
3579 break;
3580 case DISPLAY_ORIENTATION_270:
3581 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3582 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3583 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3584 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3585 naturalPhysicalLeft = mViewport.physicalTop;
3586 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3587 naturalDeviceWidth = mViewport.deviceHeight;
3588 naturalDeviceHeight = mViewport.deviceWidth;
3589 break;
3590 case DISPLAY_ORIENTATION_0:
3591 default:
3592 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3593 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3594 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3595 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3596 naturalPhysicalLeft = mViewport.physicalLeft;
3597 naturalPhysicalTop = mViewport.physicalTop;
3598 naturalDeviceWidth = mViewport.deviceWidth;
3599 naturalDeviceHeight = mViewport.deviceHeight;
3600 break;
3601 }
3602
Michael Wright358bcc72018-08-21 04:01:07 +01003603 mPhysicalWidth = naturalPhysicalWidth;
3604 mPhysicalHeight = naturalPhysicalHeight;
3605 mPhysicalLeft = naturalPhysicalLeft;
3606 mPhysicalTop = naturalPhysicalTop;
3607
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3609 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3610 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3611 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3612
3613 mSurfaceOrientation = mParameters.orientationAware ?
3614 mViewport.orientation : DISPLAY_ORIENTATION_0;
3615 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003616 mPhysicalWidth = rawWidth;
3617 mPhysicalHeight = rawHeight;
3618 mPhysicalLeft = 0;
3619 mPhysicalTop = 0;
3620
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 mSurfaceWidth = rawWidth;
3622 mSurfaceHeight = rawHeight;
3623 mSurfaceLeft = 0;
3624 mSurfaceTop = 0;
3625 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3626 }
3627 }
3628
3629 // If moving between pointer modes, need to reset some state.
3630 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3631 if (deviceModeChanged) {
3632 mOrientedRanges.clear();
3633 }
3634
3635 // Create pointer controller if needed.
3636 if (mDeviceMode == DEVICE_MODE_POINTER ||
3637 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003638 if (mPointerController == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3640 }
3641 } else {
3642 mPointerController.clear();
3643 }
3644
3645 if (viewportChanged || deviceModeChanged) {
3646 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3647 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003648 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3650
3651 // Configure X and Y factors.
3652 mXScale = float(mSurfaceWidth) / rawWidth;
3653 mYScale = float(mSurfaceHeight) / rawHeight;
3654 mXTranslate = -mSurfaceLeft;
3655 mYTranslate = -mSurfaceTop;
3656 mXPrecision = 1.0f / mXScale;
3657 mYPrecision = 1.0f / mYScale;
3658
3659 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3660 mOrientedRanges.x.source = mSource;
3661 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3662 mOrientedRanges.y.source = mSource;
3663
3664 configureVirtualKeys();
3665
3666 // Scale factor for terms that are not oriented in a particular axis.
3667 // If the pixels are square then xScale == yScale otherwise we fake it
3668 // by choosing an average.
3669 mGeometricScale = avg(mXScale, mYScale);
3670
3671 // Size of diagonal axis.
3672 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3673
3674 // Size factors.
3675 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3676 if (mRawPointerAxes.touchMajor.valid
3677 && mRawPointerAxes.touchMajor.maxValue != 0) {
3678 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3679 } else if (mRawPointerAxes.toolMajor.valid
3680 && mRawPointerAxes.toolMajor.maxValue != 0) {
3681 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3682 } else {
3683 mSizeScale = 0.0f;
3684 }
3685
3686 mOrientedRanges.haveTouchSize = true;
3687 mOrientedRanges.haveToolSize = true;
3688 mOrientedRanges.haveSize = true;
3689
3690 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3691 mOrientedRanges.touchMajor.source = mSource;
3692 mOrientedRanges.touchMajor.min = 0;
3693 mOrientedRanges.touchMajor.max = diagonalSize;
3694 mOrientedRanges.touchMajor.flat = 0;
3695 mOrientedRanges.touchMajor.fuzz = 0;
3696 mOrientedRanges.touchMajor.resolution = 0;
3697
3698 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3699 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3700
3701 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3702 mOrientedRanges.toolMajor.source = mSource;
3703 mOrientedRanges.toolMajor.min = 0;
3704 mOrientedRanges.toolMajor.max = diagonalSize;
3705 mOrientedRanges.toolMajor.flat = 0;
3706 mOrientedRanges.toolMajor.fuzz = 0;
3707 mOrientedRanges.toolMajor.resolution = 0;
3708
3709 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3710 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3711
3712 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3713 mOrientedRanges.size.source = mSource;
3714 mOrientedRanges.size.min = 0;
3715 mOrientedRanges.size.max = 1.0;
3716 mOrientedRanges.size.flat = 0;
3717 mOrientedRanges.size.fuzz = 0;
3718 mOrientedRanges.size.resolution = 0;
3719 } else {
3720 mSizeScale = 0.0f;
3721 }
3722
3723 // Pressure factors.
3724 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003725 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3727 || mCalibration.pressureCalibration
3728 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3729 if (mCalibration.havePressureScale) {
3730 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003731 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 } else if (mRawPointerAxes.pressure.valid
3733 && mRawPointerAxes.pressure.maxValue != 0) {
3734 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3735 }
3736 }
3737
3738 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3739 mOrientedRanges.pressure.source = mSource;
3740 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003741 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 mOrientedRanges.pressure.flat = 0;
3743 mOrientedRanges.pressure.fuzz = 0;
3744 mOrientedRanges.pressure.resolution = 0;
3745
3746 // Tilt
3747 mTiltXCenter = 0;
3748 mTiltXScale = 0;
3749 mTiltYCenter = 0;
3750 mTiltYScale = 0;
3751 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3752 if (mHaveTilt) {
3753 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3754 mRawPointerAxes.tiltX.maxValue);
3755 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3756 mRawPointerAxes.tiltY.maxValue);
3757 mTiltXScale = M_PI / 180;
3758 mTiltYScale = M_PI / 180;
3759
3760 mOrientedRanges.haveTilt = true;
3761
3762 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3763 mOrientedRanges.tilt.source = mSource;
3764 mOrientedRanges.tilt.min = 0;
3765 mOrientedRanges.tilt.max = M_PI_2;
3766 mOrientedRanges.tilt.flat = 0;
3767 mOrientedRanges.tilt.fuzz = 0;
3768 mOrientedRanges.tilt.resolution = 0;
3769 }
3770
3771 // Orientation
3772 mOrientationScale = 0;
3773 if (mHaveTilt) {
3774 mOrientedRanges.haveOrientation = true;
3775
3776 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3777 mOrientedRanges.orientation.source = mSource;
3778 mOrientedRanges.orientation.min = -M_PI;
3779 mOrientedRanges.orientation.max = M_PI;
3780 mOrientedRanges.orientation.flat = 0;
3781 mOrientedRanges.orientation.fuzz = 0;
3782 mOrientedRanges.orientation.resolution = 0;
3783 } else if (mCalibration.orientationCalibration !=
3784 Calibration::ORIENTATION_CALIBRATION_NONE) {
3785 if (mCalibration.orientationCalibration
3786 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3787 if (mRawPointerAxes.orientation.valid) {
3788 if (mRawPointerAxes.orientation.maxValue > 0) {
3789 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3790 } else if (mRawPointerAxes.orientation.minValue < 0) {
3791 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3792 } else {
3793 mOrientationScale = 0;
3794 }
3795 }
3796 }
3797
3798 mOrientedRanges.haveOrientation = true;
3799
3800 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3801 mOrientedRanges.orientation.source = mSource;
3802 mOrientedRanges.orientation.min = -M_PI_2;
3803 mOrientedRanges.orientation.max = M_PI_2;
3804 mOrientedRanges.orientation.flat = 0;
3805 mOrientedRanges.orientation.fuzz = 0;
3806 mOrientedRanges.orientation.resolution = 0;
3807 }
3808
3809 // Distance
3810 mDistanceScale = 0;
3811 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3812 if (mCalibration.distanceCalibration
3813 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3814 if (mCalibration.haveDistanceScale) {
3815 mDistanceScale = mCalibration.distanceScale;
3816 } else {
3817 mDistanceScale = 1.0f;
3818 }
3819 }
3820
3821 mOrientedRanges.haveDistance = true;
3822
3823 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3824 mOrientedRanges.distance.source = mSource;
3825 mOrientedRanges.distance.min =
3826 mRawPointerAxes.distance.minValue * mDistanceScale;
3827 mOrientedRanges.distance.max =
3828 mRawPointerAxes.distance.maxValue * mDistanceScale;
3829 mOrientedRanges.distance.flat = 0;
3830 mOrientedRanges.distance.fuzz =
3831 mRawPointerAxes.distance.fuzz * mDistanceScale;
3832 mOrientedRanges.distance.resolution = 0;
3833 }
3834
3835 // Compute oriented precision, scales and ranges.
3836 // Note that the maximum value reported is an inclusive maximum value so it is one
3837 // unit less than the total width or height of surface.
3838 switch (mSurfaceOrientation) {
3839 case DISPLAY_ORIENTATION_90:
3840 case DISPLAY_ORIENTATION_270:
3841 mOrientedXPrecision = mYPrecision;
3842 mOrientedYPrecision = mXPrecision;
3843
3844 mOrientedRanges.x.min = mYTranslate;
3845 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3846 mOrientedRanges.x.flat = 0;
3847 mOrientedRanges.x.fuzz = 0;
3848 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3849
3850 mOrientedRanges.y.min = mXTranslate;
3851 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3852 mOrientedRanges.y.flat = 0;
3853 mOrientedRanges.y.fuzz = 0;
3854 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3855 break;
3856
3857 default:
3858 mOrientedXPrecision = mXPrecision;
3859 mOrientedYPrecision = mYPrecision;
3860
3861 mOrientedRanges.x.min = mXTranslate;
3862 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3863 mOrientedRanges.x.flat = 0;
3864 mOrientedRanges.x.fuzz = 0;
3865 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3866
3867 mOrientedRanges.y.min = mYTranslate;
3868 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3869 mOrientedRanges.y.flat = 0;
3870 mOrientedRanges.y.fuzz = 0;
3871 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3872 break;
3873 }
3874
Jason Gerecke71b16e82014-03-10 09:47:59 -07003875 // Location
3876 updateAffineTransformation();
3877
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878 if (mDeviceMode == DEVICE_MODE_POINTER) {
3879 // Compute pointer gesture detection parameters.
3880 float rawDiagonal = hypotf(rawWidth, rawHeight);
3881 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3882
3883 // Scale movements such that one whole swipe of the touch pad covers a
3884 // given area relative to the diagonal size of the display when no acceleration
3885 // is applied.
3886 // Assume that the touch pad has a square aspect ratio such that movements in
3887 // X and Y of the same number of raw units cover the same physical distance.
3888 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3889 * displayDiagonal / rawDiagonal;
3890 mPointerYMovementScale = mPointerXMovementScale;
3891
3892 // Scale zooms to cover a smaller range of the display than movements do.
3893 // This value determines the area around the pointer that is affected by freeform
3894 // pointer gestures.
3895 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3896 * displayDiagonal / rawDiagonal;
3897 mPointerYZoomScale = mPointerXZoomScale;
3898
3899 // Max width between pointers to detect a swipe gesture is more than some fraction
3900 // of the diagonal axis of the touch pad. Touches that are wider than this are
3901 // translated into freeform gestures.
3902 mPointerGestureMaxSwipeWidth =
3903 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3904
3905 // Abort current pointer usages because the state has changed.
3906 abortPointerUsage(when, 0 /*policyFlags*/);
3907 }
3908
3909 // Inform the dispatcher about the changes.
3910 *outResetNeeded = true;
3911 bumpGeneration();
3912 }
3913}
3914
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003915void TouchInputMapper::dumpSurface(std::string& dump) {
3916 dump += StringPrintf(INDENT3 "Viewport: displayId=%d, orientation=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 "logicalFrame=[%d, %d, %d, %d], "
3918 "physicalFrame=[%d, %d, %d, %d], "
3919 "deviceSize=[%d, %d]\n",
3920 mViewport.displayId, mViewport.orientation,
3921 mViewport.logicalLeft, mViewport.logicalTop,
3922 mViewport.logicalRight, mViewport.logicalBottom,
3923 mViewport.physicalLeft, mViewport.physicalTop,
3924 mViewport.physicalRight, mViewport.physicalBottom,
3925 mViewport.deviceWidth, mViewport.deviceHeight);
3926
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003927 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3928 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3929 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3930 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003931 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3932 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3933 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3934 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003935 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936}
3937
3938void TouchInputMapper::configureVirtualKeys() {
3939 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3940 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3941
3942 mVirtualKeys.clear();
3943
3944 if (virtualKeyDefinitions.size() == 0) {
3945 return;
3946 }
3947
3948 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3949
3950 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3951 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3952 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3953 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3954
3955 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3956 const VirtualKeyDefinition& virtualKeyDefinition =
3957 virtualKeyDefinitions[i];
3958
3959 mVirtualKeys.add();
3960 VirtualKey& virtualKey = mVirtualKeys.editTop();
3961
3962 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3963 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003964 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003966 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3967 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3969 virtualKey.scanCode);
3970 mVirtualKeys.pop(); // drop the key
3971 continue;
3972 }
3973
3974 virtualKey.keyCode = keyCode;
3975 virtualKey.flags = flags;
3976
3977 // convert the key definition's display coordinates into touch coordinates for a hit box
3978 int32_t halfWidth = virtualKeyDefinition.width / 2;
3979 int32_t halfHeight = virtualKeyDefinition.height / 2;
3980
3981 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3982 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3983 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3984 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3985 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3986 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3987 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3988 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3989 }
3990}
3991
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003992void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003994 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995
3996 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3997 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003998 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
4000 i, virtualKey.scanCode, virtualKey.keyCode,
4001 virtualKey.hitLeft, virtualKey.hitRight,
4002 virtualKey.hitTop, virtualKey.hitBottom);
4003 }
4004 }
4005}
4006
4007void TouchInputMapper::parseCalibration() {
4008 const PropertyMap& in = getDevice()->getConfiguration();
4009 Calibration& out = mCalibration;
4010
4011 // Size
4012 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4013 String8 sizeCalibrationString;
4014 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4015 if (sizeCalibrationString == "none") {
4016 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4017 } else if (sizeCalibrationString == "geometric") {
4018 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4019 } else if (sizeCalibrationString == "diameter") {
4020 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4021 } else if (sizeCalibrationString == "box") {
4022 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4023 } else if (sizeCalibrationString == "area") {
4024 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4025 } else if (sizeCalibrationString != "default") {
4026 ALOGW("Invalid value for touch.size.calibration: '%s'",
4027 sizeCalibrationString.string());
4028 }
4029 }
4030
4031 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4032 out.sizeScale);
4033 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4034 out.sizeBias);
4035 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4036 out.sizeIsSummed);
4037
4038 // Pressure
4039 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4040 String8 pressureCalibrationString;
4041 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4042 if (pressureCalibrationString == "none") {
4043 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4044 } else if (pressureCalibrationString == "physical") {
4045 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4046 } else if (pressureCalibrationString == "amplitude") {
4047 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4048 } else if (pressureCalibrationString != "default") {
4049 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4050 pressureCalibrationString.string());
4051 }
4052 }
4053
4054 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4055 out.pressureScale);
4056
4057 // Orientation
4058 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4059 String8 orientationCalibrationString;
4060 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4061 if (orientationCalibrationString == "none") {
4062 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4063 } else if (orientationCalibrationString == "interpolated") {
4064 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4065 } else if (orientationCalibrationString == "vector") {
4066 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4067 } else if (orientationCalibrationString != "default") {
4068 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4069 orientationCalibrationString.string());
4070 }
4071 }
4072
4073 // Distance
4074 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4075 String8 distanceCalibrationString;
4076 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4077 if (distanceCalibrationString == "none") {
4078 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4079 } else if (distanceCalibrationString == "scaled") {
4080 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4081 } else if (distanceCalibrationString != "default") {
4082 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4083 distanceCalibrationString.string());
4084 }
4085 }
4086
4087 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4088 out.distanceScale);
4089
4090 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4091 String8 coverageCalibrationString;
4092 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4093 if (coverageCalibrationString == "none") {
4094 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4095 } else if (coverageCalibrationString == "box") {
4096 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4097 } else if (coverageCalibrationString != "default") {
4098 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4099 coverageCalibrationString.string());
4100 }
4101 }
4102}
4103
4104void TouchInputMapper::resolveCalibration() {
4105 // Size
4106 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4107 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4108 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4109 }
4110 } else {
4111 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4112 }
4113
4114 // Pressure
4115 if (mRawPointerAxes.pressure.valid) {
4116 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4117 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4118 }
4119 } else {
4120 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4121 }
4122
4123 // Orientation
4124 if (mRawPointerAxes.orientation.valid) {
4125 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4126 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4127 }
4128 } else {
4129 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4130 }
4131
4132 // Distance
4133 if (mRawPointerAxes.distance.valid) {
4134 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4135 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4136 }
4137 } else {
4138 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4139 }
4140
4141 // Coverage
4142 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4143 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4144 }
4145}
4146
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004147void TouchInputMapper::dumpCalibration(std::string& dump) {
4148 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149
4150 // Size
4151 switch (mCalibration.sizeCalibration) {
4152 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004153 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 break;
4155 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 break;
4158 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004159 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 break;
4161 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004162 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 break;
4164 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004165 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 break;
4167 default:
4168 ALOG_ASSERT(false);
4169 }
4170
4171 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004172 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 mCalibration.sizeScale);
4174 }
4175
4176 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 mCalibration.sizeBias);
4179 }
4180
4181 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004182 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 toString(mCalibration.sizeIsSummed));
4184 }
4185
4186 // Pressure
4187 switch (mCalibration.pressureCalibration) {
4188 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004189 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 break;
4191 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 break;
4194 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004195 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 break;
4197 default:
4198 ALOG_ASSERT(false);
4199 }
4200
4201 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004202 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 mCalibration.pressureScale);
4204 }
4205
4206 // Orientation
4207 switch (mCalibration.orientationCalibration) {
4208 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004209 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 break;
4211 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 break;
4214 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004215 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216 break;
4217 default:
4218 ALOG_ASSERT(false);
4219 }
4220
4221 // Distance
4222 switch (mCalibration.distanceCalibration) {
4223 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004224 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 break;
4226 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004227 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 break;
4229 default:
4230 ALOG_ASSERT(false);
4231 }
4232
4233 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004234 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 mCalibration.distanceScale);
4236 }
4237
4238 switch (mCalibration.coverageCalibration) {
4239 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004240 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 break;
4242 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004243 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 break;
4245 default:
4246 ALOG_ASSERT(false);
4247 }
4248}
4249
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004250void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4251 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004252
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004253 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4254 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4255 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4256 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4257 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4258 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004259}
4260
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004261void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004262 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4263 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004264}
4265
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266void TouchInputMapper::reset(nsecs_t when) {
4267 mCursorButtonAccumulator.reset(getDevice());
4268 mCursorScrollAccumulator.reset(getDevice());
4269 mTouchButtonAccumulator.reset(getDevice());
4270
4271 mPointerVelocityControl.reset();
4272 mWheelXVelocityControl.reset();
4273 mWheelYVelocityControl.reset();
4274
Michael Wright842500e2015-03-13 17:32:02 -07004275 mRawStatesPending.clear();
4276 mCurrentRawState.clear();
4277 mCurrentCookedState.clear();
4278 mLastRawState.clear();
4279 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 mPointerUsage = POINTER_USAGE_NONE;
4281 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004282 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004283 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 mDownTime = 0;
4285
4286 mCurrentVirtualKey.down = false;
4287
4288 mPointerGesture.reset();
4289 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004290 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291
Yi Kong9b14ac62018-07-17 13:48:38 -07004292 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4294 mPointerController->clearSpots();
4295 }
4296
4297 InputMapper::reset(when);
4298}
4299
Michael Wright842500e2015-03-13 17:32:02 -07004300void TouchInputMapper::resetExternalStylus() {
4301 mExternalStylusState.clear();
4302 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004303 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004304 mExternalStylusDataPending = false;
4305}
4306
Michael Wright43fd19f2015-04-21 19:02:58 +01004307void TouchInputMapper::clearStylusDataPendingFlags() {
4308 mExternalStylusDataPending = false;
4309 mExternalStylusFusionTimeout = LLONG_MAX;
4310}
4311
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312void TouchInputMapper::process(const RawEvent* rawEvent) {
4313 mCursorButtonAccumulator.process(rawEvent);
4314 mCursorScrollAccumulator.process(rawEvent);
4315 mTouchButtonAccumulator.process(rawEvent);
4316
4317 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4318 sync(rawEvent->when);
4319 }
4320}
4321
4322void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004323 const RawState* last = mRawStatesPending.isEmpty() ?
4324 &mCurrentRawState : &mRawStatesPending.top();
4325
4326 // Push a new state.
4327 mRawStatesPending.push();
4328 RawState* next = &mRawStatesPending.editTop();
4329 next->clear();
4330 next->when = when;
4331
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004333 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 | mCursorButtonAccumulator.getButtonState();
4335
Michael Wright842500e2015-03-13 17:32:02 -07004336 // Sync scroll
4337 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4338 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 mCursorScrollAccumulator.finishSync();
4340
Michael Wright842500e2015-03-13 17:32:02 -07004341 // Sync touch
4342 syncTouch(when, next);
4343
4344 // Assign pointer ids.
4345 if (!mHavePointerIds) {
4346 assignPointerIds(last, next);
4347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348
4349#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004350 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4351 "hovering ids 0x%08x -> 0x%08x",
4352 last->rawPointerData.pointerCount,
4353 next->rawPointerData.pointerCount,
4354 last->rawPointerData.touchingIdBits.value,
4355 next->rawPointerData.touchingIdBits.value,
4356 last->rawPointerData.hoveringIdBits.value,
4357 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358#endif
4359
Michael Wright842500e2015-03-13 17:32:02 -07004360 processRawTouches(false /*timeout*/);
4361}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362
Michael Wright842500e2015-03-13 17:32:02 -07004363void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4365 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004366 mCurrentRawState.clear();
4367 mRawStatesPending.clear();
4368 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 }
4370
Michael Wright842500e2015-03-13 17:32:02 -07004371 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4372 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4373 // touching the current state will only observe the events that have been dispatched to the
4374 // rest of the pipeline.
4375 const size_t N = mRawStatesPending.size();
4376 size_t count;
4377 for(count = 0; count < N; count++) {
4378 const RawState& next = mRawStatesPending[count];
4379
4380 // A failure to assign the stylus id means that we're waiting on stylus data
4381 // and so should defer the rest of the pipeline.
4382 if (assignExternalStylusId(next, timeout)) {
4383 break;
4384 }
4385
4386 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004387 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004388 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004389 if (mCurrentRawState.when < mLastRawState.when) {
4390 mCurrentRawState.when = mLastRawState.when;
4391 }
Michael Wright842500e2015-03-13 17:32:02 -07004392 cookAndDispatch(mCurrentRawState.when);
4393 }
4394 if (count != 0) {
4395 mRawStatesPending.removeItemsAt(0, count);
4396 }
4397
Michael Wright842500e2015-03-13 17:32:02 -07004398 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004399 if (timeout) {
4400 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4401 clearStylusDataPendingFlags();
4402 mCurrentRawState.copyFrom(mLastRawState);
4403#if DEBUG_STYLUS_FUSION
4404 ALOGD("Timeout expired, synthesizing event with new stylus data");
4405#endif
4406 cookAndDispatch(when);
4407 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4408 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4409 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4410 }
Michael Wright842500e2015-03-13 17:32:02 -07004411 }
4412}
4413
4414void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4415 // Always start with a clean state.
4416 mCurrentCookedState.clear();
4417
4418 // Apply stylus buttons to current raw state.
4419 applyExternalStylusButtonState(when);
4420
4421 // Handle policy on initial down or hover events.
4422 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4423 && mCurrentRawState.rawPointerData.pointerCount != 0;
4424
4425 uint32_t policyFlags = 0;
4426 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4427 if (initialDown || buttonsPressed) {
4428 // If this is a touch screen, hide the pointer on an initial down.
4429 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4430 getContext()->fadePointer();
4431 }
4432
4433 if (mParameters.wake) {
4434 policyFlags |= POLICY_FLAG_WAKE;
4435 }
4436 }
4437
4438 // Consume raw off-screen touches before cooking pointer data.
4439 // If touches are consumed, subsequent code will not receive any pointer data.
4440 if (consumeRawTouches(when, policyFlags)) {
4441 mCurrentRawState.rawPointerData.clear();
4442 }
4443
4444 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4445 // with cooked pointer data that has the same ids and indices as the raw data.
4446 // The following code can use either the raw or cooked data, as needed.
4447 cookPointerData();
4448
4449 // Apply stylus pressure to current cooked state.
4450 applyExternalStylusTouchState(when);
4451
4452 // Synthesize key down from raw buttons if needed.
4453 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004454 mViewport.displayId, policyFlags,
4455 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004456
4457 // Dispatch the touches either directly or by translation through a pointer on screen.
4458 if (mDeviceMode == DEVICE_MODE_POINTER) {
4459 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4460 !idBits.isEmpty(); ) {
4461 uint32_t id = idBits.clearFirstMarkedBit();
4462 const RawPointerData::Pointer& pointer =
4463 mCurrentRawState.rawPointerData.pointerForId(id);
4464 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4465 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4466 mCurrentCookedState.stylusIdBits.markBit(id);
4467 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4468 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4469 mCurrentCookedState.fingerIdBits.markBit(id);
4470 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4471 mCurrentCookedState.mouseIdBits.markBit(id);
4472 }
4473 }
4474 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4475 !idBits.isEmpty(); ) {
4476 uint32_t id = idBits.clearFirstMarkedBit();
4477 const RawPointerData::Pointer& pointer =
4478 mCurrentRawState.rawPointerData.pointerForId(id);
4479 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4480 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4481 mCurrentCookedState.stylusIdBits.markBit(id);
4482 }
4483 }
4484
4485 // Stylus takes precedence over all tools, then mouse, then finger.
4486 PointerUsage pointerUsage = mPointerUsage;
4487 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4488 mCurrentCookedState.mouseIdBits.clear();
4489 mCurrentCookedState.fingerIdBits.clear();
4490 pointerUsage = POINTER_USAGE_STYLUS;
4491 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4492 mCurrentCookedState.fingerIdBits.clear();
4493 pointerUsage = POINTER_USAGE_MOUSE;
4494 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4495 isPointerDown(mCurrentRawState.buttonState)) {
4496 pointerUsage = POINTER_USAGE_GESTURES;
4497 }
4498
4499 dispatchPointerUsage(when, policyFlags, pointerUsage);
4500 } else {
4501 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004502 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004503 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4504 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4505
4506 mPointerController->setButtonState(mCurrentRawState.buttonState);
4507 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4508 mCurrentCookedState.cookedPointerData.idToIndex,
4509 mCurrentCookedState.cookedPointerData.touchingIdBits);
4510 }
4511
Michael Wright8e812822015-06-22 16:18:21 +01004512 if (!mCurrentMotionAborted) {
4513 dispatchButtonRelease(when, policyFlags);
4514 dispatchHoverExit(when, policyFlags);
4515 dispatchTouches(when, policyFlags);
4516 dispatchHoverEnterAndMove(when, policyFlags);
4517 dispatchButtonPress(when, policyFlags);
4518 }
4519
4520 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4521 mCurrentMotionAborted = false;
4522 }
Michael Wright842500e2015-03-13 17:32:02 -07004523 }
4524
4525 // Synthesize key up from raw buttons if needed.
4526 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004527 mViewport.displayId, policyFlags,
4528 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529
4530 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004531 mCurrentRawState.rawVScroll = 0;
4532 mCurrentRawState.rawHScroll = 0;
4533
4534 // Copy current touch to last touch in preparation for the next cycle.
4535 mLastRawState.copyFrom(mCurrentRawState);
4536 mLastCookedState.copyFrom(mCurrentCookedState);
4537}
4538
4539void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004540 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004541 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4542 }
4543}
4544
4545void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004546 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4547 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004548
Michael Wright53dca3a2015-04-23 17:39:53 +01004549 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4550 float pressure = mExternalStylusState.pressure;
4551 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4552 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4553 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4554 }
4555 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4556 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4557
4558 PointerProperties& properties =
4559 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004560 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4561 properties.toolType = mExternalStylusState.toolType;
4562 }
4563 }
4564}
4565
4566bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4567 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4568 return false;
4569 }
4570
4571 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4572 && state.rawPointerData.pointerCount != 0;
4573 if (initialDown) {
4574 if (mExternalStylusState.pressure != 0.0f) {
4575#if DEBUG_STYLUS_FUSION
4576 ALOGD("Have both stylus and touch data, beginning fusion");
4577#endif
4578 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4579 } else if (timeout) {
4580#if DEBUG_STYLUS_FUSION
4581 ALOGD("Timeout expired, assuming touch is not a stylus.");
4582#endif
4583 resetExternalStylus();
4584 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004585 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4586 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004587 }
4588#if DEBUG_STYLUS_FUSION
4589 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004590 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004591#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004592 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004593 return true;
4594 }
4595 }
4596
4597 // Check if the stylus pointer has gone up.
4598 if (mExternalStylusId != -1 &&
4599 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4600#if DEBUG_STYLUS_FUSION
4601 ALOGD("Stylus pointer is going up");
4602#endif
4603 mExternalStylusId = -1;
4604 }
4605
4606 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607}
4608
4609void TouchInputMapper::timeoutExpired(nsecs_t when) {
4610 if (mDeviceMode == DEVICE_MODE_POINTER) {
4611 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4612 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4613 }
Michael Wright842500e2015-03-13 17:32:02 -07004614 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004615 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004616 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004617 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4618 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004619 }
4620 }
4621}
4622
4623void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004624 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004625 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004626 // We're either in the middle of a fused stream of data or we're waiting on data before
4627 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4628 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004629 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004630 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 }
4632}
4633
4634bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4635 // Check for release of a virtual key.
4636 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004637 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638 // Pointer went up while virtual key was down.
4639 mCurrentVirtualKey.down = false;
4640 if (!mCurrentVirtualKey.ignored) {
4641#if DEBUG_VIRTUAL_KEYS
4642 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4643 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4644#endif
4645 dispatchVirtualKey(when, policyFlags,
4646 AKEY_EVENT_ACTION_UP,
4647 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4648 }
4649 return true;
4650 }
4651
Michael Wright842500e2015-03-13 17:32:02 -07004652 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4653 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4654 const RawPointerData::Pointer& pointer =
4655 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4657 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4658 // Pointer is still within the space of the virtual key.
4659 return true;
4660 }
4661 }
4662
4663 // Pointer left virtual key area or another pointer also went down.
4664 // Send key cancellation but do not consume the touch yet.
4665 // This is useful when the user swipes through from the virtual key area
4666 // into the main display surface.
4667 mCurrentVirtualKey.down = false;
4668 if (!mCurrentVirtualKey.ignored) {
4669#if DEBUG_VIRTUAL_KEYS
4670 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4671 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4672#endif
4673 dispatchVirtualKey(when, policyFlags,
4674 AKEY_EVENT_ACTION_UP,
4675 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4676 | AKEY_EVENT_FLAG_CANCELED);
4677 }
4678 }
4679
Michael Wright842500e2015-03-13 17:32:02 -07004680 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4681 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004683 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4684 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4686 // If exactly one pointer went down, check for virtual key hit.
4687 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004688 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4690 if (virtualKey) {
4691 mCurrentVirtualKey.down = true;
4692 mCurrentVirtualKey.downTime = when;
4693 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4694 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4695 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4696 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4697
4698 if (!mCurrentVirtualKey.ignored) {
4699#if DEBUG_VIRTUAL_KEYS
4700 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4701 mCurrentVirtualKey.keyCode,
4702 mCurrentVirtualKey.scanCode);
4703#endif
4704 dispatchVirtualKey(when, policyFlags,
4705 AKEY_EVENT_ACTION_DOWN,
4706 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4707 }
4708 }
4709 }
4710 return true;
4711 }
4712 }
4713
4714 // Disable all virtual key touches that happen within a short time interval of the
4715 // most recent touch within the screen area. The idea is to filter out stray
4716 // virtual key presses when interacting with the touch screen.
4717 //
4718 // Problems we're trying to solve:
4719 //
4720 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4721 // virtual key area that is implemented by a separate touch panel and accidentally
4722 // triggers a virtual key.
4723 //
4724 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4725 // area and accidentally triggers a virtual key. This often happens when virtual keys
4726 // are layed out below the screen near to where the on screen keyboard's space bar
4727 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004728 if (mConfig.virtualKeyQuietTime > 0 &&
4729 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4731 }
4732 return false;
4733}
4734
4735void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4736 int32_t keyEventAction, int32_t keyEventFlags) {
4737 int32_t keyCode = mCurrentVirtualKey.keyCode;
4738 int32_t scanCode = mCurrentVirtualKey.scanCode;
4739 nsecs_t downTime = mCurrentVirtualKey.downTime;
4740 int32_t metaState = mContext->getGlobalMetaState();
4741 policyFlags |= POLICY_FLAG_VIRTUAL;
4742
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004743 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId,
4744 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 getListener()->notifyKey(&args);
4746}
4747
Michael Wright8e812822015-06-22 16:18:21 +01004748void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4749 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4750 if (!currentIdBits.isEmpty()) {
4751 int32_t metaState = getContext()->getGlobalMetaState();
4752 int32_t buttonState = mCurrentCookedState.buttonState;
4753 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4754 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004755 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004756 mCurrentCookedState.cookedPointerData.pointerProperties,
4757 mCurrentCookedState.cookedPointerData.pointerCoords,
4758 mCurrentCookedState.cookedPointerData.idToIndex,
4759 currentIdBits, -1,
4760 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4761 mCurrentMotionAborted = true;
4762 }
4763}
4764
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004766 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4767 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004769 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770
4771 if (currentIdBits == lastIdBits) {
4772 if (!currentIdBits.isEmpty()) {
4773 // No pointer id changes so this is a move event.
4774 // The listener takes care of batching moves so we don't have to deal with that here.
4775 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004776 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004778 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004779 mCurrentCookedState.cookedPointerData.pointerProperties,
4780 mCurrentCookedState.cookedPointerData.pointerCoords,
4781 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 currentIdBits, -1,
4783 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4784 }
4785 } else {
4786 // There may be pointers going up and pointers going down and pointers moving
4787 // all at the same time.
4788 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4789 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4790 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4791 BitSet32 dispatchedIdBits(lastIdBits.value);
4792
4793 // Update last coordinates of pointers that have moved so that we observe the new
4794 // pointer positions at the same time as other pointers that have just gone up.
4795 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004796 mCurrentCookedState.cookedPointerData.pointerProperties,
4797 mCurrentCookedState.cookedPointerData.pointerCoords,
4798 mCurrentCookedState.cookedPointerData.idToIndex,
4799 mLastCookedState.cookedPointerData.pointerProperties,
4800 mLastCookedState.cookedPointerData.pointerCoords,
4801 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004803 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 moveNeeded = true;
4805 }
4806
4807 // Dispatch pointer up events.
4808 while (!upIdBits.isEmpty()) {
4809 uint32_t upId = upIdBits.clearFirstMarkedBit();
4810
4811 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004812 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004813 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004814 mLastCookedState.cookedPointerData.pointerProperties,
4815 mLastCookedState.cookedPointerData.pointerCoords,
4816 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004817 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 dispatchedIdBits.clearBit(upId);
4819 }
4820
4821 // Dispatch move events if any of the remaining pointers moved from their old locations.
4822 // Although applications receive new locations as part of individual pointer up
4823 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004824 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4826 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004827 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004828 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004829 mCurrentCookedState.cookedPointerData.pointerProperties,
4830 mCurrentCookedState.cookedPointerData.pointerCoords,
4831 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004832 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 }
4834
4835 // Dispatch pointer down events using the new pointer locations.
4836 while (!downIdBits.isEmpty()) {
4837 uint32_t downId = downIdBits.clearFirstMarkedBit();
4838 dispatchedIdBits.markBit(downId);
4839
4840 if (dispatchedIdBits.count() == 1) {
4841 // First pointer is going down. Set down time.
4842 mDownTime = when;
4843 }
4844
4845 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004846 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004847 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004848 mCurrentCookedState.cookedPointerData.pointerProperties,
4849 mCurrentCookedState.cookedPointerData.pointerCoords,
4850 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004851 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852 }
4853 }
4854}
4855
4856void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4857 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004858 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4859 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 int32_t metaState = getContext()->getGlobalMetaState();
4861 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004862 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004863 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004864 mLastCookedState.cookedPointerData.pointerProperties,
4865 mLastCookedState.cookedPointerData.pointerCoords,
4866 mLastCookedState.cookedPointerData.idToIndex,
4867 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4869 mSentHoverEnter = false;
4870 }
4871}
4872
4873void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004874 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4875 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 int32_t metaState = getContext()->getGlobalMetaState();
4877 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004878 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004879 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004880 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004881 mCurrentCookedState.cookedPointerData.pointerProperties,
4882 mCurrentCookedState.cookedPointerData.pointerCoords,
4883 mCurrentCookedState.cookedPointerData.idToIndex,
4884 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4886 mSentHoverEnter = true;
4887 }
4888
4889 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004890 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004891 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004892 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004893 mCurrentCookedState.cookedPointerData.pointerProperties,
4894 mCurrentCookedState.cookedPointerData.pointerCoords,
4895 mCurrentCookedState.cookedPointerData.idToIndex,
4896 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4898 }
4899}
4900
Michael Wright7b159c92015-05-14 14:48:03 +01004901void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4902 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4903 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4904 const int32_t metaState = getContext()->getGlobalMetaState();
4905 int32_t buttonState = mLastCookedState.buttonState;
4906 while (!releasedButtons.isEmpty()) {
4907 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4908 buttonState &= ~actionButton;
4909 dispatchMotion(when, policyFlags, mSource,
4910 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4911 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004912 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004913 mCurrentCookedState.cookedPointerData.pointerProperties,
4914 mCurrentCookedState.cookedPointerData.pointerCoords,
4915 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4916 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4917 }
4918}
4919
4920void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4921 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4922 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4923 const int32_t metaState = getContext()->getGlobalMetaState();
4924 int32_t buttonState = mLastCookedState.buttonState;
4925 while (!pressedButtons.isEmpty()) {
4926 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4927 buttonState |= actionButton;
4928 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4929 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004930 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004931 mCurrentCookedState.cookedPointerData.pointerProperties,
4932 mCurrentCookedState.cookedPointerData.pointerCoords,
4933 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4934 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4935 }
4936}
4937
4938const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4939 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4940 return cookedPointerData.touchingIdBits;
4941 }
4942 return cookedPointerData.hoveringIdBits;
4943}
4944
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004946 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947
Michael Wright842500e2015-03-13 17:32:02 -07004948 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004949 mCurrentCookedState.deviceTimestamp =
4950 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004951 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4952 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4953 mCurrentRawState.rawPointerData.hoveringIdBits;
4954 mCurrentCookedState.cookedPointerData.touchingIdBits =
4955 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956
Michael Wright7b159c92015-05-14 14:48:03 +01004957 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4958 mCurrentCookedState.buttonState = 0;
4959 } else {
4960 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4961 }
4962
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963 // Walk through the the active pointers and map device coordinates onto
4964 // surface coordinates and adjust for display orientation.
4965 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004966 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967
4968 // Size
4969 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4970 switch (mCalibration.sizeCalibration) {
4971 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4972 case Calibration::SIZE_CALIBRATION_DIAMETER:
4973 case Calibration::SIZE_CALIBRATION_BOX:
4974 case Calibration::SIZE_CALIBRATION_AREA:
4975 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4976 touchMajor = in.touchMajor;
4977 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4978 toolMajor = in.toolMajor;
4979 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4980 size = mRawPointerAxes.touchMinor.valid
4981 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4982 } else if (mRawPointerAxes.touchMajor.valid) {
4983 toolMajor = touchMajor = in.touchMajor;
4984 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4985 ? in.touchMinor : in.touchMajor;
4986 size = mRawPointerAxes.touchMinor.valid
4987 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4988 } else if (mRawPointerAxes.toolMajor.valid) {
4989 touchMajor = toolMajor = in.toolMajor;
4990 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4991 ? in.toolMinor : in.toolMajor;
4992 size = mRawPointerAxes.toolMinor.valid
4993 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4994 } else {
4995 ALOG_ASSERT(false, "No touch or tool axes. "
4996 "Size calibration should have been resolved to NONE.");
4997 touchMajor = 0;
4998 touchMinor = 0;
4999 toolMajor = 0;
5000 toolMinor = 0;
5001 size = 0;
5002 }
5003
5004 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005005 uint32_t touchingCount =
5006 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007 if (touchingCount > 1) {
5008 touchMajor /= touchingCount;
5009 touchMinor /= touchingCount;
5010 toolMajor /= touchingCount;
5011 toolMinor /= touchingCount;
5012 size /= touchingCount;
5013 }
5014 }
5015
5016 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5017 touchMajor *= mGeometricScale;
5018 touchMinor *= mGeometricScale;
5019 toolMajor *= mGeometricScale;
5020 toolMinor *= mGeometricScale;
5021 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5022 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5023 touchMinor = touchMajor;
5024 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5025 toolMinor = toolMajor;
5026 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5027 touchMinor = touchMajor;
5028 toolMinor = toolMajor;
5029 }
5030
5031 mCalibration.applySizeScaleAndBias(&touchMajor);
5032 mCalibration.applySizeScaleAndBias(&touchMinor);
5033 mCalibration.applySizeScaleAndBias(&toolMajor);
5034 mCalibration.applySizeScaleAndBias(&toolMinor);
5035 size *= mSizeScale;
5036 break;
5037 default:
5038 touchMajor = 0;
5039 touchMinor = 0;
5040 toolMajor = 0;
5041 toolMinor = 0;
5042 size = 0;
5043 break;
5044 }
5045
5046 // Pressure
5047 float pressure;
5048 switch (mCalibration.pressureCalibration) {
5049 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5050 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5051 pressure = in.pressure * mPressureScale;
5052 break;
5053 default:
5054 pressure = in.isHovering ? 0 : 1;
5055 break;
5056 }
5057
5058 // Tilt and Orientation
5059 float tilt;
5060 float orientation;
5061 if (mHaveTilt) {
5062 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5063 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5064 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5065 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5066 } else {
5067 tilt = 0;
5068
5069 switch (mCalibration.orientationCalibration) {
5070 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5071 orientation = in.orientation * mOrientationScale;
5072 break;
5073 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5074 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5075 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5076 if (c1 != 0 || c2 != 0) {
5077 orientation = atan2f(c1, c2) * 0.5f;
5078 float confidence = hypotf(c1, c2);
5079 float scale = 1.0f + confidence / 16.0f;
5080 touchMajor *= scale;
5081 touchMinor /= scale;
5082 toolMajor *= scale;
5083 toolMinor /= scale;
5084 } else {
5085 orientation = 0;
5086 }
5087 break;
5088 }
5089 default:
5090 orientation = 0;
5091 }
5092 }
5093
5094 // Distance
5095 float distance;
5096 switch (mCalibration.distanceCalibration) {
5097 case Calibration::DISTANCE_CALIBRATION_SCALED:
5098 distance = in.distance * mDistanceScale;
5099 break;
5100 default:
5101 distance = 0;
5102 }
5103
5104 // Coverage
5105 int32_t rawLeft, rawTop, rawRight, rawBottom;
5106 switch (mCalibration.coverageCalibration) {
5107 case Calibration::COVERAGE_CALIBRATION_BOX:
5108 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5109 rawRight = in.toolMinor & 0x0000ffff;
5110 rawBottom = in.toolMajor & 0x0000ffff;
5111 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5112 break;
5113 default:
5114 rawLeft = rawTop = rawRight = rawBottom = 0;
5115 break;
5116 }
5117
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005118 // Adjust X,Y coords for device calibration
5119 // TODO: Adjust coverage coords?
5120 float xTransformed = in.x, yTransformed = in.y;
5121 mAffineTransform.applyTo(xTransformed, yTransformed);
5122
5123 // Adjust X, Y, and coverage coords for surface orientation.
5124 float x, y;
5125 float left, top, right, bottom;
5126
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127 switch (mSurfaceOrientation) {
5128 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005129 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5130 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5132 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5133 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5134 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5135 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005136 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5138 }
5139 break;
5140 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005141 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005142 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005143 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5144 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5146 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5147 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005148 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5150 }
5151 break;
5152 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005153 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005154 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005155 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5156 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5158 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5159 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005160 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005161 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5162 }
5163 break;
5164 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005165 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5166 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5168 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5169 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5170 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5171 break;
5172 }
5173
5174 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005175 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176 out.clear();
5177 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5178 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5179 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5180 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5181 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5182 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5183 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5184 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5185 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5186 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5187 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5188 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5189 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5190 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5191 } else {
5192 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5193 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5194 }
5195
5196 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005197 PointerProperties& properties =
5198 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005199 uint32_t id = in.id;
5200 properties.clear();
5201 properties.id = id;
5202 properties.toolType = in.toolType;
5203
5204 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005205 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206 }
5207}
5208
5209void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5210 PointerUsage pointerUsage) {
5211 if (pointerUsage != mPointerUsage) {
5212 abortPointerUsage(when, policyFlags);
5213 mPointerUsage = pointerUsage;
5214 }
5215
5216 switch (mPointerUsage) {
5217 case POINTER_USAGE_GESTURES:
5218 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5219 break;
5220 case POINTER_USAGE_STYLUS:
5221 dispatchPointerStylus(when, policyFlags);
5222 break;
5223 case POINTER_USAGE_MOUSE:
5224 dispatchPointerMouse(when, policyFlags);
5225 break;
5226 default:
5227 break;
5228 }
5229}
5230
5231void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5232 switch (mPointerUsage) {
5233 case POINTER_USAGE_GESTURES:
5234 abortPointerGestures(when, policyFlags);
5235 break;
5236 case POINTER_USAGE_STYLUS:
5237 abortPointerStylus(when, policyFlags);
5238 break;
5239 case POINTER_USAGE_MOUSE:
5240 abortPointerMouse(when, policyFlags);
5241 break;
5242 default:
5243 break;
5244 }
5245
5246 mPointerUsage = POINTER_USAGE_NONE;
5247}
5248
5249void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5250 bool isTimeout) {
5251 // Update current gesture coordinates.
5252 bool cancelPreviousGesture, finishPreviousGesture;
5253 bool sendEvents = preparePointerGestures(when,
5254 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5255 if (!sendEvents) {
5256 return;
5257 }
5258 if (finishPreviousGesture) {
5259 cancelPreviousGesture = false;
5260 }
5261
5262 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005263 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5264 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005265 if (finishPreviousGesture || cancelPreviousGesture) {
5266 mPointerController->clearSpots();
5267 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005268
5269 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5270 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5271 mPointerGesture.currentGestureIdToIndex,
5272 mPointerGesture.currentGestureIdBits);
5273 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274 } else {
5275 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5276 }
5277
5278 // Show or hide the pointer if needed.
5279 switch (mPointerGesture.currentGestureMode) {
5280 case PointerGesture::NEUTRAL:
5281 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005282 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5283 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 // Remind the user of where the pointer is after finishing a gesture with spots.
5285 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5286 }
5287 break;
5288 case PointerGesture::TAP:
5289 case PointerGesture::TAP_DRAG:
5290 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5291 case PointerGesture::HOVER:
5292 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005293 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 // Unfade the pointer when the current gesture manipulates the
5295 // area directly under the pointer.
5296 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5297 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 case PointerGesture::FREEFORM:
5299 // Fade the pointer when the current gesture manipulates a different
5300 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005301 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5303 } else {
5304 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5305 }
5306 break;
5307 }
5308
5309 // Send events!
5310 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005311 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312
5313 // Update last coordinates of pointers that have moved so that we observe the new
5314 // pointer positions at the same time as other pointers that have just gone up.
5315 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5316 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5317 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5318 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5319 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5320 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5321 bool moveNeeded = false;
5322 if (down && !cancelPreviousGesture && !finishPreviousGesture
5323 && !mPointerGesture.lastGestureIdBits.isEmpty()
5324 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5325 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5326 & mPointerGesture.lastGestureIdBits.value);
5327 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5328 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5329 mPointerGesture.lastGestureProperties,
5330 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5331 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005332 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333 moveNeeded = true;
5334 }
5335 }
5336
5337 // Send motion events for all pointers that went up or were canceled.
5338 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5339 if (!dispatchedGestureIdBits.isEmpty()) {
5340 if (cancelPreviousGesture) {
5341 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005342 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005343 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344 mPointerGesture.lastGestureProperties,
5345 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005346 dispatchedGestureIdBits, -1, 0,
5347 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348
5349 dispatchedGestureIdBits.clear();
5350 } else {
5351 BitSet32 upGestureIdBits;
5352 if (finishPreviousGesture) {
5353 upGestureIdBits = dispatchedGestureIdBits;
5354 } else {
5355 upGestureIdBits.value = dispatchedGestureIdBits.value
5356 & ~mPointerGesture.currentGestureIdBits.value;
5357 }
5358 while (!upGestureIdBits.isEmpty()) {
5359 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5360
5361 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005362 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005364 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365 mPointerGesture.lastGestureProperties,
5366 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5367 dispatchedGestureIdBits, id,
5368 0, 0, mPointerGesture.downTime);
5369
5370 dispatchedGestureIdBits.clearBit(id);
5371 }
5372 }
5373 }
5374
5375 // Send motion events for all pointers that moved.
5376 if (moveNeeded) {
5377 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005378 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005379 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380 mPointerGesture.currentGestureProperties,
5381 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5382 dispatchedGestureIdBits, -1,
5383 0, 0, mPointerGesture.downTime);
5384 }
5385
5386 // Send motion events for all pointers that went down.
5387 if (down) {
5388 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5389 & ~dispatchedGestureIdBits.value);
5390 while (!downGestureIdBits.isEmpty()) {
5391 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5392 dispatchedGestureIdBits.markBit(id);
5393
5394 if (dispatchedGestureIdBits.count() == 1) {
5395 mPointerGesture.downTime = when;
5396 }
5397
5398 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005399 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005400 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401 mPointerGesture.currentGestureProperties,
5402 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5403 dispatchedGestureIdBits, id,
5404 0, 0, mPointerGesture.downTime);
5405 }
5406 }
5407
5408 // Send motion events for hover.
5409 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5410 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005411 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005412 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 mPointerGesture.currentGestureProperties,
5414 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5415 mPointerGesture.currentGestureIdBits, -1,
5416 0, 0, mPointerGesture.downTime);
5417 } else if (dispatchedGestureIdBits.isEmpty()
5418 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5419 // Synthesize a hover move event after all pointers go up to indicate that
5420 // the pointer is hovering again even if the user is not currently touching
5421 // the touch pad. This ensures that a view will receive a fresh hover enter
5422 // event after a tap.
5423 float x, y;
5424 mPointerController->getPosition(&x, &y);
5425
5426 PointerProperties pointerProperties;
5427 pointerProperties.clear();
5428 pointerProperties.id = 0;
5429 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5430
5431 PointerCoords pointerCoords;
5432 pointerCoords.clear();
5433 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5434 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5435
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005436 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005437 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005439 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440 0, 0, mPointerGesture.downTime);
5441 getListener()->notifyMotion(&args);
5442 }
5443
5444 // Update state.
5445 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5446 if (!down) {
5447 mPointerGesture.lastGestureIdBits.clear();
5448 } else {
5449 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5450 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5451 uint32_t id = idBits.clearFirstMarkedBit();
5452 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5453 mPointerGesture.lastGestureProperties[index].copyFrom(
5454 mPointerGesture.currentGestureProperties[index]);
5455 mPointerGesture.lastGestureCoords[index].copyFrom(
5456 mPointerGesture.currentGestureCoords[index]);
5457 mPointerGesture.lastGestureIdToIndex[id] = index;
5458 }
5459 }
5460}
5461
5462void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5463 // Cancel previously dispatches pointers.
5464 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5465 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005466 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005468 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005469 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470 mPointerGesture.lastGestureProperties,
5471 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5472 mPointerGesture.lastGestureIdBits, -1,
5473 0, 0, mPointerGesture.downTime);
5474 }
5475
5476 // Reset the current pointer gesture.
5477 mPointerGesture.reset();
5478 mPointerVelocityControl.reset();
5479
5480 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005481 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5483 mPointerController->clearSpots();
5484 }
5485}
5486
5487bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5488 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5489 *outCancelPreviousGesture = false;
5490 *outFinishPreviousGesture = false;
5491
5492 // Handle TAP timeout.
5493 if (isTimeout) {
5494#if DEBUG_GESTURES
5495 ALOGD("Gestures: Processing timeout");
5496#endif
5497
5498 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5499 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5500 // The tap/drag timeout has not yet expired.
5501 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5502 + mConfig.pointerGestureTapDragInterval);
5503 } else {
5504 // The tap is finished.
5505#if DEBUG_GESTURES
5506 ALOGD("Gestures: TAP finished");
5507#endif
5508 *outFinishPreviousGesture = true;
5509
5510 mPointerGesture.activeGestureId = -1;
5511 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5512 mPointerGesture.currentGestureIdBits.clear();
5513
5514 mPointerVelocityControl.reset();
5515 return true;
5516 }
5517 }
5518
5519 // We did not handle this timeout.
5520 return false;
5521 }
5522
Michael Wright842500e2015-03-13 17:32:02 -07005523 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5524 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525
5526 // Update the velocity tracker.
5527 {
5528 VelocityTracker::Position positions[MAX_POINTERS];
5529 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005530 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005531 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005532 const RawPointerData::Pointer& pointer =
5533 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 positions[count].x = pointer.x * mPointerXMovementScale;
5535 positions[count].y = pointer.y * mPointerYMovementScale;
5536 }
5537 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005538 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 }
5540
5541 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5542 // to NEUTRAL, then we should not generate tap event.
5543 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5544 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5545 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5546 mPointerGesture.resetTap();
5547 }
5548
5549 // Pick a new active touch id if needed.
5550 // Choose an arbitrary pointer that just went down, if there is one.
5551 // Otherwise choose an arbitrary remaining pointer.
5552 // This guarantees we always have an active touch id when there is at least one pointer.
5553 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005554 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5555 int32_t activeTouchId = lastActiveTouchId;
5556 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005557 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005559 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560 mPointerGesture.firstTouchTime = when;
5561 }
Michael Wright842500e2015-03-13 17:32:02 -07005562 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005563 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005565 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566 } else {
5567 activeTouchId = mPointerGesture.activeTouchId = -1;
5568 }
5569 }
5570
5571 // Determine whether we are in quiet time.
5572 bool isQuietTime = false;
5573 if (activeTouchId < 0) {
5574 mPointerGesture.resetQuietTime();
5575 } else {
5576 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5577 if (!isQuietTime) {
5578 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5579 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5580 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5581 && currentFingerCount < 2) {
5582 // Enter quiet time when exiting swipe or freeform state.
5583 // This is to prevent accidentally entering the hover state and flinging the
5584 // pointer when finishing a swipe and there is still one pointer left onscreen.
5585 isQuietTime = true;
5586 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5587 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005588 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589 // Enter quiet time when releasing the button and there are still two or more
5590 // fingers down. This may indicate that one finger was used to press the button
5591 // but it has not gone up yet.
5592 isQuietTime = true;
5593 }
5594 if (isQuietTime) {
5595 mPointerGesture.quietTime = when;
5596 }
5597 }
5598 }
5599
5600 // Switch states based on button and pointer state.
5601 if (isQuietTime) {
5602 // Case 1: Quiet time. (QUIET)
5603#if DEBUG_GESTURES
5604 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5605 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5606#endif
5607 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5608 *outFinishPreviousGesture = true;
5609 }
5610
5611 mPointerGesture.activeGestureId = -1;
5612 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5613 mPointerGesture.currentGestureIdBits.clear();
5614
5615 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005616 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5618 // The pointer follows the active touch point.
5619 // Emit DOWN, MOVE, UP events at the pointer location.
5620 //
5621 // Only the active touch matters; other fingers are ignored. This policy helps
5622 // to handle the case where the user places a second finger on the touch pad
5623 // to apply the necessary force to depress an integrated button below the surface.
5624 // We don't want the second finger to be delivered to applications.
5625 //
5626 // For this to work well, we need to make sure to track the pointer that is really
5627 // active. If the user first puts one finger down to click then adds another
5628 // finger to drag then the active pointer should switch to the finger that is
5629 // being dragged.
5630#if DEBUG_GESTURES
5631 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5632 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5633#endif
5634 // Reset state when just starting.
5635 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5636 *outFinishPreviousGesture = true;
5637 mPointerGesture.activeGestureId = 0;
5638 }
5639
5640 // Switch pointers if needed.
5641 // Find the fastest pointer and follow it.
5642 if (activeTouchId >= 0 && currentFingerCount > 1) {
5643 int32_t bestId = -1;
5644 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005645 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005646 uint32_t id = idBits.clearFirstMarkedBit();
5647 float vx, vy;
5648 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5649 float speed = hypotf(vx, vy);
5650 if (speed > bestSpeed) {
5651 bestId = id;
5652 bestSpeed = speed;
5653 }
5654 }
5655 }
5656 if (bestId >= 0 && bestId != activeTouchId) {
5657 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005658#if DEBUG_GESTURES
5659 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5660 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5661#endif
5662 }
5663 }
5664
Jun Mukaifa1706a2015-12-03 01:14:46 -08005665 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005666 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005667 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005668 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005669 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005670 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005671 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5672 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005673
5674 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5675 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5676
5677 // Move the pointer using a relative motion.
5678 // When using spots, the click will occur at the position of the anchor
5679 // spot and all other spots will move there.
5680 mPointerController->move(deltaX, deltaY);
5681 } else {
5682 mPointerVelocityControl.reset();
5683 }
5684
5685 float x, y;
5686 mPointerController->getPosition(&x, &y);
5687
5688 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5689 mPointerGesture.currentGestureIdBits.clear();
5690 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5691 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5692 mPointerGesture.currentGestureProperties[0].clear();
5693 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5694 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5695 mPointerGesture.currentGestureCoords[0].clear();
5696 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5697 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5698 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5699 } else if (currentFingerCount == 0) {
5700 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5701 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5702 *outFinishPreviousGesture = true;
5703 }
5704
5705 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5706 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5707 bool tapped = false;
5708 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5709 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5710 && lastFingerCount == 1) {
5711 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5712 float x, y;
5713 mPointerController->getPosition(&x, &y);
5714 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5715 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5716#if DEBUG_GESTURES
5717 ALOGD("Gestures: TAP");
5718#endif
5719
5720 mPointerGesture.tapUpTime = when;
5721 getContext()->requestTimeoutAtTime(when
5722 + mConfig.pointerGestureTapDragInterval);
5723
5724 mPointerGesture.activeGestureId = 0;
5725 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5726 mPointerGesture.currentGestureIdBits.clear();
5727 mPointerGesture.currentGestureIdBits.markBit(
5728 mPointerGesture.activeGestureId);
5729 mPointerGesture.currentGestureIdToIndex[
5730 mPointerGesture.activeGestureId] = 0;
5731 mPointerGesture.currentGestureProperties[0].clear();
5732 mPointerGesture.currentGestureProperties[0].id =
5733 mPointerGesture.activeGestureId;
5734 mPointerGesture.currentGestureProperties[0].toolType =
5735 AMOTION_EVENT_TOOL_TYPE_FINGER;
5736 mPointerGesture.currentGestureCoords[0].clear();
5737 mPointerGesture.currentGestureCoords[0].setAxisValue(
5738 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5739 mPointerGesture.currentGestureCoords[0].setAxisValue(
5740 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5741 mPointerGesture.currentGestureCoords[0].setAxisValue(
5742 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5743
5744 tapped = true;
5745 } else {
5746#if DEBUG_GESTURES
5747 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5748 x - mPointerGesture.tapX,
5749 y - mPointerGesture.tapY);
5750#endif
5751 }
5752 } else {
5753#if DEBUG_GESTURES
5754 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5755 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5756 (when - mPointerGesture.tapDownTime) * 0.000001f);
5757 } else {
5758 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5759 }
5760#endif
5761 }
5762 }
5763
5764 mPointerVelocityControl.reset();
5765
5766 if (!tapped) {
5767#if DEBUG_GESTURES
5768 ALOGD("Gestures: NEUTRAL");
5769#endif
5770 mPointerGesture.activeGestureId = -1;
5771 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5772 mPointerGesture.currentGestureIdBits.clear();
5773 }
5774 } else if (currentFingerCount == 1) {
5775 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5776 // The pointer follows the active touch point.
5777 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5778 // When in TAP_DRAG, emit MOVE events at the pointer location.
5779 ALOG_ASSERT(activeTouchId >= 0);
5780
5781 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5782 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5783 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5784 float x, y;
5785 mPointerController->getPosition(&x, &y);
5786 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5787 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5788 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5789 } else {
5790#if DEBUG_GESTURES
5791 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5792 x - mPointerGesture.tapX,
5793 y - mPointerGesture.tapY);
5794#endif
5795 }
5796 } else {
5797#if DEBUG_GESTURES
5798 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5799 (when - mPointerGesture.tapUpTime) * 0.000001f);
5800#endif
5801 }
5802 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5803 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5804 }
5805
Jun Mukaifa1706a2015-12-03 01:14:46 -08005806 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005807 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005809 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005811 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005812 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5813 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814
5815 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5816 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5817
5818 // Move the pointer using a relative motion.
5819 // When using spots, the hover or drag will occur at the position of the anchor spot.
5820 mPointerController->move(deltaX, deltaY);
5821 } else {
5822 mPointerVelocityControl.reset();
5823 }
5824
5825 bool down;
5826 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5827#if DEBUG_GESTURES
5828 ALOGD("Gestures: TAP_DRAG");
5829#endif
5830 down = true;
5831 } else {
5832#if DEBUG_GESTURES
5833 ALOGD("Gestures: HOVER");
5834#endif
5835 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5836 *outFinishPreviousGesture = true;
5837 }
5838 mPointerGesture.activeGestureId = 0;
5839 down = false;
5840 }
5841
5842 float x, y;
5843 mPointerController->getPosition(&x, &y);
5844
5845 mPointerGesture.currentGestureIdBits.clear();
5846 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5847 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5848 mPointerGesture.currentGestureProperties[0].clear();
5849 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5850 mPointerGesture.currentGestureProperties[0].toolType =
5851 AMOTION_EVENT_TOOL_TYPE_FINGER;
5852 mPointerGesture.currentGestureCoords[0].clear();
5853 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5854 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5855 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5856 down ? 1.0f : 0.0f);
5857
5858 if (lastFingerCount == 0 && currentFingerCount != 0) {
5859 mPointerGesture.resetTap();
5860 mPointerGesture.tapDownTime = when;
5861 mPointerGesture.tapX = x;
5862 mPointerGesture.tapY = y;
5863 }
5864 } else {
5865 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5866 // We need to provide feedback for each finger that goes down so we cannot wait
5867 // for the fingers to move before deciding what to do.
5868 //
5869 // The ambiguous case is deciding what to do when there are two fingers down but they
5870 // have not moved enough to determine whether they are part of a drag or part of a
5871 // freeform gesture, or just a press or long-press at the pointer location.
5872 //
5873 // When there are two fingers we start with the PRESS hypothesis and we generate a
5874 // down at the pointer location.
5875 //
5876 // When the two fingers move enough or when additional fingers are added, we make
5877 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5878 ALOG_ASSERT(activeTouchId >= 0);
5879
5880 bool settled = when >= mPointerGesture.firstTouchTime
5881 + mConfig.pointerGestureMultitouchSettleInterval;
5882 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5883 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5884 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5885 *outFinishPreviousGesture = true;
5886 } else if (!settled && currentFingerCount > lastFingerCount) {
5887 // Additional pointers have gone down but not yet settled.
5888 // Reset the gesture.
5889#if DEBUG_GESTURES
5890 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5891 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5892 + mConfig.pointerGestureMultitouchSettleInterval - when)
5893 * 0.000001f);
5894#endif
5895 *outCancelPreviousGesture = true;
5896 } else {
5897 // Continue previous gesture.
5898 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5899 }
5900
5901 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5902 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5903 mPointerGesture.activeGestureId = 0;
5904 mPointerGesture.referenceIdBits.clear();
5905 mPointerVelocityControl.reset();
5906
5907 // Use the centroid and pointer location as the reference points for the gesture.
5908#if DEBUG_GESTURES
5909 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5910 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5911 + mConfig.pointerGestureMultitouchSettleInterval - when)
5912 * 0.000001f);
5913#endif
Michael Wright842500e2015-03-13 17:32:02 -07005914 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005915 &mPointerGesture.referenceTouchX,
5916 &mPointerGesture.referenceTouchY);
5917 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5918 &mPointerGesture.referenceGestureY);
5919 }
5920
5921 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005922 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5924 uint32_t id = idBits.clearFirstMarkedBit();
5925 mPointerGesture.referenceDeltas[id].dx = 0;
5926 mPointerGesture.referenceDeltas[id].dy = 0;
5927 }
Michael Wright842500e2015-03-13 17:32:02 -07005928 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929
5930 // Add delta for all fingers and calculate a common movement delta.
5931 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005932 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5933 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5935 bool first = (idBits == commonIdBits);
5936 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005937 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5938 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5940 delta.dx += cpd.x - lpd.x;
5941 delta.dy += cpd.y - lpd.y;
5942
5943 if (first) {
5944 commonDeltaX = delta.dx;
5945 commonDeltaY = delta.dy;
5946 } else {
5947 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5948 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5949 }
5950 }
5951
5952 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5953 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5954 float dist[MAX_POINTER_ID + 1];
5955 int32_t distOverThreshold = 0;
5956 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5957 uint32_t id = idBits.clearFirstMarkedBit();
5958 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5959 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5960 delta.dy * mPointerYZoomScale);
5961 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5962 distOverThreshold += 1;
5963 }
5964 }
5965
5966 // Only transition when at least two pointers have moved further than
5967 // the minimum distance threshold.
5968 if (distOverThreshold >= 2) {
5969 if (currentFingerCount > 2) {
5970 // There are more than two pointers, switch to FREEFORM.
5971#if DEBUG_GESTURES
5972 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5973 currentFingerCount);
5974#endif
5975 *outCancelPreviousGesture = true;
5976 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5977 } else {
5978 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005979 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005980 uint32_t id1 = idBits.clearFirstMarkedBit();
5981 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005982 const RawPointerData::Pointer& p1 =
5983 mCurrentRawState.rawPointerData.pointerForId(id1);
5984 const RawPointerData::Pointer& p2 =
5985 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005986 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5987 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5988 // There are two pointers but they are too far apart for a SWIPE,
5989 // switch to FREEFORM.
5990#if DEBUG_GESTURES
5991 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5992 mutualDistance, mPointerGestureMaxSwipeWidth);
5993#endif
5994 *outCancelPreviousGesture = true;
5995 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5996 } else {
5997 // There are two pointers. Wait for both pointers to start moving
5998 // before deciding whether this is a SWIPE or FREEFORM gesture.
5999 float dist1 = dist[id1];
6000 float dist2 = dist[id2];
6001 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6002 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6003 // Calculate the dot product of the displacement vectors.
6004 // When the vectors are oriented in approximately the same direction,
6005 // the angle betweeen them is near zero and the cosine of the angle
6006 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6007 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6008 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6009 float dx1 = delta1.dx * mPointerXZoomScale;
6010 float dy1 = delta1.dy * mPointerYZoomScale;
6011 float dx2 = delta2.dx * mPointerXZoomScale;
6012 float dy2 = delta2.dy * mPointerYZoomScale;
6013 float dot = dx1 * dx2 + dy1 * dy2;
6014 float cosine = dot / (dist1 * dist2); // denominator always > 0
6015 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6016 // Pointers are moving in the same direction. Switch to SWIPE.
6017#if DEBUG_GESTURES
6018 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6019 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6020 "cosine %0.3f >= %0.3f",
6021 dist1, mConfig.pointerGestureMultitouchMinDistance,
6022 dist2, mConfig.pointerGestureMultitouchMinDistance,
6023 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6024#endif
6025 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6026 } else {
6027 // Pointers are moving in different directions. Switch to FREEFORM.
6028#if DEBUG_GESTURES
6029 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6030 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6031 "cosine %0.3f < %0.3f",
6032 dist1, mConfig.pointerGestureMultitouchMinDistance,
6033 dist2, mConfig.pointerGestureMultitouchMinDistance,
6034 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6035#endif
6036 *outCancelPreviousGesture = true;
6037 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6038 }
6039 }
6040 }
6041 }
6042 }
6043 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6044 // Switch from SWIPE to FREEFORM if additional pointers go down.
6045 // Cancel previous gesture.
6046 if (currentFingerCount > 2) {
6047#if DEBUG_GESTURES
6048 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6049 currentFingerCount);
6050#endif
6051 *outCancelPreviousGesture = true;
6052 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6053 }
6054 }
6055
6056 // Move the reference points based on the overall group motion of the fingers
6057 // except in PRESS mode while waiting for a transition to occur.
6058 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6059 && (commonDeltaX || commonDeltaY)) {
6060 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6061 uint32_t id = idBits.clearFirstMarkedBit();
6062 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6063 delta.dx = 0;
6064 delta.dy = 0;
6065 }
6066
6067 mPointerGesture.referenceTouchX += commonDeltaX;
6068 mPointerGesture.referenceTouchY += commonDeltaY;
6069
6070 commonDeltaX *= mPointerXMovementScale;
6071 commonDeltaY *= mPointerYMovementScale;
6072
6073 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6074 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6075
6076 mPointerGesture.referenceGestureX += commonDeltaX;
6077 mPointerGesture.referenceGestureY += commonDeltaY;
6078 }
6079
6080 // Report gestures.
6081 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6082 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6083 // PRESS or SWIPE mode.
6084#if DEBUG_GESTURES
6085 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6086 "activeGestureId=%d, currentTouchPointerCount=%d",
6087 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6088#endif
6089 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6090
6091 mPointerGesture.currentGestureIdBits.clear();
6092 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6093 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6094 mPointerGesture.currentGestureProperties[0].clear();
6095 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6096 mPointerGesture.currentGestureProperties[0].toolType =
6097 AMOTION_EVENT_TOOL_TYPE_FINGER;
6098 mPointerGesture.currentGestureCoords[0].clear();
6099 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6100 mPointerGesture.referenceGestureX);
6101 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6102 mPointerGesture.referenceGestureY);
6103 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6104 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6105 // FREEFORM mode.
6106#if DEBUG_GESTURES
6107 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6108 "activeGestureId=%d, currentTouchPointerCount=%d",
6109 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6110#endif
6111 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6112
6113 mPointerGesture.currentGestureIdBits.clear();
6114
6115 BitSet32 mappedTouchIdBits;
6116 BitSet32 usedGestureIdBits;
6117 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6118 // Initially, assign the active gesture id to the active touch point
6119 // if there is one. No other touch id bits are mapped yet.
6120 if (!*outCancelPreviousGesture) {
6121 mappedTouchIdBits.markBit(activeTouchId);
6122 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6123 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6124 mPointerGesture.activeGestureId;
6125 } else {
6126 mPointerGesture.activeGestureId = -1;
6127 }
6128 } else {
6129 // Otherwise, assume we mapped all touches from the previous frame.
6130 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006131 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6132 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006133 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6134
6135 // Check whether we need to choose a new active gesture id because the
6136 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006137 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6138 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006139 !upTouchIdBits.isEmpty(); ) {
6140 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6141 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6142 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6143 mPointerGesture.activeGestureId = -1;
6144 break;
6145 }
6146 }
6147 }
6148
6149#if DEBUG_GESTURES
6150 ALOGD("Gestures: FREEFORM follow up "
6151 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6152 "activeGestureId=%d",
6153 mappedTouchIdBits.value, usedGestureIdBits.value,
6154 mPointerGesture.activeGestureId);
6155#endif
6156
Michael Wright842500e2015-03-13 17:32:02 -07006157 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006158 for (uint32_t i = 0; i < currentFingerCount; i++) {
6159 uint32_t touchId = idBits.clearFirstMarkedBit();
6160 uint32_t gestureId;
6161 if (!mappedTouchIdBits.hasBit(touchId)) {
6162 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6163 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6164#if DEBUG_GESTURES
6165 ALOGD("Gestures: FREEFORM "
6166 "new mapping for touch id %d -> gesture id %d",
6167 touchId, gestureId);
6168#endif
6169 } else {
6170 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6171#if DEBUG_GESTURES
6172 ALOGD("Gestures: FREEFORM "
6173 "existing mapping for touch id %d -> gesture id %d",
6174 touchId, gestureId);
6175#endif
6176 }
6177 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6178 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6179
6180 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006181 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006182 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6183 * mPointerXZoomScale;
6184 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6185 * mPointerYZoomScale;
6186 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6187
6188 mPointerGesture.currentGestureProperties[i].clear();
6189 mPointerGesture.currentGestureProperties[i].id = gestureId;
6190 mPointerGesture.currentGestureProperties[i].toolType =
6191 AMOTION_EVENT_TOOL_TYPE_FINGER;
6192 mPointerGesture.currentGestureCoords[i].clear();
6193 mPointerGesture.currentGestureCoords[i].setAxisValue(
6194 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6195 mPointerGesture.currentGestureCoords[i].setAxisValue(
6196 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6197 mPointerGesture.currentGestureCoords[i].setAxisValue(
6198 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6199 }
6200
6201 if (mPointerGesture.activeGestureId < 0) {
6202 mPointerGesture.activeGestureId =
6203 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6204#if DEBUG_GESTURES
6205 ALOGD("Gestures: FREEFORM new "
6206 "activeGestureId=%d", mPointerGesture.activeGestureId);
6207#endif
6208 }
6209 }
6210 }
6211
Michael Wright842500e2015-03-13 17:32:02 -07006212 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006213
6214#if DEBUG_GESTURES
6215 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6216 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6217 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6218 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6219 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6220 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6221 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6222 uint32_t id = idBits.clearFirstMarkedBit();
6223 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6224 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6225 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6226 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6227 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6228 id, index, properties.toolType,
6229 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6230 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6231 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6232 }
6233 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6234 uint32_t id = idBits.clearFirstMarkedBit();
6235 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6236 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6237 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6238 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6239 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6240 id, index, properties.toolType,
6241 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6242 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6243 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6244 }
6245#endif
6246 return true;
6247}
6248
6249void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6250 mPointerSimple.currentCoords.clear();
6251 mPointerSimple.currentProperties.clear();
6252
6253 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006254 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6255 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6256 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6257 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6258 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006259 mPointerController->setPosition(x, y);
6260
Michael Wright842500e2015-03-13 17:32:02 -07006261 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 down = !hovering;
6263
6264 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006265 mPointerSimple.currentCoords.copyFrom(
6266 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006267 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6268 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6269 mPointerSimple.currentProperties.id = 0;
6270 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006271 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006272 } else {
6273 down = false;
6274 hovering = false;
6275 }
6276
6277 dispatchPointerSimple(when, policyFlags, down, hovering);
6278}
6279
6280void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6281 abortPointerSimple(when, policyFlags);
6282}
6283
6284void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6285 mPointerSimple.currentCoords.clear();
6286 mPointerSimple.currentProperties.clear();
6287
6288 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006289 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6290 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6291 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006292 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006293 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6294 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006295 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006296 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006297 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006298 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006299 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006300 * mPointerYMovementScale;
6301
6302 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6303 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6304
6305 mPointerController->move(deltaX, deltaY);
6306 } else {
6307 mPointerVelocityControl.reset();
6308 }
6309
Michael Wright842500e2015-03-13 17:32:02 -07006310 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006311 hovering = !down;
6312
6313 float x, y;
6314 mPointerController->getPosition(&x, &y);
6315 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006316 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006317 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6318 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6319 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6320 hovering ? 0.0f : 1.0f);
6321 mPointerSimple.currentProperties.id = 0;
6322 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006323 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006324 } else {
6325 mPointerVelocityControl.reset();
6326
6327 down = false;
6328 hovering = false;
6329 }
6330
6331 dispatchPointerSimple(when, policyFlags, down, hovering);
6332}
6333
6334void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6335 abortPointerSimple(when, policyFlags);
6336
6337 mPointerVelocityControl.reset();
6338}
6339
6340void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6341 bool down, bool hovering) {
6342 int32_t metaState = getContext()->getGlobalMetaState();
6343
Yi Kong9b14ac62018-07-17 13:48:38 -07006344 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006345 if (down || hovering) {
6346 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6347 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006348 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006349 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6350 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6351 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6352 }
6353 }
6354
6355 if (mPointerSimple.down && !down) {
6356 mPointerSimple.down = false;
6357
6358 // Send up.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006359 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006360 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006361 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006362 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6363 mOrientedXPrecision, mOrientedYPrecision,
6364 mPointerSimple.downTime);
6365 getListener()->notifyMotion(&args);
6366 }
6367
6368 if (mPointerSimple.hovering && !hovering) {
6369 mPointerSimple.hovering = false;
6370
6371 // Send hover exit.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006372 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006373 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006374 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006375 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6376 mOrientedXPrecision, mOrientedYPrecision,
6377 mPointerSimple.downTime);
6378 getListener()->notifyMotion(&args);
6379 }
6380
6381 if (down) {
6382 if (!mPointerSimple.down) {
6383 mPointerSimple.down = true;
6384 mPointerSimple.downTime = when;
6385
6386 // Send down.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006387 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006388 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006389 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006390 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6391 mOrientedXPrecision, mOrientedYPrecision,
6392 mPointerSimple.downTime);
6393 getListener()->notifyMotion(&args);
6394 }
6395
6396 // Send move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006397 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006398 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006399 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006400 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6401 mOrientedXPrecision, mOrientedYPrecision,
6402 mPointerSimple.downTime);
6403 getListener()->notifyMotion(&args);
6404 }
6405
6406 if (hovering) {
6407 if (!mPointerSimple.hovering) {
6408 mPointerSimple.hovering = true;
6409
6410 // Send hover enter.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006411 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006412 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006413 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006414 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6416 mOrientedXPrecision, mOrientedYPrecision,
6417 mPointerSimple.downTime);
6418 getListener()->notifyMotion(&args);
6419 }
6420
6421 // Send hover move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006422 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006423 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006424 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006425 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006426 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6427 mOrientedXPrecision, mOrientedYPrecision,
6428 mPointerSimple.downTime);
6429 getListener()->notifyMotion(&args);
6430 }
6431
Michael Wright842500e2015-03-13 17:32:02 -07006432 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6433 float vscroll = mCurrentRawState.rawVScroll;
6434 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006435 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6436 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006437
6438 // Send scroll.
6439 PointerCoords pointerCoords;
6440 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6441 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6442 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6443
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006444 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006445 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006446 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006447 1, &mPointerSimple.currentProperties, &pointerCoords,
6448 mOrientedXPrecision, mOrientedYPrecision,
6449 mPointerSimple.downTime);
6450 getListener()->notifyMotion(&args);
6451 }
6452
6453 // Save state.
6454 if (down || hovering) {
6455 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6456 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6457 } else {
6458 mPointerSimple.reset();
6459 }
6460}
6461
6462void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6463 mPointerSimple.currentCoords.clear();
6464 mPointerSimple.currentProperties.clear();
6465
6466 dispatchPointerSimple(when, policyFlags, false, false);
6467}
6468
6469void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006470 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006471 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006472 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006473 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6474 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006475 PointerCoords pointerCoords[MAX_POINTERS];
6476 PointerProperties pointerProperties[MAX_POINTERS];
6477 uint32_t pointerCount = 0;
6478 while (!idBits.isEmpty()) {
6479 uint32_t id = idBits.clearFirstMarkedBit();
6480 uint32_t index = idToIndex[id];
6481 pointerProperties[pointerCount].copyFrom(properties[index]);
6482 pointerCoords[pointerCount].copyFrom(coords[index]);
6483
6484 if (changedId >= 0 && id == uint32_t(changedId)) {
6485 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6486 }
6487
6488 pointerCount += 1;
6489 }
6490
6491 ALOG_ASSERT(pointerCount != 0);
6492
6493 if (changedId >= 0 && pointerCount == 1) {
6494 // Replace initial down and final up action.
6495 // We can compare the action without masking off the changed pointer index
6496 // because we know the index is 0.
6497 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6498 action = AMOTION_EVENT_ACTION_DOWN;
6499 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6500 action = AMOTION_EVENT_ACTION_UP;
6501 } else {
6502 // Can't happen.
6503 ALOG_ASSERT(false);
6504 }
6505 }
6506
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006507 NotifyMotionArgs args(when, getDeviceId(), source, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006508 action, actionButton, flags, metaState, buttonState, edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006509 deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006510 xPrecision, yPrecision, downTime);
6511 getListener()->notifyMotion(&args);
6512}
6513
6514bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6515 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6516 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6517 BitSet32 idBits) const {
6518 bool changed = false;
6519 while (!idBits.isEmpty()) {
6520 uint32_t id = idBits.clearFirstMarkedBit();
6521 uint32_t inIndex = inIdToIndex[id];
6522 uint32_t outIndex = outIdToIndex[id];
6523
6524 const PointerProperties& curInProperties = inProperties[inIndex];
6525 const PointerCoords& curInCoords = inCoords[inIndex];
6526 PointerProperties& curOutProperties = outProperties[outIndex];
6527 PointerCoords& curOutCoords = outCoords[outIndex];
6528
6529 if (curInProperties != curOutProperties) {
6530 curOutProperties.copyFrom(curInProperties);
6531 changed = true;
6532 }
6533
6534 if (curInCoords != curOutCoords) {
6535 curOutCoords.copyFrom(curInCoords);
6536 changed = true;
6537 }
6538 }
6539 return changed;
6540}
6541
6542void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006543 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006544 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6545 }
6546}
6547
Jeff Brownc9aa6282015-02-11 19:03:28 -08006548void TouchInputMapper::cancelTouch(nsecs_t when) {
6549 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006550 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006551}
6552
Michael Wrightd02c5b62014-02-10 15:10:22 -08006553bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006554 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006555 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006556 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006557 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6558 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6559 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006560}
6561
6562const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6563 int32_t x, int32_t y) {
6564 size_t numVirtualKeys = mVirtualKeys.size();
6565 for (size_t i = 0; i < numVirtualKeys; i++) {
6566 const VirtualKey& virtualKey = mVirtualKeys[i];
6567
6568#if DEBUG_VIRTUAL_KEYS
6569 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6570 "left=%d, top=%d, right=%d, bottom=%d",
6571 x, y,
6572 virtualKey.keyCode, virtualKey.scanCode,
6573 virtualKey.hitLeft, virtualKey.hitTop,
6574 virtualKey.hitRight, virtualKey.hitBottom);
6575#endif
6576
6577 if (virtualKey.isHit(x, y)) {
6578 return & virtualKey;
6579 }
6580 }
6581
Yi Kong9b14ac62018-07-17 13:48:38 -07006582 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006583}
6584
Michael Wright842500e2015-03-13 17:32:02 -07006585void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6586 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6587 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006588
Michael Wright842500e2015-03-13 17:32:02 -07006589 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006590
6591 if (currentPointerCount == 0) {
6592 // No pointers to assign.
6593 return;
6594 }
6595
6596 if (lastPointerCount == 0) {
6597 // All pointers are new.
6598 for (uint32_t i = 0; i < currentPointerCount; i++) {
6599 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006600 current->rawPointerData.pointers[i].id = id;
6601 current->rawPointerData.idToIndex[id] = i;
6602 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006603 }
6604 return;
6605 }
6606
6607 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006608 && current->rawPointerData.pointers[0].toolType
6609 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006610 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006611 uint32_t id = last->rawPointerData.pointers[0].id;
6612 current->rawPointerData.pointers[0].id = id;
6613 current->rawPointerData.idToIndex[id] = 0;
6614 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006615 return;
6616 }
6617
6618 // General case.
6619 // We build a heap of squared euclidean distances between current and last pointers
6620 // associated with the current and last pointer indices. Then, we find the best
6621 // match (by distance) for each current pointer.
6622 // The pointers must have the same tool type but it is possible for them to
6623 // transition from hovering to touching or vice-versa while retaining the same id.
6624 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6625
6626 uint32_t heapSize = 0;
6627 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6628 currentPointerIndex++) {
6629 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6630 lastPointerIndex++) {
6631 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006632 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006633 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006634 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006635 if (currentPointer.toolType == lastPointer.toolType) {
6636 int64_t deltaX = currentPointer.x - lastPointer.x;
6637 int64_t deltaY = currentPointer.y - lastPointer.y;
6638
6639 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6640
6641 // Insert new element into the heap (sift up).
6642 heap[heapSize].currentPointerIndex = currentPointerIndex;
6643 heap[heapSize].lastPointerIndex = lastPointerIndex;
6644 heap[heapSize].distance = distance;
6645 heapSize += 1;
6646 }
6647 }
6648 }
6649
6650 // Heapify
6651 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6652 startIndex -= 1;
6653 for (uint32_t parentIndex = startIndex; ;) {
6654 uint32_t childIndex = parentIndex * 2 + 1;
6655 if (childIndex >= heapSize) {
6656 break;
6657 }
6658
6659 if (childIndex + 1 < heapSize
6660 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6661 childIndex += 1;
6662 }
6663
6664 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6665 break;
6666 }
6667
6668 swap(heap[parentIndex], heap[childIndex]);
6669 parentIndex = childIndex;
6670 }
6671 }
6672
6673#if DEBUG_POINTER_ASSIGNMENT
6674 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6675 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006676 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006677 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6678 heap[i].distance);
6679 }
6680#endif
6681
6682 // Pull matches out by increasing order of distance.
6683 // To avoid reassigning pointers that have already been matched, the loop keeps track
6684 // of which last and current pointers have been matched using the matchedXXXBits variables.
6685 // It also tracks the used pointer id bits.
6686 BitSet32 matchedLastBits(0);
6687 BitSet32 matchedCurrentBits(0);
6688 BitSet32 usedIdBits(0);
6689 bool first = true;
6690 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6691 while (heapSize > 0) {
6692 if (first) {
6693 // The first time through the loop, we just consume the root element of
6694 // the heap (the one with smallest distance).
6695 first = false;
6696 } else {
6697 // Previous iterations consumed the root element of the heap.
6698 // Pop root element off of the heap (sift down).
6699 heap[0] = heap[heapSize];
6700 for (uint32_t parentIndex = 0; ;) {
6701 uint32_t childIndex = parentIndex * 2 + 1;
6702 if (childIndex >= heapSize) {
6703 break;
6704 }
6705
6706 if (childIndex + 1 < heapSize
6707 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6708 childIndex += 1;
6709 }
6710
6711 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6712 break;
6713 }
6714
6715 swap(heap[parentIndex], heap[childIndex]);
6716 parentIndex = childIndex;
6717 }
6718
6719#if DEBUG_POINTER_ASSIGNMENT
6720 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6721 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006722 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006723 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6724 heap[i].distance);
6725 }
6726#endif
6727 }
6728
6729 heapSize -= 1;
6730
6731 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6732 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6733
6734 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6735 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6736
6737 matchedCurrentBits.markBit(currentPointerIndex);
6738 matchedLastBits.markBit(lastPointerIndex);
6739
Michael Wright842500e2015-03-13 17:32:02 -07006740 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6741 current->rawPointerData.pointers[currentPointerIndex].id = id;
6742 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6743 current->rawPointerData.markIdBit(id,
6744 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006745 usedIdBits.markBit(id);
6746
6747#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006748 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6749 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006750 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6751#endif
6752 break;
6753 }
6754 }
6755
6756 // Assign fresh ids to pointers that were not matched in the process.
6757 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6758 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6759 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6760
Michael Wright842500e2015-03-13 17:32:02 -07006761 current->rawPointerData.pointers[currentPointerIndex].id = id;
6762 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6763 current->rawPointerData.markIdBit(id,
6764 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006765
6766#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006767 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006768#endif
6769 }
6770}
6771
6772int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6773 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6774 return AKEY_STATE_VIRTUAL;
6775 }
6776
6777 size_t numVirtualKeys = mVirtualKeys.size();
6778 for (size_t i = 0; i < numVirtualKeys; i++) {
6779 const VirtualKey& virtualKey = mVirtualKeys[i];
6780 if (virtualKey.keyCode == keyCode) {
6781 return AKEY_STATE_UP;
6782 }
6783 }
6784
6785 return AKEY_STATE_UNKNOWN;
6786}
6787
6788int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6789 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6790 return AKEY_STATE_VIRTUAL;
6791 }
6792
6793 size_t numVirtualKeys = mVirtualKeys.size();
6794 for (size_t i = 0; i < numVirtualKeys; i++) {
6795 const VirtualKey& virtualKey = mVirtualKeys[i];
6796 if (virtualKey.scanCode == scanCode) {
6797 return AKEY_STATE_UP;
6798 }
6799 }
6800
6801 return AKEY_STATE_UNKNOWN;
6802}
6803
6804bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6805 const int32_t* keyCodes, uint8_t* outFlags) {
6806 size_t numVirtualKeys = mVirtualKeys.size();
6807 for (size_t i = 0; i < numVirtualKeys; i++) {
6808 const VirtualKey& virtualKey = mVirtualKeys[i];
6809
6810 for (size_t i = 0; i < numCodes; i++) {
6811 if (virtualKey.keyCode == keyCodes[i]) {
6812 outFlags[i] = 1;
6813 }
6814 }
6815 }
6816
6817 return true;
6818}
6819
6820
6821// --- SingleTouchInputMapper ---
6822
6823SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6824 TouchInputMapper(device) {
6825}
6826
6827SingleTouchInputMapper::~SingleTouchInputMapper() {
6828}
6829
6830void SingleTouchInputMapper::reset(nsecs_t when) {
6831 mSingleTouchMotionAccumulator.reset(getDevice());
6832
6833 TouchInputMapper::reset(when);
6834}
6835
6836void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6837 TouchInputMapper::process(rawEvent);
6838
6839 mSingleTouchMotionAccumulator.process(rawEvent);
6840}
6841
Michael Wright842500e2015-03-13 17:32:02 -07006842void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006843 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006844 outState->rawPointerData.pointerCount = 1;
6845 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006846
6847 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6848 && (mTouchButtonAccumulator.isHovering()
6849 || (mRawPointerAxes.pressure.valid
6850 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006851 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006852
Michael Wright842500e2015-03-13 17:32:02 -07006853 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006854 outPointer.id = 0;
6855 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6856 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6857 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6858 outPointer.touchMajor = 0;
6859 outPointer.touchMinor = 0;
6860 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6861 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6862 outPointer.orientation = 0;
6863 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6864 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6865 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6866 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6867 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6868 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6869 }
6870 outPointer.isHovering = isHovering;
6871 }
6872}
6873
6874void SingleTouchInputMapper::configureRawPointerAxes() {
6875 TouchInputMapper::configureRawPointerAxes();
6876
6877 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6878 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6879 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6880 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6881 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6882 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6883 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6884}
6885
6886bool SingleTouchInputMapper::hasStylus() const {
6887 return mTouchButtonAccumulator.hasStylus();
6888}
6889
6890
6891// --- MultiTouchInputMapper ---
6892
6893MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6894 TouchInputMapper(device) {
6895}
6896
6897MultiTouchInputMapper::~MultiTouchInputMapper() {
6898}
6899
6900void MultiTouchInputMapper::reset(nsecs_t when) {
6901 mMultiTouchMotionAccumulator.reset(getDevice());
6902
6903 mPointerIdBits.clear();
6904
6905 TouchInputMapper::reset(when);
6906}
6907
6908void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6909 TouchInputMapper::process(rawEvent);
6910
6911 mMultiTouchMotionAccumulator.process(rawEvent);
6912}
6913
Michael Wright842500e2015-03-13 17:32:02 -07006914void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006915 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6916 size_t outCount = 0;
6917 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006918 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006919
6920 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6921 const MultiTouchMotionAccumulator::Slot* inSlot =
6922 mMultiTouchMotionAccumulator.getSlot(inIndex);
6923 if (!inSlot->isInUse()) {
6924 continue;
6925 }
6926
6927 if (outCount >= MAX_POINTERS) {
6928#if DEBUG_POINTERS
6929 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6930 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006931 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006932#endif
6933 break; // too many fingers!
6934 }
6935
Michael Wright842500e2015-03-13 17:32:02 -07006936 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006937 outPointer.x = inSlot->getX();
6938 outPointer.y = inSlot->getY();
6939 outPointer.pressure = inSlot->getPressure();
6940 outPointer.touchMajor = inSlot->getTouchMajor();
6941 outPointer.touchMinor = inSlot->getTouchMinor();
6942 outPointer.toolMajor = inSlot->getToolMajor();
6943 outPointer.toolMinor = inSlot->getToolMinor();
6944 outPointer.orientation = inSlot->getOrientation();
6945 outPointer.distance = inSlot->getDistance();
6946 outPointer.tiltX = 0;
6947 outPointer.tiltY = 0;
6948
6949 outPointer.toolType = inSlot->getToolType();
6950 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6951 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6952 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6953 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6954 }
6955 }
6956
6957 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6958 && (mTouchButtonAccumulator.isHovering()
6959 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6960 outPointer.isHovering = isHovering;
6961
6962 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006963 if (mHavePointerIds) {
6964 int32_t trackingId = inSlot->getTrackingId();
6965 int32_t id = -1;
6966 if (trackingId >= 0) {
6967 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6968 uint32_t n = idBits.clearFirstMarkedBit();
6969 if (mPointerTrackingIdMap[n] == trackingId) {
6970 id = n;
6971 }
6972 }
6973
6974 if (id < 0 && !mPointerIdBits.isFull()) {
6975 id = mPointerIdBits.markFirstUnmarkedBit();
6976 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006977 }
Michael Wright842500e2015-03-13 17:32:02 -07006978 }
gaoshang1a632de2016-08-24 10:23:50 +08006979 if (id < 0) {
6980 mHavePointerIds = false;
6981 outState->rawPointerData.clearIdBits();
6982 newPointerIdBits.clear();
6983 } else {
6984 outPointer.id = id;
6985 outState->rawPointerData.idToIndex[id] = outCount;
6986 outState->rawPointerData.markIdBit(id, isHovering);
6987 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006988 }
Michael Wright842500e2015-03-13 17:32:02 -07006989 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006990 outCount += 1;
6991 }
6992
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006993 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006994 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006995 mPointerIdBits = newPointerIdBits;
6996
6997 mMultiTouchMotionAccumulator.finishSync();
6998}
6999
7000void MultiTouchInputMapper::configureRawPointerAxes() {
7001 TouchInputMapper::configureRawPointerAxes();
7002
7003 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7004 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7005 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7006 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7007 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7008 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7009 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7010 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7011 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7012 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7013 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7014
7015 if (mRawPointerAxes.trackingId.valid
7016 && mRawPointerAxes.slot.valid
7017 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7018 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7019 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007020 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7021 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007022 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007023 slotCount = MAX_SLOTS;
7024 }
7025 mMultiTouchMotionAccumulator.configure(getDevice(),
7026 slotCount, true /*usingSlotsProtocol*/);
7027 } else {
7028 mMultiTouchMotionAccumulator.configure(getDevice(),
7029 MAX_POINTERS, false /*usingSlotsProtocol*/);
7030 }
7031}
7032
7033bool MultiTouchInputMapper::hasStylus() const {
7034 return mMultiTouchMotionAccumulator.hasStylus()
7035 || mTouchButtonAccumulator.hasStylus();
7036}
7037
Michael Wright842500e2015-03-13 17:32:02 -07007038// --- ExternalStylusInputMapper
7039
7040ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7041 InputMapper(device) {
7042
7043}
7044
7045uint32_t ExternalStylusInputMapper::getSources() {
7046 return AINPUT_SOURCE_STYLUS;
7047}
7048
7049void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7050 InputMapper::populateDeviceInfo(info);
7051 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7052 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7053}
7054
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007055void ExternalStylusInputMapper::dump(std::string& dump) {
7056 dump += INDENT2 "External Stylus Input Mapper:\n";
7057 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007058 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007059 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007060 dumpStylusState(dump, mStylusState);
7061}
7062
7063void ExternalStylusInputMapper::configure(nsecs_t when,
7064 const InputReaderConfiguration* config, uint32_t changes) {
7065 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7066 mTouchButtonAccumulator.configure(getDevice());
7067}
7068
7069void ExternalStylusInputMapper::reset(nsecs_t when) {
7070 InputDevice* device = getDevice();
7071 mSingleTouchMotionAccumulator.reset(device);
7072 mTouchButtonAccumulator.reset(device);
7073 InputMapper::reset(when);
7074}
7075
7076void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7077 mSingleTouchMotionAccumulator.process(rawEvent);
7078 mTouchButtonAccumulator.process(rawEvent);
7079
7080 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7081 sync(rawEvent->when);
7082 }
7083}
7084
7085void ExternalStylusInputMapper::sync(nsecs_t when) {
7086 mStylusState.clear();
7087
7088 mStylusState.when = when;
7089
Michael Wright45ccacf2015-04-21 19:01:58 +01007090 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7091 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7092 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7093 }
7094
Michael Wright842500e2015-03-13 17:32:02 -07007095 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7096 if (mRawPressureAxis.valid) {
7097 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7098 } else if (mTouchButtonAccumulator.isToolActive()) {
7099 mStylusState.pressure = 1.0f;
7100 } else {
7101 mStylusState.pressure = 0.0f;
7102 }
7103
7104 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007105
7106 mContext->dispatchExternalStylusState(mStylusState);
7107}
7108
Michael Wrightd02c5b62014-02-10 15:10:22 -08007109
7110// --- JoystickInputMapper ---
7111
7112JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7113 InputMapper(device) {
7114}
7115
7116JoystickInputMapper::~JoystickInputMapper() {
7117}
7118
7119uint32_t JoystickInputMapper::getSources() {
7120 return AINPUT_SOURCE_JOYSTICK;
7121}
7122
7123void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7124 InputMapper::populateDeviceInfo(info);
7125
7126 for (size_t i = 0; i < mAxes.size(); i++) {
7127 const Axis& axis = mAxes.valueAt(i);
7128 addMotionRange(axis.axisInfo.axis, axis, info);
7129
7130 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7131 addMotionRange(axis.axisInfo.highAxis, axis, info);
7132
7133 }
7134 }
7135}
7136
7137void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7138 InputDeviceInfo* info) {
7139 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7140 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7141 /* In order to ease the transition for developers from using the old axes
7142 * to the newer, more semantically correct axes, we'll continue to register
7143 * the old axes as duplicates of their corresponding new ones. */
7144 int32_t compatAxis = getCompatAxis(axisId);
7145 if (compatAxis >= 0) {
7146 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7147 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7148 }
7149}
7150
7151/* A mapping from axes the joystick actually has to the axes that should be
7152 * artificially created for compatibility purposes.
7153 * Returns -1 if no compatibility axis is needed. */
7154int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7155 switch(axis) {
7156 case AMOTION_EVENT_AXIS_LTRIGGER:
7157 return AMOTION_EVENT_AXIS_BRAKE;
7158 case AMOTION_EVENT_AXIS_RTRIGGER:
7159 return AMOTION_EVENT_AXIS_GAS;
7160 }
7161 return -1;
7162}
7163
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007164void JoystickInputMapper::dump(std::string& dump) {
7165 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007166
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007167 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007168 size_t numAxes = mAxes.size();
7169 for (size_t i = 0; i < numAxes; i++) {
7170 const Axis& axis = mAxes.valueAt(i);
7171 const char* label = getAxisLabel(axis.axisInfo.axis);
7172 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007173 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007174 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007175 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007176 }
7177 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7178 label = getAxisLabel(axis.axisInfo.highAxis);
7179 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007180 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007181 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007182 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007183 axis.axisInfo.splitValue);
7184 }
7185 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007186 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007187 }
7188
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007189 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 -08007190 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007191 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007192 "highScale=%0.5f, highOffset=%0.5f\n",
7193 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007194 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007195 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7196 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7197 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7198 }
7199}
7200
7201void JoystickInputMapper::configure(nsecs_t when,
7202 const InputReaderConfiguration* config, uint32_t changes) {
7203 InputMapper::configure(when, config, changes);
7204
7205 if (!changes) { // first time only
7206 // Collect all axes.
7207 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7208 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7209 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7210 continue; // axis must be claimed by a different device
7211 }
7212
7213 RawAbsoluteAxisInfo rawAxisInfo;
7214 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7215 if (rawAxisInfo.valid) {
7216 // Map axis.
7217 AxisInfo axisInfo;
7218 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7219 if (!explicitlyMapped) {
7220 // Axis is not explicitly mapped, will choose a generic axis later.
7221 axisInfo.mode = AxisInfo::MODE_NORMAL;
7222 axisInfo.axis = -1;
7223 }
7224
7225 // Apply flat override.
7226 int32_t rawFlat = axisInfo.flatOverride < 0
7227 ? rawAxisInfo.flat : axisInfo.flatOverride;
7228
7229 // Calculate scaling factors and limits.
7230 Axis axis;
7231 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7232 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7233 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7234 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7235 scale, 0.0f, highScale, 0.0f,
7236 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7237 rawAxisInfo.resolution * scale);
7238 } else if (isCenteredAxis(axisInfo.axis)) {
7239 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7240 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7241 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7242 scale, offset, scale, offset,
7243 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7244 rawAxisInfo.resolution * scale);
7245 } else {
7246 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7247 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7248 scale, 0.0f, scale, 0.0f,
7249 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7250 rawAxisInfo.resolution * scale);
7251 }
7252
7253 // To eliminate noise while the joystick is at rest, filter out small variations
7254 // in axis values up front.
7255 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7256
7257 mAxes.add(abs, axis);
7258 }
7259 }
7260
7261 // If there are too many axes, start dropping them.
7262 // Prefer to keep explicitly mapped axes.
7263 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007264 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007265 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007266 pruneAxes(true);
7267 pruneAxes(false);
7268 }
7269
7270 // Assign generic axis ids to remaining axes.
7271 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7272 size_t numAxes = mAxes.size();
7273 for (size_t i = 0; i < numAxes; i++) {
7274 Axis& axis = mAxes.editValueAt(i);
7275 if (axis.axisInfo.axis < 0) {
7276 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7277 && haveAxis(nextGenericAxisId)) {
7278 nextGenericAxisId += 1;
7279 }
7280
7281 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7282 axis.axisInfo.axis = nextGenericAxisId;
7283 nextGenericAxisId += 1;
7284 } else {
7285 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7286 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007287 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007288 mAxes.removeItemsAt(i--);
7289 numAxes -= 1;
7290 }
7291 }
7292 }
7293 }
7294}
7295
7296bool JoystickInputMapper::haveAxis(int32_t axisId) {
7297 size_t numAxes = mAxes.size();
7298 for (size_t i = 0; i < numAxes; i++) {
7299 const Axis& axis = mAxes.valueAt(i);
7300 if (axis.axisInfo.axis == axisId
7301 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7302 && axis.axisInfo.highAxis == axisId)) {
7303 return true;
7304 }
7305 }
7306 return false;
7307}
7308
7309void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7310 size_t i = mAxes.size();
7311 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7312 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7313 continue;
7314 }
7315 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007316 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007317 mAxes.removeItemsAt(i);
7318 }
7319}
7320
7321bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7322 switch (axis) {
7323 case AMOTION_EVENT_AXIS_X:
7324 case AMOTION_EVENT_AXIS_Y:
7325 case AMOTION_EVENT_AXIS_Z:
7326 case AMOTION_EVENT_AXIS_RX:
7327 case AMOTION_EVENT_AXIS_RY:
7328 case AMOTION_EVENT_AXIS_RZ:
7329 case AMOTION_EVENT_AXIS_HAT_X:
7330 case AMOTION_EVENT_AXIS_HAT_Y:
7331 case AMOTION_EVENT_AXIS_ORIENTATION:
7332 case AMOTION_EVENT_AXIS_RUDDER:
7333 case AMOTION_EVENT_AXIS_WHEEL:
7334 return true;
7335 default:
7336 return false;
7337 }
7338}
7339
7340void JoystickInputMapper::reset(nsecs_t when) {
7341 // Recenter all axes.
7342 size_t numAxes = mAxes.size();
7343 for (size_t i = 0; i < numAxes; i++) {
7344 Axis& axis = mAxes.editValueAt(i);
7345 axis.resetValue();
7346 }
7347
7348 InputMapper::reset(when);
7349}
7350
7351void JoystickInputMapper::process(const RawEvent* rawEvent) {
7352 switch (rawEvent->type) {
7353 case EV_ABS: {
7354 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7355 if (index >= 0) {
7356 Axis& axis = mAxes.editValueAt(index);
7357 float newValue, highNewValue;
7358 switch (axis.axisInfo.mode) {
7359 case AxisInfo::MODE_INVERT:
7360 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7361 * axis.scale + axis.offset;
7362 highNewValue = 0.0f;
7363 break;
7364 case AxisInfo::MODE_SPLIT:
7365 if (rawEvent->value < axis.axisInfo.splitValue) {
7366 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7367 * axis.scale + axis.offset;
7368 highNewValue = 0.0f;
7369 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7370 newValue = 0.0f;
7371 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7372 * axis.highScale + axis.highOffset;
7373 } else {
7374 newValue = 0.0f;
7375 highNewValue = 0.0f;
7376 }
7377 break;
7378 default:
7379 newValue = rawEvent->value * axis.scale + axis.offset;
7380 highNewValue = 0.0f;
7381 break;
7382 }
7383 axis.newValue = newValue;
7384 axis.highNewValue = highNewValue;
7385 }
7386 break;
7387 }
7388
7389 case EV_SYN:
7390 switch (rawEvent->code) {
7391 case SYN_REPORT:
7392 sync(rawEvent->when, false /*force*/);
7393 break;
7394 }
7395 break;
7396 }
7397}
7398
7399void JoystickInputMapper::sync(nsecs_t when, bool force) {
7400 if (!filterAxes(force)) {
7401 return;
7402 }
7403
7404 int32_t metaState = mContext->getGlobalMetaState();
7405 int32_t buttonState = 0;
7406
7407 PointerProperties pointerProperties;
7408 pointerProperties.clear();
7409 pointerProperties.id = 0;
7410 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7411
7412 PointerCoords pointerCoords;
7413 pointerCoords.clear();
7414
7415 size_t numAxes = mAxes.size();
7416 for (size_t i = 0; i < numAxes; i++) {
7417 const Axis& axis = mAxes.valueAt(i);
7418 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7419 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7420 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7421 axis.highCurrentValue);
7422 }
7423 }
7424
7425 // Moving a joystick axis should not wake the device because joysticks can
7426 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7427 // button will likely wake the device.
7428 // TODO: Use the input device configuration to control this behavior more finely.
7429 uint32_t policyFlags = 0;
7430
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007431 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE,
7432 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007433 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007434 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007435 0, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007436 getListener()->notifyMotion(&args);
7437}
7438
7439void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7440 int32_t axis, float value) {
7441 pointerCoords->setAxisValue(axis, value);
7442 /* In order to ease the transition for developers from using the old axes
7443 * to the newer, more semantically correct axes, we'll continue to produce
7444 * values for the old axes as mirrors of the value of their corresponding
7445 * new axes. */
7446 int32_t compatAxis = getCompatAxis(axis);
7447 if (compatAxis >= 0) {
7448 pointerCoords->setAxisValue(compatAxis, value);
7449 }
7450}
7451
7452bool JoystickInputMapper::filterAxes(bool force) {
7453 bool atLeastOneSignificantChange = force;
7454 size_t numAxes = mAxes.size();
7455 for (size_t i = 0; i < numAxes; i++) {
7456 Axis& axis = mAxes.editValueAt(i);
7457 if (force || hasValueChangedSignificantly(axis.filter,
7458 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7459 axis.currentValue = axis.newValue;
7460 atLeastOneSignificantChange = true;
7461 }
7462 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7463 if (force || hasValueChangedSignificantly(axis.filter,
7464 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7465 axis.highCurrentValue = axis.highNewValue;
7466 atLeastOneSignificantChange = true;
7467 }
7468 }
7469 }
7470 return atLeastOneSignificantChange;
7471}
7472
7473bool JoystickInputMapper::hasValueChangedSignificantly(
7474 float filter, float newValue, float currentValue, float min, float max) {
7475 if (newValue != currentValue) {
7476 // Filter out small changes in value unless the value is converging on the axis
7477 // bounds or center point. This is intended to reduce the amount of information
7478 // sent to applications by particularly noisy joysticks (such as PS3).
7479 if (fabs(newValue - currentValue) > filter
7480 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7481 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7482 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7483 return true;
7484 }
7485 }
7486 return false;
7487}
7488
7489bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7490 float filter, float newValue, float currentValue, float thresholdValue) {
7491 float newDistance = fabs(newValue - thresholdValue);
7492 if (newDistance < filter) {
7493 float oldDistance = fabs(currentValue - thresholdValue);
7494 if (newDistance < oldDistance) {
7495 return true;
7496 }
7497 }
7498 return false;
7499}
7500
7501} // namespace android